context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace webapiskeleton.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); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Security.Claims; using System.Text; using System.Text.Json; using System.Threading.Tasks; using System.Xml.Linq; using Xunit; namespace Microsoft.AspNetCore.Authentication.JwtBearer { public class JwtBearerTests : SharedAuthenticationTests<JwtBearerOptions> { protected override string DefaultScheme => JwtBearerDefaults.AuthenticationScheme; protected override Type HandlerType => typeof(JwtBearerHandler); protected override bool SupportsSignIn { get => false; } protected override bool SupportsSignOut { get => false; } protected override void RegisterAuth(AuthenticationBuilder services, Action<JwtBearerOptions> configure) { services.AddJwtBearer(o => { ConfigureDefaults(o); configure.Invoke(o); }); } private void ConfigureDefaults(JwtBearerOptions o) { } [Fact] public async Task BearerTokenValidation() { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('a', 128))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "Bob") }; var token = new JwtSecurityToken( issuer: "issuer.contoso.com", audience: "audience.contoso.com", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var tokenText = new JwtSecurityTokenHandler().WriteToken(token); using var host = await CreateHost(o => { o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = key, }; }); var newBearerToken = "Bearer " + tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", newBearerToken); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); } [Fact] public async Task SaveBearerToken() { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('a', 128))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "Bob") }; var token = new JwtSecurityToken( issuer: "issuer.contoso.com", audience: "audience.contoso.com", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var tokenText = new JwtSecurityTokenHandler().WriteToken(token); using var host = await CreateHost(o => { o.SaveToken = true; o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = key, }; }); var newBearerToken = "Bearer " + tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/token", newBearerToken); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(tokenText, await response.Response.Content.ReadAsStringAsync()); } [Fact] public void MapInboundClaimsDefaultsToTrue() { var options = new JwtBearerOptions(); Assert.True(options.MapInboundClaims); var jwtHandler = options.SecurityTokenValidators.First() as JwtSecurityTokenHandler; Assert.NotNull(jwtHandler); Assert.True(jwtHandler.MapInboundClaims); } [Fact] public void MapInboundClaimsCanBeSetToFalse() { var options = new JwtBearerOptions(); options.MapInboundClaims = false; Assert.False(options.MapInboundClaims); var jwtHandler = options.SecurityTokenValidators.First() as JwtSecurityTokenHandler; Assert.NotNull(jwtHandler); Assert.False(jwtHandler.MapInboundClaims); } [Fact] public async Task SignInThrows() { using var host = await CreateHost(); using var server = host.GetTestServer(); var transaction = await server.SendAsync("https://example.com/signIn"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); } [Fact] public async Task SignOutThrows() { using var host = await CreateHost(); using var server = host.GetTestServer(); var transaction = await server.SendAsync("https://example.com/signOut"); Assert.Equal(HttpStatusCode.OK, transaction.Response.StatusCode); } [Fact] public async Task ThrowAtAuthenticationFailedEvent() { using var host = await CreateHost(o => { o.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { context.Response.StatusCode = 401; throw new Exception(); }, OnMessageReceived = context => { context.Token = "something"; return Task.FromResult(0); } }; o.SecurityTokenValidators.Clear(); o.SecurityTokenValidators.Insert(0, new InvalidTokenValidator()); }, async (context, next) => { try { await next(); Assert.False(true, "Expected exception is not thrown"); } catch (Exception) { context.Response.StatusCode = 401; await context.Response.WriteAsync("i got this"); } }); using var server = host.GetTestServer(); var transaction = await server.SendAsync("https://example.com/signIn"); Assert.Equal(HttpStatusCode.Unauthorized, transaction.Response.StatusCode); } [Fact] public async Task CustomHeaderReceived() { using var host = await CreateHost(o => { o.Events = new JwtBearerEvents() { OnMessageReceived = context => { var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "Bob le Magnifique"), new Claim(ClaimTypes.Email, "bob@contoso.com"), new Claim(ClaimsIdentity.DefaultNameClaimType, "bob") }; context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name)); context.Success(); return Task.FromResult<object>(null); } }; }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "someHeader someblob"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal("Bob le Magnifique", response.ResponseText); } [Fact] public async Task NoHeaderReceived() { using var host = await CreateHost(); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); } [Fact] public async Task HeaderWithoutBearerReceived() { using var host = await CreateHost(); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Token"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); } [Fact] public async Task UnrecognizedTokenReceived() { using var host = await CreateHost(); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("", response.ResponseText); } [Fact] public async Task InvalidTokenReceived() { using var host = await CreateHost(options => { options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new InvalidTokenValidator()); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("Bearer error=\"invalid_token\"", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Theory] [InlineData(typeof(SecurityTokenInvalidAudienceException), "The audience '(null)' is invalid")] [InlineData(typeof(SecurityTokenInvalidIssuerException), "The issuer '(null)' is invalid")] [InlineData(typeof(SecurityTokenNoExpirationException), "The token has no expiration")] [InlineData(typeof(SecurityTokenInvalidLifetimeException), "The token lifetime is invalid; NotBefore: '(null)', Expires: '(null)'")] [InlineData(typeof(SecurityTokenNotYetValidException), "The token is not valid before '01/01/0001 00:00:00'")] [InlineData(typeof(SecurityTokenExpiredException), "The token expired at '01/01/0001 00:00:00'")] [InlineData(typeof(SecurityTokenInvalidSignatureException), "The signature is invalid")] [InlineData(typeof(SecurityTokenSignatureKeyNotFoundException), "The signature key was not found")] public async Task ExceptionReportedInHeaderForAuthenticationFailures(Type errorType, string message) { using var host = await CreateHost(options => { options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new InvalidTokenValidator(errorType)); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal($"Bearer error=\"invalid_token\", error_description=\"{message}\"", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Theory] [InlineData(typeof(SecurityTokenInvalidAudienceException), "The audience 'Bad Audience' is invalid")] [InlineData(typeof(SecurityTokenInvalidIssuerException), "The issuer 'Bad Issuer' is invalid")] [InlineData(typeof(SecurityTokenInvalidLifetimeException), "The token lifetime is invalid; NotBefore: '01/15/2001 00:00:00', Expires: '02/20/2000 00:00:00'")] [InlineData(typeof(SecurityTokenNotYetValidException), "The token is not valid before '01/15/2045 00:00:00'")] [InlineData(typeof(SecurityTokenExpiredException), "The token expired at '02/20/2000 00:00:00'")] public async Task ExceptionReportedInHeaderWithDetailsForAuthenticationFailures(Type errorType, string message) { using var host = await CreateHost(options => { options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new DetailedInvalidTokenValidator(errorType)); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal($"Bearer error=\"invalid_token\", error_description=\"{message}\"", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Theory] [InlineData(typeof(ArgumentException))] public async Task ExceptionNotReportedInHeaderForOtherFailures(Type errorType) { using var host = await CreateHost(options => { options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new InvalidTokenValidator(errorType)); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("Bearer error=\"invalid_token\"", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Fact] public async Task ExceptionsReportedInHeaderForMultipleAuthenticationFailures() { using var host = await CreateHost(options => { options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new InvalidTokenValidator(typeof(SecurityTokenInvalidAudienceException))); options.SecurityTokenValidators.Add(new InvalidTokenValidator(typeof(SecurityTokenSignatureKeyNotFoundException))); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("Bearer error=\"invalid_token\", error_description=\"The audience '(null)' is invalid; The signature key was not found\"", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Theory] [InlineData("custom_error", "custom_description", "custom_uri")] [InlineData("custom_error", "custom_description", null)] [InlineData("custom_error", null, null)] [InlineData(null, "custom_description", "custom_uri")] [InlineData(null, "custom_description", null)] [InlineData(null, null, "custom_uri")] public async Task ExceptionsReportedInHeaderExposesUserDefinedError(string error, string description, string uri) { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents { OnChallenge = context => { context.Error = error; context.ErrorDescription = description; context.ErrorUri = uri; return Task.FromResult(0); } }; }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("", response.ResponseText); var builder = new StringBuilder(JwtBearerDefaults.AuthenticationScheme); if (!string.IsNullOrEmpty(error)) { builder.Append(" error=\""); builder.Append(error); builder.Append("\""); } if (!string.IsNullOrEmpty(description)) { if (!string.IsNullOrEmpty(error)) { builder.Append(","); } builder.Append(" error_description=\""); builder.Append(description); builder.Append('\"'); } if (!string.IsNullOrEmpty(uri)) { if (!string.IsNullOrEmpty(error) || !string.IsNullOrEmpty(description)) { builder.Append(","); } builder.Append(" error_uri=\""); builder.Append(uri); builder.Append('\"'); } Assert.Equal(builder.ToString(), response.Response.Headers.WwwAuthenticate.First().ToString()); } [Fact] public async Task ExceptionNotReportedInHeaderWhenIncludeErrorDetailsIsFalse() { using var host = await CreateHost(o => { o.IncludeErrorDetails = false; }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("Bearer", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Fact] public async Task ExceptionNotReportedInHeaderWhenTokenWasMissing() { using var host = await CreateHost(); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth"); Assert.Equal(HttpStatusCode.Unauthorized, response.Response.StatusCode); Assert.Equal("Bearer", response.Response.Headers.WwwAuthenticate.First().ToString()); Assert.Equal("", response.ResponseText); } [Fact] public async Task CustomTokenValidated() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnTokenValidated = context => { // Retrieve the NameIdentifier claim from the identity // returned by the custom security token validator. var identity = (ClaimsIdentity)context.Principal.Identity; var identifier = identity.FindFirst(ClaimTypes.NameIdentifier); Assert.Equal("Bob le Tout Puissant", identifier.Value); // Remove the existing NameIdentifier claim and replace it // with a new one containing a different value. identity.RemoveClaim(identifier); // Make sure to use a different name identifier // than the one defined by BlobTokenValidator. identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "Bob le Magnifique")); return Task.FromResult<object>(null); } }; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new BlobTokenValidator(JwtBearerDefaults.AuthenticationScheme)); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer someblob"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal("Bob le Magnifique", response.ResponseText); } [Fact] public async Task RetrievingTokenFromAlternateLocation() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnMessageReceived = context => { context.Token = "CustomToken"; return Task.FromResult<object>(null); } }; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT", token => { Assert.Equal("CustomToken", token); })); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/oauth", "Bearer Token"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal("Bob le Tout Puissant", response.ResponseText); } [Fact] public async Task EventOnMessageReceivedSkip_NoMoreEventsExecuted() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnMessageReceived = context => { context.NoResult(); return Task.FromResult(0); }, OnTokenValidated = context => { throw new NotImplementedException(); }, OnAuthenticationFailed = context => { throw new NotImplementedException(context.Exception.ToString()); }, OnChallenge = context => { throw new NotImplementedException(); }, }; }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(string.Empty, response.ResponseText); } [Fact] public async Task EventOnMessageReceivedReject_NoMoreEventsExecuted() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnMessageReceived = context => { context.Fail("Authentication was aborted from user code."); context.Response.StatusCode = StatusCodes.Status202Accepted; return Task.FromResult(0); }, OnTokenValidated = context => { throw new NotImplementedException(); }, OnAuthenticationFailed = context => { throw new NotImplementedException(context.Exception.ToString()); }, OnChallenge = context => { throw new NotImplementedException(); }, }; }); using var server = host.GetTestServer(); var exception = await Assert.ThrowsAsync<Exception>(delegate { return SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); }); Assert.Equal("Authentication was aborted from user code.", exception.InnerException.Message); } [Fact] public async Task EventOnTokenValidatedSkip_NoMoreEventsExecuted() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnTokenValidated = context => { context.NoResult(); return Task.FromResult(0); }, OnAuthenticationFailed = context => { throw new NotImplementedException(context.Exception.ToString()); }, OnChallenge = context => { throw new NotImplementedException(); }, }; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT")); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(string.Empty, response.ResponseText); } [Fact] public async Task EventOnTokenValidatedReject_NoMoreEventsExecuted() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnTokenValidated = context => { context.Fail("Authentication was aborted from user code."); context.Response.StatusCode = StatusCodes.Status202Accepted; return Task.FromResult(0); }, OnAuthenticationFailed = context => { throw new NotImplementedException(context.Exception.ToString()); }, OnChallenge = context => { throw new NotImplementedException(); }, }; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT")); }); using var server = host.GetTestServer(); var exception = await Assert.ThrowsAsync<Exception>(delegate { return SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); }); Assert.Equal("Authentication was aborted from user code.", exception.InnerException.Message); } [Fact] public async Task EventOnAuthenticationFailedSkip_NoMoreEventsExecuted() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnTokenValidated = context => { throw new Exception("Test Exception"); }, OnAuthenticationFailed = context => { context.NoResult(); return Task.FromResult(0); }, OnChallenge = context => { throw new NotImplementedException(); }, }; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT")); }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Equal(string.Empty, response.ResponseText); } [Fact] public async Task EventOnAuthenticationFailedReject_NoMoreEventsExecuted() { using var host = await CreateHost(options => { options.Events = new JwtBearerEvents() { OnTokenValidated = context => { throw new Exception("Test Exception"); }, OnAuthenticationFailed = context => { context.Fail("Authentication was aborted from user code."); context.Response.StatusCode = StatusCodes.Status202Accepted; return Task.FromResult(0); }, OnChallenge = context => { throw new NotImplementedException(); }, }; options.SecurityTokenValidators.Clear(); options.SecurityTokenValidators.Add(new BlobTokenValidator("JWT")); }); using var server = host.GetTestServer(); var exception = await Assert.ThrowsAsync<Exception>(delegate { return SendAsync(server, "http://example.com/checkforerrors", "Bearer Token"); }); Assert.Equal("Authentication was aborted from user code.", exception.InnerException.Message); } [Fact] public async Task EventOnChallengeSkip_ResponseNotModified() { using var host = await CreateHost(o => { o.Events = new JwtBearerEvents() { OnChallenge = context => { context.HandleResponse(); return Task.FromResult(0); }, }; }); using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/unauthorized", "Bearer Token"); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); Assert.Empty(response.Response.Headers.WwwAuthenticate); Assert.Equal(string.Empty, response.ResponseText); } [Fact] public async Task EventOnForbidden_ResponseNotModified() { var tokenData = CreateStandardTokenAndKey(); using var host = await CreateHost(o => { o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = tokenData.key, }; }); var newBearerToken = "Bearer " + tokenData.tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/forbidden", newBearerToken); Assert.Equal(HttpStatusCode.Forbidden, response.Response.StatusCode); } [Fact] public async Task EventOnForbiddenSkip_ResponseNotModified() { var tokenData = CreateStandardTokenAndKey(); using var host = await CreateHost(o => { o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = tokenData.key, }; o.Events = new JwtBearerEvents() { OnForbidden = context => { return Task.FromResult(0); } }; }); var newBearerToken = "Bearer " + tokenData.tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/forbidden", newBearerToken); Assert.Equal(HttpStatusCode.Forbidden, response.Response.StatusCode); } [Fact] public async Task EventOnForbidden_ResponseModified() { var tokenData = CreateStandardTokenAndKey(); using var host = await CreateHost(o => { o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = tokenData.key, }; o.Events = new JwtBearerEvents() { OnForbidden = context => { context.Response.StatusCode = 418; return context.Response.WriteAsync("You Shall Not Pass"); } }; }); var newBearerToken = "Bearer " + tokenData.tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/forbidden", newBearerToken); Assert.Equal(418, (int)response.Response.StatusCode); Assert.Equal("You Shall Not Pass", await response.Response.Content.ReadAsStringAsync()); } [Fact] public async Task ExpirationAndIssuedSetOnAuthenticateResult() { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('a', 128))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "Bob") }; var token = new JwtSecurityToken( issuer: "issuer.contoso.com", audience: "audience.contoso.com", claims: claims, notBefore: DateTime.Now.AddMinutes(-10), expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var tokenText = new JwtSecurityTokenHandler().WriteToken(token); using var host = await CreateHost(o => { o.SaveToken = true; o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = key, }; }); var newBearerToken = "Bearer " + tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/expiration", newBearerToken); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); var responseBody = await response.Response.Content.ReadAsStringAsync(); using var dom = JsonDocument.Parse(responseBody); Assert.NotEqual(DateTimeOffset.MinValue, token.ValidTo); Assert.NotEqual(DateTimeOffset.MinValue, token.ValidFrom); Assert.Equal(token.ValidTo, dom.RootElement.GetProperty("expires").GetDateTimeOffset()); Assert.Equal(token.ValidFrom, dom.RootElement.GetProperty("issued").GetDateTimeOffset()); } [Fact] public async Task ExpirationAndIssuedNullWhenMinOrMaxValue() { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('a', 128))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "Bob") }; var token = new JwtSecurityToken( issuer: "issuer.contoso.com", audience: "audience.contoso.com", claims: claims, expires: DateTime.MaxValue, signingCredentials: creds); var tokenText = new JwtSecurityTokenHandler().WriteToken(token); using var host = await CreateHost(o => { o.SaveToken = true; o.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = "issuer.contoso.com", ValidAudience = "audience.contoso.com", IssuerSigningKey = key, }; }); var newBearerToken = "Bearer " + tokenText; using var server = host.GetTestServer(); var response = await SendAsync(server, "http://example.com/expiration", newBearerToken); Assert.Equal(HttpStatusCode.OK, response.Response.StatusCode); var responseBody = await response.Response.Content.ReadAsStringAsync(); using var dom = JsonDocument.Parse(responseBody); Assert.Equal(JsonValueKind.Null, dom.RootElement.GetProperty("expires").ValueKind); Assert.Equal(JsonValueKind.Null, dom.RootElement.GetProperty("issued").ValueKind); } class InvalidTokenValidator : ISecurityTokenValidator { public InvalidTokenValidator() { ExceptionType = typeof(SecurityTokenException); } public InvalidTokenValidator(Type exceptionType) { ExceptionType = exceptionType; } public Type ExceptionType { get; set; } public bool CanValidateToken => true; public int MaximumTokenSizeInBytes { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool CanReadToken(string securityToken) => true; public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { var constructor = ExceptionType.GetTypeInfo().GetConstructor(new[] { typeof(string) }); var exception = (Exception)constructor.Invoke(new[] { ExceptionType.Name }); throw exception; } } class DetailedInvalidTokenValidator : ISecurityTokenValidator { public DetailedInvalidTokenValidator() { ExceptionType = typeof(SecurityTokenException); } public DetailedInvalidTokenValidator(Type exceptionType) { ExceptionType = exceptionType; } public Type ExceptionType { get; set; } public bool CanValidateToken => true; public int MaximumTokenSizeInBytes { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool CanReadToken(string securityToken) => true; public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { if (ExceptionType == typeof(SecurityTokenInvalidAudienceException)) { throw new SecurityTokenInvalidAudienceException("SecurityTokenInvalidAudienceException") { InvalidAudience = "Bad Audience" }; } if (ExceptionType == typeof(SecurityTokenInvalidIssuerException)) { throw new SecurityTokenInvalidIssuerException("SecurityTokenInvalidIssuerException") { InvalidIssuer = "Bad Issuer" }; } if (ExceptionType == typeof(SecurityTokenInvalidLifetimeException)) { throw new SecurityTokenInvalidLifetimeException("SecurityTokenInvalidLifetimeException") { NotBefore = new DateTime(2001, 1, 15), Expires = new DateTime(2000, 2, 20), }; } if (ExceptionType == typeof(SecurityTokenNotYetValidException)) { throw new SecurityTokenNotYetValidException("SecurityTokenNotYetValidException") { NotBefore = new DateTime(2045, 1, 15), }; } if (ExceptionType == typeof(SecurityTokenExpiredException)) { throw new SecurityTokenExpiredException("SecurityTokenExpiredException") { Expires = new DateTime(2000, 2, 20), }; } else { throw new NotImplementedException(ExceptionType.Name); } } } class BlobTokenValidator : ISecurityTokenValidator { private readonly Action<string> _tokenValidator; public BlobTokenValidator(string authenticationScheme) { AuthenticationScheme = authenticationScheme; } public BlobTokenValidator(string authenticationScheme, Action<string> tokenValidator) { AuthenticationScheme = authenticationScheme; _tokenValidator = tokenValidator; } public string AuthenticationScheme { get; } public bool CanValidateToken => true; public int MaximumTokenSizeInBytes { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool CanReadToken(string securityToken) => true; public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken) { validatedToken = new TestSecurityToken(); _tokenValidator?.Invoke(securityToken); var claims = new[] { // Make sure to use a different name identifier // than the one defined by CustomTokenValidated. new Claim(ClaimTypes.NameIdentifier, "Bob le Tout Puissant"), new Claim(ClaimTypes.Email, "bob@contoso.com"), new Claim(ClaimsIdentity.DefaultNameClaimType, "bob"), }; return new ClaimsPrincipal(new ClaimsIdentity(claims, AuthenticationScheme)); } } private static async Task<IHost> CreateHost(Action<JwtBearerOptions> options = null, Func<HttpContext, Func<Task>, Task> handlerBeforeAuth = null) { var host = new HostBuilder() .ConfigureWebHost(builder => builder.UseTestServer() .Configure(app => { if (handlerBeforeAuth != null) { app.Use(handlerBeforeAuth); } app.UseAuthentication(); app.Use(async (context, next) => { if (context.Request.Path == new PathString("/checkforerrors")) { var result = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); // this used to be "Automatic" if (result.Failure != null) { throw new Exception("Failed to authenticate", result.Failure); } return; } else if (context.Request.Path == new PathString("/oauth")) { if (context.User == null || context.User.Identity == null || !context.User.Identity.IsAuthenticated) { context.Response.StatusCode = 401; // REVIEW: no more automatic challenge await context.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme); return; } var identifier = context.User.FindFirst(ClaimTypes.NameIdentifier); if (identifier == null) { context.Response.StatusCode = 500; return; } await context.Response.WriteAsync(identifier.Value); } else if (context.Request.Path == new PathString("/token")) { var token = await context.GetTokenAsync("access_token"); await context.Response.WriteAsync(token); } else if (context.Request.Path == new PathString("/unauthorized")) { // Simulate Authorization failure var result = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); await context.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme); } else if (context.Request.Path == new PathString("/forbidden")) { // Simulate Forbidden await context.ForbidAsync(JwtBearerDefaults.AuthenticationScheme); } else if (context.Request.Path == new PathString("/signIn")) { await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal())); } else if (context.Request.Path == new PathString("/signOut")) { await Assert.ThrowsAsync<InvalidOperationException>(() => context.SignOutAsync(JwtBearerDefaults.AuthenticationScheme)); } else if (context.Request.Path == new PathString("/expiration")) { var authenticationResult = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); await context.Response.WriteAsJsonAsync( new { Expires = authenticationResult.Properties?.ExpiresUtc, Issued = authenticationResult.Properties?.IssuedUtc }); } else { await next(context); } }); }) .ConfigureServices(services => services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options))) .Build(); await host.StartAsync(); return host; } // TODO: see if we can share the TestExtensions SendAsync method (only diff is auth header) private static async Task<Transaction> SendAsync(TestServer server, string uri, string authorizationHeader = null) { var request = new HttpRequestMessage(HttpMethod.Get, uri); if (!string.IsNullOrEmpty(authorizationHeader)) { request.Headers.Add("Authorization", authorizationHeader); } var transaction = new Transaction { Request = request, Response = await server.CreateClient().SendAsync(request), }; transaction.ResponseText = await transaction.Response.Content.ReadAsStringAsync(); if (transaction.Response.Content != null && transaction.Response.Content.Headers.ContentType != null && transaction.Response.Content.Headers.ContentType.MediaType == "text/xml") { transaction.ResponseElement = XElement.Parse(transaction.ResponseText); } return transaction; } private static (string tokenText, SymmetricSecurityKey key) CreateStandardTokenAndKey() { var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(new string('a', 128))); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "Bob") }; var token = new JwtSecurityToken( issuer: "issuer.contoso.com", audience: "audience.contoso.com", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); var tokenText = new JwtSecurityTokenHandler().WriteToken(token); return (tokenText, key); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Rename.ConflictEngine; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractEditorInlineRenameService { /// <summary> /// Represents information about the ability to rename a particular location. /// </summary> private partial class SymbolInlineRenameInfo : IInlineRenameInfo { private const string AttributeSuffix = "Attribute"; private readonly object _gate = new object(); private readonly Document _document; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private Task<RenameLocationSet> _underlyingFindRenameLocationsTask; /// <summary> /// Whether or not we shortened the trigger span (say because we were renaming an attribute, /// and we didn't select the 'Attribute' portion of the name. /// </summary> private readonly bool _shortenedTriggerSpan; private readonly bool _isRenamingAttributePrefix; public bool CanRename { get; } public string LocalizedErrorMessage { get; } public TextSpan TriggerSpan { get; } public ISymbol RenameSymbol { get; } public bool HasOverloads { get; } public bool ForceRenameOverloads { get; } public SymbolInlineRenameInfo( IEnumerable<IRefactorNotifyService> refactorNotifyServices, Document document, TextSpan triggerSpan, ISymbol renameSymbol, bool forceRenameOverloads, CancellationToken cancellationToken) { this.CanRename = true; _refactorNotifyServices = refactorNotifyServices; _document = document; this.RenameSymbol = renameSymbol; this.HasOverloads = RenameLocationSet.GetOverloadedSymbols(this.RenameSymbol).Any(); this.ForceRenameOverloads = forceRenameOverloads; _isRenamingAttributePrefix = CanRenameAttributePrefix(document, triggerSpan, cancellationToken); this.TriggerSpan = GetReferenceEditSpan(new InlineRenameLocation(document, triggerSpan), cancellationToken); _shortenedTriggerSpan = this.TriggerSpan != triggerSpan; } private bool CanRenameAttributePrefix(Document document, TextSpan triggerSpan, CancellationToken cancellationToken) { // if this isn't an attribute, or it doesn't have the 'Attribute' suffix, then clearly // we can't rename just the attribute prefix. if (!this.IsRenamingAttributeTypeWithAttributeSuffix()) { return false; } // Ok, the symbol is good. Now, make sure that the trigger text starts with the prefix // of the attribute. If it does, then we can rename just the attribute prefix (otherwise // we need to rename the entire attribute). var nameWithoutAttribute = this.RenameSymbol.Name.GetWithoutAttributeSuffix(isCaseSensitive: true); var triggerText = GetSpanText(document, triggerSpan, cancellationToken); return triggerText.StartsWith(triggerText); // TODO: Always true? What was it supposed to do? } /// <summary> /// Given a span of text, we need to return the subspan that is editable and /// contains the current replacementText. /// /// These cases are currently handled: /// - Escaped identifiers [foo] => foo /// - Type suffixes in VB foo$ => foo /// - Qualified names from complexification A.foo => foo /// - Optional Attribute suffixes XAttribute => X /// Careful here: XAttribute => XAttribute if renamesymbol is XAttributeAttribute /// - Compiler-generated EventHandler suffix XEventHandler => X /// - Compiler-generated get_ and set_ prefixes get_X => X /// </summary> public TextSpan GetReferenceEditSpan(InlineRenameLocation location, CancellationToken cancellationToken) { var searchName = this.RenameSymbol.Name; if (_isRenamingAttributePrefix) { // We're only renaming the attribute prefix part. We want to adjust the span of // the reference we've found to only update the prefix portion. searchName = GetWithoutAttributeSuffix(this.RenameSymbol.Name); } var spanText = GetSpanText(location.Document, location.TextSpan, cancellationToken); var index = spanText.LastIndexOf(searchName, StringComparison.Ordinal); if (index < 0) { // Couldn't even find the search text at this reference location. This might happen // if the user used things like unicode escapes. IN that case, we'll have to rename // the entire identifier. return location.TextSpan; } return new TextSpan(location.TextSpan.Start + index, searchName.Length); } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string replacementText, CancellationToken cancellationToken) { var spanText = GetSpanText(location.Document, location.TextSpan, cancellationToken); var position = spanText.LastIndexOf(replacementText, StringComparison.Ordinal); if (_isRenamingAttributePrefix) { // We're only renaming the attribute prefix part. We want to adjust the span of // the reference we've found to only update the prefix portion. var index = spanText.LastIndexOf(replacementText + AttributeSuffix, StringComparison.Ordinal); position = index >= 0 ? index : position; } if (position < 0) { return null; } return new TextSpan(location.TextSpan.Start + position, replacementText.Length); } private static string GetSpanText(Document document, TextSpan triggerSpan, CancellationToken cancellationToken) { var sourceText = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var triggerText = sourceText.ToString(triggerSpan); return triggerText; } private static string GetWithoutAttributeSuffix(string value) { return value.GetWithoutAttributeSuffix(isCaseSensitive: true); } internal bool IsRenamingAttributeTypeWithAttributeSuffix() { if (this.RenameSymbol.IsAttribute() || (this.RenameSymbol.Kind == SymbolKind.Alias && ((IAliasSymbol)this.RenameSymbol).Target.IsAttribute())) { var name = this.RenameSymbol.Name; if (name.TryGetWithoutAttributeSuffix(isCaseSensitive: true, result: out name)) { return true; } } return false; } public string DisplayName { get { return this.RenameSymbol.Name; } } public string FullDisplayName { get { return this.RenameSymbol.ToDisplayString(); } } public Glyph Glyph { get { return this.RenameSymbol.GetGlyph(); } } public string GetFinalSymbolName(string replacementText) { if (_isRenamingAttributePrefix) { return replacementText + AttributeSuffix; } return replacementText; } public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { Task<RenameLocationSet> renameTask; lock (_gate) { if (_underlyingFindRenameLocationsTask == null) { // If this is the first call, then just start finding the initial set of rename // locations. _underlyingFindRenameLocationsTask = RenameLocationSet.FindAsync( this.RenameSymbol, _document.Project.Solution, optionSet, cancellationToken); renameTask = _underlyingFindRenameLocationsTask; // null out the option set. We don't need it anymore, and this will ensure // we don't call FindWithUpdatedOptionsAsync below. optionSet = null; } else { // We already have a task to figure out the set of rename locations. Let it // finish, then ask it to get the rename locations with the updated options. renameTask = _underlyingFindRenameLocationsTask; } } return GetLocationSet(renameTask, optionSet, cancellationToken); } private async Task<IInlineRenameLocationSet> GetLocationSet(Task<RenameLocationSet> renameTask, OptionSet optionSet, CancellationToken cancellationToken) { var locationSet = await renameTask.ConfigureAwait(false); if (optionSet != null) { locationSet = await locationSet.FindWithUpdatedOptionsAsync(optionSet, cancellationToken).ConfigureAwait(false); } return new InlineRenameLocationSet(this, locationSet); } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol, this.GetFinalSymbolName(replacementText), throwOnFailure: false); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol, this.GetFinalSymbolName(replacementText), throwOnFailure: false); } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using NLog.Config; using NLog.Internal; using NLog.Common; /// <summary> /// Abstract interface that layouts must implement. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Few people will see this conflict.")] [NLogConfigurationItem] public abstract class Layout : ISupportsInitialize, IRenderable { /// <summary> /// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/> /// </summary> internal bool IsInitialized; private bool _scannedForObjects; /// <summary> /// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread). /// </summary> /// <remarks> /// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are /// like that as well. /// /// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output. /// </remarks> internal bool ThreadAgnostic { get; set; } internal bool ThreadSafe { get; set; } internal bool MutableUnsafe { get; set; } /// <summary> /// Gets the level of stack trace information required for rendering. /// </summary> internal StackTraceUsage StackTraceUsage { get; private set; } private const int MaxInitialRenderBufferLength = 16384; private int _maxRenderedLength; /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Converts a given text to a <see cref="Layout" />. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns><see cref="SimpleLayout"/> object represented by the text.</returns> public static implicit operator Layout([Localizable(false)] string text) { return FromString(text, ConfigurationItemFactory.Default); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns>' public static Layout FromString(string layoutText) { return FromString(layoutText, ConfigurationItemFactory.Default); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromString(string layoutText, ConfigurationItemFactory configurationItemFactory) { return new SimpleLayout(layoutText, configurationItemFactory); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <param name="throwConfigExceptions">Whether <see cref="NLogConfigurationException"/> should be thrown on parse errors (false = replace unrecognized tokens with a space).</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromString(string layoutText, bool throwConfigExceptions) { try { return new SimpleLayout(layoutText, ConfigurationItemFactory.Default, throwConfigExceptions); } catch (NLogConfigurationException) { throw; } catch (Exception ex) { if (!throwConfigExceptions || ex.MustBeRethrownImmediately()) throw; throw new NLogConfigurationException($"Invalid Layout: {layoutText}", ex); } } /// <summary> /// Create a <see cref="SimpleLayout"/> from a lambda method. /// </summary> /// <param name="layoutMethod">Method that renders the layout.</param> /// <param name="options">Tell if method is safe for concurrent threading.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromMethod(Func<LogEventInfo, object> layoutMethod, LayoutRenderOptions options = LayoutRenderOptions.None) { if (layoutMethod == null) throw new ArgumentNullException(nameof(layoutMethod)); #if NETSTANDARD1_0 var name = $"{layoutMethod.Target?.ToString()}"; #else var name = $"{layoutMethod.Method?.DeclaringType?.ToString()}.{layoutMethod.Method?.Name}"; #endif var layoutRenderer = CreateFuncLayoutRenderer(layoutMethod, options, name); return new SimpleLayout(new[] { layoutRenderer }, layoutRenderer.LayoutRendererName, ConfigurationItemFactory.Default); } private static LayoutRenderers.FuncLayoutRenderer CreateFuncLayoutRenderer(Func<LogEventInfo, object> layoutMethod, LayoutRenderOptions options, string name) { if ((options & LayoutRenderOptions.ThreadAgnostic) == LayoutRenderOptions.ThreadAgnostic) return new LayoutRenderers.FuncThreadAgnosticLayoutRenderer(name, (l, c) => layoutMethod(l)); else if ((options & LayoutRenderOptions.ThreadSafe) != 0) return new LayoutRenderers.FuncThreadSafeLayoutRenderer(name, (l, c) => layoutMethod(l)); else return new LayoutRenderers.FuncLayoutRenderer(name, (l, c) => layoutMethod(l)); } /// <summary> /// Precalculates the layout for the specified log event and stores the result /// in per-log event cache. /// /// Only if the layout doesn't have [ThreadAgnostic] and doesn't contain layouts with [ThreadAgnostic]. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// Calling this method enables you to store the log event in a buffer /// and/or potentially evaluate it in another thread even though the /// layout may contain thread-dependent renderer. /// </remarks> public virtual void Precalculate(LogEventInfo logEvent) { if (!ThreadAgnostic || MutableUnsafe) { Render(logEvent); } } /// <summary> /// Renders the event info in layout. /// </summary> /// <param name="logEvent">The event info.</param> /// <returns>String representing log event.</returns> public string Render(LogEventInfo logEvent) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if (!ThreadAgnostic || MutableUnsafe) { object cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { return cachedValue?.ToString() ?? string.Empty; } } string layoutValue = GetFormattedMessage(logEvent) ?? string.Empty; if (!ThreadAgnostic || MutableUnsafe) { // Would be nice to only do this in Precalculate(), but we need to ensure internal cache // is updated for for custom Layouts that overrides Precalculate (without calling base.Precalculate) logEvent.AddCachedLayoutValue(this, layoutValue); } return layoutValue; } internal virtual void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { Precalculate(logEvent); // Allow custom Layouts to work with OptimizeBufferReuse } /// <summary> /// Optimized version of <see cref="Render(LogEventInfo)"/> for internal Layouts. Works best /// when override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available. /// </summary> /// <param name="logEvent">The event info.</param> /// <param name="target">Appends the string representing log event to target</param> /// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param> internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder target, bool cacheLayoutResult = false) { if (!IsInitialized) { Initialize(LoggingConfiguration); } if (!ThreadAgnostic || MutableUnsafe) { object cachedValue; if (logEvent.TryGetCachedLayoutValue(this, out cachedValue)) { target.Append(cachedValue?.ToString() ?? string.Empty); return; } } cacheLayoutResult = cacheLayoutResult && !ThreadAgnostic; using (var localTarget = new AppendBuilderCreator(target, cacheLayoutResult)) { RenderFormattedMessage(logEvent, localTarget.Builder); if (cacheLayoutResult) { // when needed as it generates garbage logEvent.AddCachedLayoutValue(this, localTarget.Builder.ToString()); } } } /// <summary> /// Valid default implementation of <see cref="GetFormattedMessage" />, when having implemented the optimized <see cref="RenderFormattedMessage"/> /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="reusableBuilder">StringBuilder to help minimize allocations [optional].</param> /// <returns>The rendered layout.</returns> internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder reusableBuilder = null) { int initialLength = _maxRenderedLength; if (initialLength > MaxInitialRenderBufferLength) { initialLength = MaxInitialRenderBufferLength; } var sb = reusableBuilder ?? new StringBuilder(initialLength); RenderFormattedMessage(logEvent, sb); if (sb.Length > _maxRenderedLength) { _maxRenderedLength = sb.Length; } return sb.ToString(); } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <param name="target"><see cref="StringBuilder"/> for the result</param> protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { target.Append(GetFormattedMessage(logEvent) ?? string.Empty); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { Initialize(configuration); } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { Close(); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { if (!IsInitialized) { LoggingConfiguration = configuration; IsInitialized = true; _scannedForObjects = false; PropertyHelper.CheckRequiredParameters(this); InitializeLayout(); if (!_scannedForObjects) { InternalLogger.Debug("{0} Initialized Layout done but not scanned for objects", GetType()); PerformObjectScanning(); } } } internal void PerformObjectScanning() { var objectGraphScannerList = ObjectGraphScanner.FindReachableObjects<IRenderable>(true, this); var objectGraphTypes = new HashSet<Type>(objectGraphScannerList.Select(o => o.GetType())); objectGraphTypes.Remove(typeof(SimpleLayout)); objectGraphTypes.Remove(typeof(NLog.LayoutRenderers.LiteralLayoutRenderer)); // determine whether the layout is thread-agnostic // layout is thread agnostic if it is thread-agnostic and // all its nested objects are thread-agnostic. ThreadAgnostic = objectGraphTypes.All(t => t.IsDefined(typeof(ThreadAgnosticAttribute), true)); ThreadSafe = objectGraphTypes.All(t => t.IsDefined(typeof(ThreadSafeAttribute), true)); MutableUnsafe = objectGraphTypes.Any(t => t.IsDefined(typeof(MutableUnsafeAttribute), true)); if ((ThreadAgnostic || !MutableUnsafe) && objectGraphScannerList.Count > 1 && objectGraphTypes.Count > 0) { foreach (var nestedLayout in objectGraphScannerList.OfType<Layout>()) { if (!ReferenceEquals(nestedLayout, this)) { nestedLayout.Initialize(LoggingConfiguration); ThreadAgnostic = nestedLayout.ThreadAgnostic && ThreadAgnostic; MutableUnsafe = nestedLayout.MutableUnsafe || MutableUnsafe; } } } // determine the max StackTraceUsage, to decide if Logger needs to capture callsite StackTraceUsage = StackTraceUsage.None; // In case this Layout should implement IUsesStackTrace StackTraceUsage = objectGraphScannerList.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(item => item?.StackTraceUsage ?? StackTraceUsage.None); _scannedForObjects = true; } /// <summary> /// Closes this instance. /// </summary> internal void Close() { if (IsInitialized) { LoggingConfiguration = null; IsInitialized = false; CloseLayout(); } } /// <summary> /// Initializes the layout. /// </summary> protected virtual void InitializeLayout() { PerformObjectScanning(); } /// <summary> /// Closes the layout. /// </summary> protected virtual void CloseLayout() { } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected abstract string GetFormattedMessage(LogEventInfo logEvent); /// <summary> /// Register a custom Layout. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the Layout.</typeparam> /// <param name="name"> Name of the Layout.</param> public static void Register<T>(string name) where T : Layout { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Layout. /// </summary> /// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="layoutType"> Type of the Layout.</param> /// <param name="name"> Name of the Layout.</param> public static void Register(string name, Type layoutType) { ConfigurationItemFactory.Default.Layouts .RegisterDefinition(name, layoutType); } /// <summary> /// Optimized version of <see cref="Precalculate(LogEventInfo)"/> for internal Layouts, when /// override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available. /// </summary> internal void PrecalculateBuilderInternal(LogEventInfo logEvent, StringBuilder target) { if (!ThreadAgnostic || MutableUnsafe) { RenderAppendBuilder(logEvent, target, true); } } internal string ToStringWithNestedItems<T>(IList<T> nestedItems, Func<T, string> nextItemToString) { if (nestedItems?.Count > 0) { var nestedNames = nestedItems.Select(c => nextItemToString(c)).ToArray(); return string.Concat(GetType().Name, "=", string.Join("|", nestedNames)); } return base.ToString(); } /// <summary> /// Try get value /// </summary> /// <param name="logEvent"></param> /// <param name="rawValue">rawValue if return result is true</param> /// <returns>false if we could not determine the rawValue</returns> internal virtual bool TryGetRawValue(LogEventInfo logEvent, out object rawValue) { rawValue = null; return 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.Generic; using System.Composition.Convention; using System.Composition.Hosting; using System.Composition.Hosting.Core; using System.Composition.TypedParts.ActivationFeatures; using System.Linq; using System.Reflection; namespace System.Composition.TypedParts.Discovery { internal class TypeInspector { private static readonly IDictionary<string, object> s_noMetadata = new Dictionary<string, object>(); private readonly ActivationFeature[] _activationFeatures; private readonly AttributedModelProvider _attributeContext; public TypeInspector(AttributedModelProvider attributeContext, ActivationFeature[] activationFeatures) { _attributeContext = attributeContext; _activationFeatures = activationFeatures; } public bool InspectTypeForPart(TypeInfo type, out DiscoveredPart part) { part = null; if (type.IsAbstract || !type.IsClass || _attributeContext.GetDeclaredAttribute<PartNotDiscoverableAttribute>(type.AsType(), type) != null) return false; foreach (var export in DiscoverExports(type)) { part = part ?? new DiscoveredPart(type, _attributeContext, _activationFeatures); part.AddDiscoveredExport(export); } return part != null; } private IEnumerable<DiscoveredExport> DiscoverExports(TypeInfo partType) { foreach (var export in DiscoverInstanceExports(partType)) yield return export; foreach (var export in DiscoverPropertyExports(partType)) yield return export; } private IEnumerable<DiscoveredExport> DiscoverInstanceExports(TypeInfo partType) { var partTypeAsType = partType.AsType(); foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, partType)) { IDictionary<string, object> metadata = new Dictionary<string, object>(); ReadMetadataAttribute(export, metadata); var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, partType); ReadLooseMetadata(applied, metadata); var contractType = export.ContractType ?? partTypeAsType; CheckInstanceExportCompatibility(partType, contractType.GetTypeInfo()); var exportKey = new CompositionContract(contractType, export.ContractName); if (metadata.Count == 0) metadata = s_noMetadata; yield return new DiscoveredInstanceExport(exportKey, metadata); } } private IEnumerable<DiscoveredExport> DiscoverPropertyExports(TypeInfo partType) { var partTypeAsType = partType.AsType(); foreach (var property in partTypeAsType.GetRuntimeProperties() .Where(pi => pi.CanRead && pi.GetMethod.IsPublic && !pi.GetMethod.IsStatic)) { foreach (var export in _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, property)) { IDictionary<string, object> metadata = new Dictionary<string, object>(); ReadMetadataAttribute(export, metadata); var applied = _attributeContext.GetDeclaredAttributes(partTypeAsType, property); ReadLooseMetadata(applied, metadata); var contractType = export.ContractType ?? property.PropertyType; CheckPropertyExportCompatibility(partType, property, contractType.GetTypeInfo()); var exportKey = new CompositionContract(export.ContractType ?? property.PropertyType, export.ContractName); if (metadata.Count == 0) metadata = s_noMetadata; yield return new DiscoveredPropertyExport(exportKey, metadata, property); } } } private void ReadLooseMetadata(object[] appliedAttributes, IDictionary<string, object> metadata) { foreach (var attribute in appliedAttributes) { if (attribute is ExportAttribute) continue; var ema = attribute as ExportMetadataAttribute; if (ema != null) { AddMetadata(metadata, ema.Name, ema.Value); } else { ReadMetadataAttribute((Attribute)attribute, metadata); } } } private void AddMetadata(IDictionary<string, object> metadata, string name, object value) { object existingValue; if (!metadata.TryGetValue(name, out existingValue)) { metadata.Add(name, value); return; } var valueType = existingValue.GetType(); if (valueType.IsArray) { var existingArray = (Array)existingValue; var newArray = Array.CreateInstance(value.GetType(), existingArray.Length + 1); Array.Copy(existingArray, newArray, existingArray.Length); newArray.SetValue(value, existingArray.Length); metadata[name] = newArray; } else { var newArray = Array.CreateInstance(value.GetType(), 2); newArray.SetValue(existingValue, 0); newArray.SetValue(value, 1); metadata[name] = newArray; } } private void ReadMetadataAttribute(Attribute attribute, IDictionary<string, object> metadata) { var attrType = attribute.GetType(); // Note, we don't support ReflectionContext in this scenario as if (attrType.GetTypeInfo().GetCustomAttribute<MetadataAttributeAttribute>(true) == null) return; foreach (var prop in attrType .GetRuntimeProperties() .Where(p => p.DeclaringType == attrType && p.CanRead)) { AddMetadata(metadata, prop.Name, prop.GetValue(attribute, null)); } } private static void CheckPropertyExportCompatibility(TypeInfo partType, PropertyInfo property, TypeInfo contractType) { if (partType.IsGenericTypeDefinition) { CheckGenericContractCompatibility(partType, property.PropertyType.GetTypeInfo(), contractType); } else if (!contractType.IsAssignableFrom(property.PropertyType.GetTypeInfo())) { var message = string.Format(Properties.Resources.TypeInspector_ExportedContractTypeNotAssignable, contractType.Name, property.Name, partType.Name); throw new CompositionFailedException(message); } } private static void CheckGenericContractCompatibility(TypeInfo partType, TypeInfo exportingMemberType, TypeInfo contractType) { if (!contractType.IsGenericTypeDefinition) { var message = string.Format(Properties.Resources.TypeInspector_NoExportNonGenericContract, partType.Name, contractType.Name); throw new CompositionFailedException(message); } var compatible = false; foreach (var ifce in GetAssignableTypes(exportingMemberType)) { if (ifce == contractType || (ifce.IsGenericType && ifce.GetGenericTypeDefinition() == contractType.AsType())) { var mappedType = ifce; if (!(mappedType == partType || mappedType.GenericTypeArguments.SequenceEqual(partType.GenericTypeParameters))) { var message = string.Format(Properties.Resources.TypeInspector_ArgumentMissmatch, contractType.Name, partType.Name); throw new CompositionFailedException(message); } compatible = true; break; } } if (!compatible) { var message = string.Format(Properties.Resources.TypeInspector_ExportNotCompatible, exportingMemberType.Name, partType.Name, contractType.Name); throw new CompositionFailedException(message); } } private static IEnumerable<TypeInfo> GetAssignableTypes(TypeInfo exportingMemberType) { foreach (var ifce in exportingMemberType.ImplementedInterfaces) yield return ifce.GetTypeInfo(); var b = exportingMemberType; while (b != null) { yield return b; b = b.BaseType.GetTypeInfo(); } } private static void CheckInstanceExportCompatibility(TypeInfo partType, TypeInfo contractType) { if (partType.IsGenericTypeDefinition) { CheckGenericContractCompatibility(partType, partType, contractType); } else if (!contractType.IsAssignableFrom(partType)) { var message = string.Format(Properties.Resources.TypeInspector_ContractNotAssignable, contractType.Name, partType.Name); throw new CompositionFailedException(message); } } } }
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 MediaUpload.Areas.HelpPage.ModelDescriptions; using MediaUpload.Areas.HelpPage.Models; namespace MediaUpload.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); } } } }
// 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.Globalization; using System.IO; using System.Security; using System.Security.Principal; using System.Threading; using System.ComponentModel; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // The class does the real work in authentication and // user data encryption with NEGO SSPI package. // // This is part of the NegotiateStream PAL. // internal static partial class NegotiateStreamPal { internal static IIdentity GetIdentity(NTAuthentication context) { IIdentity result = null; string name = context.IsServer ? context.AssociatedName : context.Spn; string protocol = context.ProtocolName; if (context.IsServer) { SecurityContextTokenHandle token = null; try { SecurityStatusPal status; SafeDeleteContext securityContext = context.GetContext(out status); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { throw new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status)); } // This will return a client token when conducted authentication on server side. // This token can be used for impersonation. We use it to create a WindowsIdentity and hand it out to the server app. Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.QuerySecurityContextToken( GlobalSSPI.SSPIAuth, securityContext, out token); if (winStatus != Interop.SECURITY_STATUS.OK) { throw new Win32Exception((int)winStatus); } string authtype = context.ProtocolName; // TODO #5241: // The following call was also specifying WindowsAccountType.Normal, true. // WindowsIdentity.IsAuthenticated is no longer supported in CoreFX. result = new WindowsIdentity(token.DangerousGetHandle(), authtype); return result; } catch (SecurityException) { // Ignore and construct generic Identity if failed due to security problem. } finally { if (token != null) { token.Dispose(); } } } // On the client we don't have access to the remote side identity. result = new GenericIdentity(name, protocol); return result; } internal static string QueryContextAssociatedName(SafeDeleteContext securityContext) { return SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES) as string; } internal static void ValidateImpersonationLevel(TokenImpersonationLevel impersonationLevel) { if (impersonationLevel != TokenImpersonationLevel.Identification && impersonationLevel != TokenImpersonationLevel.Impersonation && impersonationLevel != TokenImpersonationLevel.Delegation) { throw new ArgumentOutOfRangeException(nameof(impersonationLevel), impersonationLevel.ToString(), SR.net_auth_supported_impl_levels); } } internal static int Encrypt( SafeDeleteContext securityContext, byte[] buffer, int offset, int count, bool isConfidential, bool isNtlm, ref byte[] output, uint sequenceNumber) { SecPkgContext_Sizes sizes = SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES ) as SecPkgContext_Sizes; try { int maxCount = checked(int.MaxValue - 4 - sizes.cbBlockSize - sizes.cbSecurityTrailer); if (count > maxCount || count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.net_io_out_range, maxCount)); } } catch (Exception e) when (!ExceptionCheck.IsFatal(e)) { NetEventSource.Fail(null, "Arguments out of range."); throw; } int resultSize = count + sizes.cbSecurityTrailer + sizes.cbBlockSize; if (output == null || output.Length < resultSize + 4) { output = new byte[resultSize + 4]; } // Make a copy of user data for in-place encryption. Buffer.BlockCopy(buffer, offset, output, 4 + sizes.cbSecurityTrailer, count); // Prepare buffers TOKEN(signature), DATA and Padding. var securityBuffer = new SecurityBuffer[3]; securityBuffer[0] = new SecurityBuffer(output, 4, sizes.cbSecurityTrailer, SecurityBufferType.SECBUFFER_TOKEN); securityBuffer[1] = new SecurityBuffer(output, 4 + sizes.cbSecurityTrailer, count, SecurityBufferType.SECBUFFER_DATA); securityBuffer[2] = new SecurityBuffer(output, 4 + sizes.cbSecurityTrailer + count, sizes.cbBlockSize, SecurityBufferType.SECBUFFER_PADDING); int errorCode; if (isConfidential) { errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } else { if (isNtlm) { securityBuffer[1].type |= SecurityBufferType.SECBUFFER_READONLY; } errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0); } if (errorCode != 0) { Exception e = new Win32Exception(errorCode); if (NetEventSource.IsEnabled) NetEventSource.Error(null, e); throw e; } // Compacting the result. resultSize = securityBuffer[0].size; bool forceCopy = false; if (resultSize != sizes.cbSecurityTrailer) { forceCopy = true; Buffer.BlockCopy(output, securityBuffer[1].offset, output, 4 + resultSize, securityBuffer[1].size); } resultSize += securityBuffer[1].size; if (securityBuffer[2].size != 0 && (forceCopy || resultSize != (count + sizes.cbSecurityTrailer))) { Buffer.BlockCopy(output, securityBuffer[2].offset, output, 4 + resultSize, securityBuffer[2].size); } resultSize += securityBuffer[2].size; unchecked { output[0] = (byte)((resultSize) & 0xFF); output[1] = (byte)(((resultSize) >> 8) & 0xFF); output[2] = (byte)(((resultSize) >> 16) & 0xFF); output[3] = (byte)(((resultSize) >> 24) & 0xFF); } return resultSize + 4; } internal static int Decrypt( SafeDeleteContext securityContext, byte[] buffer, int offset, int count, bool isConfidential, bool isNtlm, out int newOffset, uint sequenceNumber) { if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { NetEventSource.Fail(null, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset)) { NetEventSource.Fail(null, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } if (isNtlm) { return DecryptNtlm(securityContext, buffer, offset, count, isConfidential, out newOffset, sequenceNumber); } // // Kerberos and up // var securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.SECBUFFER_STREAM); securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.SECBUFFER_DATA); int errorCode; if (isConfidential) { errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } else { errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } if (errorCode != 0) { Exception e = new Win32Exception(errorCode); if (NetEventSource.IsEnabled) NetEventSource.Error(null, e); throw e; } if (securityBuffer[1].type != SecurityBufferType.SECBUFFER_DATA) { throw new InternalException(securityBuffer[1].type); } newOffset = securityBuffer[1].offset; return securityBuffer[1].size; } private static int DecryptNtlm( SafeDeleteContext securityContext, byte[] buffer, int offset, int count, bool isConfidential, out int newOffset, uint sequenceNumber) { const int ntlmSignatureLength = 16; // For the most part the arguments are verified in Decrypt(). if (count < ntlmSignatureLength) { NetEventSource.Fail(null, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } var securityBuffer = new SecurityBuffer[2]; securityBuffer[0] = new SecurityBuffer(buffer, offset, ntlmSignatureLength, SecurityBufferType.SECBUFFER_TOKEN); securityBuffer[1] = new SecurityBuffer(buffer, offset + ntlmSignatureLength, count - ntlmSignatureLength, SecurityBufferType.SECBUFFER_DATA); int errorCode; SecurityBufferType realDataType = SecurityBufferType.SECBUFFER_DATA; if (isConfidential) { errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } else { realDataType |= SecurityBufferType.SECBUFFER_READONLY; securityBuffer[1].type = realDataType; errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber); } if (errorCode != 0) { Exception e = new Win32Exception(errorCode); if (NetEventSource.IsEnabled) NetEventSource.Error(null, e); throw new Win32Exception(errorCode); } if (securityBuffer[1].type != realDataType) { throw new InternalException(securityBuffer[1].type); } newOffset = securityBuffer[1].offset; return securityBuffer[1].size; } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Channels { using System; using System.Diagnostics; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; abstract class RequestContextBase : RequestContext { TimeSpan defaultSendTimeout; TimeSpan defaultCloseTimeout; CommunicationState state = CommunicationState.Opened; Message requestMessage; Exception requestMessageException; bool replySent; bool replyInitiated; bool aborted; object thisLock = new object(); protected RequestContextBase(Message requestMessage, TimeSpan defaultCloseTimeout, TimeSpan defaultSendTimeout) { this.defaultSendTimeout = defaultSendTimeout; this.defaultCloseTimeout = defaultCloseTimeout; this.requestMessage = requestMessage; } public void ReInitialize(Message requestMessage) { this.state = CommunicationState.Opened; this.requestMessageException = null; this.replySent = false; this.replyInitiated = false; this.aborted = false; this.requestMessage = requestMessage; } public override Message RequestMessage { get { if (this.requestMessageException != null) { #pragma warning suppress 56503 // [....], see outcome of DCR 50092 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(this.requestMessageException); } return requestMessage; } } protected void SetRequestMessage(Message requestMessage) { Fx.Assert(this.requestMessageException == null, "Cannot have both a requestMessage and a requestException."); this.requestMessage = requestMessage; } protected void SetRequestMessage(Exception requestMessageException) { Fx.Assert(this.requestMessage == null, "Cannot have both a requestMessage and a requestException."); this.requestMessageException = requestMessageException; } protected bool ReplyInitiated { get { return this.replyInitiated; } } protected object ThisLock { get { return thisLock; } } public bool Aborted { get { return this.aborted; } } public TimeSpan DefaultCloseTimeout { get { return this.defaultCloseTimeout; } } public TimeSpan DefaultSendTimeout { get { return this.defaultSendTimeout; } } public override void Abort() { lock (ThisLock) { if (state == CommunicationState.Closed) return; state = CommunicationState.Closing; this.aborted = true; } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.RequestContextAbort, SR.GetString(SR.TraceCodeRequestContextAbort), this); } try { this.OnAbort(); } finally { state = CommunicationState.Closed; } } public override void Close() { this.Close(this.defaultCloseTimeout); } public override void Close(TimeSpan timeout) { if (timeout < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("timeout", timeout, SR.GetString(SR.ValueMustBeNonNegative))); } bool sendAck = false; lock (ThisLock) { if (state != CommunicationState.Opened) return; if (TryInitiateReply()) { sendAck = true; } state = CommunicationState.Closing; } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); bool throwing = true; try { if (sendAck) { OnReply(null, timeoutHelper.RemainingTime()); } OnClose(timeoutHelper.RemainingTime()); state = CommunicationState.Closed; throwing = false; } finally { if (throwing) this.Abort(); } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (!disposing) return; if (this.replySent) { this.Close(); } else { this.Abort(); } } protected abstract void OnAbort(); protected abstract void OnClose(TimeSpan timeout); protected abstract void OnReply(Message message, TimeSpan timeout); protected abstract IAsyncResult OnBeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state); protected abstract void OnEndReply(IAsyncResult result); protected void ThrowIfInvalidReply() { if (state == CommunicationState.Closed || state == CommunicationState.Closing) { if (aborted) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationObjectAbortedException(SR.GetString(SR.RequestContextAborted))); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName)); } if (this.replyInitiated) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ReplyAlreadySent))); } /// <summary> /// Attempts to initiate the reply. If a reply is not initiated already (and the object is opened), /// then it initiates the reply and returns true. Otherwise, it returns false. /// </summary> protected bool TryInitiateReply() { lock (this.thisLock) { if ((this.state != CommunicationState.Opened) || this.replyInitiated) { return false; } else { this.replyInitiated = true; return true; } } } public override IAsyncResult BeginReply(Message message, AsyncCallback callback, object state) { return this.BeginReply(message, this.defaultSendTimeout, callback, state); } public override IAsyncResult BeginReply(Message message, TimeSpan timeout, AsyncCallback callback, object state) { // "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here lock (this.thisLock) { this.ThrowIfInvalidReply(); this.replyInitiated = true; } return OnBeginReply(message, timeout, callback, state); } public override void EndReply(IAsyncResult result) { OnEndReply(result); this.replySent = true; } public override void Reply(Message message) { this.Reply(message, this.defaultSendTimeout); } public override void Reply(Message message, TimeSpan timeout) { // "null" is a valid reply (signals a 202-style "ack"), so we don't have a null-check here lock (this.thisLock) { this.ThrowIfInvalidReply(); this.replyInitiated = true; } this.OnReply(message, timeout); this.replySent = true; } // This method is designed for WebSocket only, and will only be used once the WebSocket response was sent. // For WebSocket, we never call HttpRequestContext.Reply to send the response back. // Instead we call AcceptWebSocket directly. So we need to set the replyInitiated and // replySent boolean to be true once the response was sent successfully. Otherwise when we // are disposing the HttpRequestContext, we will see a bunch of warnings in trace log. protected void SetReplySent() { lock (this.thisLock) { this.ThrowIfInvalidReply(); this.replyInitiated = true; } this.replySent = true; } } class RequestContextMessageProperty : IDisposable { RequestContext context; object thisLock = new object(); public RequestContextMessageProperty(RequestContext context) { this.context = context; } public static string Name { get { return "requestContext"; } } void IDisposable.Dispose() { bool success = false; RequestContext thisContext; lock (this.thisLock) { if (this.context == null) return; thisContext = this.context; this.context = null; } try { thisContext.Close(); success = true; } catch (CommunicationException e) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } catch (TimeoutException e) { if (TD.CloseTimeoutIsEnabled()) { TD.CloseTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } finally { if (!success) { thisContext.Abort(); } } } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 511513 $ * $Date: 2007-02-25 06:46:57 -0700 (Sun, 25 Feb 2007) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using IBatisNet.Common.Exceptions; namespace IBatisNet.Common.Utilities.Objects { /// <summary> /// This class represents a cached set of class definition information that /// allows for easy mapping between property names and get/set methods. /// </summary> public sealed class ReflectionInfo { /// <summary> /// /// </summary> public static BindingFlags BINDING_FLAGS_PROPERTY = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ; /// <summary> /// /// </summary> public static BindingFlags BINDING_FLAGS_FIELD = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance ; private static readonly string[] _emptyStringArray = new string[0]; private static ArrayList _simleTypeMap = new ArrayList(); private static Hashtable _reflectionInfoMap = Hashtable.Synchronized(new Hashtable()); private string _className = string.Empty; private string[] _readableMemberNames = _emptyStringArray; private string[] _writeableMemberNames = _emptyStringArray; // (memberName, MemberInfo) private Hashtable _setMembers = new Hashtable(); // (memberName, MemberInfo) private Hashtable _getMembers = new Hashtable(); // (memberName, member type) private Hashtable _setTypes = new Hashtable(); // (memberName, member type) private Hashtable _getTypes = new Hashtable(); /// <summary> /// /// </summary> public string ClassName { get { return _className; } } /// <summary> /// /// </summary> static ReflectionInfo() { _simleTypeMap.Add(typeof(string)); _simleTypeMap.Add(typeof(byte)); _simleTypeMap.Add(typeof(char)); _simleTypeMap.Add(typeof(bool)); _simleTypeMap.Add(typeof(Guid)); _simleTypeMap.Add(typeof(Int16)); _simleTypeMap.Add(typeof(Int32)); _simleTypeMap.Add(typeof(Int64)); _simleTypeMap.Add(typeof(Single)); _simleTypeMap.Add(typeof(Double)); _simleTypeMap.Add(typeof(Decimal)); _simleTypeMap.Add(typeof(DateTime)); _simleTypeMap.Add(typeof(TimeSpan)); _simleTypeMap.Add(typeof(Hashtable)); _simleTypeMap.Add(typeof(SortedList)); _simleTypeMap.Add(typeof(ListDictionary)); _simleTypeMap.Add(typeof(HybridDictionary)); // _simleTypeMap.Add(Class.class); // _simleTypeMap.Add(Collection.class); // _simleTypeMap.Add(HashMap.class); // _simleTypeMap.Add(TreeMap.class); _simleTypeMap.Add(typeof(ArrayList)); // _simleTypeMap.Add(HashSet.class); // _simleTypeMap.Add(TreeSet.class); // _simleTypeMap.Add(Vector.class); _simleTypeMap.Add(typeof(IEnumerator)); } /// <summary> /// /// </summary> /// <param name="type"></param> private ReflectionInfo(Type type) { _className = type.Name; AddMembers(type); string[] getArray = new string[_getMembers.Count]; _getMembers.Keys.CopyTo(getArray,0); _readableMemberNames = getArray; string[] setArray = new string[_setMembers.Count]; _setMembers.Keys.CopyTo(setArray,0); _writeableMemberNames = setArray; } /// <summary> /// /// </summary> /// <param name="type"></param> private void AddMembers(Type type) { #region Properties PropertyInfo[] properties = type.GetProperties(BINDING_FLAGS_PROPERTY); for (int i = 0; i < properties.Length; i++) { if (properties[i].CanWrite) { string name = properties[i].Name; _setMembers[name] = properties[i]; _setTypes[name] = properties[i].PropertyType; } if (properties[i].CanRead) { string name = properties[i].Name; _getMembers[name] = properties[i]; _getTypes[name] = properties[i].PropertyType; } } #endregion #region Fields FieldInfo[] fields = type.GetFields(BINDING_FLAGS_FIELD) ; for (int i = 0; i < fields.Length; i++) { string name = fields[i].Name; _setMembers[name] = fields[i]; _setTypes[name] = fields[i].FieldType; _getMembers[name] = fields[i]; _getTypes[name] = fields[i].FieldType; } #endregion // Fix for problem with interfaces inheriting other interfaces if (type.IsInterface) { // Loop through interfaces for the type and add members from // these types too foreach (Type interf in type.GetInterfaces()) { AddMembers(interf); } } } /// <summary> /// /// </summary> /// <param name="memberName"></param> /// <returns></returns> public MemberInfo GetSetter(string memberName) { MemberInfo memberInfo = (MemberInfo) _setMembers[memberName]; if (memberInfo == null) { throw new ProbeException("There is no Set member named '" + memberName + "' in class '" + _className + "'"); } return memberInfo; } /// <summary> /// Gets the <see cref="MemberInfo"/>. /// </summary> /// <param name="memberName">Member's name.</param> /// <returns>The <see cref="MemberInfo"/></returns> public MemberInfo GetGetter(string memberName) { MemberInfo memberInfo = _getMembers[memberName] as MemberInfo; if (memberInfo == null) { throw new ProbeException("There is no Get member named '" + memberName + "' in class '" + _className + "'"); } return memberInfo; } /// <summary> /// Gets the type of the member. /// </summary> /// <param name="memberName">Member's name.</param> /// <returns></returns> public Type GetSetterType(string memberName) { Type type = (Type) _setTypes[memberName]; if (type == null) { throw new ProbeException("There is no Set member named '" + memberName + "' in class '" + _className + "'"); } return type; } /// <summary> /// /// </summary> /// <param name="memberName"></param> /// <returns></returns> public Type GetGetterType(string memberName) { Type type = (Type) _getTypes[memberName]; if (type == null) { throw new ProbeException("There is no Get member named '" + memberName + "' in class '" + _className + "'"); } return type; } /// <summary> /// /// </summary> /// <returns></returns> public string[] GetReadableMemberNames() { return _readableMemberNames; } /// <summary> /// /// </summary> /// <returns></returns> public string[] GetWriteableMemberNames() { return _writeableMemberNames; } /// <summary> /// /// </summary> /// <param name="memberName"></param> /// <returns></returns> public bool HasWritableMember(string memberName) { return _setMembers.ContainsKey(memberName); } /// <summary> /// /// </summary> /// <param name="memberName"></param> /// <returns></returns> public bool HasReadableMember(string memberName) { return _getMembers.ContainsKey(memberName); } /// <summary> /// /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsKnownType(Type type) { if (_simleTypeMap.Contains(type)) { return true; } else if (typeof(IList).IsAssignableFrom(type)) { return true; } else if (typeof(IDictionary).IsAssignableFrom(type)) { return true; } else if (typeof(IEnumerator).IsAssignableFrom(type)) { return true; } else { return false; } } /// <summary> /// Gets an instance of ReflectionInfo for the specified type. /// </summary>summary> /// <param name="type">The type for which to lookup the method cache.</param> /// <returns>The properties cache for the type</returns> public static ReflectionInfo GetInstance(Type type) { lock (type) { ReflectionInfo cache = (ReflectionInfo) _reflectionInfoMap[type]; if (cache == null) { cache = new ReflectionInfo(type); _reflectionInfoMap.Add(type, cache); } return cache; } } } }
/* This file is licensed to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Xml; using System.Xml.Linq; using Org.XmlUnit.Input; namespace Org.XmlUnit.Builder { /// <summary> /// Fluent API to create ISource instances. /// </summary> public sealed class Input { /// <summary> /// Builder for <see cref="ISource"/>. /// </summary> public interface IBuilder { /// <summary> /// build the actual ISource instance. /// </summary> ISource Build(); } internal class SourceHoldingBuilder : IBuilder { protected readonly ISource source; internal SourceHoldingBuilder(ISource source) { this.source = source; } public ISource Build() { return source; } } /// <summary> /// Build an ISource from a DOM Document. /// </summary> public static IBuilder FromDocument(XmlDocument d) { return new SourceHoldingBuilder(new DOMSource(d)); } /// <summary> /// Build an ISource from a DOM Node. /// </summary> public static IBuilder FromNode(XmlNode n) { return new SourceHoldingBuilder(new DOMSource(n)); } internal class StreamBuilder : SourceHoldingBuilder { internal StreamBuilder(string s) : base(new StreamSource(s)) { } internal StreamBuilder(Stream s) : base(new StreamSource(s)) { } internal StreamBuilder(TextReader r) : base(new StreamSource(r)) { } internal string SystemId { set { source.SystemId = value ?? string.Empty; } } } /// <summary> /// Build an ISource from a named file. /// </summary> public static IBuilder FromFile(string name) { return new StreamBuilder(name); } /// <summary> /// Build an ISource from a stream. /// </summary> public static IBuilder FromStream(Stream s) { StreamBuilder b = new StreamBuilder(s); if (s is FileStream) { b.SystemId = new Uri(Path.GetFullPath((s as FileStream).Name)) .ToString(); } return b; } /// <summary> /// Build an ISource from a reader. /// </summary> public static IBuilder FromReader(TextReader r) { StreamBuilder b = new StreamBuilder(r); StreamReader s = r as StreamReader; if (s != null && s.BaseStream is FileStream) { b.SystemId = new Uri(Path.GetFullPath((s.BaseStream as FileStream).Name)) .ToString(); } return b; } /// <summary> /// Build an ISource from a string. /// </summary> public static IBuilder FromString(string s) { return new SourceHoldingBuilder(new StringSource(s)); } /// <summary> /// Build an ISource from an array of bytes. /// </summary> public static IBuilder FromByteArray(byte[] b) { return new SourceHoldingBuilder(new ByteArraySource(b)); } /// <summary> /// Build an ISource from an URI. /// <param name="uri">must represent a valid URL</param> /// </summary> public static IBuilder FromURI(string uri) { return new StreamBuilder(uri); } /// <summary> /// Build an ISource from an URI. /// <param name="uri">must represent a valid URL</param> /// </summary> public static IBuilder FromURI(System.Uri uri) { return new StreamBuilder(uri.AbsoluteUri); } /// <summary> /// Builds <see cref="ISource"/> by applying an XSLT transformation on a different <see cref="ISource"/>. /// </summary> public interface ITransformationBuilder : ITransformationBuilderBase<ITransformationBuilder>, IBuilder { /// <summary> /// Sets the stylesheet to use. /// </summary> ITransformationBuilder WithStylesheet(IBuilder b); } internal class Transformation : AbstractTransformationBuilder<ITransformationBuilder>, ITransformationBuilder { internal Transformation(ISource s) : base(s) { } public ITransformationBuilder WithStylesheet(IBuilder b) { return WithStylesheet(b.Build()); } public ISource Build() { return new DOMSource(Helper.TransformToDocument()); } } /// <summary> /// Build an ISource by XSLT transforming a different ISource. /// </summary> public static ITransformationBuilder ByTransforming(ISource s) { return new Transformation(s); } /// <summary> /// Build an ISource by XSLT transforming a different ISource. /// </summary> public static ITransformationBuilder ByTransforming(IBuilder b) { return ByTransforming(b.Build()); } /// <summary> /// Build an ISource from a System.Xml.Linq Document. /// </summary> public static IBuilder FromDocument(XDocument d) { return new SourceHoldingBuilder(new LinqSource(d)); } /// <summary> /// Build an ISource from a System.Xml.Linq Node. /// </summary> public static IBuilder FromNode(XNode n) { return new SourceHoldingBuilder(new LinqSource(n)); } /// <summary> /// Return the matching Builder for the supported types: /// ISource, IBuilder, XmlDocument, XmlNode, byte[] (XML as /// byte[]), string (XML as String) Uri (to an XML-Document), /// Stream, TextReader, XDocument, XNode /// </summary> public static IBuilder From(object source) { IBuilder xml; if (source is ISource) { xml = new SourceHoldingBuilder((ISource) source); } else if (source is IBuilder) { xml = (IBuilder) source; } else if (source is XmlDocument) { xml = Input.FromDocument((XmlDocument) source); } else if (source is XmlNode) { xml = Input.FromNode((XmlNode) source); } else if (source is byte[]) { xml = Input.FromByteArray((byte[]) source); } else if (source is string) { xml = Input.FromString((string) source); } else if (source is Uri) { xml = Input.FromURI((Uri) source); } else if (source is Stream) { xml = Input.FromStream((Stream) source); } else if (source is TextReader) { xml = Input.FromReader((TextReader) source); } else if (source is XDocument) { xml = Input.FromDocument((XDocument) source); } else if (source is XNode) { xml = Input.FromNode((XNode) source); } else { throw new ArgumentException("unsupported type", "source"); } return xml; } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using Mono.Collections.Generic; using SR = System.Reflection; using Mono.Cecil.Metadata; namespace Mono.Cecil { public interface IMetadataImporterProvider { IMetadataImporter GetMetadataImporter (ModuleDefinition module); } public interface IMetadataImporter { AssemblyNameReference ImportReference (AssemblyNameReference reference); TypeReference ImportReference (TypeReference type, IGenericParameterProvider context); FieldReference ImportReference (FieldReference field, IGenericParameterProvider context); MethodReference ImportReference (MethodReference method, IGenericParameterProvider context); } public interface IReflectionImporterProvider { IReflectionImporter GetReflectionImporter (ModuleDefinition module); } public interface IReflectionImporter { AssemblyNameReference ImportReference (SR.AssemblyName reference); TypeReference ImportReference (Type type, IGenericParameterProvider context); FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context); MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context); } struct ImportGenericContext { Collection<IGenericParameterProvider> stack; public bool IsEmpty { get { return stack == null; } } public ImportGenericContext (IGenericParameterProvider provider) { if (provider == null) throw new ArgumentNullException ("provider"); stack = null; Push (provider); } public void Push (IGenericParameterProvider provider) { if (stack == null) stack = new Collection<IGenericParameterProvider> (1) { provider }; else stack.Add (provider); } public void Pop () { stack.RemoveAt (stack.Count - 1); } public TypeReference MethodParameter (string method, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = stack [i] as MethodReference; if (candidate == null) continue; if (method != NormalizeMethodName (candidate)) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } public string NormalizeMethodName (MethodReference method) { return method.DeclaringType.GetElementType ().FullName + "." + method.Name; } public TypeReference TypeParameter (string type, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = GenericTypeFor (stack [i]); if (candidate.FullName != type) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } static TypeReference GenericTypeFor (IGenericParameterProvider context) { var type = context as TypeReference; if (type != null) return type.GetElementType (); var method = context as MethodReference; if (method != null) return method.DeclaringType.GetElementType (); throw new InvalidOperationException (); } public static ImportGenericContext For (IGenericParameterProvider context) { return context != null ? new ImportGenericContext (context) : default (ImportGenericContext); } } public class DefaultReflectionImporter : IReflectionImporter { readonly protected ModuleDefinition module; public DefaultReflectionImporter (ModuleDefinition module) { Mixin.CheckModule (module); this.module = module; } enum ImportGenericKind { Definition, Open, } static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) { { typeof (void), ElementType.Void }, { typeof (bool), ElementType.Boolean }, { typeof (char), ElementType.Char }, { typeof (sbyte), ElementType.I1 }, { typeof (byte), ElementType.U1 }, { typeof (short), ElementType.I2 }, { typeof (ushort), ElementType.U2 }, { typeof (int), ElementType.I4 }, { typeof (uint), ElementType.U4 }, { typeof (long), ElementType.I8 }, { typeof (ulong), ElementType.U8 }, { typeof (float), ElementType.R4 }, { typeof (double), ElementType.R8 }, { typeof (string), ElementType.String }, { typeof (TypedReference), ElementType.TypedByRef }, { typeof (IntPtr), ElementType.I }, { typeof (UIntPtr), ElementType.U }, { typeof (object), ElementType.Object }, }; TypeReference ImportType (Type type, ImportGenericContext context) { return ImportType (type, context, ImportGenericKind.Open); } TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind) { if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind)) return ImportTypeSpecification (type, context); var reference = new TypeReference ( string.Empty, type.Name, module, ImportScope (type), type.IsValueType); reference.etype = ImportElementType (type); if (IsNestedType (type)) reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind); else reference.Namespace = type.Namespace ?? string.Empty; if (type.IsGenericType) ImportGenericParameters (reference, type.GetGenericArguments ()); return reference; } protected virtual IMetadataScope ImportScope (Type type) { return ImportScope (type.Assembly); } static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind) { return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open; } static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind) { return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open; } static bool IsNestedType (Type type) { return type.IsNested; } TypeReference ImportTypeSpecification (Type type, ImportGenericContext context) { if (type.IsByRef) return new ByReferenceType (ImportType (type.GetElementType (), context)); if (type.IsPointer) return new PointerType (ImportType (type.GetElementType (), context)); if (type.IsArray) return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ()); if (type.IsGenericType) return ImportGenericInstance (type, context); if (type.IsGenericParameter) return ImportGenericParameter (type, context); throw new NotSupportedException (type.FullName); } static TypeReference ImportGenericParameter (Type type, ImportGenericContext context) { if (context.IsEmpty) throw new InvalidOperationException (); if (type.DeclaringMethod != null) return context.MethodParameter (NormalizeMethodName (type.DeclaringMethod), type.GenericParameterPosition); if (type.DeclaringType != null) return context.TypeParameter (NormalizeTypeFullName (type.DeclaringType), type.GenericParameterPosition); throw new InvalidOperationException(); } static string NormalizeMethodName (SR.MethodBase method) { return NormalizeTypeFullName (method.DeclaringType) + "." + method.Name; } static string NormalizeTypeFullName (Type type) { if (IsNestedType (type)) return NormalizeTypeFullName (type.DeclaringType) + "/" + type.Name; return type.FullName; } TypeReference ImportGenericInstance (Type type, ImportGenericContext context) { var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition); var arguments = type.GetGenericArguments (); var instance = new GenericInstanceType (element_type, arguments.Length); var instance_arguments = instance.GenericArguments; context.Push (element_type); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool IsTypeSpecification (Type type) { return type.HasElementType || IsGenericInstance (type) || type.IsGenericParameter; } static bool IsGenericInstance (Type type) { return type.IsGenericType && !type.IsGenericTypeDefinition; } static ElementType ImportElementType (Type type) { ElementType etype; if (!type_etype_mapping.TryGetValue (type, out etype)) return ElementType.None; return etype; } protected AssemblyNameReference ImportScope (SR.Assembly assembly) { return ImportReference (assembly.GetName ()); } public virtual AssemblyNameReference ImportReference (SR.AssemblyName name) { Mixin.CheckName (name); AssemblyNameReference reference; if (TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { PublicKeyToken = name.GetPublicKeyToken (), Culture = name.CultureInfo.Name, HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm, }; module.AssemblyReferences.Add (reference); return reference; } bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); if (IsGenericInstance (field.DeclaringType)) field = ResolveFieldDefinition (field); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field) { return field.Module.ResolveField (field.MetadataToken); } static SR.MethodBase ResolveMethodDefinition (SR.MethodBase method) { return method.Module.ResolveMethod (method.MetadataToken); } MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind)) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); if (IsGenericInstance (method.DeclaringType)) method = ResolveMethodDefinition (method); var reference = new MethodReference { Name = method.Name, HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention (method, SR.CallingConventions.VarArgs)) reference.CallingConvention &= MethodCallingConvention.VarArg; if (method.IsGenericMethod) ImportGenericParameters (reference, method.GetGenericArguments ()); context.Push (reference); try { var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType (method_info.ReturnType, context) : ImportType (typeof (void), default (ImportGenericContext)); var parameters = method.GetParameters (); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); reference.DeclaringType = declaring_type; return reference; } finally { context.Pop (); } } static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments) { var provider_parameters = provider.GenericParameters; for (int i = 0; i < arguments.Length; i++) provider_parameters.Add (new GenericParameter (arguments [i].Name, provider)); } static bool IsMethodSpecification (SR.MethodBase method) { return method.IsGenericMethod && !method.IsGenericMethodDefinition; } MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) throw new InvalidOperationException (); var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod (element_method); var arguments = method.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_method); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions) { return (method.CallingConvention & conventions) != 0; } public virtual TypeReference ImportReference (Type type, IGenericParameterProvider context) { Mixin.CheckType (type); return ImportType ( type, ImportGenericContext.For (context), context != null ? ImportGenericKind.Open : ImportGenericKind.Definition); } public virtual FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context) { Mixin.CheckField (field); return ImportField (field, ImportGenericContext.For (context)); } public virtual MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context) { Mixin.CheckMethod (method); return ImportMethod (method, ImportGenericContext.For (context), context != null ? ImportGenericKind.Open : ImportGenericKind.Definition); } } public class DefaultMetadataImporter : IMetadataImporter { readonly protected ModuleDefinition module; public DefaultMetadataImporter (ModuleDefinition module) { Mixin.CheckModule (module); this.module = module; } TypeReference ImportType (TypeReference type, ImportGenericContext context) { if (type.IsTypeSpecification ()) return ImportTypeSpecification (type, context); var reference = new TypeReference ( type.Namespace, type.Name, module, ImportScope (type), type.IsValueType); MetadataSystem.TryProcessPrimitiveTypeReference (reference); if (type.IsNested) reference.DeclaringType = ImportType (type.DeclaringType, context); if (type.HasGenericParameters) ImportGenericParameters (reference, type); return reference; } protected virtual IMetadataScope ImportScope (TypeReference type) { return ImportScope (type.Scope); } protected IMetadataScope ImportScope (IMetadataScope scope) { switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ImportReference ((AssemblyNameReference) scope); case MetadataScopeType.ModuleDefinition: if (scope == module) return scope; return ImportReference (((ModuleDefinition) scope).Assembly.Name); case MetadataScopeType.ModuleReference: throw new NotImplementedException (); } throw new NotSupportedException (); } public virtual AssemblyNameReference ImportReference (AssemblyNameReference name) { Mixin.CheckName (name); AssemblyNameReference reference; if (module.TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { Culture = name.Culture, HashAlgorithm = name.HashAlgorithm, IsRetargetable = name.IsRetargetable, IsWindowsRuntime = name.IsWindowsRuntime, }; var pk_token = !name.PublicKeyToken.IsNullOrEmpty () ? new byte [name.PublicKeyToken.Length] : Empty<byte>.Array; if (pk_token.Length > 0) Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length); reference.PublicKeyToken = pk_token; module.AssemblyReferences.Add (reference); return reference; } static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original) { var parameters = original.GenericParameters; var imported_parameters = imported.GenericParameters; for (int i = 0; i < parameters.Count; i++) imported_parameters.Add (new GenericParameter (parameters [i].Name, imported)); } TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context) { switch (type.etype) { case ElementType.SzArray: var vector = (ArrayType) type; return new ArrayType (ImportType (vector.ElementType, context)); case ElementType.Ptr: var pointer = (PointerType) type; return new PointerType (ImportType (pointer.ElementType, context)); case ElementType.ByRef: var byref = (ByReferenceType) type; return new ByReferenceType (ImportType (byref.ElementType, context)); case ElementType.Pinned: var pinned = (PinnedType) type; return new PinnedType (ImportType (pinned.ElementType, context)); case ElementType.Sentinel: var sentinel = (SentinelType) type; return new SentinelType (ImportType (sentinel.ElementType, context)); case ElementType.FnPtr: var fnptr = (FunctionPointerType) type; var imported_fnptr = new FunctionPointerType () { HasThis = fnptr.HasThis, ExplicitThis = fnptr.ExplicitThis, CallingConvention = fnptr.CallingConvention, ReturnType = ImportType (fnptr.ReturnType, context), }; if (!fnptr.HasParameters) return imported_fnptr; for (int i = 0; i < fnptr.Parameters.Count; i++) imported_fnptr.Parameters.Add (new ParameterDefinition ( ImportType (fnptr.Parameters [i].ParameterType, context))); return imported_fnptr; case ElementType.CModOpt: var modopt = (OptionalModifierType) type; return new OptionalModifierType ( ImportType (modopt.ModifierType, context), ImportType (modopt.ElementType, context)); case ElementType.CModReqD: var modreq = (RequiredModifierType) type; return new RequiredModifierType ( ImportType (modreq.ModifierType, context), ImportType (modreq.ElementType, context)); case ElementType.Array: var array = (ArrayType) type; var imported_array = new ArrayType (ImportType (array.ElementType, context)); if (array.IsVector) return imported_array; var dimensions = array.Dimensions; var imported_dimensions = imported_array.Dimensions; imported_dimensions.Clear (); for (int i = 0; i < dimensions.Count; i++) { var dimension = dimensions [i]; imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound)); } return imported_array; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var element_type = ImportType (instance.ElementType, context); var arguments = instance.GenericArguments; var imported_instance = new GenericInstanceType (element_type, arguments.Count); var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; case ElementType.Var: var var_parameter = (GenericParameter) type; if (var_parameter.DeclaringType == null) throw new InvalidOperationException (); return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position); case ElementType.MVar: var mvar_parameter = (GenericParameter) type; if (mvar_parameter.DeclaringMethod == null) throw new InvalidOperationException (); return context.MethodParameter (context.NormalizeMethodName (mvar_parameter.DeclaringMethod), mvar_parameter.Position); } throw new NotSupportedException (type.etype.ToString ()); } FieldReference ImportField (FieldReference field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } MethodReference ImportMethod (MethodReference method, ImportGenericContext context) { if (method.IsGenericInstance) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); var reference = new MethodReference { Name = method.Name, HasThis = method.HasThis, ExplicitThis = method.ExplicitThis, DeclaringType = declaring_type, CallingConvention = method.CallingConvention, }; if (method.HasGenericParameters) ImportGenericParameters (reference, method); context.Push (reference); try { reference.ReturnType = ImportType (method.ReturnType, context); if (!method.HasParameters) return reference; var parameters = method.Parameters; var reference_parameters = reference.parameters = new ParameterDefinitionCollection (reference, parameters.Count); for (int i = 0; i < parameters.Count; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); return reference; } finally { context.Pop(); } } MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context) { if (!method.IsGenericInstance) throw new NotSupportedException (); var instance = (GenericInstanceMethod) method; var element_method = ImportMethod (instance.ElementMethod, context); var imported_instance = new GenericInstanceMethod (element_method); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; } public virtual TypeReference ImportReference (TypeReference type, IGenericParameterProvider context) { Mixin.CheckType (type); return ImportType (type, ImportGenericContext.For (context)); } public virtual FieldReference ImportReference (FieldReference field, IGenericParameterProvider context) { Mixin.CheckField (field); return ImportField (field, ImportGenericContext.For (context)); } public virtual MethodReference ImportReference (MethodReference method, IGenericParameterProvider context) { Mixin.CheckMethod (method); return ImportMethod (method, ImportGenericContext.For (context)); } } static partial class Mixin { public static void CheckModule (ModuleDefinition module) { if (module == null) throw new ArgumentNullException (Argument.module.ToString ()); } public static bool TryGetAssemblyNameReference (this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (!Equals (name_reference, reference)) continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } static bool Equals (byte [] a, byte [] b) { if (ReferenceEquals (a, b)) return true; if (a == null) return false; if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) if (a [i] != b [i]) return false; return true; } static bool Equals<T> (T a, T b) where T : class, IEquatable<T> { if (ReferenceEquals (a, b)) return true; if (a == null) return false; return a.Equals (b); } static bool Equals (AssemblyNameReference a, AssemblyNameReference b) { if (ReferenceEquals (a, b)) return true; if (a.Name != b.Name) return false; if (!Equals (a.Version, b.Version)) return false; if (a.Culture != b.Culture) return false; if (!Equals (a.PublicKeyToken, b.PublicKeyToken)) return false; return true; } } }
namespace android.inputmethodservice { [global::MonoJavaBridge.JavaClass()] public partial class KeyboardView : android.view.View, android.view.View.OnClickListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected KeyboardView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_))] public partial interface OnKeyboardActionListener : global::MonoJavaBridge.IJavaObject { void onKey(int arg0, int[] arg1); void onPress(int arg0); void onRelease(int arg0); void onText(java.lang.CharSequence arg0); void swipeLeft(); void swipeRight(); void swipeDown(); void swipeUp(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener))] internal sealed partial class OnKeyboardActionListener_ : java.lang.Object, OnKeyboardActionListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnKeyboardActionListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onKey(int arg0, int[] arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onKey", "(I[I)V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onPress(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onPress", "(I)V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onRelease(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onRelease", "(I)V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.onText(java.lang.CharSequence arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "onText", "(Ljava/lang/CharSequence;)V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeLeft() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeLeft", "()V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m4); } private static global::MonoJavaBridge.MethodId _m5; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeRight() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeRight", "()V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m5); } private static global::MonoJavaBridge.MethodId _m6; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeDown() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeDown", "()V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m6); } private static global::MonoJavaBridge.MethodId _m7; void android.inputmethodservice.KeyboardView.OnKeyboardActionListener.swipeUp() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass, "swipeUp", "()V", ref global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_._m7); } static OnKeyboardActionListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/inputmethodservice/KeyboardView$OnKeyboardActionListener")); } } private static global::MonoJavaBridge.MethodId _m0; public virtual void closing() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "closing", "()V", ref global::android.inputmethodservice.KeyboardView._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void onClick(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onClick", "(Landroid/view/View;)V", ref global::android.inputmethodservice.KeyboardView._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public override bool onTouchEvent(android.view.MotionEvent arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.inputmethodservice.KeyboardView._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void onDetachedFromWindow() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onDetachedFromWindow", "()V", ref global::android.inputmethodservice.KeyboardView._m3); } private static global::MonoJavaBridge.MethodId _m4; public virtual void onSizeChanged(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onSizeChanged", "(IIII)V", ref global::android.inputmethodservice.KeyboardView._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void onDraw(android.graphics.Canvas arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onDraw", "(Landroid/graphics/Canvas;)V", ref global::android.inputmethodservice.KeyboardView._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void onMeasure(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onMeasure", "(II)V", ref global::android.inputmethodservice.KeyboardView._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new bool Shifted { set { setShifted(value); } } private static global::MonoJavaBridge.MethodId _m7; public virtual bool setShifted(bool arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setShifted", "(Z)Z", ref global::android.inputmethodservice.KeyboardView._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public virtual bool isShifted() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "isShifted", "()Z", ref global::android.inputmethodservice.KeyboardView._m8); } private static global::MonoJavaBridge.MethodId _m9; protected virtual void swipeLeft() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "swipeLeft", "()V", ref global::android.inputmethodservice.KeyboardView._m9); } private static global::MonoJavaBridge.MethodId _m10; protected virtual void swipeRight() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "swipeRight", "()V", ref global::android.inputmethodservice.KeyboardView._m10); } private static global::MonoJavaBridge.MethodId _m11; protected virtual void swipeDown() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "swipeDown", "()V", ref global::android.inputmethodservice.KeyboardView._m11); } private static global::MonoJavaBridge.MethodId _m12; protected virtual void swipeUp() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "swipeUp", "()V", ref global::android.inputmethodservice.KeyboardView._m12); } private static global::MonoJavaBridge.MethodId _m13; public virtual void setOnKeyboardActionListener(android.inputmethodservice.KeyboardView.OnKeyboardActionListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setOnKeyboardActionListener", "(Landroid/inputmethodservice/KeyboardView$OnKeyboardActionListener;)V", ref global::android.inputmethodservice.KeyboardView._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; protected virtual global::android.inputmethodservice.KeyboardView.OnKeyboardActionListener getOnKeyboardActionListener() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.inputmethodservice.KeyboardView.OnKeyboardActionListener>(this, global::android.inputmethodservice.KeyboardView.staticClass, "getOnKeyboardActionListener", "()Landroid/inputmethodservice/KeyboardView$OnKeyboardActionListener;", ref global::android.inputmethodservice.KeyboardView._m14) as android.inputmethodservice.KeyboardView.OnKeyboardActionListener; } private static global::MonoJavaBridge.MethodId _m15; public virtual void setKeyboard(android.inputmethodservice.Keyboard arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setKeyboard", "(Landroid/inputmethodservice/Keyboard;)V", ref global::android.inputmethodservice.KeyboardView._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.inputmethodservice.Keyboard Keyboard { get { return getKeyboard(); } set { setKeyboard(value); } } private static global::MonoJavaBridge.MethodId _m16; public virtual global::android.inputmethodservice.Keyboard getKeyboard() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "getKeyboard", "()Landroid/inputmethodservice/Keyboard;", ref global::android.inputmethodservice.KeyboardView._m16) as android.inputmethodservice.Keyboard; } public new bool PreviewEnabled { set { setPreviewEnabled(value); } } private static global::MonoJavaBridge.MethodId _m17; public virtual void setPreviewEnabled(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setPreviewEnabled", "(Z)V", ref global::android.inputmethodservice.KeyboardView._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m18; public virtual bool isPreviewEnabled() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "isPreviewEnabled", "()Z", ref global::android.inputmethodservice.KeyboardView._m18); } public new int VerticalCorrection { set { setVerticalCorrection(value); } } private static global::MonoJavaBridge.MethodId _m19; public virtual void setVerticalCorrection(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setVerticalCorrection", "(I)V", ref global::android.inputmethodservice.KeyboardView._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.view.View PopupParent { set { setPopupParent(value); } } private static global::MonoJavaBridge.MethodId _m20; public virtual void setPopupParent(android.view.View arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setPopupParent", "(Landroid/view/View;)V", ref global::android.inputmethodservice.KeyboardView._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m21; public virtual void setPopupOffset(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setPopupOffset", "(II)V", ref global::android.inputmethodservice.KeyboardView._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new bool ProximityCorrectionEnabled { set { setProximityCorrectionEnabled(value); } } private static global::MonoJavaBridge.MethodId _m22; public virtual void setProximityCorrectionEnabled(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "setProximityCorrectionEnabled", "(Z)V", ref global::android.inputmethodservice.KeyboardView._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m23; public virtual bool isProximityCorrectionEnabled() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "isProximityCorrectionEnabled", "()Z", ref global::android.inputmethodservice.KeyboardView._m23); } private static global::MonoJavaBridge.MethodId _m24; public virtual void invalidateAllKeys() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "invalidateAllKeys", "()V", ref global::android.inputmethodservice.KeyboardView._m24); } private static global::MonoJavaBridge.MethodId _m25; public virtual void invalidateKey(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "invalidateKey", "(I)V", ref global::android.inputmethodservice.KeyboardView._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; protected virtual bool onLongPress(android.inputmethodservice.Keyboard.Key arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "onLongPress", "(Landroid/inputmethodservice/Keyboard$Key;)Z", ref global::android.inputmethodservice.KeyboardView._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m27; public virtual bool handleBack() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.inputmethodservice.KeyboardView.staticClass, "handleBack", "()Z", ref global::android.inputmethodservice.KeyboardView._m27); } private static global::MonoJavaBridge.MethodId _m28; public KeyboardView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.inputmethodservice.KeyboardView._m28.native == global::System.IntPtr.Zero) global::android.inputmethodservice.KeyboardView._m28 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m29; public KeyboardView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.inputmethodservice.KeyboardView._m29.native == global::System.IntPtr.Zero) global::android.inputmethodservice.KeyboardView._m29 = @__env.GetMethodIDNoThrow(global::android.inputmethodservice.KeyboardView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.inputmethodservice.KeyboardView.staticClass, global::android.inputmethodservice.KeyboardView._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } static KeyboardView() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.inputmethodservice.KeyboardView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/inputmethodservice/KeyboardView")); } } }
using System; using MbUnit.Framework; using Moq; using Subtext.Extensibility.Interfaces; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Providers; using Subtext.Framework.Services; using Subtext.Framework.Web.HttpModules; namespace UnitTests.Subtext.Framework.Services { [TestFixture] public class BlogLookupServiceTests { [Test] public void Request_WithMatchingHost_ReturnsCorrespondingBlog() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns(new Blog {Host = "example.com"}); var service = new BlogLookupService(repository.Object, new HostInfo()); //act BlogLookupResult result = service.Lookup(new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false)); //assert Assert.IsNotNull(result.Blog); Assert.IsNull(result.AlternateUrl); } [Test] public void Request_WithNonMatchingHostButAlternativeHostMatches_ReturnsAlternativeHost() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns(new Blog {Host = "www.example.com"}); var service = new BlogLookupService(repository.Object, new HostInfo()); //act BlogLookupResult result = service.Lookup(new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false)); //assert Assert.IsNull(result.Blog); Assert.AreEqual("http://www.example.com/foo/bar", result.AlternateUrl.ToString()); } [Test] public void Request_MatchingActiveAlias_RedirectsToPrimary() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("blog.example.com", It.IsAny<string>())).Returns(new Blog {Host = "www.example.com"}); var service = new BlogLookupService(repository.Object, new HostInfo()); //act BlogLookupResult result = service.Lookup(new BlogRequest("blog.example.com", string.Empty, new Uri("http://blog.example.com/foo/bar"), false)); //assert Assert.IsNull(result.Blog); Assert.AreEqual("http://www.example.com/foo/bar", result.AlternateUrl.ToString()); } [Test] public void Request_MatchingActiveAliasWithSubfolder_RedirectsToPrimaryWithoutSubfolder() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("blog.example.com", "sub")).Returns(new Blog {Host = "www.example.com", Subfolder = ""}); var service = new BlogLookupService(repository.Object, new HostInfo()); //act BlogLookupResult result = service.Lookup(new BlogRequest("blog.example.com", "sub", new Uri("http://blog.example.com/sub/foo/bar"), false)); //assert Assert.IsNull(result.Blog); Assert.AreEqual("http://www.example.com/foo/bar", result.AlternateUrl.ToString()); } [Test] public void Request_MatchingActiveAliasWithoutSubfolder_RedirectsToPrimaryWithSubfolder() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("blog.example.com", string.Empty)).Returns(new Blog {Host = "www.example.com", Subfolder = "sub"}); var service = new BlogLookupService(repository.Object, new HostInfo()); //act BlogLookupResult result = service.Lookup(new BlogRequest("blog.example.com", string.Empty, new Uri("http://blog.example.com/foo/bar"), false)); //assert Assert.IsNull(result.Blog); Assert.AreEqual("http://www.example.com/sub/foo/bar", result.AlternateUrl.ToString()); } [Test] public void Request_MatchingActiveAliasWithSubfolder_RedirectsToPrimaryWithDifferentSubfolder() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("blog.example.com", "notsub")).Returns(new Blog {Host = "www.example.com", Subfolder = "sub"}); repository.Setup(r => r.GetBlogByDomainAlias("blog.example.com", "notsub", It.IsAny<bool>())).Returns( new Blog {Host = "www.example.com", Subfolder = "sub"}); var service = new BlogLookupService(repository.Object, new HostInfo()); //act BlogLookupResult result = service.Lookup(new BlogRequest("blog.example.com", "notsub", new Uri("http://blog.example.com/notsub/foo/bar"), false)); //assert Assert.IsNull(result.Blog); Assert.AreEqual("http://www.example.com/sub/foo/bar", result.AlternateUrl.ToString()); } [Test] public void Request_NotMatchingAnyBlog_ReturnsNull() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null); var pagedCollection = new Mock<IPagedCollection<Blog>>(); pagedCollection.Setup(p => p.MaxItems).Returns(0); repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns( pagedCollection.Object); var service = new BlogLookupService(repository.Object, new HostInfo {BlogAggregationEnabled = false}); //act BlogLookupResult result = service.Lookup(new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false)); //assert Assert.IsNull(result); } [Test] public void RequestNotMatchingAnyBlog_ButWithAggregateBlogsEnabledAndActiveBlogsInTheSystem_ReturnsAggregateBlog () { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null); var onlyBlog = new Blog {Host = "example.com", Subfolder = "not-sub"}; var pagedCollection = new PagedCollection<Blog> {onlyBlog}; pagedCollection.MaxItems = 1; repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns( pagedCollection); var aggregateBlog = new Blog(); var service = new BlogLookupService(repository.Object, new HostInfo {BlogAggregationEnabled = true, AggregateBlog = aggregateBlog}); var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false); //act BlogLookupResult result = service.Lookup(blogRequest); //assert Assert.AreSame(aggregateBlog, result.Blog); } [Test] public void RequestWithSubfolderNotMatchingAnyBlog_ButWithAggregateBlogsEnabledAndMoreThanOneActiveBlogsInTheSystem_ReturnsNull() { //arrange var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null); var blog1 = new Blog { Host = "example.com", Subfolder = "not-sub" }; var blog2 = new Blog { Host = "example.com", Subfolder = "not-sub-2" }; var pagedCollection = new PagedCollection<Blog> {blog1, blog2}; pagedCollection.MaxItems = 2; repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns( pagedCollection); var aggregateBlog = new Blog(); var service = new BlogLookupService(repository.Object, new HostInfo { BlogAggregationEnabled = true, AggregateBlog = aggregateBlog }); var blogRequest = new BlogRequest("example.com", "blog1234", new Uri("http://example.com/foo/bar"), false); //act BlogLookupResult result = service.Lookup(blogRequest); //assert Assert.IsNull(result); } /// <summary> /// This test makes sure we deal gracefully with a common deployment problem. /// A user sets up the blog on his/her local machine (aka "localhost"), then /// deploys the database to their production server. The hostname in the db /// should be changed to the new domain. /// </summary> [Test] public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithMatchingHostButDifferentSubfolder_RedirectsToOnlyBlog () { //arrange var onlyBlog = new Blog {Host = "example.com", Subfolder = "not-sub"}; var pagedCollection = new PagedCollection<Blog> {onlyBlog}; pagedCollection.MaxItems = 1; var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", "sub")).Returns((Blog)null); repository.Setup(r => r.GetBlog("example.com", "not-sub")).Returns(onlyBlog); repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns( pagedCollection); var service = new BlogLookupService(repository.Object, new HostInfo {BlogAggregationEnabled = false}); var blogRequest = new BlogRequest("example.com", "sub", new Uri("http://example.com/Subtext.Web/sub/bar"), false, RequestLocation.Blog, "/Subtext.Web"); //act BlogLookupResult result = service.Lookup(blogRequest); //assert Assert.IsNull(result.Blog); Assert.AreEqual("http://example.com/Subtext.Web/not-sub/bar", result.AlternateUrl.ToString()); } /// <summary> /// This test makes sure we deal gracefully with a common deployment problem. /// A user sets up the blog on his/her local machine (aka "localhost"), then /// deploys the database to their production server. The hostname in the db /// should be changed to the new domain. /// </summary> [Test] public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithLocalHost_ReturnsThatBlogAndUpdatesItsHost() { //arrange var onlyBlog = new Blog {Host = "localhost", Subfolder = ""}; var pagedCollection = new PagedCollection<Blog> {onlyBlog}; pagedCollection.MaxItems = 1; var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null); repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns( pagedCollection); var service = new BlogLookupService(repository.Object, new HostInfo {BlogAggregationEnabled = false}); var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false); //act BlogLookupResult result = service.Lookup(blogRequest); //assert Assert.IsNotNull(result.Blog); Assert.IsNull(result.AlternateUrl); Assert.AreEqual("example.com", result.Blog.Host); Assert.AreEqual("example.com", onlyBlog.Host); repository.Verify(r => r.UpdateBlog(It.IsAny<Blog>())); } /// <summary> /// This test makes sure we deal gracefully with a common deployment problem. /// A user sets up the blog on his/her local machine (aka "localhost"), then /// deploys the database to their production server. The hostname in the db /// should be changed to the new domain. /// </summary> [Test] public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithLocalHostButNotMatchingSubfolder_ReturnsUpdatesItsHostThenRedirectsToSubfolder () { //arrange var onlyBlog = new Blog {Host = "localhost", Subfolder = "sub"}; var pagedCollection = new PagedCollection<Blog> {onlyBlog}; pagedCollection.MaxItems = 1; var repository = new Mock<ObjectProvider>(); repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null); repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns( pagedCollection); var service = new BlogLookupService(repository.Object, new HostInfo {BlogAggregationEnabled = false}); var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false); //act BlogLookupResult result = service.Lookup(blogRequest); //assert Assert.IsNull(result.Blog); Assert.IsNotNull(result.AlternateUrl); Assert.AreEqual("http://example.com/sub/foo/bar", result.AlternateUrl.ToString()); Assert.AreEqual("example.com", onlyBlog.Host); repository.Verify(r => r.UpdateBlog(It.IsAny<Blog>())); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type int with 2 columns and 4 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct imat2x4 : IReadOnlyList<int>, IEquatable<imat2x4> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public int m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public int m01; /// <summary> /// Column 0, Rows 2 /// </summary> [DataMember] public int m02; /// <summary> /// Column 0, Rows 3 /// </summary> [DataMember] public int m03; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public int m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public int m11; /// <summary> /// Column 1, Rows 2 /// </summary> [DataMember] public int m12; /// <summary> /// Column 1, Rows 3 /// </summary> [DataMember] public int m13; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public imat2x4(int m00, int m01, int m02, int m03, int m10, int m11, int m12, int m13) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; } /// <summary> /// Constructs this matrix from a imat2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a imat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a imat4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(ivec2 c0, ivec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0; this.m03 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(ivec3 c0, ivec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(ivec4 c0, ivec4 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = c0.w; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = c1.w; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public int[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public int[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public ivec4 Column0 { get { return new ivec4(m00, m01, m02, m03); } set { m00 = value.x; m01 = value.y; m02 = value.z; m03 = value.w; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public ivec4 Column1 { get { return new ivec4(m10, m11, m12, m13); } set { m10 = value.x; m11 = value.y; m12 = value.z; m13 = value.w; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public ivec2 Row0 { get { return new ivec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public ivec2 Row1 { get { return new ivec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public ivec2 Row2 { get { return new ivec2(m02, m12); } set { m02 = value.x; m12 = value.y; } } /// <summary> /// Gets or sets the row nr 3 /// </summary> public ivec2 Row3 { get { return new ivec2(m03, m13); } set { m03 = value.x; m13 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static imat2x4 Zero { get; } = new imat2x4(0, 0, 0, 0, 0, 0, 0, 0); /// <summary> /// Predefined all-ones matrix /// </summary> public static imat2x4 Ones { get; } = new imat2x4(1, 1, 1, 1, 1, 1, 1, 1); /// <summary> /// Predefined identity matrix /// </summary> public static imat2x4 Identity { get; } = new imat2x4(1, 0, 0, 0, 0, 1, 0, 0); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static imat2x4 AllMaxValue { get; } = new imat2x4(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static imat2x4 DiagonalMaxValue { get; } = new imat2x4(int.MaxValue, 0, 0, 0, 0, int.MaxValue, 0, 0); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static imat2x4 AllMinValue { get; } = new imat2x4(int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static imat2x4 DiagonalMinValue { get; } = new imat2x4(int.MinValue, 0, 0, 0, 0, int.MinValue, 0, 0); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<int> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m03; yield return m10; yield return m11; yield return m12; yield return m13; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 4 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public int this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m03; case 4: return m10; case 5: return m11; case 6: return m12; case 7: return m13; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m03 = value; break; case 4: this.m10 = value; break; case 5: this.m11 = value; break; case 6: this.m12 = value; break; case 7: this.m13 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public int this[int col, int row] { get { return this[col * 4 + row]; } set { this[col * 4 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(imat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is imat2x4 && Equals((imat2x4) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(imat2x4 lhs, imat2x4 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(imat2x4 lhs, imat2x4 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public imat4x2 Transposed => new imat4x2(m00, m10, m01, m11, m02, m12, m03, m13); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public int MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public int MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public float LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))); /// <summary> /// Returns the sum of all fields. /// </summary> public int Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public int NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication imat2x4 * imat2 -> imat2x4. /// </summary> public static imat2x4 operator*(imat2x4 lhs, imat2 rhs) => new imat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication imat2x4 * imat3x2 -> imat3x4. /// </summary> public static imat3x4 operator*(imat2x4 lhs, imat3x2 rhs) => new imat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication imat2x4 * imat4x2 -> imat4. /// </summary> public static imat4 operator*(imat2x4 lhs, imat4x2 rhs) => new imat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static ivec4 operator*(imat2x4 m, ivec2 v) => new ivec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y)); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static imat2x4 CompMul(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static imat2x4 CompDiv(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat2x4 CompAdd(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat2x4 CompSub(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat2x4 operator+(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat2x4 operator+(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat2x4 operator+(int lhs, imat2x4 rhs) => new imat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat2x4 operator-(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat2x4 operator-(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat2x4 operator-(int lhs, imat2x4 rhs) => new imat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat2x4 operator/(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat2x4 operator/(int lhs, imat2x4 rhs) => new imat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat2x4 operator*(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat2x4 operator*(int lhs, imat2x4 rhs) => new imat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static imat2x4 operator%(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m02 % rhs.m02, lhs.m03 % rhs.m03, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m12 % rhs.m12, lhs.m13 % rhs.m13); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat2x4 operator%(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m02 % rhs, lhs.m03 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m12 % rhs, lhs.m13 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat2x4 operator%(int lhs, imat2x4 rhs) => new imat2x4(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m02, lhs % rhs.m03, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m12, lhs % rhs.m13); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static imat2x4 operator^(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m02 ^ rhs.m02, lhs.m03 ^ rhs.m03, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m12 ^ rhs.m12, lhs.m13 ^ rhs.m13); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat2x4 operator^(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m02 ^ rhs, lhs.m03 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m12 ^ rhs, lhs.m13 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat2x4 operator^(int lhs, imat2x4 rhs) => new imat2x4(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m02, lhs ^ rhs.m03, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m12, lhs ^ rhs.m13); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static imat2x4 operator|(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m02 | rhs.m02, lhs.m03 | rhs.m03, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m12 | rhs.m12, lhs.m13 | rhs.m13); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat2x4 operator|(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m02 | rhs, lhs.m03 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m12 | rhs, lhs.m13 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat2x4 operator|(int lhs, imat2x4 rhs) => new imat2x4(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m02, lhs | rhs.m03, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m12, lhs | rhs.m13); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static imat2x4 operator&(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m02 & rhs.m02, lhs.m03 & rhs.m03, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m12 & rhs.m12, lhs.m13 & rhs.m13); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat2x4 operator&(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m02 & rhs, lhs.m03 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m12 & rhs, lhs.m13 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat2x4 operator&(int lhs, imat2x4 rhs) => new imat2x4(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m02, lhs & rhs.m03, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m12, lhs & rhs.m13); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static imat2x4 operator<<(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m02 << rhs, lhs.m03 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m12 << rhs, lhs.m13 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static imat2x4 operator>>(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m02 >> rhs, lhs.m03 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m12 >> rhs, lhs.m13 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat2x4 operator<(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2x4 operator<(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2x4 operator<(int lhs, imat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat2x4 operator<=(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator<=(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator<=(int lhs, imat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat2x4 operator>(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2x4 operator>(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2x4 operator>(int lhs, imat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat2x4 operator>=(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator>=(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator>=(int lhs, imat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13); } }
namespace FakeItEasy.Configuration { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using FakeItEasy.Core; internal partial class RuleBuilder : IAnyCallConfigurationWithVoidReturnType, IVoidAfterCallbackConfiguredConfiguration, IAfterCallConfiguredWithOutAndRefParametersConfiguration<IVoidConfiguration>, IThenConfiguration<IVoidConfiguration> { private readonly FakeAsserter.Factory asserterFactory; private readonly FakeManager manager; private bool wasRuleAdded; internal RuleBuilder(BuildableCallRule ruleBeingBuilt, FakeManager manager, FakeAsserter.Factory asserterFactory) { this.RuleBeingBuilt = ruleBeingBuilt; this.manager = manager; this.asserterFactory = asserterFactory; } /// <summary> /// Represents a delegate that creates a configuration object from /// a fake object and the rule to build. /// </summary> /// <param name="ruleBeingBuilt">The rule that's being built.</param> /// <param name="fakeObject">The fake object the rule is for.</param> /// <returns>A configuration object.</returns> internal delegate RuleBuilder Factory(BuildableCallRule ruleBeingBuilt, FakeManager fakeObject); public BuildableCallRule RuleBeingBuilt { get; } IVoidConfiguration IThenConfiguration<IVoidConfiguration>.Then => this.Then; public IEnumerable<CompletedFakeObjectCall> Calls => this.manager.GetRecordedCalls(); public ICallMatcher Matcher => new RuleMatcher(this); private RuleBuilder Then { get { var newRule = this.RuleBeingBuilt.CloneCallSpecification(); return new RuleBuilder(newRule, this.manager, this.asserterFactory) { PreviousRule = this.RuleBeingBuilt }; } } [DisallowNull] private BuildableCallRule? PreviousRule { get; set; } public IThenConfiguration<IVoidConfiguration> NumberOfTimes(int numberOfTimes) { if (numberOfTimes <= 0) { throw new ArgumentOutOfRangeException( nameof(numberOfTimes), numberOfTimes, ExceptionMessages.NumberOfTimesNotGreaterThanZero); } this.RuleBeingBuilt.NumberOfTimesToCall = numberOfTimes; return this; } public virtual IAfterCallConfiguredConfiguration<IVoidConfiguration> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) { Guard.AgainstNull(exceptionFactory); this.AddRuleIfNeeded(); this.RuleBeingBuilt.UseApplicator(call => throw exceptionFactory(call)); return this; } public IAfterCallConfiguredConfiguration<IVoidConfiguration> Throws<T>() where T : Exception, new() => this.Throws<IVoidConfiguration, T>(); public IVoidConfiguration WhenArgumentsMatch(Func<ArgumentCollection, bool> argumentsPredicate) { Guard.AgainstNull(argumentsPredicate); this.RuleBeingBuilt.UsePredicateToValidateArguments(argumentsPredicate); return this; } public virtual IAfterCallConfiguredConfiguration<IVoidConfiguration> DoesNothing() { this.AddRuleIfNeeded(); this.RuleBeingBuilt.UseDefaultApplicator(); return this; } public virtual IVoidAfterCallbackConfiguredConfiguration Invokes(Action<IFakeObjectCall> action) { Guard.AgainstNull(action); this.AddRuleIfNeeded(); this.RuleBeingBuilt.Actions.Add(action); return this; } public virtual IAfterCallConfiguredConfiguration<IVoidConfiguration> CallsBaseMethod() { if (this.manager.FakeObjectType.IsSubclassOf(typeof(Delegate))) { throw new FakeConfigurationException(ExceptionMessages.DelegateCannotCallBaseMethod); } this.AddRuleIfNeeded(); this.RuleBeingBuilt.UseApplicator(x => { }); this.RuleBeingBuilt.CallBaseMethod = true; return this; } public virtual IAfterCallConfiguredConfiguration<IVoidConfiguration> CallsWrappedMethod() { var wrappedObjectRule = this.manager.Rules.OfType<WrappedObjectRule>().FirstOrDefault(); if (wrappedObjectRule is null) { throw new FakeConfigurationException(ExceptionMessages.NotAWrappingFake); } this.AddRuleIfNeeded(); this.RuleBeingBuilt.UseApplicator(x => { }); this.RuleBeingBuilt.CallWrappedMethodOn = wrappedObjectRule.WrappedObject; return this; } public virtual IAfterCallConfiguredConfiguration<IVoidConfiguration> AssignsOutAndRefParametersLazily(Func<IFakeObjectCall, ICollection<object?>> valueProducer) { Guard.AgainstNull(valueProducer); this.AddRuleIfNeeded(); this.RuleBeingBuilt.SetOutAndRefParametersValueProducer(valueProducer); return this; } public UnorderedCallAssertion MustHaveHappened(int numberOfTimes, Times timesOption) { Guard.AgainstNull(timesOption); return this.MustHaveHappened(timesOption.ToCallCountConstraint(numberOfTimes)); } public UnorderedCallAssertion MustHaveHappenedANumberOfTimesMatching(Expression<Func<int, bool>> predicate) { Guard.AgainstNull(predicate); return this.MustHaveHappened(new CallCountConstraint(predicate.Compile(), $"a number of times matching the predicate '{predicate}'")); } public IAnyCallConfigurationWithVoidReturnType Where(Func<IFakeObjectCall, bool> predicate, Action<IOutputWriter> descriptionWriter) { Guard.AgainstNull(predicate); Guard.AgainstNull(descriptionWriter); this.RuleBeingBuilt.ApplyWherePredicate(predicate, descriptionWriter); return this; } private UnorderedCallAssertion MustHaveHappened(CallCountConstraint callCountConstraint) { var asserter = this.asserterFactory.Invoke(this.Calls, this.manager.GetLastRecordedSequenceNumber()); asserter.AssertWasCalled(this.Matcher.Matches, this.RuleBeingBuilt.WriteDescriptionOfValidCall, callCountConstraint); return new UnorderedCallAssertion(this.manager, this.Matcher, this.RuleBeingBuilt.WriteDescriptionOfValidCall, callCountConstraint); } private void AddRuleIfNeeded() { if (!this.wasRuleAdded) { if (this.PreviousRule is not null) { this.manager.AddRuleAfter(this.PreviousRule, this.RuleBeingBuilt); } else { this.manager.AddRuleFirst(this.RuleBeingBuilt); } this.wasRuleAdded = true; } } public partial class ReturnValueConfiguration<TMember> : IAnyCallConfigurationWithReturnTypeSpecified<TMember>, IAfterCallConfiguredWithOutAndRefParametersConfiguration<IReturnValueConfiguration<TMember>>, IThenConfiguration<IReturnValueConfiguration<TMember>> { public ReturnValueConfiguration(RuleBuilder parentConfiguration) { this.ParentConfiguration = parentConfiguration; } public ICallMatcher Matcher => this.ParentConfiguration.Matcher; public IReturnValueConfiguration<TMember> Then => new ReturnValueConfiguration<TMember>(this.ParentConfiguration.Then); public IEnumerable<ICompletedFakeObjectCall> Calls => this.ParentConfiguration.Calls; private RuleBuilder ParentConfiguration { get; } public IAfterCallConfiguredConfiguration<IReturnValueConfiguration<TMember>> Throws(Func<IFakeObjectCall, Exception> exceptionFactory) { this.ParentConfiguration.Throws(exceptionFactory); return this; } public IAfterCallConfiguredConfiguration<IReturnValueConfiguration<TMember>> Throws<T>() where T : Exception, new() => this.Throws<IReturnValueConfiguration<TMember>, T>(); public IAfterCallConfiguredWithOutAndRefParametersConfiguration<IReturnValueConfiguration<TMember>> ReturnsLazily(Func<IFakeObjectCall, TMember> valueProducer) { Guard.AgainstNull(valueProducer); this.ParentConfiguration.AddRuleIfNeeded(); this.ParentConfiguration.RuleBeingBuilt.UseApplicator(call => call.SetReturnValue(valueProducer(call))); return this; } public IReturnValueConfiguration<TMember> Invokes(Action<IFakeObjectCall> action) { this.ParentConfiguration.Invokes(action); return this; } public IAfterCallConfiguredConfiguration<IReturnValueConfiguration<TMember>> CallsBaseMethod() { this.ParentConfiguration.CallsBaseMethod(); return this; } public IAfterCallConfiguredConfiguration<IReturnValueConfiguration<TMember>> CallsWrappedMethod() { this.ParentConfiguration.CallsWrappedMethod(); return this; } public IReturnValueConfiguration<TMember> WhenArgumentsMatch(Func<ArgumentCollection, bool> argumentsPredicate) { this.ParentConfiguration.WhenArgumentsMatch(argumentsPredicate); return this; } public UnorderedCallAssertion MustHaveHappened(int numberOfTimes, Times timesOption) => this.ParentConfiguration.MustHaveHappened(numberOfTimes, timesOption); public UnorderedCallAssertion MustHaveHappenedANumberOfTimesMatching(Expression<Func<int, bool>> predicate) => this.ParentConfiguration.MustHaveHappenedANumberOfTimesMatching(predicate); public IAnyCallConfigurationWithReturnTypeSpecified<TMember> Where(Func<IFakeObjectCall, bool> predicate, Action<IOutputWriter> descriptionWriter) { Guard.AgainstNull(predicate); Guard.AgainstNull(descriptionWriter); this.ParentConfiguration.RuleBeingBuilt.ApplyWherePredicate(predicate, descriptionWriter); return this; } public IAfterCallConfiguredConfiguration<IReturnValueConfiguration<TMember>> AssignsOutAndRefParametersLazily(Func<IFakeObjectCall, ICollection<object?>> valueProducer) { this.ParentConfiguration.AssignsOutAndRefParametersLazily(valueProducer); return this; } public IThenConfiguration<IReturnValueConfiguration<TMember>> NumberOfTimes(int numberOfTimes) { this.ParentConfiguration.NumberOfTimes(numberOfTimes); return this; } } private class RuleMatcher : ICallMatcher { private readonly RuleBuilder builder; public RuleMatcher(RuleBuilder builder) { this.builder = builder; } public bool Matches(IFakeObjectCall call) { Guard.AgainstNull(call); return this.builder.RuleBeingBuilt.IsApplicableTo(call) && ReferenceEquals(this.builder.manager.Object, call.FakedObject); } public override string? ToString() => this.builder.RuleBeingBuilt.ToString(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Resources; using System.Text; using System.Text.RegularExpressions; using System.Web; using DDay.iCal.Serialization.iCalendar; using NUnit.Framework; namespace DDay.iCal.Test { [TestFixture] public class ProgramTest { [Test] public void LoadAndDisplayCalendar() { // The following code loads and displays an iCalendar // with US Holidays for 2006. // IICalendar iCal = iCalendar.LoadFromFile(@"Calendars\Serialization\USHolidays.ics")[0]; Assert.IsNotNull(iCal, "iCalendar did not load. Are you connected to the internet?"); IList<Occurrence> occurrences = iCal.GetOccurrences( new iCalDateTime(2006, 1, 1, "US-Eastern"), new iCalDateTime(2006, 12, 31, "US-Eastern")); foreach (Occurrence o in occurrences) { IEvent evt = o.Source as IEvent; if (evt != null) { // Display the date of the event Console.Write(o.Period.StartTime.Local.Date.ToString("MM/dd/yyyy") + " -\t"); // Display the event summary Console.Write(evt.Summary); // Display the time the event happens (unless it's an all-day event) if (evt.Start.HasTime) { Console.Write(" (" + evt.Start.Local.ToShortTimeString() + " - " + evt.End.Local.ToShortTimeString()); if (evt.Start.TimeZoneObservance != null && evt.Start.TimeZoneObservance.HasValue) Console.Write(" " + evt.Start.TimeZoneObservance.Value.TimeZoneInfo.TimeZoneName); Console.Write(")"); } Console.Write(Environment.NewLine); } } } private DateTime Start; private DateTime End; private TimeSpan TotalTime; private string tzid; [TestFixtureSetUp] public void InitAll() { TotalTime = new TimeSpan(0); tzid = "US-Eastern"; } [TestFixtureTearDown] public void DisposeAll() { Console.WriteLine("Total Processing Time: " + Math.Round(TotalTime.TotalMilliseconds) + "ms"); } [SetUp] public void Init() { Start = DateTime.Now; } [TearDown] public void Dispose() { End = DateTime.Now; TotalTime = TotalTime.Add(End - Start); Console.WriteLine("Time: " + Math.Round(End.Subtract(Start).TotalMilliseconds) + "ms"); } static public void TestCal(IICalendar iCal) { Assert.IsNotNull(iCal, "The iCalendar was not loaded"); if (iCal.Events.Count > 0) Assert.IsTrue(iCal.Events.Count == 1, "Calendar should contain 1 event; however, the iCalendar loaded " + iCal.Events.Count + " events"); else if (iCal.Todos.Count > 0) Assert.IsTrue(iCal.Todos.Count == 1, "Calendar should contain 1 todo; however, the iCalendar loaded " + iCal.Todos.Count + " todos"); } [Test] public void LoadFromFile() { string path = @"Calendars\Serialization\Calendar1.ics"; Assert.IsTrue(File.Exists(path), "File '" + path + "' does not exist."); IICalendar iCal = iCalendar.LoadFromFile(path)[0]; Assert.AreEqual(14, iCal.Events.Count); } [Test] public void LoadFromUri() { string path = Directory.GetCurrentDirectory(); path = Path.Combine(path, "Calendars/Serialization/Calendar1.ics").Replace(@"\", "/"); path = "file:///" + path; Uri uri = new Uri(path); IICalendar iCal = iCalendar.LoadFromUri(uri)[0]; Assert.AreEqual(14, iCal.Events.Count); } /// <summary> /// Ensures that Period.GetHashCode() does not throw NullReferenceException, even /// if its properties are null. /// </summary> [Test] public void Bug3258032() { Period p = new Period(); p.GetHashCode(); } /// <summary> /// The following test is an aggregate of MonthlyCountByMonthDay3() and MonthlyByDay1() in the /// <see cref="Recurrence"/> class. /// </summary> [Test] public void Merge1() { IICalendar iCal1 = iCalendar.LoadFromFile(@"Calendars\Recurrence\MonthlyCountByMonthDay3.ics")[0]; IICalendar iCal2 = iCalendar.LoadFromFile(@"Calendars\Recurrence\MonthlyByDay1.ics")[0]; // Change the UID of the 2nd event to make sure it's different iCal2.Events[iCal1.Events[0].UID].UID = "1234567890"; iCal1.MergeWith(iCal2); IEvent evt1 = iCal1.Events.First(); IEvent evt2 = iCal1.Events.Skip(1).First(); // Get occurrences for the first event IList<Occurrence> occurrences = evt1.GetOccurrences( new iCalDateTime(1996, 1, 1, tzid), new iCalDateTime(2000, 1, 1, tzid)); iCalDateTime[] DateTimes = new iCalDateTime[] { new iCalDateTime(1997, 9, 10, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 11, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 12, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 13, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 14, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 15, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 10, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 11, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 12, 9, 0, 0, tzid), new iCalDateTime(1999, 3, 13, 9, 0, 0, tzid), }; string[] TimeZones = new string[] { "EDT", "EDT", "EDT", "EDT", "EDT", "EDT", "EST", "EST", "EST", "EST" }; for (int i = 0; i < DateTimes.Length; i++) { IDateTime dt = DateTimes[i]; IDateTime start = occurrences[i].Period.StartTime; Assert.AreEqual(dt, start); Assert.IsTrue(dt.TimeZoneName == TimeZones[i], "Event " + dt + " should occur in the " + TimeZones[i] + " timezone"); } Assert.IsTrue(occurrences.Count == DateTimes.Length, "There should be exactly " + DateTimes.Length + " occurrences; there were " + occurrences.Count); // Get occurrences for the 2nd event occurrences = evt2.GetOccurrences( new iCalDateTime(1996, 1, 1, tzid), new iCalDateTime(1998, 4, 1, tzid)); iCalDateTime[] DateTimes1 = new iCalDateTime[] { new iCalDateTime(1997, 9, 2, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 9, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 16, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 23, 9, 0, 0, tzid), new iCalDateTime(1997, 9, 30, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 4, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 11, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 18, 9, 0, 0, tzid), new iCalDateTime(1997, 11, 25, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 6, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 13, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 20, 9, 0, 0, tzid), new iCalDateTime(1998, 1, 27, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 3, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 10, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 17, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 24, 9, 0, 0, tzid), new iCalDateTime(1998, 3, 31, 9, 0, 0, tzid) }; string[] TimeZones1 = new string[] { "EDT", "EDT", "EDT", "EDT", "EDT", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST", "EST" }; for (int i = 0; i < DateTimes1.Length; i++) { IDateTime dt = DateTimes1[i]; IDateTime start = occurrences[i].Period.StartTime; Assert.AreEqual(dt, start); Assert.IsTrue(dt.TimeZoneName == TimeZones1[i], "Event " + dt + " should occur in the " + TimeZones1[i] + " timezone"); } Assert.AreEqual(DateTimes1.Length, occurrences.Count, "There should be exactly " + DateTimes1.Length + " occurrences; there were " + occurrences.Count); } [Test] public void Merge2() { iCalendar iCal = new iCalendar(); IICalendar tmp_cal = iCalendar.LoadFromFile(@"Calendars\Serialization\TimeZone3.ics")[0]; iCal.MergeWith(tmp_cal); tmp_cal = iCalendar.LoadFromFile(@"Calendars\Serialization\TimeZone3.ics")[0]; // Compare the two calendars -- they should match exactly SerializationTest.CompareCalendars(iCal, tmp_cal); } /// <summary> /// The following tests the MergeWith() method of iCalendar to /// ensure that unique component merging happens as expected. /// </summary> [Test] public void Merge3() { IICalendar iCal1 = iCalendar.LoadFromFile(@"Calendars\Recurrence\MonthlyCountByMonthDay3.ics")[0]; IICalendar iCal2 = iCalendar.LoadFromFile(@"Calendars\Recurrence\YearlyByMonth1.ics")[0]; iCal1.MergeWith(iCal2); Assert.AreEqual(1, iCal1.Events.Count); } #if !SILVERLIGHT /// <summary> /// Tests conversion of the system time zone to one compatible with DDay.iCal. /// Also tests the gaining/loss of an hour over time zone boundaries. /// </summary> [Test] public void SystemTimeZone1() { System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); Assert.IsNotNull(tzi); iCalendar iCal = new iCalendar(); ITimeZone tz = iCal.AddTimeZone(tzi, new DateTime(2000, 1, 1), false); iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(iCal, @"Calendars\Serialization\SystemTimeZone1.ics"); // Ensure the time zone transition works as expected // (i.e. it takes 1 hour and 1 second to transition from // 2003-10-26 1:59:59 AM to // 2003-10-26 2:00:00 AM) iCalDateTime dt1 = new iCalDateTime(2003, 10, 26, 1, 59, 59, tz.TZID, iCal); iCalDateTime dt2 = new iCalDateTime(2003, 10, 26, 2, 0, 0, tz.TZID, iCal); TimeSpan result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), result); // Ensure another time zone transition works as expected // (i.e. it takes negative 59 minutes and 59 seconds to transition from // 2004-04-04 01:59:59 AM to // 2004-04-04 02:00:00 AM) // NOTE: We have a negative difference between the two values // because we 'spring ahead', and an hour is lost. dt1 = new iCalDateTime(2004, 4, 4, 1, 59, 59, tz.TZID, iCal); dt2 = new iCalDateTime(2004, 4, 4, 2, 0, 0, tz.TZID, iCal); result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(-1) + TimeSpan.FromSeconds(1), result); } /// <summary> /// Ensures the AddTimeZone() method works as expected. /// </summary> [Test] public void SystemTimeZone2() { System.TimeZoneInfo tzi = System.TimeZoneInfo.FindSystemTimeZoneById("Mountain Standard Time"); Assert.IsNotNull(tzi); iCalendar iCal = new iCalendar(); ITimeZone tz = iCal.AddTimeZone(tzi, new DateTime(2000, 1, 1), false); Assert.IsNotNull(tz); iCalendarSerializer serializer = new iCalendarSerializer(); serializer.Serialize(iCal, @"Calendars\Serialization\SystemTimeZone2.ics"); // Ensure the time zone transition works as expected // (i.e. it takes 1 hour and 1 second to transition from // 2003-10-26 1:59:59 AM to // 2003-10-26 2:00:00 AM) iCalDateTime dt1 = new iCalDateTime(2003, 10, 26, 1, 59, 59, tz.TZID, iCal); iCalDateTime dt2 = new iCalDateTime(2003, 10, 26, 2, 0, 0, tz.TZID, iCal); TimeSpan result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(1) + TimeSpan.FromSeconds(1), result); // Ensure another time zone transition works as expected // (i.e. it takes negative 59 minutes and 59 seconds to transition from // 2004-04-04 1:59:59 AM to // 2004-04-04 2:00:00 AM) dt1 = new iCalDateTime(2004, 4, 4, 1, 59, 59, tz.TZID, iCal); dt2 = new iCalDateTime(2004, 4, 4, 2, 0, 0, tz.TZID, iCal); result = dt2 - dt1; Assert.AreEqual(TimeSpan.FromHours(-1) + TimeSpan.FromSeconds(1), result); } [Test] public void SystemTimeZone3() { // Per Jon Udell's test, we should be able to get all // system time zones on the machine and ensure they // are properly translated. var zones = System.TimeZoneInfo.GetSystemTimeZones(); TimeZoneInfo tzinfo; foreach (var zone in zones) { tzinfo = null; try { tzinfo = System.TimeZoneInfo.FindSystemTimeZoneById(zone.Id); } catch (Exception e) { Assert.Fail("Not found: " + zone.StandardName); } if (tzinfo != null) { var ical_tz = DDay.iCal.iCalTimeZone.FromSystemTimeZone(tzinfo); Assert.AreNotEqual(0, ical_tz.TimeZoneInfos.Count, zone.StandardName + ": no time zone information was extracted."); } } } #endif } }
using System; using UnityEngine.Serialization; using UnityEngine.Experimental.Rendering; namespace UnityEngine.Experimental.Rendering.HDPipeline { [Serializable] public partial class InfluenceVolume { // Serialized data [SerializeField, FormerlySerializedAs("m_ShapeType")] InfluenceShape m_Shape = InfluenceShape.Box; // Box [SerializeField, FormerlySerializedAs("m_BoxBaseSize")] Vector3 m_BoxSize = Vector3.one * 10; [SerializeField, FormerlySerializedAs("m_BoxInfluencePositiveFade")] Vector3 m_BoxBlendDistancePositive; [SerializeField, FormerlySerializedAs("m_BoxInfluenceNegativeFade")] Vector3 m_BoxBlendDistanceNegative; [SerializeField, FormerlySerializedAs("m_BoxInfluenceNormalPositiveFade")] Vector3 m_BoxBlendNormalDistancePositive; [SerializeField, FormerlySerializedAs("m_BoxInfluenceNormalNegativeFade")] Vector3 m_BoxBlendNormalDistanceNegative; [SerializeField, FormerlySerializedAs("m_BoxPositiveFaceFade")] Vector3 m_BoxSideFadePositive = Vector3.one; [SerializeField, FormerlySerializedAs("m_BoxNegativeFaceFade")] Vector3 m_BoxSideFadeNegative = Vector3.one; // Sphere [SerializeField, FormerlySerializedAs("m_SphereBaseRadius")] float m_SphereRadius = 3f; [SerializeField, FormerlySerializedAs("m_SphereInfluenceFade")] float m_SphereBlendDistance; [SerializeField, FormerlySerializedAs("m_SphereInfluenceNormalFade")] float m_SphereBlendNormalDistance; // Public API /// <summary>Shape of this InfluenceVolume.</summary> public InfluenceShape shape { get => m_Shape; set => m_Shape = value; } /// <summary>Get the extents of the influence.</summary> public Vector3 extents => GetExtents(shape); /// <summary>Size of the InfluenceVolume in Box Mode.</summary> public Vector3 boxSize { get => m_BoxSize; set => m_BoxSize = value; } /// <summary>Offset of sub volume defining fading.</summary> public Vector3 boxBlendOffset => (boxBlendDistanceNegative - boxBlendDistancePositive) * 0.5f; /// <summary>Size of sub volume defining fading.</summary> public Vector3 boxBlendSize => -(boxBlendDistancePositive + boxBlendDistanceNegative); /// <summary> /// Position of fade sub volume maxOffset point relative to InfluenceVolume max corner. /// Values between 0 (on InfluenceVolume hull) to half of boxSize corresponding axis. /// </summary> public Vector3 boxBlendDistancePositive { get => m_BoxBlendDistancePositive; set => m_BoxBlendDistancePositive = value; } /// <summary> /// Position of fade sub volume minOffset point relative to InfluenceVolume min corner. /// Values between 0 (on InfluenceVolume hull) to half of boxSize corresponding axis. /// </summary> public Vector3 boxBlendDistanceNegative { get => m_BoxBlendDistanceNegative; set => m_BoxBlendDistanceNegative = value; } /// <summary>Offset of sub volume defining fading relative to normal orientation.</summary> public Vector3 boxBlendNormalOffset => (boxBlendNormalDistanceNegative - boxBlendNormalDistancePositive) * 0.5f; /// <summary>Size of sub volume defining fading relative to normal orientation.</summary> public Vector3 boxBlendNormalSize => -(boxBlendNormalDistancePositive + boxBlendNormalDistanceNegative); /// <summary> /// Position of normal fade sub volume maxOffset point relative to InfluenceVolume max corner. /// Values between 0 (on InfluenceVolume hull) to half of boxSize corresponding axis (on origin for this axis). /// </summary> public Vector3 boxBlendNormalDistancePositive { get => m_BoxBlendNormalDistancePositive; set => m_BoxBlendNormalDistancePositive = value; } /// <summary> /// Position of normal fade sub volume minOffset point relative to InfluenceVolume min corner. /// Values between 0 (on InfluenceVolume hull) to half of boxSize corresponding axis (on origin for this axis). /// </summary> public Vector3 boxBlendNormalDistanceNegative { get => m_BoxBlendNormalDistanceNegative; set => m_BoxBlendNormalDistanceNegative = value; } /// <summary>Define fading percent of +X, +Y and +Z locally oriented face. (values from 0 to 1)</summary> public Vector3 boxSideFadePositive { get => m_BoxSideFadePositive; set => m_BoxSideFadePositive = value; } /// <summary>Define fading percent of -X, -Y and -Z locally oriented face. (values from 0 to 1)</summary> public Vector3 boxSideFadeNegative { get => m_BoxSideFadeNegative; set => m_BoxSideFadeNegative = value; } /// <summary>Radius of the InfluenceVolume in Sphere Mode.</summary> public float sphereRadius { get => m_SphereRadius; set => m_SphereRadius = value; } /// <summary> /// Offset of the fade sub volume from InfluenceVolume hull. /// Value between 0 (on InfluenceVolume hull) and sphereRadius (fade sub volume reduced to a point). /// </summary> public float sphereBlendDistance { get => m_SphereBlendDistance; set => m_SphereBlendDistance = value; } /// <summary> /// Offset of the normal fade sub volume from InfluenceVolume hull. /// Value between 0 (on InfluenceVolume hull) and sphereRadius (fade sub volume reduced to a point). /// </summary> public float sphereBlendNormalDistance { get => m_SphereBlendNormalDistance; set => m_SphereBlendNormalDistance = value; } /// <summary>Compute a hash of the influence properties.</summary> /// <returns></returns> public Hash128 ComputeHash() { var h = new Hash128(); var h2 = new Hash128(); HashUtilities.ComputeHash128(ref m_Shape, ref h); HashUtilities.ComputeHash128(ref m_ObsoleteOffset, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxBlendDistanceNegative, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxBlendDistancePositive, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxBlendNormalDistanceNegative, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxBlendNormalDistancePositive, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxSideFadeNegative, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxSideFadePositive, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_BoxSize, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_SphereBlendDistance, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_SphereBlendNormalDistance, ref h2); HashUtilities.AppendHash(ref h2, ref h); HashUtilities.ComputeHash128(ref m_SphereRadius, ref h2); HashUtilities.AppendHash(ref h2, ref h); return h; } internal BoundingSphere GetBoundingSphereAt(Vector3 position) { switch (shape) { default: case InfluenceShape.Sphere: return new BoundingSphere(position, sphereRadius); case InfluenceShape.Box: { var radius = Mathf.Max(boxSize.x, Mathf.Max(boxSize.y, boxSize.z)); return new BoundingSphere(position, radius); } } } internal Bounds GetBoundsAt(Vector3 position) { switch (shape) { default: case InfluenceShape.Sphere: return new Bounds(position, Vector3.one * sphereRadius); case InfluenceShape.Box: { return new Bounds(position, boxSize); } } } internal Matrix4x4 GetInfluenceToWorld(Transform transform) => Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); internal EnvShapeType envShape { get { switch (shape) { default: case InfluenceShape.Box: return EnvShapeType.Box; case InfluenceShape.Sphere: return EnvShapeType.Sphere; } } } internal void CopyTo(InfluenceVolume data) { //keep the m_Probe as it is used to reset the probe data.m_Shape = m_Shape; data.m_ObsoleteOffset = m_ObsoleteOffset; data.m_BoxSize = m_BoxSize; data.m_BoxBlendDistancePositive = m_BoxBlendDistancePositive; data.m_BoxBlendDistanceNegative = m_BoxBlendDistanceNegative; data.m_BoxBlendNormalDistancePositive = m_BoxBlendNormalDistancePositive; data.m_BoxBlendNormalDistanceNegative = m_BoxBlendNormalDistanceNegative; data.m_BoxSideFadePositive = m_BoxSideFadePositive; data.m_BoxSideFadeNegative = m_BoxSideFadeNegative; data.m_SphereRadius = m_SphereRadius; data.m_SphereBlendDistance = m_SphereBlendDistance; data.m_SphereBlendNormalDistance = m_SphereBlendNormalDistance; #if UNITY_EDITOR data.m_EditorAdvancedModeBlendDistancePositive = m_EditorAdvancedModeBlendDistancePositive; data.m_EditorAdvancedModeBlendDistanceNegative = m_EditorAdvancedModeBlendDistanceNegative; data.m_EditorSimplifiedModeBlendDistance = m_EditorSimplifiedModeBlendDistance; data.m_EditorAdvancedModeBlendNormalDistancePositive = m_EditorAdvancedModeBlendNormalDistancePositive; data.m_EditorAdvancedModeBlendNormalDistanceNegative = m_EditorAdvancedModeBlendNormalDistanceNegative; data.m_EditorSimplifiedModeBlendNormalDistance = m_EditorSimplifiedModeBlendNormalDistance; data.m_EditorAdvancedModeEnabled = m_EditorAdvancedModeEnabled; data.m_EditorAdvancedModeFaceFadePositive = m_EditorAdvancedModeFaceFadePositive; data.m_EditorAdvancedModeFaceFadeNegative = m_EditorAdvancedModeFaceFadeNegative; #endif } Vector3 GetExtents(InfluenceShape shape) { switch (shape) { default: case InfluenceShape.Box: return Vector3.Max(Vector3.one * 0.0001f, boxSize * 0.5f); case InfluenceShape.Sphere: return Mathf.Max(0.0001f, sphereRadius) * Vector3.one; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.NetCore.Analyzers.Composition.UnitTests { public class DoNotMixAttributesFromDifferentVersionsOfMEFTests : DiagnosticAnalyzerTestBase { private const string CSharpWellKnownAttributesDefinition = @" namespace System.Composition { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } public class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } public class ImportAttribute : System.Attribute { public ImportAttribute() { } } public class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } } [System.Composition.MetadataAttribute] public class SystemCompositionMetadataAttribute : System.Attribute { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } public class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } public class ImportAttribute : System.Attribute { public ImportAttribute() { } } public class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } } namespace System.ComponentModel.Composition { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } public class MetadataAttributeAttribute : System.Attribute { public MetadataAttributeAttribute() { } } public class ImportAttribute : System.Attribute { public ImportAttribute() { } } public class ImportingConstructorAttribute : System.Attribute { public ImportingConstructorAttribute() { } } } [System.ComponentModel.Composition.MetadataAttribute] public class SystemComponentModelCompositionMetadataAttribute : System.Attribute { } "; private const string BasicWellKnownAttributesDefinition = @" Namespace System.Composition Public Class ExportAttribute Inherits System.Attribute Public Sub New(contractType As System.Type) End Sub End Class Public Class MetadataAttributeAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportingConstructorAttribute Inherits System.Attribute Public Sub New() End Sub End Class End Namespace <System.Composition.MetadataAttribute> _ Public Class SystemCompositionMetadataAttribute Inherits System.Attribute End Class Namespace System.ComponentModel.Composition Public Class ExportAttribute Inherits System.Attribute Public Sub New(contractType As System.Type) End Sub End Class Public Class MetadataAttributeAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportAttribute Inherits System.Attribute Public Sub New() End Sub End Class Public Class ImportingConstructorAttribute Inherits System.Attribute Public Sub New() End Sub End Class End Namespace <System.ComponentModel.Composition.MetadataAttribute> _ Public Class SystemComponentModelCompositionMetadataAttribute Inherits System.Attribute End Class "; protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer(); } #region No Diagnostic Tests [Fact] public void NoDiagnosticCases_SingleMefAttribute() { VerifyCSharp(@" using System; [System.Composition.Export(typeof(C))] public class C { } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { } " + CSharpWellKnownAttributesDefinition); VerifyBasic(@" Imports System <System.Composition.Export(GetType(C))> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 End Class " + BasicWellKnownAttributesDefinition); } [Fact] public void NoDiagnosticCases_SingleMefAttributeAndValidMetadataAttribute() { VerifyCSharp(@" using System; [System.Composition.Export(typeof(C))] [SystemCompositionMetadataAttribute] public class C { } [System.ComponentModel.Composition.Export(typeof(C2))] [SystemComponentModelCompositionMetadataAttribute] public class C2 { } " + CSharpWellKnownAttributesDefinition); VerifyBasic(@" Imports System <System.Composition.Export(GetType(C))> _ <SystemCompositionMetadataAttribute> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ <SystemComponentModelCompositionMetadataAttribute> _ Public Class C2 End Class " + BasicWellKnownAttributesDefinition); } [Fact] public void NoDiagnosticCases_SingleMefAttributeAndAnotherExportAttribute() { VerifyCSharp(@" using System; [System.Composition.Export(typeof(C)), MyNamespace.Export(typeof(C))] public class C { } [System.ComponentModel.Composition.Export(typeof(C2)), MyNamespace.Export(typeof(C2))] public class C2 { } namespace MyNamespace { public class ExportAttribute : System.Attribute { public ExportAttribute(System.Type contractType){ } } } " + CSharpWellKnownAttributesDefinition); VerifyBasic(@" Imports System <System.Composition.Export(GetType(C)), MyNamespace.Export(GetType(C))> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2)), MyNamespace.Export(GetType(C2))> _ Public Class C2 End Class Namespace MyNamespace Public Class ExportAttribute Inherits System.Attribute Public Sub New(contractType As System.Type) End Sub End Class End Namespace " + BasicWellKnownAttributesDefinition); } [Fact] public void NoDiagnosticCases_SingleMefAttributeOnTypeAndValidMefAttributeOnMember() { VerifyCSharp(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.Composition.ImportingConstructor] public C([System.Composition.Import]B b) { } [System.Composition.Import] public B PropertyB { get; } } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { [System.ComponentModel.Composition.ImportingConstructor] public C2([System.ComponentModel.Composition.Import]B b) { } [System.ComponentModel.Composition.Import] public B PropertyB { get; } } " + CSharpWellKnownAttributesDefinition); VerifyBasic(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.Composition.ImportingConstructor> _ Public Sub New(<System.Composition.Import> b As B) End Sub <System.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 <System.ComponentModel.Composition.ImportingConstructor> _ Public Sub New(<System.ComponentModel.Composition.Import> b As B) End Sub <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class " + BasicWellKnownAttributesDefinition); } [Fact] public void NoDiagnosticCases_UnresolvedTypes() { VerifyCSharp(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.ComponentModel.Composition.Import] public B PropertyB { get; } } ", TestValidationMode.AllowCompileErrors); VerifyBasic(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class ", TestValidationMode.AllowCompileErrors); } [Fact] public void NoDiagnosticCases_MultiMefMetadataAttribute() { VerifyCSharp(@" using System; [System.ComponentModel.Composition.Export(typeof(C)), MyNamespace.MultiMefMetadataAttribute] public class C { } namespace MyNamespace { [System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute] public class MultiMefMetadataAttribute : System.Attribute { } } " + CSharpWellKnownAttributesDefinition); VerifyBasic(@" Imports System <System.ComponentModel.Composition.Export(GetType(C)), MyNamespace.MultiMefMetadataAttribute> _ Public Class C End Class Namespace MyNamespace <System.ComponentModel.Composition.MetadataAttribute, System.Composition.MetadataAttribute> _ Public Class MultiMefMetadataAttribute Inherits System.Attribute End Class End Namespace " + BasicWellKnownAttributesDefinition); } #endregion #region Diagnostic Tests [Fact] public void DiagnosticCases_BadMetadataAttribute() { VerifyCSharp(@" using System; [System.Composition.Export(typeof(C))] [SystemComponentModelCompositionMetadataAttribute] public class C { } [System.ComponentModel.Composition.Export(typeof(C2))] [SystemCompositionMetadataAttribute] public class C2 { } " + CSharpWellKnownAttributesDefinition, // Test0.cs(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"), // Test0.cs(11,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(11, 2, "SystemCompositionMetadataAttribute", "C2")); VerifyBasic(@" Imports System <System.Composition.Export(GetType(C))> _ <SystemComponentModelCompositionMetadataAttribute> _ Public Class C End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ <SystemCompositionMetadataAttribute> _ Public Class C2 End Class " + BasicWellKnownAttributesDefinition, // Test0.vb(5,2): warning RS0006: Attribute 'SystemComponentModelCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(5, 2, "SystemComponentModelCompositionMetadataAttribute", "C"), // Test0.vb(10,2): warning RS0006: Attribute 'SystemCompositionMetadataAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(10, 2, "SystemCompositionMetadataAttribute", "C2")); } [Fact] public void DiagnosticCases_BadMefAttributeOnMember() { VerifyCSharp(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.ComponentModel.Composition.ImportingConstructor] public C([System.Composition.Import]B b) { } [System.ComponentModel.Composition.Import] public B PropertyB { get; } } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { [System.Composition.ImportingConstructor] public C2([System.ComponentModel.Composition.Import]B b) { } [System.Composition.Import] public B PropertyB { get; } } " + CSharpWellKnownAttributesDefinition, // Test0.cs(9,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(9, 6, "ImportingConstructorAttribute", "C"), // Test0.cs(12,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(12, 6, "ImportAttribute", "C"), // Test0.cs(19,6): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(19, 6, "ImportingConstructorAttribute", "C2"), // Test0.cs(22,6): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(22, 6, "ImportAttribute", "C2") ); VerifyBasic(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.ComponentModel.Composition.ImportingConstructor> _ Public Sub New(<System.Composition.Import> b As B) End Sub <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 <System.Composition.ImportingConstructor> _ Public Sub New(<System.ComponentModel.Composition.Import> b As B) End Sub <System.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class " + BasicWellKnownAttributesDefinition, // Test0.vb(7,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(7, 3, "ImportingConstructorAttribute", "C"), // Test0.vb(11,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(11, 3, "ImportAttribute", "C"), // Test0.vb(17,3): warning RS0006: Attribute 'ImportingConstructorAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(17, 3, "ImportingConstructorAttribute", "C2"), // Test0.vb(21,3): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(21, 3, "ImportAttribute", "C2") ); } [Fact] public void DiagnosticCases_BadMefAttributeOnParameter() { VerifyCSharp(@" using System; public class B { } [System.Composition.Export(typeof(C))] public class C { [System.Composition.ImportingConstructor] public C([System.ComponentModel.Composition.Import]B b) { } [System.Composition.Import] public B PropertyB { get; } } [System.ComponentModel.Composition.Export(typeof(C2))] public class C2 { [System.ComponentModel.Composition.ImportingConstructor] public C2([System.Composition.Import]B b) { } [System.ComponentModel.Composition.Import] public B PropertyB { get; } } " + CSharpWellKnownAttributesDefinition, // Test0.cs(10,15): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetCSharpResultAt(10, 15, "ImportAttribute", "C"), // Test0.cs(20,16): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetCSharpResultAt(20, 16, "ImportAttribute", "C2")); VerifyBasic(@" Public Class B End Class <System.Composition.Export(GetType(C))> _ Public Class C <System.Composition.ImportingConstructor> _ Public Sub New(<System.ComponentModel.Composition.Import> b As B) End Sub <System.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class <System.ComponentModel.Composition.Export(GetType(C2))> _ Public Class C2 <System.ComponentModel.Composition.ImportingConstructor> _ Public Sub New(<System.Composition.Import> b As B) End Sub <System.ComponentModel.Composition.Import> _ Public ReadOnly Property PropertyB() As B End Class " + BasicWellKnownAttributesDefinition, // Test0.vb(8,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C' GetBasicResultAt(8, 18, "ImportAttribute", "C"), // Test0.vb(18,18): warning RS0006: Attribute 'ImportAttribute' comes from a different version of MEF than the export attribute on 'C2' GetBasicResultAt(18, 18, "ImportAttribute", "C2")); } #endregion private static new DiagnosticResult GetCSharpResultAt(int line, int column, string attributeName, string typeName) { var message = string.Format(MicrosoftCompositionAnalyzersResources.DoNotMixAttributesFromDifferentVersionsOfMEFMessage, attributeName, typeName); return DiagnosticAnalyzerTestBase.GetCSharpResultAt(line, column, DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer.RuleId, message); } private static new DiagnosticResult GetBasicResultAt(int line, int column, string attributeName, string typeName) { var message = string.Format(MicrosoftCompositionAnalyzersResources.DoNotMixAttributesFromDifferentVersionsOfMEFMessage, attributeName, typeName); return DiagnosticAnalyzerTestBase.GetBasicResultAt(line, column, DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer.RuleId, message); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using System.Threading; namespace Microsoft.AspNetCore.Razor.Language.Syntax { [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract partial class SyntaxNode { public SyntaxNode(GreenNode green, SyntaxNode parent, int position) { Green = green; Parent = parent; Position = position; } internal GreenNode Green { get; } public SyntaxNode Parent { get; } public int Position { get; } public int EndPosition => Position + FullWidth; public SyntaxKind Kind => Green.Kind; public int Width => Green.Width; public int FullWidth => Green.FullWidth; public int SpanStart => Position + Green.GetLeadingTriviaWidth(); public TextSpan FullSpan => new TextSpan(Position, Green.FullWidth); public TextSpan Span { get { // Start with the full span. var start = Position; var width = Green.FullWidth; // adjust for preceding trivia (avoid calling this twice, do not call Green.Width) var precedingWidth = Green.GetLeadingTriviaWidth(); start += precedingWidth; width -= precedingWidth; // adjust for following trivia width width -= Green.GetTrailingTriviaWidth(); Debug.Assert(width >= 0); return new TextSpan(start, width); } } internal int SlotCount => Green.SlotCount; public bool IsList => Green.IsList; public bool IsMissing => Green.IsMissing; public bool IsToken => Green.IsToken; public bool IsTrivia => Green.IsTrivia; public bool HasLeadingTrivia { get { return GetLeadingTrivia().Count > 0; } } public bool HasTrailingTrivia { get { return GetTrailingTrivia().Count > 0; } } public bool ContainsDiagnostics => Green.ContainsDiagnostics; public bool ContainsAnnotations => Green.ContainsAnnotations; internal string SerializedValue => SyntaxSerializer.Serialize(this); public abstract TResult Accept<TResult>(SyntaxVisitor<TResult> visitor); public abstract void Accept(SyntaxVisitor visitor); internal abstract SyntaxNode GetNodeSlot(int index); internal abstract SyntaxNode GetCachedSlot(int index); internal SyntaxNode GetRed(ref SyntaxNode field, int slot) { var result = field; if (result == null) { var green = Green.GetSlot(slot); if (green != null) { Interlocked.CompareExchange(ref field, green.CreateRed(this, GetChildPosition(slot)), null); result = field; } } return result; } // Special case of above function where slot = 0, does not need GetChildPosition internal SyntaxNode GetRedAtZero(ref SyntaxNode field) { var result = field; if (result == null) { var green = Green.GetSlot(0); if (green != null) { Interlocked.CompareExchange(ref field, green.CreateRed(this, Position), null); result = field; } } return result; } protected T GetRed<T>(ref T field, int slot) where T : SyntaxNode { var result = field; if (result == null) { var green = Green.GetSlot(slot); if (green != null) { Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, this.GetChildPosition(slot)), null); result = field; } } return result; } // special case of above function where slot = 0, does not need GetChildPosition protected T GetRedAtZero<T>(ref T field) where T : SyntaxNode { var result = field; if (result == null) { var green = Green.GetSlot(0); if (green != null) { Interlocked.CompareExchange(ref field, (T)green.CreateRed(this, Position), null); result = field; } } return result; } internal SyntaxNode GetRedElement(ref SyntaxNode element, int slot) { Debug.Assert(IsList); var result = element; if (result == null) { var green = Green.GetSlot(slot); // passing list's parent Interlocked.CompareExchange(ref element, green.CreateRed(Parent, GetChildPosition(slot)), null); result = element; } return result; } internal virtual int GetChildPosition(int index) { var offset = 0; var green = Green; while (index > 0) { index--; var prevSibling = GetCachedSlot(index); if (prevSibling != null) { return prevSibling.EndPosition + offset; } var greenChild = green.GetSlot(index); if (greenChild != null) { offset += greenChild.FullWidth; } } return Position + offset; } public virtual SyntaxTriviaList GetLeadingTrivia() { var firstToken = GetFirstToken(); return firstToken != null ? firstToken.GetLeadingTrivia() : default(SyntaxTriviaList); } public virtual SyntaxTriviaList GetTrailingTrivia() { var lastToken = GetLastToken(); return lastToken != null ? lastToken.GetTrailingTrivia() : default(SyntaxTriviaList); } internal SyntaxToken GetFirstToken() { return ((SyntaxToken)GetFirstTerminal()); } internal SyntaxList<SyntaxToken> GetTokens() { var tokens = SyntaxListBuilder<SyntaxToken>.Create(); AddTokens(this, tokens); return tokens; static void AddTokens(SyntaxNode current, SyntaxListBuilder<SyntaxToken> tokens) { if (current.SlotCount == 0 && current is SyntaxToken token) { // Token tokens.Add(token); return; } for (var i = 0; i < current.SlotCount; i++) { var child = current.GetNodeSlot(i); if (child != null) { AddTokens(child, tokens); } } } } internal SyntaxToken GetLastToken() { return ((SyntaxToken)GetLastTerminal()); } public SyntaxNode GetFirstTerminal() { var node = this; do { var foundChild = false; for (int i = 0, n = node.SlotCount; i < n; i++) { var child = node.GetNodeSlot(i); if (child != null) { node = child; foundChild = true; break; } } if (!foundChild) { return null; } } while (node.SlotCount != 0); return node == this ? this : node; } public SyntaxNode GetLastTerminal() { var node = this; do { SyntaxNode lastChild = null; for (var i = node.SlotCount - 1; i >= 0; i--) { var child = node.GetNodeSlot(i); if (child != null && child.FullWidth > 0) { lastChild = child; break; } } node = lastChild; } while (node?.SlotCount > 0); return node; } /// <summary> /// The list of child nodes of this node, where each element is a SyntaxNode instance. /// </summary> public ChildSyntaxList ChildNodes() { return new ChildSyntaxList(this); } /// <summary> /// Gets a list of ancestor nodes /// </summary> public IEnumerable<SyntaxNode> Ancestors() { return Parent? .AncestorsAndSelf() ?? Array.Empty<SyntaxNode>(); } /// <summary> /// Gets a list of ancestor nodes (including this node) /// </summary> public IEnumerable<SyntaxNode> AncestorsAndSelf() { for (var node = this; node != null; node = node.Parent) { yield return node; } } /// <summary> /// Gets the first node of type TNode that matches the predicate. /// </summary> public TNode FirstAncestorOrSelf<TNode>(Func<TNode, bool> predicate = null) where TNode : SyntaxNode { for (var node = this; node != null; node = node.Parent) { if (node is TNode tnode && (predicate == null || predicate(tnode))) { return tnode; } } return default; } /// <summary> /// Gets a list of descendant nodes in prefix document order. /// </summary> /// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param> public IEnumerable<SyntaxNode> DescendantNodes(Func<SyntaxNode, bool> descendIntoChildren = null) { return DescendantNodesImpl(FullSpan, descendIntoChildren, includeSelf: false); } /// <summary> /// Gets a list of descendant nodes (including this node) in prefix document order. /// </summary> /// <param name="descendIntoChildren">An optional function that determines if the search descends into the argument node's children.</param> public IEnumerable<SyntaxNode> DescendantNodesAndSelf(Func<SyntaxNode, bool> descendIntoChildren = null) { return DescendantNodesImpl(FullSpan, descendIntoChildren, includeSelf: true); } protected internal SyntaxNode ReplaceCore<TNode>( IEnumerable<TNode> nodes = null, Func<TNode, TNode, SyntaxNode> computeReplacementNode = null) where TNode : SyntaxNode { return SyntaxReplacer.Replace(this, nodes, computeReplacementNode); } protected internal SyntaxNode ReplaceNodeInListCore(SyntaxNode originalNode, IEnumerable<SyntaxNode> replacementNodes) { return SyntaxReplacer.ReplaceNodeInList(this, originalNode, replacementNodes); } protected internal SyntaxNode InsertNodesInListCore(SyntaxNode nodeInList, IEnumerable<SyntaxNode> nodesToInsert, bool insertBefore) { return SyntaxReplacer.InsertNodeInList(this, nodeInList, nodesToInsert, insertBefore); } public RazorDiagnostic[] GetDiagnostics() { return Green.GetDiagnostics(); } public SyntaxAnnotation[] GetAnnotations() { return Green.GetAnnotations(); } public bool IsEquivalentTo(SyntaxNode other) { if (this == other) { return true; } if (other == null) { return false; } return Green.IsEquivalentTo(other.Green); } public override string ToString() { var builder = new StringBuilder(); builder.Append(Green.ToString()); builder.AppendFormat(CultureInfo.InvariantCulture, " at {0}::{1}", Position, FullWidth); return builder.ToString(); } public virtual string ToFullString() { return Green.ToFullString(); } protected virtual string GetDebuggerDisplay() { if (IsToken) { return string.Format(CultureInfo.InvariantCulture, "{0};[{1}]", Kind, ToFullString()); } return string.Format(CultureInfo.InvariantCulture, "{0} [{1}..{2})", Kind, Position, EndPosition); } } }
using System.Collections.Concurrent; using System.Globalization; using System.Text.Json.Serialization; using Signum.Engine.Basics; using Signum.Engine.Maps; using Signum.Entities.Reflection; using Signum.Utilities.Reflection; using Signum.Entities.Basics; namespace Signum.React.Facades; public static class ReflectionServer { public static Func<object> GetContext = GetCurrentValidCulture; public static object GetCurrentValidCulture() { var ci = CultureInfo.CurrentCulture; while (ci != CultureInfo.InvariantCulture && !EntityAssemblies.Keys.Any(a => DescriptionManager.GetLocalizedAssembly(a, ci) != null)) ci = ci.Parent; return ci != CultureInfo.InvariantCulture ? ci : CultureInfo.GetCultureInfo("en"); } public static DateTimeOffset LastModified { get; private set; } = DateTimeOffset.UtcNow; public static ConcurrentDictionary<object, Dictionary<string, TypeInfoTS>> cache = new ConcurrentDictionary<object, Dictionary<string, TypeInfoTS>>(); public static Dictionary<Assembly, HashSet<string>> EntityAssemblies = null!; public static ResetLazy<Dictionary<string, Type>> TypesByName = new ResetLazy<Dictionary<string, Type>>( () => GetTypes().Where(t => typeof(ModifiableEntity).IsAssignableFrom(t) || t.IsEnum && !t.Name.EndsWith("Query") && !t.Name.EndsWith("Message")) .ToDictionaryEx(GetTypeName, "Types")); public static Dictionary<string, Func<bool>> OverrideIsNamespaceAllowed = new Dictionary<string, Func<bool>>(); public static void RegisterLike(Type type, Func<bool> allowed) { TypesByName.Reset(); EntityAssemblies.GetOrCreate(type.Assembly).Add(type.Namespace!); OverrideIsNamespaceAllowed[type.Namespace!] = allowed; } internal static void Start() { DescriptionManager.Invalidated += InvalidateCache; Schema.Current.OnMetadataInvalidated += InvalidateCache; Schema.Current.InvalidateCache += InvalidateCache; var mainTypes = Schema.Current.Tables.Keys; var mixins = mainTypes.SelectMany(t => MixinDeclarations.GetMixinDeclarations(t)); var operations = OperationLogic.RegisteredOperations.Select(o => o.FieldInfo.DeclaringType!); EntityAssemblies = mainTypes.Concat(mixins).Concat(operations).AgGroupToDictionary(t => t.Assembly, gr => gr.Select(a => a.Namespace!).ToHashSet()); } public static void InvalidateCache() { cache.Clear(); LastModified = DateTimeOffset.UtcNow; } const BindingFlags instanceFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; const BindingFlags staticFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly; public static event Func<TypeInfoTS, Type, TypeInfoTS?>? TypeExtension; static TypeInfoTS? OnTypeExtension(TypeInfoTS ti, Type t) { foreach (var a in TypeExtension.GetInvocationListTyped()) { ti = a(ti, t)!; if (ti == null) return null; } return ti; } public static event Func<MemberInfoTS, PropertyRoute, MemberInfoTS?>? PropertyRouteExtension; static MemberInfoTS? OnPropertyRouteExtension(MemberInfoTS mi, PropertyRoute m) { if (PropertyRouteExtension == null) return mi; foreach (var a in PropertyRouteExtension.GetInvocationListTyped()) { mi = a(mi, m)!; if (mi == null) return null; } return mi; } public static event Func<MemberInfoTS, FieldInfo, MemberInfoTS?>? FieldInfoExtension; static MemberInfoTS? OnFieldInfoExtension(MemberInfoTS mi, FieldInfo m) { if (FieldInfoExtension == null) return mi; foreach (var a in FieldInfoExtension.GetInvocationListTyped()) { mi = a(mi, m)!; if (mi == null) return null; } return mi; } public static event Func<OperationInfoTS, OperationInfo, Type, OperationInfoTS?>? OperationExtension; static OperationInfoTS? OnOperationExtension(OperationInfoTS oi, OperationInfo o, Type type) { if (OperationExtension == null) return oi; foreach (var a in OperationExtension.GetInvocationListTyped()) { oi = a(oi, o, type)!; if (oi == null) return null; } return oi; } public static HashSet<Type> ExcludeTypes = new HashSet<Type>(); internal static Dictionary<string, TypeInfoTS> GetTypeInfoTS() { return cache.GetOrAdd(GetContext(), ci => { var result = new Dictionary<string, TypeInfoTS>(); var allTypes = GetTypes(); allTypes = allTypes.Except(ExcludeTypes).ToList(); result.AddRange(GetEntities(allTypes), "typeInfo"); result.AddRange(GetSymbolContainers(allTypes), "typeInfo"); result.AddRange(GetEnums(allTypes), "typeInfo"); return result; }); } public static List<Type> GetTypes() { return EntityAssemblies.SelectMany(kvp => { var normalTypes = kvp.Key.GetTypes().Where(t => kvp.Value.Contains(t.Namespace!)); var usedEnums = (from type in normalTypes where typeof(ModifiableEntity).IsAssignableFrom(type) from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) let pt = (p.PropertyType.ElementType() ?? p.PropertyType).UnNullify() where pt.IsEnum && !EntityAssemblies.ContainsKey(pt.Assembly) select pt).ToList(); var importedTypes = kvp.Key.GetCustomAttributes<ImportInTypeScriptAttribute>().Where(a => kvp.Value.Contains(a.ForNamesace)).Select(a => a.Type); return normalTypes.Concat(importedTypes).Concat(usedEnums); }).Distinct().ToList(); } static MethodInfo miToString = ReflectionTools.GetMethodInfo((object o) => o.ToString()); public static Dictionary<string, TypeInfoTS> GetEntities(IEnumerable<Type> allTypes) { var models = (from type in allTypes where typeof(ModelEntity).IsAssignableFrom(type) && !type.IsAbstract select type).ToList(); var queries = QueryLogic.Queries; var schema = Schema.Current; var settings = Schema.Current.Settings; var result = (from type in TypeLogic.TypeToEntity.Keys.Concat(models) where !type.IsEnumEntity() && !type.IsGenericType &&!ReflectionServer.ExcludeTypes.Contains(type) let descOptions = LocalizedAssembly.GetDescriptionOptions(type) let allOperations = !type.IsEntity() ? null : OperationLogic.GetAllOperationInfos(type) select KeyValuePair.Create(GetTypeName(type), OnTypeExtension(new TypeInfoTS { Kind = KindOfType.Entity, FullName = type.FullName!, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, NicePluralName = descOptions.HasFlag(DescriptionOptions.PluralDescription) ? type.NicePluralName() : null, Gender = descOptions.HasFlag(DescriptionOptions.Gender) ? type.GetGender().ToString() : null, EntityKind = type.IsIEntity() ? EntityKindCache.GetEntityKind(type) : (EntityKind?)null, EntityData = type.IsIEntity() ? EntityKindCache.GetEntityData(type) : (EntityData?)null, IsLowPopulation = type.IsIEntity() ? EntityKindCache.IsLowPopulation(type) : false, IsSystemVersioned = type.IsIEntity() ? schema.Table(type).SystemVersioned != null : false, ToStringFunction = typeof(Symbol).IsAssignableFrom(type) ? null : LambdaToJavascriptConverter.ToJavascript(ExpressionCleaner.GetFieldExpansion(type, miToString)!), QueryDefined = queries.QueryDefined(type), Members = PropertyRoute.GenerateRoutes(type) .Where(pr => InTypeScript(pr)) .Select(p => { var validators = Entities.Validator.TryGetPropertyValidator(p)?.Validators; var mi = new MemberInfoTS { NiceName = p.PropertyInfo!.NiceName(), Format = p.PropertyRouteType == PropertyRouteType.FieldOrProperty ? Reflector.FormatString(p) : null, IsReadOnly = !IsId(p) && (p.PropertyInfo?.IsReadOnly() ?? false), Required = !IsId(p) && ((p.Type.IsValueType && !p.Type.IsNullable()) || (validators?.Any(v => !v.DisabledInModelBinder && (!p.Type.IsMList() ? (v is NotNullValidatorAttribute) : (v is CountIsValidatorAttribute c && c.IsGreaterThanZero))) ?? false)), Unit = UnitAttribute.GetTranslation(p.PropertyInfo?.GetCustomAttribute<UnitAttribute>()?.UnitName), Type = new TypeReferenceTS(IsId(p) ? PrimaryKey.Type(type).Nullify() : p.PropertyInfo!.PropertyType, p.Type.IsMList() ? p.Add("Item").TryGetImplementations() : p.TryGetImplementations()), IsMultiline = validators?.OfType<StringLengthValidatorAttribute>().FirstOrDefault()?.MultiLine ?? false, IsVirtualMList = p.IsVirtualMList(), MaxLength = validators?.OfType<StringLengthValidatorAttribute>().FirstOrDefault()?.Max.DefaultToNull(-1), PreserveOrder = settings.FieldAttributes(p)?.OfType<PreserveOrderAttribute>().Any() ?? false, }; return KeyValuePair.Create(p.PropertyString(), OnPropertyRouteExtension(mi, p)!); }) .Where(kvp => kvp.Value != null) .ToDictionaryEx("properties"), HasConstructorOperation = allOperations != null && allOperations.Any(oi => oi.OperationType == OperationType.Constructor), Operations = allOperations == null ? null : allOperations.Select(oi => KeyValuePair.Create(oi.OperationSymbol.Key, OnOperationExtension(new OperationInfoTS(oi), oi, type)!)).Where(kvp => kvp.Value != null).ToDictionaryEx("operations"), RequiresEntityPack = allOperations != null && allOperations.Any(oi => oi.HasCanExecute != null), }, type))) .Where(kvp => kvp.Value != null) .ToDictionaryEx("entities"); return result; } public static bool InTypeScript(PropertyRoute pr) { return (pr.Parent == null || InTypeScript(pr.Parent)) && (pr.PropertyInfo == null || (pr.PropertyInfo.GetCustomAttribute<InTypeScriptAttribute>()?.GetInTypeScript() ?? !IsExpression(pr.Parent!.Type, pr.PropertyInfo))); } private static bool IsExpression(Type type, PropertyInfo propertyInfo) { return propertyInfo.SetMethod == null && ExpressionCleaner.HasExpansions(type, propertyInfo); } static string? GetTypeNiceName(Type type) { if (type.IsModifiableEntity() && !type.IsEntity()) return type.NiceName(); return null; } public static bool IsId(PropertyRoute p) { return p.PropertyRouteType == PropertyRouteType.FieldOrProperty && p.PropertyInfo!.Name == nameof(Entity.Id) && p.Parent!.PropertyRouteType == PropertyRouteType.Root; } public static Dictionary<string, TypeInfoTS> GetEnums(IEnumerable<Type> allTypes) { var queries = QueryLogic.Queries; var result = (from type in allTypes where type.IsEnum let descOptions = LocalizedAssembly.GetDescriptionOptions(type) where descOptions != DescriptionOptions.None let kind = type.Name.EndsWith("Query") ? KindOfType.Query : type.Name.EndsWith("Message") ? KindOfType.Message : KindOfType.Enum select KeyValuePair.Create(GetTypeName(type), OnTypeExtension(new TypeInfoTS { Kind = kind, FullName = type.FullName!, NiceName = descOptions.HasFlag(DescriptionOptions.Description) ? type.NiceName() : null, Members = type.GetFields(staticFlags) .Where(fi => kind != KindOfType.Query || queries.QueryDefined(fi.GetValue(null)!)) .Select(fi => KeyValuePair.Create(fi.Name, OnFieldInfoExtension(new MemberInfoTS { NiceName = fi.NiceName(), IsIgnoredEnum = kind == KindOfType.Enum && fi.HasAttribute<IgnoreAttribute>() }, fi)!)) .Where(a=>a.Value != null) .ToDictionaryEx("query"), }, type))) .Where(a => a.Value != null) .ToDictionaryEx("enums"); return result; } public static Dictionary<string, TypeInfoTS> GetSymbolContainers(IEnumerable<Type> allTypes) { SymbolLogic.LoadAll(); var result = (from type in allTypes where type.IsStaticClass() && type.HasAttribute<AutoInitAttribute>() select KeyValuePair.Create(GetTypeName(type), OnTypeExtension(new TypeInfoTS { Kind = KindOfType.SymbolContainer, FullName = type.FullName!, Members = type.GetFields(staticFlags) .Select(f => GetSymbolInfo(f)) .Where(s => s.FieldInfo != null && /*Duplicated like in Dynamic*/ s.IdOrNull.HasValue /*Not registered*/) .Select(s => KeyValuePair.Create(s.FieldInfo.Name, OnFieldInfoExtension(new MemberInfoTS { NiceName = s.FieldInfo.NiceName(), Id = s.IdOrNull!.Value.Object }, s.FieldInfo)!)) .Where(a => a.Value != null) .ToDictionaryEx("fields"), }, type))) .Where(a => a.Value != null && a.Value.Members.Any()) .ToDictionaryEx("symbols"); return result; } private static (FieldInfo FieldInfo, PrimaryKey? IdOrNull) GetSymbolInfo(FieldInfo m) { object? v = m.GetValue(null); if (v is IOperationSymbolContainer osc) v = osc.Symbol; if (v is Symbol s) return (s.FieldInfo, s.IdOrNull); if(v is SemiSymbol semiS) return (semiS.FieldInfo!, semiS.IdOrNull); throw new InvalidOperationException(); } public static string GetTypeName(Type t) { if (typeof(ModifiableEntity).IsAssignableFrom(t)) return TypeLogic.TryGetCleanName(t) ?? t.Name; return t.Name; } } public class TypeInfoTS { public KindOfType Kind { get; set; } public string FullName { get; set; } = null!; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]public string? NiceName { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? NicePluralName { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Gender { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public EntityKind? EntityKind { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public EntityData? EntityData { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool IsLowPopulation { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool IsSystemVersioned { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? ToStringFunction { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool QueryDefined { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary<string, MemberInfoTS> Members { get; set; } = null!; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool HasConstructorOperation { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public Dictionary<string, OperationInfoTS>? Operations { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool RequiresEntityPack { get; set; } [JsonExtensionData] public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>(); public override string ToString() => $"{Kind} {NiceName} {EntityKind} {EntityData}"; } public class MemberInfoTS { [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public TypeReferenceTS? Type { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? NiceName { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool IsReadOnly { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool Required { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Unit { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? Format { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool IsIgnoredEnum { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool IsVirtualMList { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public int? MaxLength { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool IsMultiline { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool PreserveOrder { get; internal set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public object? Id { get; set; } [JsonExtensionData] public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>(); } public class OperationInfoTS { public OperationType OperationType; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]public bool? CanBeNew; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]public bool? CanBeModified; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]public bool? HasCanExecute; [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]public bool? HasStates; [JsonExtensionData] public Dictionary<string, object> Extension { get; set; } = new Dictionary<string, object>(); public OperationInfoTS(OperationInfo oper) { this.CanBeNew = oper.CanBeNew; this.CanBeModified = oper.CanBeModified; this.HasCanExecute = oper.HasCanExecute; this.HasStates = oper.HasStates; this.OperationType = oper.OperationType; } } public class TypeReferenceTS { [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]public bool IsCollection { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]public bool IsLite { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]public bool IsNotNullable { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]public bool IsEmbedded { get; set; } public string Name { get; set; } [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public string? TypeNiceName { get; set; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public TypeReferenceTS() { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public TypeReferenceTS(Type type, Implementations? implementations) { this.IsCollection = type != typeof(string) && type != typeof(byte[]) && type.ElementType() != null; var clean = type == typeof(string) ? type : (type.ElementType() ?? type); this.IsLite = clean.IsLite(); this.IsNotNullable = clean.IsValueType && !clean.IsNullable(); this.IsEmbedded = clean.IsEmbeddedEntity(); if (this.IsEmbedded && !this.IsCollection) this.TypeNiceName = type.NiceName(); if(implementations != null) { try { this.Name = implementations.Value.Key(); } catch (Exception) when (StartParameters.IgnoredCodeErrors != null) { this.Name = "ERROR"; } } else { this.Name = TypeScriptType(type); } } private static string TypeScriptType(Type type) { type = CleanMList(type); type = type.UnNullify().CleanType(); return BasicType(type) ?? ReflectionServer.GetTypeName(type) ?? "any"; } private static Type CleanMList(Type type) { if (type.IsMList()) type = type.ElementType()!; return type; } public static string? BasicType(Type type) { if (type.IsEnum) return null; switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "boolean"; case TypeCode.Char: return "string"; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return "number"; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return "decimal"; case TypeCode.DateTime: return "datetime"; case TypeCode.String: return "string"; } return null; } } public enum KindOfType { Entity, Enum, Message, Query, SymbolContainer, }
using System; using System.Collections.Generic; using System.Linq; using GetSocialSdk.Core; using GetSocialSdk.Ui; using UnityEngine; public class ActivitiesSection : BaseListSection<ActivitiesQuery, Activity> { public ActivitiesQuery Query; public bool Comments; private bool _isTrending = false; public bool ShowFilter = true; protected override string GetSectionName() { return "Activities"; } protected override void Load(PagingQuery<ActivitiesQuery> query, Action<PagingResult<Activity>> success, Action<GetSocialError> error) { Communities.GetActivities(query, success, error); } protected override void Count(ActivitiesQuery query, Action<int> success, Action<GetSocialError> error) { // Not supported } protected override bool HasQuery() { return false; } protected override void DrawItem(Activity item) { GUILayout.Label(item.Author.DisplayName, GSStyles.BigLabelText); GUILayout.Label(item.Text, GSStyles.NormalLabelText); if (item.Button != null) { DemoGuiUtils.DrawButton(item.Button.Title, () => { _console.LogD("Handling: " + item.Button.ToString()); GetSocial.Handle(item.Button.Action); }, style: GSStyles.Button); } GUILayout.Label("Created at: " + DateUtils.FromUnixTime(item.CreatedAt).ToShortDateString(), GSStyles.NormalLabelText); GUILayout.Label("Popularity: " + item.Popularity, GSStyles.NormalLabelText); DemoGuiUtils.DrawButton("Actions", () => ShowActions(item), style:GSStyles.Button); } private void ShowActions(Activity activity) { var popup = Dialog().WithTitle("Actions"); popup.AddAction("Info", () => _console.LogD(activity.ToString())); if (!activity.Author.IsApp) { popup.AddAction("Author", () => ShowActions(activity.Author)); } popup.AddAction("Details View", () => Details(activity)); if (activity.Source.IsActionAllowed(CommunitiesAction.React)) { popup.AddAction("React", () => React(activity)); } popup.AddAction("Reactions", () => ListReactions(activity)); if (!Comments) { popup.AddAction("Comments", () => ShowComments(activity)); if (activity.Source.IsActionAllowed(CommunitiesAction.Comment)) { popup.AddAction("Post Comment", () => PostComment(activity)); } } if (activity.Author.Id.Equals(GetSocial.GetCurrentUser().Id)) { popup.AddAction("Edit", () => Edit(activity)); popup.AddAction("Remove", () => Remove(activity)); } else { if (!activity.Author.IsApp) { popup.AddAction("Report as Spam", () => Report(activity, ReportingReason.Spam, "This activity is spam!")); popup.AddAction("Report as Inappropriate", () => Report(activity, ReportingReason.InappropriateContent, "This activity is inappropriate!")); } } popup.AddAction("Cancel", () => { }); popup.Show(); } private void PostComment(Activity activity) { demoController.PushMenuSection<PostActivitySection>(section => { section.Target = PostActivityTarget.Comment(activity.Id); }); } private void Report(Activity activity, ReportingReason reason, string explanation) { Communities.ReportActivity(activity.Id, reason, explanation, () => _console.LogD("Activity reported"), error => _console.LogE("Failed to report: " + error.Message)); } private void Edit(Activity activity) { demoController.PushMenuSection<PostActivitySection>(section => { section.SetActivity(activity); section.Target = PostActivityTarget.Topic(Query.Ids.Ids.ToArray()[0]); }); } private void Remove(Activity activity) { List<string> list = new List<string>(); list.Add(activity.Id); var query = RemoveActivitiesQuery.ActivityIds(list); Communities.RemoveActivities(query, () => { var index = _items.FindIndex(item => item == activity); _items.RemoveAt(index); _console.LogD("Activity removed"); }, error => _console.LogE("Failed to remove: " + error.Message)); } private void Details(Activity activity) { ActivityDetailsViewBuilder.Create(activity.Id) .SetViewStateCallbacks(() => _console.LogD("Feed opened"), () => _console.LogD("Feed closed")) .SetActionListener(OnAction) .SetMentionClickListener(OnMentionClicked) .SetAvatarClickListener(OnUserAvatarClicked) .SetTagClickListener(OnTagClicked) .SetUiActionListener(OnUiAction) .Show(); } private void ShowComments(Activity activity) { demoController.PushMenuSection<ActivitiesSection>(section => { section.Comments = true; section.ShowFilter = false; section.Query = ActivitiesQuery.CommentsToActivity(activity.Id); }); } private void ListReactions(Activity activity) { demoController.PushMenuSection<ReactionsListSection>(section => { section.Activity = activity; }); } private void React(Activity activity) { var popup = Dialog().WithTitle("Actions"); var reactions = new List<string> { Reactions.Like, Reactions.Angry, Reactions.Haha, Reactions.Love, Reactions.Sad, Reactions.Wow }; foreach (var reaction in reactions) { popup.AddAction(reaction, () => { Communities.AddReaction(reaction, activity.Id, () => { Refresh(activity); _console.LogD("Reacted to activity", false); }, error => _console.LogE(error.ToString())); }); } if (activity.MyReactions.Count > 0) { popup.AddAction("Delete Reaction", () => { Communities.RemoveReaction(activity.MyReactions.First(), activity.Id, () => { Refresh(activity); _console.LogD("Reacted to activity", false); }, error => _console.LogE(error.ToString())); }); } popup.AddAction("Cancel", () => { }); popup.Show(); } protected override void DrawHeader() { if (this.ShowFilter) { GUILayout.BeginHorizontal(); DemoGuiUtils.DrawButton(_isTrending ? "All" : "Only Trending", () => { _isTrending = !_isTrending; Reload(); }, style: GSStyles.Button); DemoGuiUtils.Space(); GUILayout.EndHorizontal(); } } private void Refresh(Activity activity) { Communities.GetActivity(activity.Id, refreshed => { _items[_items.FindIndex(item => item == activity)] = refreshed; }, error => _console.LogE(error.ToString())); } protected override ActivitiesQuery CreateQuery(string query) { Query = Query.OnlyTrending(_isTrending); return Query; } private void OnMentionClicked(string mention) { if (mention.Equals(MentionTypes.App)) { _console.LogD("Application mention clicked."); return; } Communities.GetUser(UserId.Create(mention), OnUserAvatarClicked, error => _console.LogE("Failed to get user details, error:" + error.Message)); } private void OnTagClicked(string tag) { GetSocialUi.CloseView(); demoController.PushMenuSection<ActivitiesSection>(section => { section.Query = ActivitiesQuery.Everywhere().WithTag(tag); }); } private void OnUserAvatarClicked(User publicUser) { if (GetSocial.GetCurrentUser().Id.Equals(publicUser.Id)) { var popup = new MNPopup ("Action", "Choose Action"); popup.AddAction("Show My Feed", () => OpenUserGlobalFeed(publicUser)); popup.AddAction("Cancel", () => { }); popup.Show(); } else { Communities.IsFriend(UserId.Create(publicUser.Id), isFriend => { if (isFriend) { var popup = new MNPopup ("Action", "Choose Action"); popup.AddAction("Show " + publicUser.DisplayName + " Feed", () => OpenUserGlobalFeed(publicUser)); popup.AddAction("Remove from Friends", () => RemoveFriend(publicUser)); popup.AddAction("Cancel", () => { }); popup.Show(); } else { var popup = new MNPopup ("Action", "Choose Action"); popup.AddAction("Show " + publicUser.DisplayName + " Feed", () => OpenUserGlobalFeed(publicUser)); popup.AddAction("Add to Friends", () => AddFriend(publicUser)); popup.AddAction("Cancel", () => { }); popup.Show(); } }, error => _console.LogE("Failed to check if friends with " + publicUser.DisplayName + ", error:" + error.Message)); } } private void AddFriend(User user) { Communities.AddFriends(UserIdList.Create(user.Id), friendsCount => { var message = user.DisplayName + " is now your friend."; _console.LogD(message); }, error => _console.LogE("Failed to add a friend " + user.DisplayName + ", error:" + error.Message)); } private void RemoveFriend(User user) { Communities.RemoveFriends(UserIdList.Create(user.Id), friendsCount => { var message = user.DisplayName + " is not your friend anymore."; _console.LogD(message); }, error => _console.LogE("Failed to remove a friend " + user.DisplayName + ", error:" + error.Message)); } private void OnUiAction(UiAction action, Action pendingAction) { var forbiddenForAnonymous = new List<UiAction>() { UiAction.LikeActivity, UiAction.LikeComment, UiAction.PostActivity, UiAction.PostComment }; if (forbiddenForAnonymous.Contains(action) && GetSocial.GetCurrentUser().IsAnonymous) { var message = "Action " + action + " is not allowed for anonymous."; _console.LogD(message); } else { pendingAction(); } } void OnAction(GetSocialAction action) { demoController.HandleAction(action); } private void OpenUserGlobalFeed(User user) { ActivityFeedViewBuilder.Create(ActivitiesQuery.FeedOf(UserId.Create(user.Id))) .SetWindowTitle("Feed of " + user.DisplayName) .SetViewStateCallbacks(() => _console.LogD("Feed opened"), () => _console.LogD("Feed closed")) .SetActionListener(OnAction) .SetMentionClickListener(OnMentionClicked) .SetAvatarClickListener(OnUserAvatarClicked) .SetTagClickListener(OnTagClicked) .SetUiActionListener(OnUiAction) .Show(); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ColumnConverter.cs" company="Microsoft Corporation"> // Copyright (c) Microsoft Corporation. // </copyright> // <summary> // Contains methods to set and get data from the ESENT database. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace FabricTableService.Journal.Database { using System; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text; using Microsoft.Isam.Esent.Interop; /// <summary> /// Contains methods to set and get data from the ESENT /// database. /// </summary> internal class ColumnConverter { /// <summary> /// A mapping of types to SetColumn functions. /// </summary> private static readonly IDictionary<Type, SetColumnDelegate> SetColumnDelegates = new Dictionary<Type, SetColumnDelegate> { { typeof(byte[]), (s, t, c, o) => Api.SetColumn(s, t, c, (byte[])o) }, { typeof(bool), (s, t, c, o) => Api.SetColumn(s, t, c, (bool)o) }, { typeof(byte), (s, t, c, o) => Api.SetColumn(s, t, c, (byte)o) }, { typeof(short), (s, t, c, o) => Api.SetColumn(s, t, c, (short)o) }, { typeof(ushort), (s, t, c, o) => Api.SetColumn(s, t, c, (ushort)o) }, { typeof(int), (s, t, c, o) => Api.SetColumn(s, t, c, (int)o) }, { typeof(uint), (s, t, c, o) => Api.SetColumn(s, t, c, (uint)o) }, { typeof(long), (s, t, c, o) => Api.SetColumn(s, t, c, (long)o) }, { typeof(ulong), (s, t, c, o) => Api.SetColumn(s, t, c, (ulong)o) }, { typeof(float), (s, t, c, o) => Api.SetColumn(s, t, c, (float)o) }, { typeof(double), (s, t, c, o) => Api.SetColumn(s, t, c, (double)o) }, { typeof(DateTime), (s, t, c, o) => Api.SetColumn(s, t, c, ((DateTime)o).Ticks) }, { typeof(TimeSpan), (s, t, c, o) => Api.SetColumn(s, t, c, ((TimeSpan)o).Ticks) }, { typeof(Guid), (s, t, c, o) => Api.SetColumn(s, t, c, (Guid)o) }, { typeof(string), (s, t, c, o) => Api.SetColumn(s, t, c, (string)o, Encoding.Unicode) }, }; /// <summary> /// A mapping of types to RetrieveColumn functions. /// </summary> private static readonly IDictionary<Type, RetrieveColumnDelegate> RetrieveColumnDelegates = new Dictionary<Type, RetrieveColumnDelegate> { { typeof(byte[]), Api.RetrieveColumn }, { typeof(bool), (s, t, c) => Api.RetrieveColumnAsBoolean(s, t, c) }, { typeof(byte), (s, t, c) => Api.RetrieveColumnAsByte(s, t, c) }, { typeof(short), (s, t, c) => Api.RetrieveColumnAsInt16(s, t, c) }, { typeof(ushort), (s, t, c) => Api.RetrieveColumnAsUInt16(s, t, c) }, { typeof(int), (s, t, c) => Api.RetrieveColumnAsInt32(s, t, c) }, { typeof(uint), (s, t, c) => Api.RetrieveColumnAsUInt32(s, t, c) }, { typeof(long), (s, t, c) => Api.RetrieveColumnAsInt64(s, t, c) }, { typeof(ulong), (s, t, c) => Api.RetrieveColumnAsUInt64(s, t, c) }, { typeof(float), (s, t, c) => Api.RetrieveColumnAsFloat(s, t, c) }, { typeof(double), (s, t, c) => Api.RetrieveColumnAsDouble(s, t, c) }, { typeof(Guid), (s, t, c) => Api.RetrieveColumnAsGuid(s, t, c) }, { typeof(string), (s, t, c) => Api.RetrieveColumnAsString(s, t, c, Encoding.Unicode) }, { typeof(DateTime), (s, t, c) => RetrieveDateTime(s, t, c) }, { typeof(TimeSpan), (s, t, c) => RetrieveTimeSpan(s, t, c) }, }; /// <summary> /// A mapping of types to ESENT column types. /// </summary> private static readonly IDictionary<Type, JET_coltyp> Coltyps = new Dictionary<Type, JET_coltyp> { { typeof(bool), JET_coltyp.Bit }, { typeof(byte), JET_coltyp.UnsignedByte }, { typeof(short), JET_coltyp.Short }, { typeof(ushort), JET_coltyp.Binary }, { typeof(byte[]), JET_coltyp.Binary }, { typeof(int), JET_coltyp.Long }, { typeof(uint), JET_coltyp.Binary }, { typeof(long), JET_coltyp.Currency }, { typeof(ulong), JET_coltyp.Binary }, { typeof(float), JET_coltyp.IEEESingle }, { typeof(double), JET_coltyp.IEEEDouble }, { typeof(DateTime), JET_coltyp.Currency }, { typeof(TimeSpan), JET_coltyp.Currency }, { typeof(Guid), JET_coltyp.Binary }, { typeof(string), JET_coltyp.LongText }, }; /// <summary> /// Initializes static members of the ColumnConverter class. This sets up /// the conversion ditionaries. /// </summary> static ColumnConverter() { AddNullableDelegates<bool>(); AddNullableDelegates<byte>(); AddNullableDelegates<short>(); AddNullableDelegates<ushort>(); AddNullableDelegates<int>(); AddNullableDelegates<uint>(); AddNullableDelegates<long>(); AddNullableDelegates<ulong>(); AddNullableDelegates<float>(); AddNullableDelegates<double>(); AddNullableDelegates<DateTime>(); AddNullableDelegates<TimeSpan>(); AddNullableDelegates<Guid>(); } /// <summary> /// Initializes a new instance of the ColumnConverter class. /// </summary> /// <param name="type">The type to convert to/from.</param> public ColumnConverter(Type type) { if (null == type) { throw new ArgumentNullException(nameof(type)); } SetColumnDelegate setColumnDelegate; if (!SetColumnDelegates.TryGetValue(type, out setColumnDelegate)) { if (!IsSerializable(type)) { throw new ArgumentOutOfRangeException(nameof(type), type, "Not supported for SetColumn"); } this.SetColumn = Api.SerializeObjectToColumn; } else { this.SetColumn = setColumnDelegate; } RetrieveColumnDelegate getColumnDelegate; if (!RetrieveColumnDelegates.TryGetValue(type, out getColumnDelegate)) { if (!IsSerializable(type)) { throw new ArgumentOutOfRangeException(nameof(type), type, "Not supported for RetrieveColumn"); } this.RetrieveColumn = Api.DeserializeObjectFromColumn; } else { this.RetrieveColumn = getColumnDelegate; } JET_coltyp value; if (!Coltyps.TryGetValue(type, out value)) { if (!IsSerializable(type)) { throw new ArgumentOutOfRangeException(nameof(type), type, "Has no matching ESENT column type"); } this.Coltyp = JET_coltyp.LongBinary; } else { this.Coltyp = value; } } /// <summary> /// Represents a SetColumn operation. /// </summary> /// <param name="sesid">The session to use.</param> /// <param name="tableid">The cursor to set the value in. An update should be prepared.</param> /// <param name="columnid">The column to set.</param> /// <param name="value">The value to set.</param> public delegate void SetColumnDelegate(JET_SESID sesid, JET_TABLEID tableid, JET_COLUMNID columnid, object value); /// <summary> /// Represents a RetrieveColumn operation. /// </summary> /// <param name="sesid">The session to use.</param> /// <param name="tableid">The cursor to retrieve the value from.</param> /// <param name="columnid">The column to retrieve.</param> /// <returns>The retrieved value.</returns> public delegate object RetrieveColumnDelegate(JET_SESID sesid, JET_TABLEID tableid, JET_COLUMNID columnid); /// <summary> /// Gets the type of database column the value should be stored in. /// </summary> public JET_coltyp Coltyp { get; } /// <summary> /// Gets a delegate that can be used to set the Key column with an object of /// type <see cref="Type"/>. /// </summary> public SetColumnDelegate SetColumn { get; } /// <summary> /// Gets a delegate that can be used to retrieve the Key column, returning /// type <see cref="Type"/>. /// </summary> public RetrieveColumnDelegate RetrieveColumn { get; } /// <summary> /// Determine if the given type is a serializable structure. /// </summary> /// <param name="type">The type to check.</param> /// <returns> /// True if the type (and the types it contains) are all serializable structures. /// </returns> private static bool IsSerializable(Type type) { // Strings are fine (they are immutable) if (typeof(string) == type) { return true; } // Immutable serializable classes from .NET framework. if (typeof(Uri) == type || typeof(IPAddress) == type) { return true; } // A primitive serializable type is fine if (type.IsPrimitive && type.IsSerializable) { return true; } // If this isn't a serializable struct, the type definitely isn't serializable if (!(type.IsValueType && type.IsSerializable)) { return false; } // This is a serializable struct. Recursively check that all members are serializable. // Unlike classes, structs cannot have cycles in their definitions so a simple enumeration // will work. foreach (var member in type.GetMembers(BindingFlags.NonPublic | BindingFlags.Instance)) { if (member.MemberType == MemberTypes.Field) { var fieldinfo = (FieldInfo)member; if (!IsSerializable(fieldinfo.FieldType)) { return false; } } } return true; } /// <summary> /// Generate nullable MakeKey/SetKey delegates for the type. /// </summary> /// <typeparam name="T">The (non-nullable) type to add delegates for.</typeparam> private static void AddNullableDelegates<T>() where T : struct { AddNullableSetColumn<T>(); // Retrieve column already returns a nullable object. RetrieveColumnDelegates[typeof(T?)] = RetrieveColumnDelegates[typeof(T)]; // All ESENT columns are nullable Coltyps[typeof(T?)] = Coltyps[typeof(T)]; } /// <summary> /// Adds a SetColumn delegate that takes a nullable version of the specified type /// to the <see cref="SetColumnDelegates"/> object. /// </summary> /// <typeparam name="T">The type to add the delegate for.</typeparam> private static void AddNullableSetColumn<T>() where T : struct { SetColumnDelegates[typeof(T?)] = MakeNullableSetColumn<T>(SetColumnDelegates[typeof(T)]); } /// <summary> /// Creates a delegate which takes a nullable object and wraps the /// non-nullable SetColumn method. /// </summary> /// <typeparam name="T">The type that will be nullable.</typeparam> /// <param name="wrappedSetColumn">The (non-nullable) delegrate to wrap.</param> /// <returns> /// A SetColumnDelegate that takes a Nullable<typeparamref name="T"/> and /// either sets the column to null or calls the wrapped delegate. /// </returns> private static SetColumnDelegate MakeNullableSetColumn<T>(SetColumnDelegate wrappedSetColumn) where T : struct { return (s, t, c, o) => { if (((T?)o).HasValue) { wrappedSetColumn(s, t, c, o); } else { Api.SetColumn(s, t, c, null); } }; } /// <summary> /// Retrieve a nullable date time. We do not use Api.RetrieveColumnAsDateTime because /// that stores the value in OADate format, which is less accurate than System.DateTime. /// Instead we store a DateTime as its Tick value in an Int64 column. /// </summary> /// <param name="sesid">The session to use.</param> /// <param name="tableid">The table to retrieve the value from.</param> /// <param name="columnid">The column containing the value.</param> /// <returns>A nullable DateTime constructed from the column.</returns> private static DateTime? RetrieveDateTime(JET_SESID sesid, JET_TABLEID tableid, JET_COLUMNID columnid) { var ticks = Api.RetrieveColumnAsInt64(sesid, tableid, columnid); if (ticks.HasValue) { return new DateTime(ticks.Value); } return null; } /// <summary> /// Retrieve a nullable TimeSpan. /// </summary> /// <param name="sesid">The session to use.</param> /// <param name="tableid">The table to retrieve the value from.</param> /// <param name="columnid">The column containing the value.</param> /// <returns>A nullable TimeSpan constructed from the column.</returns> private static TimeSpan? RetrieveTimeSpan(JET_SESID sesid, JET_TABLEID tableid, JET_COLUMNID columnid) { var ticks = Api.RetrieveColumnAsInt64(sesid, tableid, columnid); if (ticks.HasValue) { return new TimeSpan(ticks.Value); } return 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. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // RuntimeHelpers // This class defines a set of static methods that provide support for compilers. // using Internal.Reflection.Augments; using Internal.Reflection.Core.NonPortable; using Internal.Runtime.Augments; using System.Runtime; using System.Runtime.Serialization; using System.Threading; namespace System.Runtime.CompilerServices { public static class RuntimeHelpers { [Intrinsic] public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle); public static void RunClassConstructor(RuntimeTypeHandle type) { if (type.IsNull) throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized); IntPtr pStaticClassConstructionContext = RuntimeAugments.Callbacks.TryGetStaticClassConstructionContext(type); if (pStaticClassConstructionContext == IntPtr.Zero) return; unsafe { ClassConstructorRunner.EnsureClassConstructorRun((StaticClassConstructionContext*)pStaticClassConstructionContext); } } public static void RunModuleConstructor(ModuleHandle module) { if (module.AssociatedModule == null) throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized); ReflectionAugments.ReflectionCoreCallbacks.RunModuleConstructor(module.AssociatedModule); } public static Object GetObjectValue(Object obj) { if (obj == null) return null; EETypePtr eeType = obj.EETypePtr; if ((!eeType.IsValueType) || eeType.IsPrimitive) return obj; return RuntimeImports.RhMemberwiseClone(obj); } public new static bool Equals(Object obj1, Object obj2) { if (obj1 == obj2) return true; if ((obj1 == null) || (obj2 == null)) return false; // If it's not a value class, don't compare by value if (!obj1.EETypePtr.IsValueType) return false; // Make sure they are the same type. if (obj1.EETypePtr != obj2.EETypePtr) return false; return RuntimeImports.RhCompareObjectContentsAndPadding(obj1, obj2); } #if !FEATURE_SYNCTABLE private const int HASHCODE_BITS = 26; private const int MASK_HASHCODE = (1 << HASHCODE_BITS) - 1; #endif [ThreadStatic] private static int t_hashSeed; internal static int GetNewHashCode() { int multiplier = Environment.CurrentManagedThreadId * 4 + 5; // Every thread has its own generator for hash codes so that we won't get into a situation // where two threads consistently give out the same hash codes. // Choice of multiplier guarantees period of 2**32 - see Knuth Vol 2 p16 (3.2.1.2 Theorem A). t_hashSeed = t_hashSeed * multiplier + 1; return t_hashSeed; } public static unsafe int GetHashCode(Object o) { #if FEATURE_SYNCTABLE return ObjectHeader.GetHashCode(o); #else if (o == null) return 0; fixed (IntPtr* pEEType = &o.m_pEEType) { int* pSyncBlockIndex = (int*)((byte*)pEEType - 4); // skipping exactly 4 bytes for the SyncTableEntry (exactly 4 bytes not a pointer size). int hash = *pSyncBlockIndex & MASK_HASHCODE; if (hash == 0) return MakeHashCode(o, pSyncBlockIndex); else return hash; } #endif } #if !FEATURE_SYNCTABLE private static unsafe int MakeHashCode(Object o, int* pSyncBlockIndex) { int hash = GetNewHashCode() & MASK_HASHCODE; if (hash == 0) hash = 1; while (true) { int oldIndex = Volatile.Read(ref *pSyncBlockIndex); int currentHash = oldIndex & MASK_HASHCODE; if (currentHash != 0) { // Someone else set the hash code. hash = currentHash; break; } int newIndex = oldIndex | hash; if (Interlocked.CompareExchange(ref *pSyncBlockIndex, newIndex, oldIndex) == oldIndex) break; // If we get here someone else modified the header. They may have set the hash code, or maybe some // other bits. Let's try again. } return hash; } #endif public static int OffsetToStringData { get { // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. // This property allows C#'s fixed statement to work on Strings. return String.FIRST_CHAR_OFFSET; } } [ThreadStatic] private static unsafe byte* t_sufficientStackLimit; public static unsafe void EnsureSufficientExecutionStack() { byte* limit = t_sufficientStackLimit; if (limit == null) limit = GetSufficientStackLimit(); byte* currentStackPtr = (byte*)(&limit); if (currentStackPtr < limit) throw new InsufficientExecutionStackException(); } public static unsafe bool TryEnsureSufficientExecutionStack() { byte* limit = t_sufficientStackLimit; if (limit == null) limit = GetSufficientStackLimit(); byte* currentStackPtr = (byte*)(&limit); return (currentStackPtr >= limit); } [MethodImpl(MethodImplOptions.NoInlining)] // Only called once per thread, no point in inlining. private static unsafe byte* GetSufficientStackLimit() { IntPtr lower, upper; RuntimeImports.RhGetCurrentThreadStackBounds(out lower, out upper); // Compute the limit used by EnsureSufficientExecutionStack and cache it on the thread. This minimum // stack size should be sufficient to allow a typical non-recursive call chain to execute, including // potential exception handling and garbage collection. #if BIT64 const int MinExecutionStackSize = 128 * 1024; #else const int MinExecutionStackSize = 64 * 1024; #endif byte* limit = (((byte*)upper - (byte*)lower > MinExecutionStackSize)) ? ((byte*)lower + MinExecutionStackSize) : ((byte*)upper); return (t_sufficientStackLimit = limit); } [Intrinsic] public static bool IsReferenceOrContainsReferences<T>() { var pEEType = EETypePtr.EETypePtrOf<T>(); return !pEEType.IsValueType || pEEType.HasPointers; } // Constrained Execution Regions APIs are NOP's because we do not support CERs in .NET Core at all. public static void ProbeForSufficientStack() { } public static void PrepareConstrainedRegions() { } public static void PrepareConstrainedRegionsNoOP() { } public static void PrepareMethod(RuntimeMethodHandle method) { } public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { } public static void PrepareContractedDelegate(Delegate d) { } public static void PrepareDelegate(Delegate d) { if (d == null) throw new ArgumentNullException(nameof(d)); } public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) { if (code == null) throw new ArgumentNullException(nameof(code)); if (backoutCode == null) throw new ArgumentNullException(nameof(backoutCode)); bool exceptionThrown = false; try { code(userData); } catch { exceptionThrown = true; throw; } finally { backoutCode(userData, exceptionThrown); } } public delegate void TryCode(Object userData); public delegate void CleanupCode(Object userData, bool exceptionThrown); public static object GetUninitializedObject(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type), SR.ArgumentNull_Type); } if(!type.IsRuntimeImplemented()) { throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type.ToString())); } if (type.IsArray || type.IsByRef || type.IsPointer) { throw new ArgumentException(SR.Argument_InvalidValue); } if (type.ContainsGenericParameters) { throw new MemberAccessException(SR.Acc_CreateGeneric); } if (type.IsCOMObject) { throw new NotSupportedException(SR.NotSupported_ManagedActivation); } EETypePtr eeTypePtr = type.TypeHandle.ToEETypePtr(); if (eeTypePtr == EETypePtr.EETypePtrOf<string>()) { throw new ArgumentException(SR.Argument_NoUninitializedStrings); } if (eeTypePtr.IsAbstract) { throw new MemberAccessException(SR.Acc_CreateAbst); } if (eeTypePtr.IsByRefLike) { throw new NotSupportedException(SR.NotSupported_ByRefLike); } if (eeTypePtr.IsNullable) { return GetUninitializedObject(ReflectionCoreNonPortable.GetRuntimeTypeForEEType(eeTypePtr.NullableType)); } // Triggering the .cctor here is slightly different than desktop/CoreCLR, which // decide based on BeforeFieldInit, but we don't want to include BeforeFieldInit // in EEType just for this API to behave slightly differently. RunClassConstructor(type.TypeHandle); return RuntimeImports.RhNewObject(eeTypePtr); } } }
using System; using System.Linq; using System.Web.Security; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Core.Security; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Web.Security.Providers; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class MemberServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); //hack! but we have no choice until we remove the SavePassword method from IMemberService var providerMock = new Mock<MembersMembershipProvider>(ServiceContext.MemberService) { CallBase = true }; providerMock.Setup(@base => @base.AllowManuallyChangingPassword).Returns(false); providerMock.Setup(@base => @base.PasswordFormat).Returns(MembershipPasswordFormat.Hashed); var provider = providerMock.Object; ((MemberService)ServiceContext.MemberService).MembershipProvider = provider; } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Can_Set_Password_On_New_Member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); //this will construct a member without a password var member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "test"); ServiceContext.MemberService.Save(member); Assert.IsTrue(member.RawPasswordValue.StartsWith(Constants.Security.EmptyPasswordPrefix)); ServiceContext.MemberService.SavePassword(member, "hello123456$!"); var foundMember = ServiceContext.MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreNotEqual("hello123456$!", foundMember.RawPasswordValue); Assert.IsFalse(member.RawPasswordValue.StartsWith(Constants.Security.EmptyPasswordPrefix)); } [Test] public void Can_Not_Set_Password_On_Existing_Member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); //this will construct a member with a password var member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "hello123456$!", "test"); ServiceContext.MemberService.Save(member); Assert.IsFalse(member.RawPasswordValue.StartsWith(Constants.Security.EmptyPasswordPrefix)); Assert.Throws<NotSupportedException>(() => ServiceContext.MemberService.SavePassword(member, "HELLO123456$!")); } [Test] public void Can_Create_Member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.AreNotEqual(0, member.Id); var foundMember = ServiceContext.MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreEqual("test@test.com", foundMember.Email); } [Test] public void Can_Create_Member_With_Long_TLD_In_Email() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.marketing", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.AreNotEqual(0, member.Id); var foundMember = ServiceContext.MemberService.GetById(member.Id); Assert.IsNotNull(foundMember); Assert.AreEqual("test@test.marketing", foundMember.Email); } [Test] public void Can_Create_Role() { ServiceContext.MemberService.AddRole("MyTestRole"); var found = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); } [Test] public void Can_Create_Duplicate_Role() { ServiceContext.MemberService.AddRole("MyTestRole"); ServiceContext.MemberService.AddRole("MyTestRole"); var found = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(1, found.Count()); Assert.AreEqual("MyTestRole", found.Single()); } [Test] public void Can_Get_All_Roles() { ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AddRole("MyTestRole2"); ServiceContext.MemberService.AddRole("MyTestRole3"); var found = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(3, found.Count()); } [Test] public void Can_Get_All_Roles_By_Member_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AddRole("MyTestRole2"); ServiceContext.MemberService.AddRole("MyTestRole3"); ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); var memberRoles = ServiceContext.MemberService.GetAllRoles(member.Id); Assert.AreEqual(2, memberRoles.Count()); } [Test] public void Can_Get_All_Roles_By_Member_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); //need to test with '@' symbol in the lookup IMember member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AddRole("MyTestRole2"); ServiceContext.MemberService.AddRole("MyTestRole3"); ServiceContext.MemberService.AssignRoles(new[] { member.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); var memberRoles = ServiceContext.MemberService.GetAllRoles("test"); Assert.AreEqual(2, memberRoles.Count()); var memberRoles2 = ServiceContext.MemberService.GetAllRoles("test2@test.com"); Assert.AreEqual(2, memberRoles2.Count()); } [Test] public void Can_Delete_Role() { ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.DeleteRole("MyTestRole1", false); var memberRoles = ServiceContext.MemberService.GetAllRoles(); Assert.AreEqual(0, memberRoles.Count()); } [Test] public void Throws_When_Deleting_Assigned_Role() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); ServiceContext.MemberService.AddRole("MyTestRole1"); ServiceContext.MemberService.AssignRoles(new[] { member.Id }, new[] { "MyTestRole1", "MyTestRole2" }); Assert.Throws<InvalidOperationException>(() => ServiceContext.MemberService.DeleteRole("MyTestRole1", true)); } [Test] public void Can_Get_Members_In_Role() { ServiceContext.MemberService.AddRole("MyTestRole1"); var roleId = DatabaseContext.Database.ExecuteScalar<int>("SELECT id from umbracoNode where [text] = 'MyTestRole1'"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); DatabaseContext.Database.Insert(new Member2MemberGroupDto {MemberGroup = roleId, Member = member1.Id}); DatabaseContext.Database.Insert(new Member2MemberGroupDto { MemberGroup = roleId, Member = member2.Id }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Cannot_Save_Member_With_Empty_Name() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, string.Empty, "test@test.com", "pass", "test"); // Act & Assert Assert.Throws<ArgumentException>(() => ServiceContext.MemberService.Save(member)); } [TestCase("MyTestRole1", "test1", StringPropertyMatchType.StartsWith, 1)] [TestCase("MyTestRole1", "test", StringPropertyMatchType.StartsWith, 3)] [TestCase("MyTestRole1", "test1", StringPropertyMatchType.Exact, 1)] [TestCase("MyTestRole1", "test", StringPropertyMatchType.Exact, 0)] [TestCase("MyTestRole1", "st2", StringPropertyMatchType.EndsWith, 1)] [TestCase("MyTestRole1", "test%", StringPropertyMatchType.Wildcard, 3)] public void Find_Members_In_Role(string roleName1, string usernameToMatch, StringPropertyMatchType matchType, int resultCount) { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); var member3 = MockedMember.CreateSimpleMember(memberType, "test3", "test3@test.com", "pass", "test3"); ServiceContext.MemberService.Save(member3); ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id, member3.Id }, new[] { roleName1 }); var result = ServiceContext.MemberService.FindMembersInRole(roleName1, usernameToMatch, matchType); Assert.AreEqual(resultCount, result.Count()); } [Test] public void Associate_Members_To_Roles_With_Member_Id() { ServiceContext.MemberService.AddRole("MyTestRole1"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); // temp make sure they exist Assert.IsNotNull(ServiceContext.MemberService.GetById(member1.Id)); Assert.IsNotNull(ServiceContext.MemberService.GetById(member2.Id)); ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Associate_Members_To_Roles_With_Member_Username() { ServiceContext.MemberService.AddRole("MyTestRole1"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Associate_Members_To_Roles_With_Member_Username_Containing_At_Symbols() { ServiceContext.MemberService.AddRole("MyTestRole1"); IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1@test.com"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2@test.com"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Associate_Members_To_Roles_With_New_Role() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); //implicitly create the role ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(2, membersInRole.Count()); } [Test] public void Remove_Members_From_Roles_With_Member_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole1", "MyTestRole2" }); ServiceContext.MemberService.DissociateRoles(new[] {member1.Id }, new[] {"MyTestRole1"}); ServiceContext.MemberService.DissociateRoles(new[] { member1.Id, member2.Id }, new[] { "MyTestRole2" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); } [Test] public void Remove_Members_From_Roles_With_Member_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member1 = MockedMember.CreateSimpleMember(memberType, "test1", "test1@test.com", "pass", "test1"); ServiceContext.MemberService.Save(member1); var member2 = MockedMember.CreateSimpleMember(memberType, "test2", "test2@test.com", "pass", "test2"); ServiceContext.MemberService.Save(member2); ServiceContext.MemberService.AssignRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole1", "MyTestRole2" }); ServiceContext.MemberService.DissociateRoles(new[] { member1.Username }, new[] { "MyTestRole1" }); ServiceContext.MemberService.DissociateRoles(new[] { member1.Username, member2.Username }, new[] { "MyTestRole2" }); var membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole1"); Assert.AreEqual(1, membersInRole.Count()); membersInRole = ServiceContext.MemberService.GetMembersInRole("MyTestRole2"); Assert.AreEqual(0, membersInRole.Count()); } [Test] public void Can_Delete_member() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); ServiceContext.MemberService.Delete(member); var deleted = ServiceContext.MemberService.GetById(member.Id); // Assert Assert.That(deleted, Is.Null); } [Test] public void ContentXml_Created_When_Saved() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = member.Id }); Assert.IsNotNull(xml); } [Test] public void Exists_By_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); IMember member2 = MockedMember.CreateSimpleMember(memberType, "test", "test2@test.com", "pass", "test2@test.com"); ServiceContext.MemberService.Save(member2); Assert.IsTrue(ServiceContext.MemberService.Exists("test")); Assert.IsFalse(ServiceContext.MemberService.Exists("notFound")); Assert.IsTrue(ServiceContext.MemberService.Exists("test2@test.com")); } [Test] public void Exists_By_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsTrue(ServiceContext.MemberService.Exists(member.Id)); Assert.IsFalse(ServiceContext.MemberService.Exists(9876)); } [Test] public void Tracks_Dirty_Changes() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); var resolved = ServiceContext.MemberService.GetByEmail(member.Email); //NOTE: This will not trigger a property isDirty because this is not based on a 'Property', it is // just a c# property of the Member object resolved.Email = "changed@test.com"; //NOTE: this WILL trigger a property isDirty because setting this c# property actually sets a value of // the underlying 'Property' resolved.FailedPasswordAttempts = 1234; var dirtyMember = (ICanBeDirty)resolved; var dirtyProperties = resolved.Properties.Where(x => x.IsDirty()).ToList(); Assert.IsTrue(dirtyMember.IsDirty()); Assert.AreEqual(1, dirtyProperties.Count()); } [Test] public void Get_By_Email() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsNotNull(ServiceContext.MemberService.GetByEmail(member.Email)); Assert.IsNull(ServiceContext.MemberService.GetByEmail("do@not.find")); } [Test] public void Get_Member_Name() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "Test Real Name", "test@test.com", "pass", "testUsername"); ServiceContext.MemberService.Save(member); Assert.AreEqual("Test Real Name", member.Name); } [Test] public void Get_Member_Name_In_Created_Event() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); TypedEventHandler<IMemberService, NewEventArgs<IMember>> callback = (sender, args) => { Assert.AreEqual("Test Real Name", args.Entity.Name); }; MemberService.Created += callback; var member = ServiceContext.MemberService.CreateMember("testUsername", "test@test.com", "Test Real Name", memberType); MemberService.Created -= callback; } [Test] public void Get_By_Username() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsNotNull(ServiceContext.MemberService.GetByUsername(member.Username)); Assert.IsNull(ServiceContext.MemberService.GetByUsername("notFound")); } [Test] public void Get_By_Object_Id() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); IMember member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "pass", "test"); ServiceContext.MemberService.Save(member); Assert.IsNotNull(ServiceContext.MemberService.GetById(member.Id)); Assert.IsNull(ServiceContext.MemberService.GetById(9876)); } [Test] public void Get_All_Paged_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); int totalRecs; var found = ServiceContext.MemberService.GetAll(0, 2, out totalRecs); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); Assert.AreEqual("test0", found.First().Username); Assert.AreEqual("test1", found.Last().Username); } [Test] public void Get_All_Paged_Members_With_Filter() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); long totalRecs; var found = ServiceContext.MemberService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, true, null, "Member No-"); Assert.AreEqual(2, found.Count()); Assert.AreEqual(10, totalRecs); Assert.AreEqual("test0", found.First().Username); Assert.AreEqual("test1", found.Last().Username); found = ServiceContext.MemberService.GetAll(0, 2, out totalRecs, "username", Direction.Ascending, true, null, "Member No-5"); Assert.AreEqual(1, found.Count()); Assert.AreEqual(1, totalRecs); Assert.AreEqual("test5", found.First().Username); } [Test] public void Find_By_Name_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "Bob", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindMembersByDisplayName("B", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(1, found.Count()); } [Test] public void Find_By_Email_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //don't find this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello","hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Find_By_Email_Ends_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("test.com", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Email_Contains() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Email_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByEmail("hello@test.com", 0, 100, out totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Find_By_Login_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //don't find this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("tes", 0, 100, out totalRecs, StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Find_By_Login_Ends_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("llo", 0, 100, out totalRecs, StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); } [Test] public void Find_By_Login_Contains() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hellotest"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("test", 0, 100, out totalRecs, StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Find_By_Login_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); //include this var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); int totalRecs; var found = ServiceContext.MemberService.FindByUsername("hello", 0, 100, out totalRecs, StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Get_By_Property_String_Value_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", "hello member", StringPropertyMatchType.Exact); Assert.AreEqual(1, found.Count()); } [Test] public void Get_By_Property_String_Value_Contains() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", " member", StringPropertyMatchType.Contains); Assert.AreEqual(11, found.Count()); } [Test] public void Get_By_Property_String_Value_Starts_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", "Member No", StringPropertyMatchType.StartsWith); Assert.AreEqual(10, found.Count()); } [Test] public void Get_By_Property_String_Value_Ends_With() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("title", "title of mine"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "title", "mine", StringPropertyMatchType.EndsWith); Assert.AreEqual(1, found.Count()); } [Test] public void Get_By_Property_Int_Value_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "number") { Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 2); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 2, ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); } [Test] public void Get_By_Property_Int_Value_Greater_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "number") { Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); } [Test] public void Get_By_Property_Int_Value_Greater_Than_Equal_To() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "number") { Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 10); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 3, ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); } [Test] public void Get_By_Property_Int_Value_Less_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.DateAlias, DataTypeDatabaseType.Date, "number") { Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); } [Test] public void Get_By_Property_Int_Value_Less_Than_Or_Equal() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "number") { Name = "Number", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -51 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("number", i)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("number", 1); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "number", 5, ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); } [Test] public void Get_By_Property_Date_Value_Exact() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "date") { Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 2, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 2, 0), ValuePropertyMatchType.Exact); Assert.AreEqual(2, found.Count()); } [Test] public void Get_By_Property_Date_Value_Greater_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "date") { Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThan); Assert.AreEqual(7, found.Count()); } [Test] public void Get_By_Property_Date_Value_Greater_Than_Equal_To() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "date") { Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 10, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 3, 0), ValuePropertyMatchType.GreaterThanOrEqualTo); Assert.AreEqual(8, found.Count()); } [Test] public void Get_By_Property_Date_Value_Less_Than() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "date") { Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThan); Assert.AreEqual(6, found.Count()); } [Test] public void Get_By_Property_Date_Value_Less_Than_Or_Equal() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.AddPropertyType(new PropertyType(Constants.PropertyEditors.IntegerAlias, DataTypeDatabaseType.Integer, "date") { Name = "Date", //NOTE: This is what really determines the db type - the above definition doesn't really do anything DataTypeDefinitionId = -36 }, "Content"); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.SetValue("date", new DateTime(2013, 12, 20, 1, i, 0))); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue("date", new DateTime(2013, 12, 20, 1, 1, 0)); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetMembersByPropertyValue( "date", new DateTime(2013, 12, 20, 1, 5, 0), ValuePropertyMatchType.LessThanOrEqualTo); Assert.AreEqual(7, found.Count()); } [Test] public void Count_All_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.All); Assert.AreEqual(11, found); } [Test] public void Count_All_Online_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.LastLoginDate = DateTime.Now.AddMinutes(i * -2)); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.LastLoginDate, DateTime.Now); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.Online); Assert.AreEqual(9, found); } [Test] public void Count_All_Locked_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.IsLockedOut = i % 2 == 0); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsLockedOut, true); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.LockedOut); Assert.AreEqual(6, found); } [Test] public void Count_All_Approved_Members() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var members = MockedMember.CreateSimpleMember(memberType, 10, (i, member) => member.IsApproved = i % 2 == 0); ServiceContext.MemberService.Save(members); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); customMember.SetValue(Constants.Conventions.Member.IsApproved, false); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetCount(MemberCountType.Approved); Assert.AreEqual(5, found); } [Test] public void Setting_Property_On_Built_In_Member_Property_When_Property_Doesnt_Exist_On_Type_Is_Ok() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); memberType.RemovePropertyType(Constants.Conventions.Member.Comments); ServiceContext.MemberTypeService.Save(memberType); Assert.IsFalse(memberType.PropertyTypes.Any(x => x.Alias == Constants.Conventions.Member.Comments)); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); //this should not throw an exception customMember.Comments = "hello world"; ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetById(customMember.Id); Assert.IsTrue(found.Comments.IsNullOrWhiteSpace()); } /// <summary> /// Because we are forcing some of the built-ins to be Labels which have an underlying db type as nvarchar but we need /// to ensure that the dates/int get saved to the correct column anyways. /// </summary> [Test] public void Setting_DateTime_Property_On_Built_In_Member_Property_Saves_To_Correct_Column() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var member = MockedMember.CreateSimpleMember(memberType, "test", "test@test.com", "test", "test"); var date = DateTime.Now; member.LastLoginDate = DateTime.Now; ServiceContext.MemberService.Save(member); var result = ServiceContext.MemberService.GetById(member.Id); Assert.AreEqual( date.TruncateTo(DateTimeExtensions.DateTruncate.Second), result.LastLoginDate.TruncateTo(DateTimeExtensions.DateTruncate.Second)); //now ensure the col is correct var sql = new Sql().Select("cmsPropertyData.*") .From<PropertyDataDto>() .InnerJoin<PropertyTypeDto>() .On<PropertyDataDto, PropertyTypeDto>(dto => dto.PropertyTypeId, dto => dto.Id) .Where<PropertyDataDto>(dto => dto.NodeId == member.Id) .Where<PropertyTypeDto>(dto => dto.Alias == Constants.Conventions.Member.LastLoginDate); var colResult = DatabaseContext.Database.Fetch<PropertyDataDto>(sql); Assert.AreEqual(1, colResult.Count); Assert.IsTrue(colResult.First().Date.HasValue); Assert.IsFalse(colResult.First().Integer.HasValue); Assert.IsNull(colResult.First().Text); Assert.IsNull(colResult.First().VarChar); } [Test] public void New_Member_Approved_By_Default() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var found = ServiceContext.MemberService.GetById(customMember.Id); Assert.IsTrue(found.IsApproved); } [Test] public void Ensure_Content_Xml_Created() { IMemberType memberType = MockedContentTypes.CreateSimpleMemberType(); ServiceContext.MemberTypeService.Save(memberType); var customMember = MockedMember.CreateSimpleMember(memberType, "hello", "hello@test.com", "hello", "hello"); ServiceContext.MemberService.Save(customMember); var provider = new PetaPocoUnitOfWorkProvider(Logger); using (var uow = provider.GetUnitOfWork()) { Assert.IsTrue(uow.Database.Exists<ContentXmlDto>(customMember.Id)); } } } }
// Copyright (C) 2014 dot42 // // Original filename: Javax.Microedition.Khronos.Egl.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Javax.Microedition.Khronos.Egl { /// <java-name> /// javax/microedition/khronos/egl/EGL /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL", AccessFlags = 1537)] public partial interface IEGL /* scope: __dot42__ */ { } /// <java-name> /// javax/microedition/khronos/egl/EGLContext /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLContext", AccessFlags = 1057)] public abstract partial class EGLContext /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLContext() /* MethodBuilder.Create */ { } /// <java-name> /// getEGL /// </java-name> [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] public static global::Javax.Microedition.Khronos.Egl.IEGL GetEGL() /* MethodBuilder.Create */ { return default(global::Javax.Microedition.Khronos.Egl.IEGL); } /// <java-name> /// getGL /// </java-name> [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] public abstract global::Javax.Microedition.Khronos.Opengles.IGL GetGL() /* MethodBuilder.Create */ ; /// <java-name> /// getEGL /// </java-name> public static global::Javax.Microedition.Khronos.Egl.IEGL EGL { [Dot42.DexImport("getEGL", "()Ljavax/microedition/khronos/egl/EGL;", AccessFlags = 9)] get{ return GetEGL(); } } /// <java-name> /// getGL /// </java-name> public global::Javax.Microedition.Khronos.Opengles.IGL GL { [Dot42.DexImport("getGL", "()Ljavax/microedition/khronos/opengles/GL;", AccessFlags = 1025)] get{ return GetGL(); } } } /// <java-name> /// javax/microedition/khronos/egl/EGLSurface /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLSurface", AccessFlags = 1057)] public abstract partial class EGLSurface /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLSurface() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL11Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_CONTEXT_LOST /// </java-name> [Dot42.DexImport("EGL_CONTEXT_LOST", "I", AccessFlags = 25)] public const int EGL_CONTEXT_LOST = 12302; } /// <java-name> /// javax/microedition/khronos/egl/EGL11 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL11", AccessFlags = 1537)] public partial interface IEGL11 : global::Javax.Microedition.Khronos.Egl.IEGL10 /* scope: __dot42__ */ { } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IEGL10Constants /* scope: __dot42__ */ { /// <java-name> /// EGL_SUCCESS /// </java-name> [Dot42.DexImport("EGL_SUCCESS", "I", AccessFlags = 25)] public const int EGL_SUCCESS = 12288; /// <java-name> /// EGL_NOT_INITIALIZED /// </java-name> [Dot42.DexImport("EGL_NOT_INITIALIZED", "I", AccessFlags = 25)] public const int EGL_NOT_INITIALIZED = 12289; /// <java-name> /// EGL_BAD_ACCESS /// </java-name> [Dot42.DexImport("EGL_BAD_ACCESS", "I", AccessFlags = 25)] public const int EGL_BAD_ACCESS = 12290; /// <java-name> /// EGL_BAD_ALLOC /// </java-name> [Dot42.DexImport("EGL_BAD_ALLOC", "I", AccessFlags = 25)] public const int EGL_BAD_ALLOC = 12291; /// <java-name> /// EGL_BAD_ATTRIBUTE /// </java-name> [Dot42.DexImport("EGL_BAD_ATTRIBUTE", "I", AccessFlags = 25)] public const int EGL_BAD_ATTRIBUTE = 12292; /// <java-name> /// EGL_BAD_CONFIG /// </java-name> [Dot42.DexImport("EGL_BAD_CONFIG", "I", AccessFlags = 25)] public const int EGL_BAD_CONFIG = 12293; /// <java-name> /// EGL_BAD_CONTEXT /// </java-name> [Dot42.DexImport("EGL_BAD_CONTEXT", "I", AccessFlags = 25)] public const int EGL_BAD_CONTEXT = 12294; /// <java-name> /// EGL_BAD_CURRENT_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_CURRENT_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_CURRENT_SURFACE = 12295; /// <java-name> /// EGL_BAD_DISPLAY /// </java-name> [Dot42.DexImport("EGL_BAD_DISPLAY", "I", AccessFlags = 25)] public const int EGL_BAD_DISPLAY = 12296; /// <java-name> /// EGL_BAD_MATCH /// </java-name> [Dot42.DexImport("EGL_BAD_MATCH", "I", AccessFlags = 25)] public const int EGL_BAD_MATCH = 12297; /// <java-name> /// EGL_BAD_NATIVE_PIXMAP /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_PIXMAP", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_PIXMAP = 12298; /// <java-name> /// EGL_BAD_NATIVE_WINDOW /// </java-name> [Dot42.DexImport("EGL_BAD_NATIVE_WINDOW", "I", AccessFlags = 25)] public const int EGL_BAD_NATIVE_WINDOW = 12299; /// <java-name> /// EGL_BAD_PARAMETER /// </java-name> [Dot42.DexImport("EGL_BAD_PARAMETER", "I", AccessFlags = 25)] public const int EGL_BAD_PARAMETER = 12300; /// <java-name> /// EGL_BAD_SURFACE /// </java-name> [Dot42.DexImport("EGL_BAD_SURFACE", "I", AccessFlags = 25)] public const int EGL_BAD_SURFACE = 12301; /// <java-name> /// EGL_BUFFER_SIZE /// </java-name> [Dot42.DexImport("EGL_BUFFER_SIZE", "I", AccessFlags = 25)] public const int EGL_BUFFER_SIZE = 12320; /// <java-name> /// EGL_ALPHA_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_SIZE = 12321; /// <java-name> /// EGL_BLUE_SIZE /// </java-name> [Dot42.DexImport("EGL_BLUE_SIZE", "I", AccessFlags = 25)] public const int EGL_BLUE_SIZE = 12322; /// <java-name> /// EGL_GREEN_SIZE /// </java-name> [Dot42.DexImport("EGL_GREEN_SIZE", "I", AccessFlags = 25)] public const int EGL_GREEN_SIZE = 12323; /// <java-name> /// EGL_RED_SIZE /// </java-name> [Dot42.DexImport("EGL_RED_SIZE", "I", AccessFlags = 25)] public const int EGL_RED_SIZE = 12324; /// <java-name> /// EGL_DEPTH_SIZE /// </java-name> [Dot42.DexImport("EGL_DEPTH_SIZE", "I", AccessFlags = 25)] public const int EGL_DEPTH_SIZE = 12325; /// <java-name> /// EGL_STENCIL_SIZE /// </java-name> [Dot42.DexImport("EGL_STENCIL_SIZE", "I", AccessFlags = 25)] public const int EGL_STENCIL_SIZE = 12326; /// <java-name> /// EGL_CONFIG_CAVEAT /// </java-name> [Dot42.DexImport("EGL_CONFIG_CAVEAT", "I", AccessFlags = 25)] public const int EGL_CONFIG_CAVEAT = 12327; /// <java-name> /// EGL_CONFIG_ID /// </java-name> [Dot42.DexImport("EGL_CONFIG_ID", "I", AccessFlags = 25)] public const int EGL_CONFIG_ID = 12328; /// <java-name> /// EGL_LEVEL /// </java-name> [Dot42.DexImport("EGL_LEVEL", "I", AccessFlags = 25)] public const int EGL_LEVEL = 12329; /// <java-name> /// EGL_MAX_PBUFFER_HEIGHT /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_HEIGHT", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_HEIGHT = 12330; /// <java-name> /// EGL_MAX_PBUFFER_PIXELS /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_PIXELS", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_PIXELS = 12331; /// <java-name> /// EGL_MAX_PBUFFER_WIDTH /// </java-name> [Dot42.DexImport("EGL_MAX_PBUFFER_WIDTH", "I", AccessFlags = 25)] public const int EGL_MAX_PBUFFER_WIDTH = 12332; /// <java-name> /// EGL_NATIVE_RENDERABLE /// </java-name> [Dot42.DexImport("EGL_NATIVE_RENDERABLE", "I", AccessFlags = 25)] public const int EGL_NATIVE_RENDERABLE = 12333; /// <java-name> /// EGL_NATIVE_VISUAL_ID /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_ID", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_ID = 12334; /// <java-name> /// EGL_NATIVE_VISUAL_TYPE /// </java-name> [Dot42.DexImport("EGL_NATIVE_VISUAL_TYPE", "I", AccessFlags = 25)] public const int EGL_NATIVE_VISUAL_TYPE = 12335; /// <java-name> /// EGL_SAMPLES /// </java-name> [Dot42.DexImport("EGL_SAMPLES", "I", AccessFlags = 25)] public const int EGL_SAMPLES = 12337; /// <java-name> /// EGL_SAMPLE_BUFFERS /// </java-name> [Dot42.DexImport("EGL_SAMPLE_BUFFERS", "I", AccessFlags = 25)] public const int EGL_SAMPLE_BUFFERS = 12338; /// <java-name> /// EGL_SURFACE_TYPE /// </java-name> [Dot42.DexImport("EGL_SURFACE_TYPE", "I", AccessFlags = 25)] public const int EGL_SURFACE_TYPE = 12339; /// <java-name> /// EGL_TRANSPARENT_TYPE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_TYPE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_TYPE = 12340; /// <java-name> /// EGL_TRANSPARENT_BLUE_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_BLUE_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_BLUE_VALUE = 12341; /// <java-name> /// EGL_TRANSPARENT_GREEN_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_GREEN_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_GREEN_VALUE = 12342; /// <java-name> /// EGL_TRANSPARENT_RED_VALUE /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RED_VALUE", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RED_VALUE = 12343; /// <java-name> /// EGL_NONE /// </java-name> [Dot42.DexImport("EGL_NONE", "I", AccessFlags = 25)] public const int EGL_NONE = 12344; /// <java-name> /// EGL_LUMINANCE_SIZE /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_SIZE", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_SIZE = 12349; /// <java-name> /// EGL_ALPHA_MASK_SIZE /// </java-name> [Dot42.DexImport("EGL_ALPHA_MASK_SIZE", "I", AccessFlags = 25)] public const int EGL_ALPHA_MASK_SIZE = 12350; /// <java-name> /// EGL_COLOR_BUFFER_TYPE /// </java-name> [Dot42.DexImport("EGL_COLOR_BUFFER_TYPE", "I", AccessFlags = 25)] public const int EGL_COLOR_BUFFER_TYPE = 12351; /// <java-name> /// EGL_RENDERABLE_TYPE /// </java-name> [Dot42.DexImport("EGL_RENDERABLE_TYPE", "I", AccessFlags = 25)] public const int EGL_RENDERABLE_TYPE = 12352; /// <java-name> /// EGL_SLOW_CONFIG /// </java-name> [Dot42.DexImport("EGL_SLOW_CONFIG", "I", AccessFlags = 25)] public const int EGL_SLOW_CONFIG = 12368; /// <java-name> /// EGL_NON_CONFORMANT_CONFIG /// </java-name> [Dot42.DexImport("EGL_NON_CONFORMANT_CONFIG", "I", AccessFlags = 25)] public const int EGL_NON_CONFORMANT_CONFIG = 12369; /// <java-name> /// EGL_TRANSPARENT_RGB /// </java-name> [Dot42.DexImport("EGL_TRANSPARENT_RGB", "I", AccessFlags = 25)] public const int EGL_TRANSPARENT_RGB = 12370; /// <java-name> /// EGL_RGB_BUFFER /// </java-name> [Dot42.DexImport("EGL_RGB_BUFFER", "I", AccessFlags = 25)] public const int EGL_RGB_BUFFER = 12430; /// <java-name> /// EGL_LUMINANCE_BUFFER /// </java-name> [Dot42.DexImport("EGL_LUMINANCE_BUFFER", "I", AccessFlags = 25)] public const int EGL_LUMINANCE_BUFFER = 12431; /// <java-name> /// EGL_VENDOR /// </java-name> [Dot42.DexImport("EGL_VENDOR", "I", AccessFlags = 25)] public const int EGL_VENDOR = 12371; /// <java-name> /// EGL_VERSION /// </java-name> [Dot42.DexImport("EGL_VERSION", "I", AccessFlags = 25)] public const int EGL_VERSION = 12372; /// <java-name> /// EGL_EXTENSIONS /// </java-name> [Dot42.DexImport("EGL_EXTENSIONS", "I", AccessFlags = 25)] public const int EGL_EXTENSIONS = 12373; /// <java-name> /// EGL_HEIGHT /// </java-name> [Dot42.DexImport("EGL_HEIGHT", "I", AccessFlags = 25)] public const int EGL_HEIGHT = 12374; /// <java-name> /// EGL_WIDTH /// </java-name> [Dot42.DexImport("EGL_WIDTH", "I", AccessFlags = 25)] public const int EGL_WIDTH = 12375; /// <java-name> /// EGL_LARGEST_PBUFFER /// </java-name> [Dot42.DexImport("EGL_LARGEST_PBUFFER", "I", AccessFlags = 25)] public const int EGL_LARGEST_PBUFFER = 12376; /// <java-name> /// EGL_RENDER_BUFFER /// </java-name> [Dot42.DexImport("EGL_RENDER_BUFFER", "I", AccessFlags = 25)] public const int EGL_RENDER_BUFFER = 12422; /// <java-name> /// EGL_COLORSPACE /// </java-name> [Dot42.DexImport("EGL_COLORSPACE", "I", AccessFlags = 25)] public const int EGL_COLORSPACE = 12423; /// <java-name> /// EGL_ALPHA_FORMAT /// </java-name> [Dot42.DexImport("EGL_ALPHA_FORMAT", "I", AccessFlags = 25)] public const int EGL_ALPHA_FORMAT = 12424; /// <java-name> /// EGL_HORIZONTAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_HORIZONTAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_HORIZONTAL_RESOLUTION = 12432; /// <java-name> /// EGL_VERTICAL_RESOLUTION /// </java-name> [Dot42.DexImport("EGL_VERTICAL_RESOLUTION", "I", AccessFlags = 25)] public const int EGL_VERTICAL_RESOLUTION = 12433; /// <java-name> /// EGL_PIXEL_ASPECT_RATIO /// </java-name> [Dot42.DexImport("EGL_PIXEL_ASPECT_RATIO", "I", AccessFlags = 25)] public const int EGL_PIXEL_ASPECT_RATIO = 12434; /// <java-name> /// EGL_SINGLE_BUFFER /// </java-name> [Dot42.DexImport("EGL_SINGLE_BUFFER", "I", AccessFlags = 25)] public const int EGL_SINGLE_BUFFER = 12421; /// <java-name> /// EGL_CORE_NATIVE_ENGINE /// </java-name> [Dot42.DexImport("EGL_CORE_NATIVE_ENGINE", "I", AccessFlags = 25)] public const int EGL_CORE_NATIVE_ENGINE = 12379; /// <java-name> /// EGL_DRAW /// </java-name> [Dot42.DexImport("EGL_DRAW", "I", AccessFlags = 25)] public const int EGL_DRAW = 12377; /// <java-name> /// EGL_READ /// </java-name> [Dot42.DexImport("EGL_READ", "I", AccessFlags = 25)] public const int EGL_READ = 12378; /// <java-name> /// EGL_DONT_CARE /// </java-name> [Dot42.DexImport("EGL_DONT_CARE", "I", AccessFlags = 25)] public const int EGL_DONT_CARE = -1; /// <java-name> /// EGL_PBUFFER_BIT /// </java-name> [Dot42.DexImport("EGL_PBUFFER_BIT", "I", AccessFlags = 25)] public const int EGL_PBUFFER_BIT = 1; /// <java-name> /// EGL_PIXMAP_BIT /// </java-name> [Dot42.DexImport("EGL_PIXMAP_BIT", "I", AccessFlags = 25)] public const int EGL_PIXMAP_BIT = 2; /// <java-name> /// EGL_WINDOW_BIT /// </java-name> [Dot42.DexImport("EGL_WINDOW_BIT", "I", AccessFlags = 25)] public const int EGL_WINDOW_BIT = 4; /// <java-name> /// EGL_DEFAULT_DISPLAY /// </java-name> [Dot42.DexImport("EGL_DEFAULT_DISPLAY", "Ljava/lang/Object;", AccessFlags = 25)] public static readonly object EGL_DEFAULT_DISPLAY; /// <java-name> /// EGL_NO_DISPLAY /// </java-name> [Dot42.DexImport("EGL_NO_DISPLAY", "Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLDisplay EGL_NO_DISPLAY; /// <java-name> /// EGL_NO_CONTEXT /// </java-name> [Dot42.DexImport("EGL_NO_CONTEXT", "Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLContext EGL_NO_CONTEXT; /// <java-name> /// EGL_NO_SURFACE /// </java-name> [Dot42.DexImport("EGL_NO_SURFACE", "Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 25)] public static readonly global::Javax.Microedition.Khronos.Egl.EGLSurface EGL_NO_SURFACE; } /// <java-name> /// javax/microedition/khronos/egl/EGL10 /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGL10", AccessFlags = 1537)] public partial interface IEGL10 : global::Javax.Microedition.Khronos.Egl.IEGL /* scope: __dot42__ */ { /// <java-name> /// eglChooseConfig /// </java-name> [Dot42.DexImport("eglChooseConfig", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I[Ljavax/microedition/khronos/egl/EG" + "LConfig;I[I)Z", AccessFlags = 1025)] bool EglChooseConfig(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] attrib_list, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglCopyBuffers /// </java-name> [Dot42.DexImport("eglCopyBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljava/lang/Object;)Z", AccessFlags = 1025)] bool EglCopyBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, object native_pixmap) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateContext /// </java-name> [Dot42.DexImport("eglCreateContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljavax/microedition/khronos/egl/EGLContext;[I)Ljavax/microedition/khronos/e" + "gl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglCreateContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, global::Javax.Microedition.Khronos.Egl.EGLContext share_context, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePbufferSurface /// </java-name> [Dot42.DexImport("eglCreatePbufferSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePbufferSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreatePixmapSurface /// </java-name> [Dot42.DexImport("eglCreatePixmapSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreatePixmapSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_pixmap, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglCreateWindowSurface /// </java-name> [Dot42.DexImport("eglCreateWindowSurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;Ljava/lang/Object;[I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglCreateWindowSurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, object native_window, int[] attrib_list) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroyContext /// </java-name> [Dot42.DexImport("eglDestroyContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;)Z", AccessFlags = 1025)] bool EglDestroyContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglDestroySurface /// </java-name> [Dot42.DexImport("eglDestroySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglDestroySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigAttrib /// </java-name> [Dot42.DexImport("eglGetConfigAttrib", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "nfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigAttrib(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig config, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetConfigs /// </java-name> [Dot42.DexImport("eglGetConfigs", "(Ljavax/microedition/khronos/egl/EGLDisplay;[Ljavax/microedition/khronos/egl/EGLC" + "onfig;I[I)Z", AccessFlags = 1025)] bool EglGetConfigs(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLConfig[] configs, int config_size, int[] num_config) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentContext /// </java-name> [Dot42.DexImport("eglGetCurrentContext", "()Ljavax/microedition/khronos/egl/EGLContext;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLContext EglGetCurrentContext() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentDisplay /// </java-name> [Dot42.DexImport("eglGetCurrentDisplay", "()Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetCurrentDisplay() /* MethodBuilder.Create */ ; /// <java-name> /// eglGetCurrentSurface /// </java-name> [Dot42.DexImport("eglGetCurrentSurface", "(I)Ljavax/microedition/khronos/egl/EGLSurface;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLSurface EglGetCurrentSurface(int readdraw) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetDisplay /// </java-name> [Dot42.DexImport("eglGetDisplay", "(Ljava/lang/Object;)Ljavax/microedition/khronos/egl/EGLDisplay;", AccessFlags = 1025)] global::Javax.Microedition.Khronos.Egl.EGLDisplay EglGetDisplay(object native_display) /* MethodBuilder.Create */ ; /// <java-name> /// eglGetError /// </java-name> [Dot42.DexImport("eglGetError", "()I", AccessFlags = 1025)] int EglGetError() /* MethodBuilder.Create */ ; /// <java-name> /// eglInitialize /// </java-name> [Dot42.DexImport("eglInitialize", "(Ljavax/microedition/khronos/egl/EGLDisplay;[I)Z", AccessFlags = 1025)] bool EglInitialize(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int[] major_minor) /* MethodBuilder.Create */ ; /// <java-name> /// eglMakeCurrent /// </java-name> [Dot42.DexImport("eglMakeCurrent", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;Ljavax/microedition/khronos/egl/EGLSurface;Ljavax/microedition/khronos/egl" + "/EGLContext;)Z", AccessFlags = 1025)] bool EglMakeCurrent(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface draw, global::Javax.Microedition.Khronos.Egl.EGLSurface read, global::Javax.Microedition.Khronos.Egl.EGLContext context) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryContext /// </java-name> [Dot42.DexImport("eglQueryContext", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLCo" + "ntext;I[I)Z", AccessFlags = 1025)] bool EglQueryContext(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLContext context, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglQueryString /// </java-name> [Dot42.DexImport("eglQueryString", "(Ljavax/microedition/khronos/egl/EGLDisplay;I)Ljava/lang/String;", AccessFlags = 1025)] string EglQueryString(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, int name) /* MethodBuilder.Create */ ; /// <java-name> /// eglQuerySurface /// </java-name> [Dot42.DexImport("eglQuerySurface", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;I[I)Z", AccessFlags = 1025)] bool EglQuerySurface(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface, int attribute, int[] value) /* MethodBuilder.Create */ ; /// <java-name> /// eglSwapBuffers /// </java-name> [Dot42.DexImport("eglSwapBuffers", "(Ljavax/microedition/khronos/egl/EGLDisplay;Ljavax/microedition/khronos/egl/EGLSu" + "rface;)Z", AccessFlags = 1025)] bool EglSwapBuffers(global::Javax.Microedition.Khronos.Egl.EGLDisplay display, global::Javax.Microedition.Khronos.Egl.EGLSurface surface) /* MethodBuilder.Create */ ; /// <java-name> /// eglTerminate /// </java-name> [Dot42.DexImport("eglTerminate", "(Ljavax/microedition/khronos/egl/EGLDisplay;)Z", AccessFlags = 1025)] bool EglTerminate(global::Javax.Microedition.Khronos.Egl.EGLDisplay display) /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitGL /// </java-name> [Dot42.DexImport("eglWaitGL", "()Z", AccessFlags = 1025)] bool EglWaitGL() /* MethodBuilder.Create */ ; /// <java-name> /// eglWaitNative /// </java-name> [Dot42.DexImport("eglWaitNative", "(ILjava/lang/Object;)Z", AccessFlags = 1025)] bool EglWaitNative(int engine, object bindTarget) /* MethodBuilder.Create */ ; } /// <java-name> /// javax/microedition/khronos/egl/EGLConfig /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLConfig", AccessFlags = 1057)] public abstract partial class EGLConfig /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLConfig() /* MethodBuilder.Create */ { } } /// <java-name> /// javax/microedition/khronos/egl/EGLDisplay /// </java-name> [Dot42.DexImport("javax/microedition/khronos/egl/EGLDisplay", AccessFlags = 1057)] public abstract partial class EGLDisplay /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public EGLDisplay() /* MethodBuilder.Create */ { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Xml; using System.Globalization; namespace System.Runtime.Serialization.Json { internal class JsonWriterDelegator : XmlWriterDelegator { private DateTimeFormat _dateTimeFormat; public JsonWriterDelegator(XmlWriter writer) : base(writer) { } public JsonWriterDelegator(XmlWriter writer, DateTimeFormat dateTimeFormat) : this(writer) { _dateTimeFormat = dateTimeFormat; } internal override void WriteChar(char value) { WriteString(XmlConvert.ToString(value)); } internal override void WriteBase64(byte[] bytes) { if (bytes == null) { return; } ByteArrayHelperWithString.Instance.WriteArray(Writer, bytes, 0, bytes.Length); } internal override void WriteQName(XmlQualifiedName value) { if (value != XmlQualifiedName.Empty) { writer.WriteString(value.Name); writer.WriteString(JsonGlobals.NameValueSeparatorString); writer.WriteString(value.Namespace); } } internal override void WriteUnsignedLong(ulong value) { WriteDecimal((decimal)value); } internal override void WriteDecimal(decimal value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteDecimal(value); } internal override void WriteDouble(double value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteDouble(value); } internal override void WriteFloat(float value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteFloat(value); } internal override void WriteLong(long value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteLong(value); } internal override void WriteSignedByte(sbyte value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteSignedByte(value); } internal override void WriteUnsignedInt(uint value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteUnsignedInt(value); } internal override void WriteUnsignedShort(ushort value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteUnsignedShort(value); } internal override void WriteUnsignedByte(byte value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteUnsignedByte(value); } internal override void WriteShort(short value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteShort(value); } internal override void WriteBoolean(bool value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.booleanString); base.WriteBoolean(value); } internal override void WriteInt(int value) { writer.WriteAttributeString(JsonGlobals.typeString, JsonGlobals.numberString); base.WriteInt(value); } internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteBoolean(value[i], itemName, itemNamespace); } } internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteDateTime(value[i], itemName, itemNamespace); } } internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteDecimal(value[i], itemName, itemNamespace); } } internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteInt(value[i], itemName, itemNamespace); } } internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteLong(value[i], itemName, itemNamespace); } } internal override void WriteDateTime(DateTime value) { if (_dateTimeFormat == null) { WriteDateTimeInDefaultFormat(value); } else { writer.WriteString(value.ToString(_dateTimeFormat.FormatString, _dateTimeFormat.FormatProvider)); } } private void WriteDateTimeInDefaultFormat(DateTime value) { // ToUniversalTime() truncates dates to DateTime.MaxValue or DateTime.MinValue instead of throwing // This will break round-tripping of these dates (see if (value.Kind != DateTimeKind.Utc) { //long tickCount = value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks; long tickCount = value.Ticks - TimeZoneInfo.Local.GetUtcOffset(value).Ticks; if ((tickCount > DateTime.MaxValue.Ticks) || (tickCount < DateTime.MinValue.Ticks)) { throw XmlObjectSerializer.CreateSerializationException(SR.JsonDateTimeOutOfRange, new ArgumentOutOfRangeException("value")); } } writer.WriteString(JsonGlobals.DateTimeStartGuardReader); writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000); switch (value.Kind) { case DateTimeKind.Unspecified: case DateTimeKind.Local: // +"zzzz"; //TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime()); TimeSpan ts = TimeZoneInfo.Local.GetUtcOffset(value.ToLocalTime()); if (ts.Ticks < 0) { writer.WriteString("-"); } else { writer.WriteString("+"); } int hours = Math.Abs(ts.Hours); writer.WriteString((hours < 10) ? "0" + hours : hours.ToString(CultureInfo.InvariantCulture)); int minutes = Math.Abs(ts.Minutes); writer.WriteString((minutes < 10) ? "0" + minutes : minutes.ToString(CultureInfo.InvariantCulture)); break; case DateTimeKind.Utc: break; } writer.WriteString(JsonGlobals.DateTimeEndGuardReader); } internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteFloat(value[i], itemName, itemNamespace); } } internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { for (int i = 0; i < value.Length; i++) { WriteDouble(value[i], itemName, itemNamespace); } } internal override void WriteStartElement(string prefix, string localName, string ns) { if (localName != null && localName.Length == 0) { base.WriteStartElement(JsonGlobals.itemString, JsonGlobals.itemString); base.WriteAttributeString(null, JsonGlobals.itemString, null, localName); } else { base.WriteStartElement(prefix, localName, ns); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Net; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Data.Tables.Models; using Azure.Data.Tables.Queryable; using Azure.Data.Tables.Sas; namespace Azure.Data.Tables { /// <summary> /// The <see cref="TableClient"/> allows you to interact with Azure Storage /// Tables. /// </summary> public class TableClient { private readonly string _table; private readonly OdataMetadataFormat _format; private readonly ClientDiagnostics _diagnostics; private readonly TableRestClient _tableOperations; private readonly string _version; private readonly bool _isPremiumEndpoint; private readonly ResponseFormat _returnNoContent = ResponseFormat.ReturnNoContent; /// <summary> /// Initializes a new instance of the <see cref="TableClient"/>. /// </summary> /// <param name="endpoint"> /// A <see cref="Uri"/> referencing the table service account. /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/". /// </param> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="options"> /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request. /// </param> /// <exception cref="ArgumentException"><paramref name="endpoint"/> is not https.</exception> public TableClient(Uri endpoint, string tableName, TableClientOptions options = null) : this(endpoint, tableName, default(TableSharedKeyPipelinePolicy), options) { Argument.AssertNotNull(tableName, nameof(tableName)); if (endpoint.Scheme != "https") { throw new ArgumentException("Cannot use TokenCredential without HTTPS.", nameof(endpoint)); } } /// <summary> /// Initializes a new instance of the <see cref="TableClient"/>. /// </summary> /// <param name="endpoint"> /// A <see cref="Uri"/> referencing the table service account. /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/". /// </param> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="credential">The shared key credential used to sign requests.</param> /// <exception cref="ArgumentNullException"><paramref name="tableName"/> or <paramref name="credential"/> is null.</exception> public TableClient(Uri endpoint, string tableName, TableSharedKeyCredential credential) : this(endpoint, tableName, new TableSharedKeyPipelinePolicy(credential), null) { Argument.AssertNotNull(tableName, nameof(tableName)); Argument.AssertNotNull(credential, nameof(credential)); } /// <summary> /// Initializes a new instance of the <see cref="TableClient"/>. /// </summary> /// <param name="endpoint"> /// A <see cref="Uri"/> referencing the table service account. /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/". /// </param> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="credential">The shared key credential used to sign requests.</param> /// <param name="options"> /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request. /// </param> /// <exception cref="ArgumentNullException"><paramref name="tableName"/> or <paramref name="credential"/> is null.</exception> public TableClient(Uri endpoint, string tableName, TableSharedKeyCredential credential, TableClientOptions options = null) : this(endpoint, tableName, new TableSharedKeyPipelinePolicy(credential), options) { Argument.AssertNotNull(tableName, nameof(tableName)); Argument.AssertNotNull(credential, nameof(credential)); } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <param name="connectionString"> /// A connection string includes the authentication information /// required for your application to access data in an Azure Storage /// account at runtime. /// /// For more information, /// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string"> /// Configure Azure Storage connection strings</see>. /// </param> /// <param name="tableName">The name of the table with which this client instance will interact.</param> public TableClient(string connectionString, string tableName) : this(connectionString, tableName, default) { } /// <summary> /// Initializes a new instance of the <see cref="TableServiceClient"/>. /// </summary> /// <param name="connectionString"> /// A connection string includes the authentication information /// required for your application to access data in an Azure Storage /// account at runtime. /// /// For more information, /// <see href="https://docs.microsoft.com/azure/storage/common/storage-configure-connection-string"> /// Configure Azure Storage connection strings</see>. /// </param> /// <param name="tableName">The name of the table with which this client instance will interact.</param> /// <param name="options"> /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request. /// </param> public TableClient(string connectionString, string tableName, TableClientOptions options = null) { Argument.AssertNotNull(connectionString, nameof(connectionString)); TableConnectionString connString = TableConnectionString.Parse(connectionString); options ??= new TableClientOptions(); var endpointString = connString.TableStorageUri.PrimaryUri.ToString(); TableSharedKeyPipelinePolicy policy = connString.Credentials switch { TableSharedKeyCredential credential => new TableSharedKeyPipelinePolicy(credential), _ => default }; HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy); _diagnostics = new ClientDiagnostics(options); _tableOperations = new TableRestClient(_diagnostics, pipeline, endpointString); _version = options.VersionString; _table = tableName; _format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata; _isPremiumEndpoint = TableServiceClient.IsPremiumEndpoint(connString.TableStorageUri.PrimaryUri); } internal TableClient(Uri endpoint, string tableName, TableSharedKeyPipelinePolicy policy, TableClientOptions options) { Argument.AssertNotNull(tableName, nameof(tableName)); Argument.AssertNotNull(endpoint, nameof(endpoint)); options ??= new TableClientOptions(); HttpPipeline pipeline = HttpPipelineBuilder.Build(options, policy); _diagnostics = new ClientDiagnostics(options); _tableOperations = new TableRestClient(_diagnostics, pipeline, endpoint.ToString()); _version = options.VersionString; _table = tableName; _format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata; _isPremiumEndpoint = TableServiceClient.IsPremiumEndpoint(endpoint); } internal TableClient(string table, TableRestClient tableOperations, string version, ClientDiagnostics diagnostics, bool isPremiumEndpoint) { _tableOperations = tableOperations; _version = version; _table = table; _format = OdataMetadataFormat.ApplicationJsonOdataMinimalmetadata; _diagnostics = diagnostics; _isPremiumEndpoint = isPremiumEndpoint; } /// <summary> /// Initializes a new instance of the <see cref="TableClient"/> /// class for mocking. /// </summary> protected TableClient() { } /// <summary> /// Gets a <see cref="TableSasBuilder"/> instance scoped to the current table. /// </summary> /// <param name="permissions"><see cref="TableSasPermissions"/> containing the allowed permissions.</param> /// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param> /// <returns>An instance of <see cref="TableSasBuilder"/>.</returns> public virtual TableSasBuilder GetSasBuilder(TableSasPermissions permissions, DateTimeOffset expiresOn) { return new TableSasBuilder(_table, permissions, expiresOn) { Version = _version }; } /// <summary> /// Gets a <see cref="TableSasBuilder"/> instance scoped to the current table. /// </summary> /// <param name="rawPermissions">The permissions associated with the shared access signature. This string should contain one or more of the following permission characters in this order: "racwdl".</param> /// <param name="expiresOn">The time at which the shared access signature becomes invalid.</param> /// <returns>An instance of <see cref="TableSasBuilder"/>.</returns> public virtual TableSasBuilder GetSasBuilder(string rawPermissions, DateTimeOffset expiresOn) { return new TableSasBuilder(_table, rawPermissions, expiresOn) { Version = _version }; } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns> public virtual Response<TableItem> Create(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Create)}"); scope.Start(); try { var response = _tableOperations.Create(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>A <see cref="Response{TableItem}"/> containing properties of the table.</returns> public virtual async Task<Response<TableItem>> CreateAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Create)}"); scope.Start(); try { var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns> public virtual Response<TableItem> CreateIfNotExists(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(CreateIfNotExists)}"); scope.Start(); try { var response = _tableOperations.Create(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict) { return default; } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>If the table does not already exist, a <see cref="Response{TableItem}"/>. If the table already exists, <c>null</c>.</returns> public virtual async Task<Response<TableItem>> CreateIfNotExistsAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(CreateIfNotExists)}"); scope.Start(); try { var response = await _tableOperations.CreateAsync(new TableProperties() { TableName = _table }, null, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value as TableItem, response.GetRawResponse()); } catch (RequestFailedException ex) when (ex.Status == (int)HttpStatusCode.Conflict) { return default; } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual Response Delete(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Delete)}"); scope.Start(); try { return _tableOperations.Delete(table: _table, null, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes the current table. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual async Task<Response> DeleteAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Delete)}"); scope.Start(); try { return await _tableOperations.DeleteAsync(table: _table, null, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Adds a Table Entity into the Table. /// </summary> /// <param name="entity">The entity to add.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>A <see cref="Response"/> containing headers such as ETag.</returns> /// <exception cref="RequestFailedException">Exception thrown if entity already exists.</exception> public virtual async Task<Response> AddEntityAsync<T>(T entity, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(AddEntity)}"); scope.Start(); try { var response = await _tableOperations.InsertEntityAsync(_table, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), responsePreference: _returnNoContent, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); return response.GetRawResponse(); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Adds a Table Entity into the Table. /// </summary> /// <param name="entity">The entity to add.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>A <see cref="Response"/> containing headers such as ETag</returns> /// <exception cref="RequestFailedException">Exception thrown if entity already exists.</exception> public virtual Response AddEntity<T>(T entity, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(AddEntity)}"); scope.Start(); try { var response = _tableOperations.InsertEntity(_table, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), responsePreference: _returnNoContent, queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); return response.GetRawResponse(); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> /// <exception cref="RequestFailedException">Exception thrown if the entity doesn't exist.</exception> /// <exception cref="ArgumentNullException"><paramref name="partitionKey"/> or <paramref name="rowKey"/> is null.</exception> public virtual Response<T> GetEntity<T>(string partitionKey, string rowKey, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull("message", nameof(partitionKey)); Argument.AssertNotNull("message", nameof(rowKey)); string selectArg = select == null ? null : string.Join(",", select); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetEntity)}"); scope.Start(); try { var response = _tableOperations.QueryEntitiesWithPartitionAndRowKey( _table, partitionKey, rowKey, queryOptions: new QueryOptions() { Format = _format, Select = selectArg }, cancellationToken: cancellationToken); var result = ((Dictionary<string, object>)response.Value).ToTableEntity<T>(); return Response.FromValue(result, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> /// <exception cref="RequestFailedException">Exception thrown if the entity doesn't exist.</exception> /// <exception cref="ArgumentNullException"><paramref name="partitionKey"/> or <paramref name="rowKey"/> is null.</exception> public virtual async Task<Response<T>> GetEntityAsync<T>(string partitionKey, string rowKey, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull("message", nameof(partitionKey)); Argument.AssertNotNull("message", nameof(rowKey)); string selectArg = select == null ? null : string.Join(",", select); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetEntity)}"); scope.Start(); try { var response = await _tableOperations.QueryEntitiesWithPartitionAndRowKeyAsync( _table, partitionKey, rowKey, queryOptions: new QueryOptions() { Format = _format, Select = selectArg }, cancellationToken: cancellationToken).ConfigureAwait(false); var result = ((Dictionary<string, object>)response.Value).ToTableEntity<T>(); return Response.FromValue(result, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. Creates the entity if it does not exist. /// </summary> /// <param name="entity">The entity to upsert.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual async Task<Response> UpsertEntityAsync<T>(T entity, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpsertEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return await _tableOperations.UpdateEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else if (mode == TableUpdateMode.Merge) { return await _tableOperations.MergeEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. Creates the entity if it does not exist. /// </summary> /// <param name="entity">The entity to upsert.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual Response UpsertEntity<T>(T entity, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpsertEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return _tableOperations.UpdateEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else if (mode == TableUpdateMode.Merge) { return _tableOperations.MergeEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. /// </summary> /// <param name="entity">The entity to update.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual async Task<Response> UpdateEntityAsync<T>(T entity, ETag ifMatch, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); Argument.AssertNotDefault(ref ifMatch, nameof(ifMatch)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpdateEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return await _tableOperations.UpdateEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch.ToString(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else if (mode == TableUpdateMode.Merge) { return await _tableOperations.MergeEntityAsync(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch.ToString(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces the specified table entity, if it exists. /// </summary> /// <param name="entity">The entity to update.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency.</param> /// <param name="mode">An enum that determines which upsert operation to perform.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual Response UpdateEntity<T>(T entity, ETag ifMatch, TableUpdateMode mode = TableUpdateMode.Merge, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { Argument.AssertNotNull(entity, nameof(entity)); Argument.AssertNotNull(entity?.PartitionKey, nameof(entity.PartitionKey)); Argument.AssertNotNull(entity?.RowKey, nameof(entity.RowKey)); Argument.AssertNotDefault(ref ifMatch, nameof(ifMatch)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(UpdateEntity)}"); scope.Start(); try { if (mode == TableUpdateMode.Replace) { return _tableOperations.UpdateEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch.ToString(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else if (mode == TableUpdateMode.Merge) { return _tableOperations.MergeEntity(_table, entity.PartitionKey, entity.RowKey, tableEntityProperties: entity.ToOdataAnnotatedDictionary(), ifMatch: ifMatch.ToString(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } else { throw new ArgumentException($"Unexpected value for {nameof(mode)}: {mode}"); } } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual AsyncPageable<T> QueryAsync<T>(Expression<Func<T, bool>> filter, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { return QueryAsync<T>(Bind(filter), maxPerPage, select, cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Pageable<T> Query<T>(Expression<Func<T, bool>> filter, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { return Query<T>(Bind(filter), maxPerPage, select, cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <returns></returns> public virtual AsyncPageable<T> QueryAsync<T>(string filter = null, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { string selectArg = select == null ? null : string.Join(",", select); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { return PageableHelpers.CreateAsyncEnumerable(async _ => { var response = await _tableOperations.QueryEntitiesAsync( _table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); }, async (continuationToken, _) => { var (NextPartitionKey, NextRowKey) = ParseContinuationToken(continuationToken); var response = await _tableOperations.QueryEntitiesAsync( _table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, nextPartitionKey: NextPartitionKey, nextRowKey: NextRowKey, cancellationToken: cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); }); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Queries entities in the table. /// </summary> /// <param name="filter">Returns only entities that satisfy the specified filter.</param> /// <param name="maxPerPage">The maximum number of entities that will be returned per page.</param> /// <param name="select">Selects which set of entity properties to return in the result set.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Pageable<T> Query<T>(string filter = null, int? maxPerPage = null, IEnumerable<string> select = null, CancellationToken cancellationToken = default) where T : class, ITableEntity, new() { string selectArg = select == null ? null : string.Join(",", select); return PageableHelpers.CreateEnumerable((int? _) => { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { var response = _tableOperations.QueryEntities(_table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, cancellationToken: cancellationToken); return Page.FromValues( response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } }, (continuationToken, _) => { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(Query)}"); scope.Start(); try { var (NextPartitionKey, NextRowKey) = ParseContinuationToken(continuationToken); var response = _tableOperations.QueryEntities( _table, queryOptions: new QueryOptions() { Format = _format, Top = maxPerPage, Filter = filter, Select = selectArg }, nextPartitionKey: NextPartitionKey, nextRowKey: NextRowKey, cancellationToken: cancellationToken); return Page.FromValues(response.Value.Value.ToTableEntityList<T>(), CreateContinuationTokenFromHeaders(response.Headers), response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } }); } /// <summary> /// Deletes the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual async Task<Response> DeleteEntityAsync(string partitionKey, string rowKey, ETag ifMatch = default, CancellationToken cancellationToken = default) { Argument.AssertNotNull(partitionKey, nameof(partitionKey)); Argument.AssertNotNull(rowKey, nameof(rowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(DeleteEntity)}"); scope.Start(); try { return await _tableOperations.DeleteEntityAsync(_table, partitionKey, rowKey, ifMatch: ifMatch == default ? ETag.All.ToString() : ifMatch.ToString(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes the specified table entity. /// </summary> /// <param name="partitionKey">The partitionKey that identifies the table entity.</param> /// <param name="rowKey">The rowKey that identifies the table entity.</param> /// <param name="ifMatch">The If-Match value to be used for optimistic concurrency. The default is to delete unconditionally.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> /// <returns>The <see cref="Response"/> indicating the result of the operation.</returns> public virtual Response DeleteEntity(string partitionKey, string rowKey, ETag ifMatch = default, CancellationToken cancellationToken = default) { Argument.AssertNotNull(partitionKey, nameof(partitionKey)); Argument.AssertNotNull(rowKey, nameof(rowKey)); using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(DeleteEntity)}"); scope.Start(); try { return _tableOperations.DeleteEntity(_table, partitionKey, rowKey, ifMatch: ifMatch == default ? ETag.All.ToString() : ifMatch.ToString(), queryOptions: new QueryOptions() { Format = _format }, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Retrieves details about any stored access policies specified on the table that may be used with Shared Access Signatures. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response<IReadOnlyList<SignedIdentifier>>> GetAccessPolicyAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetAccessPolicy)}"); scope.Start(); try { var response = await _tableOperations.GetAccessPolicyAsync(_table, cancellationToken: cancellationToken).ConfigureAwait(false); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> Retrieves details about any stored access policies specified on the table that may be used with Shared Access Signatures. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response<IReadOnlyList<SignedIdentifier>> GetAccessPolicy(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(GetAccessPolicy)}"); scope.Start(); try { var response = _tableOperations.GetAccessPolicy(_table, cancellationToken: cancellationToken); return Response.FromValue(response.Value, response.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> sets stored access policies for the table that may be used with Shared Access Signatures. </summary> /// <param name="tableAcl"> the access policies for the table. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task<Response> SetAccessPolicyAsync(IEnumerable<SignedIdentifier> tableAcl, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(SetAccessPolicy)}"); scope.Start(); try { return await _tableOperations.SetAccessPolicyAsync(_table, tableAcl: tableAcl, cancellationToken: cancellationToken).ConfigureAwait(false); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> sets stored access policies for the table that may be used with Shared Access Signatures. </summary> /// <param name="tableAcl"> the access policies for the table. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response SetAccessPolicy(IEnumerable<SignedIdentifier> tableAcl, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _diagnostics.CreateScope($"{nameof(TableClient)}.{nameof(SetAccessPolicy)}"); scope.Start(); try { return _tableOperations.SetAccessPolicy(_table, tableAcl: tableAcl, cancellationToken: cancellationToken); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates an Odata filter query string from the provided expression. /// </summary> /// <typeparam name="T">The type of the entity being queried. Typically this will be derrived from <see cref="ITableEntity"/> or <see cref="Dictionary{String, Object}"/>.</typeparam> /// <param name="filter">A filter expresssion.</param> /// <returns>The string representation of the filter expression.</returns> public static string CreateQueryFilter<T>(Expression<Func<T, bool>> filter) => Bind(filter); /// <summary> /// Create a <see cref="TableTransactionalBatch" /> for the given partitionkey value. /// </summary> /// <param name="partitionKey">The partitionKey context for the batch.</param> /// <returns></returns> public virtual TableTransactionalBatch CreateTransactionalBatch(string partitionKey) { return new TableTransactionalBatch(_table, _tableOperations, _format); } internal static string Bind(Expression expression) { Argument.AssertNotNull(expression, nameof(expression)); Dictionary<Expression, Expression> normalizerRewrites = new Dictionary<Expression, Expression>(ReferenceEqualityComparer<Expression>.Instance); // Evaluate any local valid expressions ( lambdas etc) Expression partialEvaluatedExpression = Evaluator.PartialEval(expression); // Normalize expression, replace String Comparisons etc. Expression normalizedExpression = ExpressionNormalizer.Normalize(partialEvaluatedExpression, normalizerRewrites); // Parse the Bound expression into an OData filter. ExpressionParser parser = new ExpressionParser(); parser.Translate(normalizedExpression); // Return the FilterString. return parser.FilterString == "true" ? null : parser.FilterString; } private static string CreateContinuationTokenFromHeaders(TableQueryEntitiesHeaders headers) { if (headers.XMsContinuationNextPartitionKey == null && headers.XMsContinuationNextRowKey == null) { return null; } else { return $"{headers.XMsContinuationNextPartitionKey} {headers.XMsContinuationNextRowKey}"; } } private static (string NextPartitionKey, string NextRowKey) ParseContinuationToken(string continuationToken) { // There were no headers passed and the continuation token contains just the space delimiter if (continuationToken?.Length <= 1) { return (null, null); } var tokens = continuationToken.Split(' '); return (tokens[0], tokens.Length > 1 ? tokens[1] : null); } } }
//------------------------------------------------------------------------------ // <copyright file="AutoCompleteStringCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Collections; using System.Security.Permissions; using System.ComponentModel; /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection"]/*' /> /// <devdoc> /// <para>Represents a collection of strings.</para> /// </devdoc> public class AutoCompleteStringCollection : IList { CollectionChangeEventHandler onCollectionChanged; private ArrayList data = new ArrayList(); public AutoCompleteStringCollection() { } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.this"]/*' /> /// <devdoc> /// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/>.</para> /// </devdoc> public string this[int index] { get { return ((string)data[index]); } set { OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, data[index])); data[index] = value; OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.Count"]/*' /> /// <devdoc> /// <para>Gets the number of strings in the /// <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> .</para> /// </devdoc> public int Count { get { return data.Count; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.IsReadOnly"]/*' /> bool IList.IsReadOnly { get { return false; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.IsFixedSize"]/*' /> bool IList.IsFixedSize { get { return false; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.CollectionChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public event CollectionChangeEventHandler CollectionChanged { add { this.onCollectionChanged += value; } remove { this.onCollectionChanged -= value; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.OnCollectionChanged"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected void OnCollectionChanged(CollectionChangeEventArgs e) { if (this.onCollectionChanged != null) { this.onCollectionChanged(this, e); } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.Add"]/*' /> /// <devdoc> /// <para>Adds a string with the specified value to the /// <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> .</para> /// </devdoc> public int Add(string value) { int index = data.Add(value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); return index; } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.AddRange"]/*' /> /// <devdoc> /// <para>Copies the elements of a string array to the end of the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/>.</para> /// </devdoc> public void AddRange(string[] value) { if (value == null) { throw new ArgumentNullException("value"); } data.AddRange(value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.Clear"]/*' /> /// <devdoc> /// <para>Removes all the strings from the /// <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> .</para> /// </devdoc> public void Clear() { data.Clear(); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, null)); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.Contains"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether the /// <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> contains a string with the specified /// value.</para> /// </devdoc> public bool Contains(string value) { return data.Contains(value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.CopyTo"]/*' /> /// <devdoc> /// <para>Copies the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the /// specified index.</para> /// </devdoc> public void CopyTo(string[] array, int index) { data.CopyTo(array, index); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IndexOf"]/*' /> /// <devdoc> /// <para>Returns the index of the first occurrence of a string in /// the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> .</para> /// </devdoc> public int IndexOf(string value) { return data.IndexOf(value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.Insert"]/*' /> /// <devdoc> /// <para>Inserts a string into the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> at the specified /// index.</para> /// </devdoc> public void Insert(int index, string value) { data.Insert(index, value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Add, value)); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IsReadOnly"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> is read-only.</para> /// </devdoc> public bool IsReadOnly { get { return false; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IsSynchronized"]/*' /> /// <devdoc> /// <para>Gets a value indicating whether access to the /// <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> /// is synchronized (thread-safe).</para> /// </devdoc> public bool IsSynchronized { get { return false; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.Remove"]/*' /> /// <devdoc> /// <para> Removes a specific string from the /// <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/> .</para> /// </devdoc> public void Remove(string value) { data.Remove(value); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, value)); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.RemoveAt"]/*' /> /// <devdoc> /// <para>Removes the string at the specified index of the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/>.</para> /// </devdoc> public void RemoveAt(int index) { string value = (string)data[index]; data.RemoveAt(index); OnCollectionChanged(new CollectionChangeEventArgs(CollectionChangeAction.Remove, value)); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.SyncRoot"]/*' /> /// <devdoc> /// <para>Gets an object that can be used to synchronize access to the <see cref='System.Collections.Specialized.AutoCompleteStringCollection'/>.</para> /// </devdoc> public object SyncRoot { [HostProtection(Synchronization=true)] [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] get { return this; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.this"]/*' /> object IList.this[int index] { get { return this[index]; } set { this[index] = (string)value; } } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.Add"]/*' /> int IList.Add(object value) { return Add((string)value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.Contains"]/*' /> bool IList.Contains(object value) { return Contains((string) value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.IndexOf"]/*' /> int IList.IndexOf(object value) { return IndexOf((string)value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.Insert"]/*' /> void IList.Insert(int index, object value) { Insert(index, (string)value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IList.Remove"]/*' /> void IList.Remove(object value) { Remove((string)value); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.ICollection.CopyTo"]/*' /> void ICollection.CopyTo(Array array, int index) { data.CopyTo(array, index); } /// <include file='doc\AutoCompleteStringCollection.uex' path='docs/doc[@for="AutoCompleteStringCollection.IEnumerable.GetEnumerator"]/*' /> public IEnumerator GetEnumerator() { return data.GetEnumerator(); } } }
// 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.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Security; using System.Threading; using Windows.Foundation; using Windows.UI.Core; using System.Diagnostics.Tracing; namespace System.Threading { #if FEATURE_APPX #region class WinRTSynchronizationContextFactory [FriendAccessAllowed] internal sealed class WinRTSynchronizationContextFactory : WinRTSynchronizationContextFactoryBase { // // It's important that we always return the same SynchronizationContext object for any particular ICoreDispatcher // object, as long as any existing instance is still reachable. This allows reference equality checks against the // SynchronizationContext to determine if two instances represent the same dispatcher. Async frameworks rely on this. // To accomplish this, we use a ConditionalWeakTable to track which instances of WinRTSynchronizationContext are bound // to each ICoreDispatcher instance. // private static readonly ConditionalWeakTable<CoreDispatcher, WinRTSynchronizationContext> s_contextCache = new ConditionalWeakTable<CoreDispatcher, WinRTSynchronizationContext>(); public override SynchronizationContext Create(object dispatcherObj) { Debug.Assert(dispatcherObj != null); // // Get the RCW for the dispatcher // CoreDispatcher dispatcher = (CoreDispatcher)dispatcherObj; // // The dispatcher is supposed to belong to this thread // Debug.Assert(dispatcher == CoreWindow.GetForCurrentThread().Dispatcher); Debug.Assert(dispatcher.HasThreadAccess); // // Get the WinRTSynchronizationContext instance that represents this CoreDispatcher. // return s_contextCache.GetValue(dispatcher, _dispatcher => new WinRTSynchronizationContext(_dispatcher)); } } #endregion class WinRTSynchronizationContextFactory #region class WinRTSynchronizationContext internal sealed class WinRTSynchronizationContext : SynchronizationContext { private readonly CoreDispatcher _dispatcher; internal WinRTSynchronizationContext(CoreDispatcher dispatcher) { _dispatcher = dispatcher; } #region class WinRTSynchronizationContext.Invoker private class Invoker { private readonly ExecutionContext _executionContext; private readonly SendOrPostCallback _callback; private readonly object _state; private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext); private delegate void DelEtwFireThreadTransferSendObj(object id, int kind, string info, bool multiDequeues); private delegate void DelEtwFireThreadTransferObj(object id, int kind, string info); private static DelEtwFireThreadTransferSendObj s_EtwFireThreadTransferSendObj; private static DelEtwFireThreadTransferObj s_EtwFireThreadTransferReceiveObj; private static DelEtwFireThreadTransferObj s_EtwFireThreadTransferReceiveHandledObj; private static volatile bool s_TriedGetEtwDelegates; public Invoker(SendOrPostCallback callback, object state) { _executionContext = ExecutionContext.FastCapture(); _callback = callback; _state = state; if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferSendObj(this); } public void Invoke() { if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferReceiveObj(this); if (_executionContext == null) InvokeCore(); else ExecutionContext.Run(_executionContext, s_contextCallback, this, preserveSyncCtx: true); // If there was an ETW event that fired at the top of the winrt event handling loop, ETW listeners could // use it as a marker of completion of the previous request. Since such an event does not exist we need to // fire the "done handling off-thread request" event in order to enable correct work item assignment. if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferReceiveHandledObj(this); } private static void InvokeInContext(object thisObj) { ((Invoker)thisObj).InvokeCore(); } private void InvokeCore() { try { _callback(_state); } catch (Exception ex) { // // If we let exceptions propagate to CoreDispatcher, it will swallow them with the idea that someone will // observe them later using the IAsyncInfo returned by CoreDispatcher.RunAsync. However, we ignore // that IAsyncInfo, because there's nothing Post can do with it (since Post returns void). // So, to avoid these exceptions being lost forever, we post them to the ThreadPool. // if (!(ex is ThreadAbortException) && !(ex is AppDomainUnloadedException)) { if (!WindowsRuntimeMarshal.ReportUnhandledError(ex)) { var edi = ExceptionDispatchInfo.Capture(ex); ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o).Throw(), edi); } } } } #region ETW Activity-tracing support private static void InitEtwMethods() { Type fest = typeof(FrameworkEventSource); var mi1 = fest.GetMethod("ThreadTransferSendObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var mi2 = fest.GetMethod("ThreadTransferReceiveObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var mi3 = fest.GetMethod("ThreadTransferReceiveHandledObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (mi1 != null && mi2 != null && mi3 != null) { s_EtwFireThreadTransferSendObj = (DelEtwFireThreadTransferSendObj)mi1.CreateDelegate(typeof(DelEtwFireThreadTransferSendObj), FrameworkEventSource.Log); s_EtwFireThreadTransferReceiveObj = (DelEtwFireThreadTransferObj)mi2.CreateDelegate(typeof(DelEtwFireThreadTransferObj), FrameworkEventSource.Log); s_EtwFireThreadTransferReceiveHandledObj = (DelEtwFireThreadTransferObj)mi3.CreateDelegate(typeof(DelEtwFireThreadTransferObj), FrameworkEventSource.Log); } s_TriedGetEtwDelegates = true; } private static void EtwFireThreadTransferSendObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferSendObj != null) s_EtwFireThreadTransferSendObj(id, 3, string.Empty, false); } private static void EtwFireThreadTransferReceiveObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferReceiveObj != null) s_EtwFireThreadTransferReceiveObj(id, 3, string.Empty); } private static void EtwFireThreadTransferReceiveHandledObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferReceiveHandledObj != null) s_EtwFireThreadTransferReceiveHandledObj(id, 3, string.Empty); } #endregion ETW Activity-tracing support } #endregion class WinRTSynchronizationContext.Invoker [SecuritySafeCritical] public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); Contract.EndContractBlock(); var ignored = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, new Invoker(d, state).Invoke); } [SecuritySafeCritical] public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext); } public override SynchronizationContext CreateCopy() { return new WinRTSynchronizationContext(_dispatcher); } } #endregion class WinRTSynchronizationContext #endif //FEATURE_APPX } // namespace
using System; using System.Collections.Generic; using Foundation; using CoreMedia; using AVFoundation; using CoreGraphics; namespace AVCompositionDebugVieweriOS { public class SimpleEditor : NSObject { public List<AVAsset> Clips { get; set; } public List<NSValue> ClipTimeRanges { get; set; } public int TransitionType { get; set; } public CMTime TransitionDuration { get; set; } AVMutableComposition composition; public AVMutableComposition Composition { get { if (composition == null) composition = AVMutableComposition.Create (); return composition; } set { composition = value; } } public AVMutableVideoComposition VideoComposition { get; set; } public AVMutableAudioMix AudioMix { get; set; } public AVPlayerItem PlayerItem { get { AVPlayerItem playerItem = AVPlayerItem.FromAsset (Composition); playerItem.VideoComposition = VideoComposition; playerItem.AudioMix = AudioMix; return playerItem; } } public SimpleEditor () : base() { } private void BuildTransitionComposition(AVMutableComposition composition, AVMutableVideoComposition videoComposition, AVMutableAudioMix audioMix) { CMTime nextClipStartTime = CMTime.Zero; int clipsCount = Clips.Count; // Make transitionDuration no greater than half the shortest clip duration. CMTime transitionDuration = TransitionDuration; Console.WriteLine ("Clips Count:" + clipsCount); Console.WriteLine ("Clips Range Count:" + ClipTimeRanges.Count); for (int i = 0; i < clipsCount; i++) { NSValue clipTimeRange = ClipTimeRanges [i]; if(clipTimeRange != null) { CMTime halfClipDuration = clipTimeRange.CMTimeRangeValue.Duration; halfClipDuration.TimeScale *= 2; transitionDuration = CMTime.GetMinimum(transitionDuration,halfClipDuration); } } // Add two video tracks and two audio tracks. var compositionVideoTracks = new AVMutableCompositionTrack [] { composition.AddMutableTrack (AVMediaType.Video, 0), composition.AddMutableTrack (AVMediaType.Video, 0) }; var compositionAudioTracks = new AVMutableCompositionTrack [] { composition.AddMutableTrack (AVMediaType.Audio, 0), composition.AddMutableTrack (AVMediaType.Audio, 0) }; var passThroughTimeRanges = new CMTimeRange[clipsCount]; var transitionTimeRanges = new CMTimeRange[clipsCount]; // Place clips into alternating video & audio tracks in composition, overlapped by transitionDuration. for(int i = 0; i < clipsCount; i++) { int alternatingIndex = i % 2; AVAsset asset = Clips [i]; NSValue clipTimeRange = ClipTimeRanges [i]; CMTimeRange timeRangeInAsset; if (clipTimeRange != null) timeRangeInAsset = clipTimeRange.CMTimeRangeValue; else { timeRangeInAsset = new CMTimeRange (); timeRangeInAsset.Start = CMTime.Zero; timeRangeInAsset.Duration = asset.Duration; } NSError error; AVAssetTrack clipVideoTrack = asset.TracksWithMediaType (AVMediaType.Video) [0]; compositionVideoTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipVideoTrack, nextClipStartTime,out error); AVAssetTrack clipAudioTrack = asset.TracksWithMediaType (AVMediaType.Audio) [0]; compositionAudioTracks [alternatingIndex].InsertTimeRange (timeRangeInAsset, clipAudioTrack, nextClipStartTime,out error); // Remember the time range in which this clip should pass through. // First clip ends with a transition. // Second clip begins with a transition. // Exclude that transition from the pass through time ranges CMTimeRange timeRange = new CMTimeRange(); timeRange.Start = nextClipStartTime; timeRange.Duration = timeRangeInAsset.Duration; passThroughTimeRanges [i] = timeRange; if (i > 0) { passThroughTimeRanges[i].Start = CMTime.Add(passThroughTimeRanges[i].Start,transitionDuration); passThroughTimeRanges[i].Duration = CMTime.Subtract(passThroughTimeRanges[i].Duration,transitionDuration); } if(i + 1 < clipsCount) { passThroughTimeRanges[i].Duration = CMTime.Subtract(passThroughTimeRanges[i].Duration,transitionDuration); } // The end of this clip will overlap the start of the next by transitionDuration. // (Note: this arithmetic falls apart if timeRangeInAsset.duration < 2 * transitionDuration.) nextClipStartTime = CMTime.Add (nextClipStartTime, timeRangeInAsset.Duration); nextClipStartTime = CMTime.Subtract (nextClipStartTime, transitionDuration); // Remember the time range for the transition to the next item if(i + 1 < clipsCount) { transitionTimeRanges [i] = new CMTimeRange () { Start = nextClipStartTime, Duration = transitionDuration }; } } List<AVVideoCompositionInstruction> instructions = new List<AVVideoCompositionInstruction> (); List<AVMutableAudioMixInputParameters> trackMixArray = new List<AVMutableAudioMixInputParameters> (); // Set up the video composition if we are to perform crossfade transitions between clips. for (int i = 0; i < clipsCount; i++) { int alternatingIndex = i % 2; AVMutableVideoCompositionInstruction passThroughInstructions = AVMutableVideoCompositionInstruction.Create () as AVMutableVideoCompositionInstruction; passThroughInstructions.TimeRange = passThroughTimeRanges [i]; AVMutableVideoCompositionLayerInstruction passThroughLayerInstructions = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [alternatingIndex]); passThroughInstructions.LayerInstructions = new AVVideoCompositionLayerInstruction[] { passThroughLayerInstructions }; instructions.Add (passThroughInstructions); if (i + 1 < clipsCount) { var transitionInstruction = AVMutableVideoCompositionInstruction.Create () as AVMutableVideoCompositionInstruction; transitionInstruction.TimeRange = transitionTimeRanges [i]; var fromLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [alternatingIndex]); var toLayer = AVMutableVideoCompositionLayerInstruction.FromAssetTrack (compositionVideoTracks [1 - alternatingIndex]); // Fade in the toLayer by setting a ramp from 0.0 to 1.0. toLayer.SetOpacityRamp (0.0f, 1.0f, transitionTimeRanges [i]); transitionInstruction.LayerInstructions = new AVVideoCompositionLayerInstruction[] { toLayer, fromLayer, }; instructions.Add(transitionInstruction); // Add AudioMix to fade in the volume ramps var trackMix = AVMutableAudioMixInputParameters.FromTrack(compositionAudioTracks[0]); trackMix.SetVolumeRamp (1f, 0f, transitionTimeRanges[0]); trackMixArray.Add (trackMix); trackMix = AVMutableAudioMixInputParameters.FromTrack (compositionAudioTracks[1]); trackMix.SetVolumeRamp (0f, 1f, transitionTimeRanges[0]); trackMix.SetVolumeRamp (1f, 1f, passThroughTimeRanges[1]); trackMixArray.Add (trackMix); } } videoComposition.Instructions = instructions.ToArray (); audioMix.InputParameters = trackMixArray.ToArray(); } public void BuildCompositionObjects(Boolean playBack) { if (Clips == null || Clips.Count == 0) { Composition = null; VideoComposition = null; AudioMix = null; return; } CGSize videoSize = Clips [0].NaturalSize; var composition1 = AVMutableComposition.Create (); var videoComposition1 = AVMutableVideoComposition.Create (); var audioMix = AVMutableAudioMix.Create (); composition1.NaturalSize = videoSize; BuildTransitionComposition (composition1, videoComposition1, audioMix); if (videoComposition1 != null) { videoComposition1.FrameDuration = new CMTime (1, 30); videoComposition1.RenderSize = videoSize; } Composition = composition1; VideoComposition = videoComposition1; AudioMix = audioMix; } public AVAssetExportSession AssetExportSession (string presetName) { var session = new AVAssetExportSession (Composition, presetName); session.VideoComposition = VideoComposition; session.AudioMix = AudioMix; return session; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Reflection.Emit; namespace System.Linq.Expressions.Interpreter { /// <summary> /// Contains compiler state corresponding to a LabelTarget /// See also LabelScopeInfo. /// </summary> internal sealed class LabelInfo { // The tree node representing this label private readonly LabelTarget _node; // The BranchLabel label, will be mutated if Node is redefined private BranchLabel _label; // The blocks where this label is defined. If it has more than one item, // the blocks can't be jumped to except from a child block // If there's only 1 block (the common case) it's stored here, if there's multiple blocks it's stored // as a HashSet<LabelScopeInfo> private object _definitions; // Blocks that jump to this block private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>(); // True if at least one jump is across blocks // If we have any jump across blocks to this label, then the // LabelTarget can only be defined in one place private bool _acrossBlockJump; internal LabelInfo(LabelTarget node) { _node = node; } internal BranchLabel GetLabel(LightCompiler compiler) { EnsureLabel(compiler); return _label; } internal void Reference(LabelScopeInfo block) { _references.Add(block); if (HasDefinitions) { ValidateJump(block); } } internal void Define(LabelScopeInfo block) { // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) for (LabelScopeInfo j = block; j != null; j = j.Parent) { if (j.ContainsTarget(_node)) { Error.LabelTargetAlreadyDefined(_node.Name); } } AddDefinition(block); block.AddLabelInfo(_node, this); // Once defined, validate all jumps if (HasDefinitions && !HasMultipleDefinitions) { foreach (var r in _references) { ValidateJump(r); } } else { // Was just redefined, if we had any across block jumps, they're // now invalid if (_acrossBlockJump) { throw Error.AmbiguousJump(_node.Name); } // For local jumps, we need a new IL label // This is okay because: // 1. no across block jumps have been made or will be made // 2. we don't allow the label to be shadowed _label = null; } } private void ValidateJump(LabelScopeInfo reference) { // look for a simple jump out for (LabelScopeInfo j = reference; j != null; j = j.Parent) { if (DefinedIn(j)) { // found it, jump is valid! return; } if (j.Kind == LabelScopeKind.Finally || j.Kind == LabelScopeKind.Filter) { break; } } _acrossBlockJump = true; if (HasMultipleDefinitions) { throw Error.AmbiguousJump(_node.Name); } // We didn't find an outward jump. Look for a jump across blocks LabelScopeInfo def = FirstDefinition(); LabelScopeInfo common = CommonNode(def, reference, b => b.Parent); // Validate that we aren't jumping across a finally for (LabelScopeInfo j = reference; j != common; j = j.Parent) { if (j.Kind == LabelScopeKind.Finally) { throw Error.ControlCannotLeaveFinally(); } if (j.Kind == LabelScopeKind.Filter) { throw Error.ControlCannotLeaveFilterTest(); } } // Validate that we aren't jumping into a catch or an expression for (LabelScopeInfo j = def; j != common; j = j.Parent) { if (!j.CanJumpInto) { if (j.Kind == LabelScopeKind.Expression) { throw Error.ControlCannotEnterExpression(); } else { throw Error.ControlCannotEnterTry(); } } } } internal void ValidateFinish() { // Make sure that if this label was jumped to, it is also defined if (_references.Count > 0 && !HasDefinitions) { throw Error.LabelTargetUndefined(_node.Name); } } private void EnsureLabel(LightCompiler compiler) { if (_label == null) { _label = compiler.Instructions.MakeLabel(); } } private bool DefinedIn(LabelScopeInfo scope) { if (_definitions == scope) { return true; } HashSet<LabelScopeInfo> definitions = _definitions as HashSet<LabelScopeInfo>; if (definitions != null) { return definitions.Contains(scope); } return false; } private bool HasDefinitions { get { return _definitions != null; } } private LabelScopeInfo FirstDefinition() { LabelScopeInfo scope = _definitions as LabelScopeInfo; if (scope != null) { return scope; } foreach (var x in (HashSet<LabelScopeInfo>)_definitions) { return x; } throw new InvalidOperationException(); } private void AddDefinition(LabelScopeInfo scope) { if (_definitions == null) { _definitions = scope; } else { HashSet<LabelScopeInfo> set = _definitions as HashSet<LabelScopeInfo>; if (set == null) { _definitions = set = new HashSet<LabelScopeInfo>() { (LabelScopeInfo)_definitions }; } set.Add(scope); } } private bool HasMultipleDefinitions { get { return _definitions is HashSet<LabelScopeInfo>; } } internal static T CommonNode<T>(T first, T second, Func<T, T> parent) where T : class { var cmp = EqualityComparer<T>.Default; if (cmp.Equals(first, second)) { return first; } var set = new HashSet<T>(cmp); for (T t = first; t != null; t = parent(t)) { set.Add(t); } for (T t = second; t != null; t = parent(t)) { if (set.Contains(t)) { return t; } } return null; } } internal enum LabelScopeKind { // any "statement like" node that can be jumped into Statement, // these correspond to the node of the same name Block, Switch, Lambda, Try, // these correspond to the part of the try block we're in Catch, Finally, Filter, // the catch-all value for any other expression type // (means we can't jump into it) Expression, } // // Tracks scoping information for LabelTargets. Logically corresponds to a // "label scope". Even though we have arbitrary goto support, we still need // to track what kinds of nodes that gotos are jumping through, both to // emit property IL ("leave" out of a try block), and for validation, and // to allow labels to be duplicated in the tree, as long as the jumps are // considered "up only" jumps. // // We create one of these for every Expression that can be jumped into, as // well as creating them for the first expression we can't jump into. The // "Kind" property indicates what kind of scope this is. // internal sealed class LabelScopeInfo { private HybridReferenceDictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block internal readonly LabelScopeKind Kind; internal readonly LabelScopeInfo Parent; internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) { Parent = parent; Kind = kind; } /// <summary> /// Returns true if we can jump into this node /// </summary> internal bool CanJumpInto { get { switch (Kind) { case LabelScopeKind.Block: case LabelScopeKind.Statement: case LabelScopeKind.Switch: case LabelScopeKind.Lambda: return true; } return false; } } internal bool ContainsTarget(LabelTarget target) { if (_labels == null) { return false; } return _labels.ContainsKey(target); } internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) { if (_labels == null) { info = null; return false; } return _labels.TryGetValue(target, out info); } internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); if (_labels == null) { _labels = new HybridReferenceDictionary<LabelTarget, LabelInfo>(); } _labels[target] = info; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; public static class Reflection { static readonly object Empty = new object(); static readonly Dictionary<BondDataType, string> bondTypeName = new Dictionary<BondDataType, string> { {BondDataType.BT_BOOL, "bool"}, {BondDataType.BT_UINT8, "uint8"}, {BondDataType.BT_UINT16, "uint16"}, {BondDataType.BT_UINT32, "uint32"}, {BondDataType.BT_UINT64, "uint64"}, {BondDataType.BT_FLOAT, "float"}, {BondDataType.BT_DOUBLE, "double"}, {BondDataType.BT_STRING, "string"}, {BondDataType.BT_LIST, "list"}, {BondDataType.BT_SET, "set"}, {BondDataType.BT_MAP, "map"}, {BondDataType.BT_INT8, "int8"}, {BondDataType.BT_INT16, "int16"}, {BondDataType.BT_INT32, "int32"}, {BondDataType.BT_INT64, "int64"}, {BondDataType.BT_WSTRING, "wstring"} }; #region Public APIs /// <summary> /// Get list of fields for a Bond schema /// </summary> public static IEnumerable<ISchemaField> GetSchemaFields(this Type type) { var fields = from fieldInfo in type.GetDeclaredFields().Where(f => f.IsPublic) let idAttr = fieldInfo.GetAttribute<IdAttribute>() where idAttr != null select new Field(fieldInfo, idAttr.Value) as ISchemaField; var properties = from propertyInfo in type.GetDeclaredProperties() let idAttr = propertyInfo.GetAttribute<IdAttribute>() where idAttr != null select new Property(propertyInfo, idAttr.Value) as ISchemaField; var concatenated = fields.Concat(properties); return concatenated.OrderBy(m => m.Id); } /// <summary> /// Get the inner Type of composite/container types /// </summary> public static Type GetValueType(this Type type) { if (type.IsBondNullable() || type.IsBonded()) return type.GetGenericArguments()[0]; if (type.IsArray) return type.GetElementType(); if (type.IsBondBlob()) return typeof(sbyte); return type.GetMethod(typeof(IEnumerable<>), "GetEnumerator") .ReturnType .GetDeclaredProperty("Current") .PropertyType; } /// <summary> /// Get the key and value Type for a map /// </summary> public static KeyValuePair<Type, Type> GetKeyValueType(this Type type) { var types = GetValueType(type).GetGenericArguments(); if (types.Length != 2) { throw new InvalidOperationException("Expected generic type with 2 type arguments."); } return new KeyValuePair<Type, Type>(types[0], types[1]); } /// <summary> /// Get a value indicating whether the Type is a Bond schema /// </summary> public static bool IsBondStruct(this Type type) { return null != type.GetAttribute<SchemaAttribute>(); } /// <summary> /// Get a value indicating whether the Type is a bonded&lt;T> /// </summary> public static bool IsBonded(this Type type) { if (type.IsGenericType()) { var definition = type.GetGenericTypeDefinition(); return definition == typeof(IBonded<>) || definition == typeof(Tag.bonded<>); } return false; } /// <summary> /// Get a value indicating whether the Type is a Bond nullable type /// </summary> public static bool IsBondNullable(this Type type) { return type.IsGenericType() && (type.GetGenericTypeDefinition() == typeof(Tag.nullable<>)); } /// <summary> /// Get a value indicating whether the Type is a Bond blob /// </summary> public static bool IsBondBlob(this Type type) { return type == typeof(Tag.blob) || type == typeof(ArraySegment<byte>); } /// <summary> /// Get a value indicating whether the Type is a Bond list /// </summary> public static bool IsBondList(this Type type) { if (type.IsGenericType()) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IList<>) || genericType == typeof(ICollection<>)) return true; } return typeof(IList).IsAssignableFrom(type) || typeof(ICollection).IsAssignableFrom(type); } /// <summary> /// Get a value indicating whether the Type is a Bond map /// </summary> public static bool IsBondMap(this Type type) { if (type.IsGenericType()) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IDictionary<,>)) return true; } return typeof(IDictionary).IsAssignableFrom(type); } /// <summary> /// Get a value indicating whether the Type is a Bond set /// </summary> public static bool IsBondSet(this Type type) { if (!type.IsGenericType()) return false; return typeof(ISet<>).MakeGenericType(type.GetGenericArguments()[0]).IsAssignableFrom(type); } /// <summary> /// Get a value indicating whether the Type is a Bond container /// </summary> public static bool IsBondContainer(this Type type) { return type.IsBondList() || type.IsBondSet() || type.IsBondMap() || type.IsBondBlob(); } /// <summary> /// Get the BondDataType value for the Type /// </summary> public static BondDataType GetBondDataType(this Type type) { while (true) { if (type.IsBondStruct() || type.IsBonded()) return BondDataType.BT_STRUCT; if (type.IsBondNullable()) return BondDataType.BT_LIST; if (type.IsBondMap()) return BondDataType.BT_MAP; if (type.IsBondSet()) return BondDataType.BT_SET; if (type.IsBondList() || type.IsBondBlob()) return BondDataType.BT_LIST; if (type.IsEnum()) return BondDataType.BT_INT32; if (type == typeof(string)) return BondDataType.BT_STRING; if (type == typeof(Tag.wstring)) return BondDataType.BT_WSTRING; if (type == typeof(bool)) return BondDataType.BT_BOOL; if (type == typeof(byte)) return BondDataType.BT_UINT8; if (type == typeof(UInt16)) return BondDataType.BT_UINT16; if (type == typeof(UInt32)) return BondDataType.BT_UINT32; if (type == typeof(UInt64)) return BondDataType.BT_UINT64; if (type == typeof(float)) return BondDataType.BT_FLOAT; if (type == typeof(double)) return BondDataType.BT_DOUBLE; if (type == typeof(sbyte)) return BondDataType.BT_INT8; if (type == typeof(Int16)) return BondDataType.BT_INT16; if (type == typeof(Int32)) return BondDataType.BT_INT32; if (type == typeof(Int64)) return BondDataType.BT_INT64; if (type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetValueType(); continue; } return BondDataType.BT_UNAVAILABLE; } } /// <summary> /// Get the Type representing the base schema or null if the schema has no base /// </summary> public static Type GetBaseSchemaType(this Type type) { if (type.IsClass()) { var baseType = type.GetBaseType(); return baseType != null && baseType.GetAttribute<SchemaAttribute>() != null ? baseType : null; } if (type.IsInterface()) { // Get all base interfaces. In case if an inheritance chain longer than 2, this returns all // the base interfaces flattened in no particular order, so we have to find the direct parent. var baseInterfaces = type.GetInterfaces() .Where(t => t.GetAttribute<SchemaAttribute>() != null).ToArray(); for (var i = 0; i < baseInterfaces.Length; i++) { var baseInterface = baseInterfaces[i]; var indirectBaseInterfacesCount = baseInterface.GetInterfaces() .Count(t => t.GetAttribute<SchemaAttribute>() != null); if (indirectBaseInterfacesCount == baseInterfaces.Length - 1) { return baseInterface; } } } return null; } /// <summary> /// Get the Type of the schema field, including any type annotations from TypeAttribute /// </summary> /// <remarks> /// In some cases this may not be the actual type of the property or field. /// If the property or field has a TypeAttribute, this will be the attribute's value /// and can provide schema information that is not available on the actual /// property/field type. /// </remarks> public static Type GetSchemaType(this ISchemaField schemaField) { var type = schemaField.MemberType; var typeAttr = schemaField.GetAttribute<TypeAttribute>(); if (typeAttr != null) { type = ResolveTypeArgumentTags(type, typeAttr.Value); } return type; } #endregion #region PCL compatibility internal static bool IsClass(this Type type) { return type.GetTypeInfo().IsClass; } static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } internal static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } static Type GetBaseType(this Type type) { return type.GetTypeInfo().BaseType; } internal static bool IsAssignableFrom(this Type type, Type that) { return type.GetTypeInfo().IsAssignableFrom(that.GetTypeInfo()); } internal static MethodInfo GetMethod(this Type type, string name, params Type[] paramTypes) { var methods = type.GetDeclaredMethods(name); return ( from method in methods let parameters = method.GetParameters() where parameters != null where parameters.Select(p => p.ParameterType).Where(t => !t.IsGenericParameter).SequenceEqual(paramTypes) select method).FirstOrDefault(); } internal static MethodInfo FindMethod(this Type type, string name, params Type[] argumentTypes) { var methods = type.GetDeclaredMethods(name); var typeArgs = new Type[0]; foreach (var method in methods) { var parameters = method.GetParameters(); if (parameters.Length != argumentTypes.Length) continue; int paramIndex; for (paramIndex = 0; paramIndex < parameters.Length; ++paramIndex) { var param = parameters[paramIndex].ParameterType; var arg = argumentTypes[paramIndex]; if (param == arg) continue; if (param.IsGenericType() && arg.IsGenericType() && param.GetGenericTypeDefinition() == arg.GetGenericTypeDefinition() && param.GetGenericArguments().All(p => p.IsGenericParameter)) { typeArgs = arg.GetGenericArguments(); continue; } break; } if (paramIndex == parameters.Length) return typeArgs.Length == 0 ? method : method.MakeGenericMethod(typeArgs); } return null; } internal static MethodInfo GetMethod(this Type type, Type declaringType, string name, params Type[] paramTypes) { return declaringType.MakeGenericTypeFrom(type).GetMethod(name, paramTypes); } internal static ConstructorInfo GetConstructor(this Type type, params Type[] paramTypes) { var methods = type.GetDeclaredConstructors(); return ( from method in methods let parameters = method.GetParameters() where parameters != null where parameters.Select(p => p.ParameterType).SequenceEqual(paramTypes) select method).FirstOrDefault(); } internal static PropertyInfo GetDeclaredProperty(this Type type, string name, Type returnType) { var property = type.GetDeclaredProperty(name); return (property != null && property.PropertyType == returnType) ? property : null; } internal static PropertyInfo GetDeclaredProperty(this Type type, Type declaringType, string name, Type returnType) { return declaringType.MakeGenericTypeFrom(type).GetDeclaredProperty(name, returnType); } static Type MakeGenericTypeFrom(this Type genericType, Type concreteType) { var typeArguments = concreteType.GetGenericArguments(); if (concreteType.IsArray) { typeArguments = new[] { concreteType.GetElementType() }; } var typeParameters = genericType.GetGenericParameters(); if (typeArguments.Length == 2 && typeParameters.Length == 1) typeArguments = new[] { typeof(KeyValuePair<,>).MakeGenericType(typeArguments) }; return genericType.MakeGenericType(typeArguments); } #endregion #region Internal /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "int Math::Abs(int)" overload, you can write: /// <code>(MethodInfo)Reflection.InfoOf((int x) => Math.Abs(x))</code> /// </example> static MemberInfo InfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { if (expression == null) throw new ArgumentNullException("expression"); return InfoOf(expression.Body); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if that member is not a method. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "int Math::Abs(int)" overload, you can write: /// <code>Reflection.MethodInfoOf((int x) => Math.Abs(x))</code> /// </example> internal static MethodInfo MethodInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { return InfoOf(expression) as MethodInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a generic method definition. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the generic method definition for some "int Foo::Bar&lt;T>(T)" overload, you can write: /// <code>Reflection.GenericMethodInfoOf((int x) => Foo.Bar(x))</code>, which returns the definition Foo.Bar&lt;> /// </example> internal static MethodInfo GenericMethodInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { var methodInfo = MethodInfoOf(expression); return methodInfo == null ? null : methodInfo.GetGenericMethodDefinition(); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a PropertyInfo. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the PropertyInfo for the "int Foo::SomeProperty", you can write: /// <code>Reflection.PropertyInfoOf((Foo f) => f.SomeProperty)</code> /// </example> internal static PropertyInfo PropertyInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { return InfoOf(expression) as PropertyInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a FieldInfo. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the FieldInfo for the "int Foo::someField" field, you can write: /// <code>Reflection.FieldInfoOf((Foo f) => f.someField)</code> /// </example> internal static FieldInfo FieldInfoOf<T, TResult>(Expression<Func<T, TResult>> expression) { return InfoOf(expression) as FieldInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the PropertyInfo of "DateTime DateTime::Now { get; }", you can write: /// <code>(PropertyInfo)Reflection.InfoOf(() => DateTime.Now)</code> /// </example> static MemberInfo InfoOf<TResult>(Expression<Func<TResult>> expression) { if (expression == null) throw new ArgumentNullException("expression"); return InfoOf(expression.Body); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if that member is not a method. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "int Math::Abs(int)" overload, you can write: /// <code>Reflection.MethodInfoOf(() => Math.Abs(default(int)))</code> /// </example> internal static MethodInfo MethodInfoOf<TResult>(Expression<Func<TResult>> expression) { return InfoOf(expression) as MethodInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="TResult">Return type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a generic method definition. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the generic method definition for some "int Foo::Bar&lt;T>(T)" overload, you can write: /// <code>Reflection.GenericMethodInfoOf(() => Foo.Bar(default(int)))</code>, which returns the definition Foo.Bar&lt;> /// </example> internal static MethodInfo GenericMethodInfoOf<TResult>(Expression<Func<TResult>> expression) { var methodInfo = MethodInfoOf(expression); return methodInfo == null ? null : methodInfo.GetGenericMethodDefinition(); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "void Console::WriteLine(string)" overload, you can write: /// <code>(MethodInfo)Reflection.InfoOf((string s) => Console.WriteLine(s))</code> /// </example> static MemberInfo InfoOf<T>(Expression<Action<T>> expression) { if (expression == null) throw new ArgumentNullException("expression"); return InfoOf(expression.Body); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if that member is not a method. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the MethodInfo for the "void Foo::DoThing(int)" overload, you can write: /// <code>Reflection.MethodInfoOf(() => Foo.DoThing(default(int)))</code> /// </example> internal static MethodInfo MethodInfoOf<T>(Expression<Action<T>> expression) { return InfoOf(expression) as MethodInfo; } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <typeparam name="T">Input type of the lambda.</typeparam> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. Return null if the member is not a generic method definition. An exception occurs if this node does not contain member information.</returns> /// <example> /// To obtain the generic method definition for some "void Foo::Bar&lt;T>(T)" overload, you can write: /// <code>Reflection.GenericMethodInfoOf(() => Foo.Bar(default(int)))</code>, which returns the definition Foo.Bar&lt;> /// </example> internal static MethodInfo GenericMethodInfoOf<T>(Expression<Action<T>> expression) { var methodInfo = MethodInfoOf(expression); return methodInfo == null ? null : methodInfo.GetGenericMethodDefinition(); } /// <summary> /// Gets the reflection member information from the top-level node in the body of the given lambda expression. /// </summary> /// <param name="expression">Lambda expression to extract reflection information from</param> /// <returns>Member information of the top-level node in the body of the lambda expression. An exception occurs if this node does not contain member information.</returns> static MemberInfo InfoOf(Expression expression) { if (expression == null) throw new ArgumentNullException("expression"); MethodCallExpression mce; MemberExpression me; NewExpression ne; UnaryExpression ue; BinaryExpression be; if ((mce = expression as MethodCallExpression) != null) { return mce.Method; } else if ((me = expression as MemberExpression) != null) { return me.Member; } else if ((ne = expression as NewExpression) != null) { return ne.Constructor; } else if ((ue = expression as UnaryExpression) != null) { if (ue.Method != null) { return ue.Method; } } else if ((be = expression as BinaryExpression) != null) { if (be.Method != null) { return be.Method; } } throw new NotSupportedException("Expression tree type doesn't have an extractable MemberInfo object."); } internal static Modifier GetModifier(this ISchemaField schemaField) { return schemaField.GetAttribute<RequiredAttribute>() != null ? Modifier.Required : schemaField.GetAttribute<RequiredOptionalAttribute>() != null ? Modifier.RequiredOptional : Modifier.Optional; } internal static int GetHierarchyDepth(this RuntimeSchema schema) { if (!schema.IsStruct) return 0; var depth = 0; for (var type = schema.TypeDef; type != null; type = schema.SchemaDef.structs[type.struct_def].base_def) depth++; return depth; } internal static int GetHierarchyDepth(this Type type) { var depth = 0; for (; type != null; type = type.GetBaseSchemaType()) depth++; return depth; } internal static string GetSchemaName(this Type type) { string name; if (type.IsBondStruct() || type.IsEnum()) { name = type.Name; var n = name.IndexOf('`'); if (n >= 0) name = name.Remove(n); } else if (type.IsBondBlob()) { return "blob"; } else if (type.IsBonded()) { name = "bonded"; } else if (type.IsBondNullable()) { name = "nullable"; } else { name = bondTypeName[type.GetBondDataType()]; } if (!type.IsGenericType()) return name; var args = type.GetGenericArguments(); var builder = new StringBuilder(name, args.Length * 64); builder.Append("<"); for (var i = 0; i < args.Length; ++i) { if (i != 0) builder.Append(", "); builder.Append(args[i].GetSchemaFullName()); } builder.Append(">"); return builder.ToString(); } internal static string GetSchemaFullName(this Type type) { if (type.IsBondStruct() || type.IsEnum()) return type.GetSchemaNamespace() + "." + type.GetSchemaName(); return type.GetSchemaName(); } static string GetSchemaNamespace(this Type type) { var attr = type.GetAttribute<NamespaceAttribute>(); if (attr != null) return attr.Value; return type.Namespace; } static T GetAttribute<T>(this MemberInfo type) where T : class { return type.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T; } internal static T GetAttribute<T>(this Type type) where T : class { // ReSharper disable once RedundantCast // This explicit cast is needed because when targeting non-portable runtime, // type.GetTypeInfo returns an object which is also a Type, causing wrong call. return GetAttribute<T>(type.GetTypeInfo() as MemberInfo); } static T GetAttribute<T>(this ISchemaField schemaField) where T : class { return schemaField.MemberInfo.GetAttribute<T>(); } static Type ResolveTypeArgumentTags(Type memberType, Type schemaType) { if (schemaType.IsGenericType()) { Type[] memberTypeArguments; var schemaGenericType = schemaType.GetGenericTypeDefinition(); var memberGenericType = memberType.IsGenericType() ? memberType.GetGenericTypeDefinition() : null; if ((schemaGenericType == typeof(Tag.nullable<>) && memberGenericType != typeof(Nullable<>)) || (schemaGenericType == typeof(Tag.bonded<>) && memberGenericType != typeof(IBonded<>))) { memberTypeArguments = new[] { memberType }; } else { memberTypeArguments = memberType.GetGenericArguments(); } return schemaGenericType.MakeGenericType(Enumerable.Zip( memberTypeArguments, schemaType.GetGenericArguments(), ResolveTypeArgumentTags).ToArray()); } return (schemaType == typeof(Tag.structT) || schemaType == typeof(Tag.classT)) ? memberType : schemaType; } internal static Type GetObjectType(this Type schemaType) { if (schemaType == typeof(Tag.wstring)) { return typeof(string); } if (schemaType == typeof(Tag.blob)) { return typeof(ArraySegment<byte>); } if (schemaType.IsGenericType()) { return schemaType.GetGenericTypeDefinition().MakeGenericType( schemaType.GetGenericArguments().Select(type => { if (type.IsGenericType()) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(Tag.nullable<>)) { var nullableValue = type.GetGenericArguments()[0]; return nullableValue.IsClass() || nullableValue.IsBondBlob() ? nullableValue.GetObjectType() : typeof(Nullable<>).MakeGenericType(nullableValue.GetObjectType()); } if (genericType == typeof(Tag.bonded<>)) { return typeof(IBonded<>).MakeGenericType(type.GetGenericArguments()[0].GetObjectType()); } } return type.GetObjectType(); }).ToArray()); } return schemaType; } internal static object GetDefaultValue(this ISchemaField schemaField) { var declaringType = schemaField.DeclaringType; var declaringTypeInfo = declaringType.GetTypeInfo(); var defaultAttribute = schemaField.GetAttribute<DefaultAttribute>(); // For interfaces determine member default value from the type and/or DefaultAttribute if (declaringTypeInfo.IsInterface) { var schemaType = schemaField.GetSchemaType(); if (defaultAttribute != null) { if (defaultAttribute.Value == null) { return null; } if (schemaType.IsBondNullable() || schemaType.IsBondStruct() || schemaType.IsBondContainer()) { InvalidDefaultAttribute(schemaField, defaultAttribute.Value); } return defaultAttribute.Value; } else { if (schemaType.IsBondNullable()) { return null; } if (schemaType.IsBondStruct() || schemaType.IsBondContainer()) { return Empty; } throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, "Default value for property {0}.{1} must be specified using the DefaultAttribute", schemaField.DeclaringType.Name, schemaField.Name)); } } if (defaultAttribute != null) { InvalidDefaultAttribute(schemaField, defaultAttribute.Value); } // For classes create a default instance and get the actual default value of the member var objectType = declaringType.GetObjectType(); var objectMemeber = objectType.GetSchemaFields().Single(m => m.Id == schemaField.Id); var obj = Activator.CreateInstance(objectType); var defaultValue = objectMemeber.GetValue(obj); return defaultValue; } static void InvalidDefaultAttribute(ISchemaField schemaField, object value) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Invalid default value '{2}' specified by DefaultAttribute for {0}.{1}", schemaField.DeclaringType, schemaField.Name, value == null ? "null" : value.ToString())); } #endregion } }
using System.Collections.Generic; using Cake.Common.Tests.Fixtures.Tools; using Cake.Common.Tools.Fixie; using Cake.Core; using Cake.Core.IO; using NSubstitute; using Xunit; namespace Cake.Common.Tests.Unit.Tools.Fixie { public sealed class FixieRunnerTests { public sealed class TheRunMethod { [Fact] public void Should_Throw_If_Assembly_Path_Is_Null() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run((FilePath) null, new FixieSettings())); // Then Assert.IsArgumentNullException(result, "assemblyPath"); } [Fact] public void Should_Throw_If_Fixie_Runner_Was_Not_Found() { // Given var fixture = new FixieRunnerFixture(defaultToolExist: false); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("./Test1.dll", new FixieSettings())); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Could not locate executable.", result.Message); } [Theory] [InlineData("C:/Fixie/Fixie.Console.exe", "C:/Fixie/Fixie.Console.exe")] [InlineData("./tools/Fixie/Fixie.Console.exe", "/Working/tools/Fixie/Fixie.Console.exe")] public void Should_Use_Fixie_Runner_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new FixieRunnerFixture(expected); var runner = fixture.CreateRunner(); // When runner.Run("./Test1.dll", new FixieSettings { ToolPath = toolPath }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Is<FilePath>(p => p.FullPath == expected), Arg.Any<ProcessSettings>()); } [Fact] public void Should_Find_Fixie_Runner_If_Tool_Path_Not_Provided() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test1.dll", new FixieSettings()); // Then fixture.ProcessRunner.Received(1).Start( Arg.Is<FilePath>(p => p.FullPath == "/Working/tools/Fixie.Console.exe"), Arg.Any<ProcessSettings>()); } [Fact] public void Should_Use_Provided_Assembly_Path_In_Process_Arguments() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test1.dll", new FixieSettings()); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>( p => p.Arguments.Render() == "\"/Working/Test1.dll\"")); } [Fact] public void Should_Use_Provided_Assembly_Paths_In_Process_Arguments() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run(new List<FilePath> { "./Test1.dll", "./Test2.dll" }, new FixieSettings()); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>( p => p.Arguments.Render() == "\"/Working/Test1.dll\" \"/Working/Test2.dll\"")); } [Fact] public void Should_Set_Working_Directory() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Test1.dll", new FixieSettings()); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>( p => p.WorkingDirectory.FullPath == "/Working")); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new FixieRunnerFixture(); fixture.ProcessRunner.Start(Arg.Any<FilePath>(), Arg.Any<ProcessSettings>()).Returns((IProcess)null); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("./Test1.dll", new FixieSettings())); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Process was not started.", result.Message); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new FixieRunnerFixture(); fixture.Process.GetExitCode().Returns(1); var runner = fixture.CreateRunner(); // When var result = Record.Exception(() => runner.Run("./Test1.dll", new FixieSettings())); // Then Assert.IsType<CakeException>(result); Assert.Equal("Fixie: Process returned an error.", result.Message); } [Fact] public void Should_Set_NUnitXml_Output_File() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./blarg.dll", new FixieSettings { NUnitXml = "nunit-style-results.xml", }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>(p => p.Arguments.Render() == "\"/Working/blarg.dll\" --NUnitXml \"/Working/nunit-style-results.xml\"")); } [Fact] public void Should_Set_xUnitXml_Output_File() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./blarg.dll", new FixieSettings { XUnitXml = "xunit-results.xml", }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>(p => p.Arguments.Render() == "\"/Working/blarg.dll\" --xUnitXml \"/Working/xunit-results.xml\"")); } [Theory] [InlineData(true, "on")] [InlineData(false, "off")] public void Should_Set_TeamCity_Value(bool teamCityOutput, string teamCityValue) { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Tests.dll", new FixieSettings { TeamCity = teamCityOutput, }); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>( p => p.Arguments.Render() == string.Format("\"/Working/Tests.dll\" --TeamCity {0}", teamCityValue))); } [Fact] public void Should_Set_Custom_Options() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Tests.dll", new FixieSettings() .WithOption("--include", "CategoryA") .WithOption("--include", "CategoryB")); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>( p => p.Arguments.Render() == string.Format("\"/Working/Tests.dll\" --include CategoryA --include CategoryB"))); } [Fact] public void Should_Set_Multiple_Options() { // Given var fixture = new FixieRunnerFixture(); var runner = fixture.CreateRunner(); // When runner.Run("./Tests.dll", new FixieSettings() .WithOption("--type", "fast") .WithOption("--include", "CategoryA", "CategoryB") .WithOption("--output", "fixie-log.txt")); // Then fixture.ProcessRunner.Received(1).Start( Arg.Any<FilePath>(), Arg.Is<ProcessSettings>( p => p.Arguments.Render() == string.Format("\"/Working/Tests.dll\" --type fast --include CategoryA --include CategoryB --output fixie-log.txt"))); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace MGTK.Controls { public class TreeListBox : Control { private ListBox lstBox; private List<TreeListBoxItem> items; public List<TreeListBoxItem> Items { get { return items; } set { if (items != value) { items = value; TranslateToLstBox(); } } } public object SelectedValue { get { return lstBox.SelectedValue; } } public int SelectedIndex { get { if (Items != null && lstBox.Items != null && lstBox.Items.Count > 0 && lstBox.SelectedIndex >= 0 && lstBox.SelectedIndex < lstBox.Items.Count) { for (int i = 0; i < Items.Count; i++) { if (lstBox.Items[lstBox.SelectedIndex].tag is TreeListBoxItem && lstBox.Items[lstBox.SelectedIndex].tag == Items[i]) return i; } } return -1; } } public bool UseVerticalScrollBar { get { return lstBox.UseVerticalScrollBar; } set { lstBox.UseVerticalScrollBar = value; lstBox.ConfigureCoordinatesAndSizes(); } } public bool UseHorizontalScrollBar { get { return lstBox.UseHorizontalScrollBar; } set { lstBox.UseHorizontalScrollBar = value; lstBox.ConfigureCoordinatesAndSizes(); } } public event EventHandler SelectedIndexChanged; public TreeListBox(Form formowner) : base(formowner) { lstBox = new ListBox(formowner) { Parent = this, Width = Width, Height = Height }; lstBox.SelectedIndexChanged += new EventHandler(lstBox_SelectedIndexChanged); Controls.Add(lstBox); this.WidthChanged += new EventHandler(TreeListBox_SizeChanged); this.HeightChanged += new EventHandler(TreeListBox_SizeChanged); } void lstBox_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedIndexChanged != null) SelectedIndexChanged(this, new EventArgs()); } void TreeListBox_SizeChanged(object sender, EventArgs e) { lstBox.Width = Width; lstBox.Height = Height; lstBox.ConfigureCoordinatesAndSizes(); } private void TranslateToLstBox() { lstBox.Items = GetListBoxItems(Items, null, 4); lstBox.ConfigureCoordinatesAndSizes(); } private Control GetExpandCollapseButton(TreeListBoxItem tLBIOwner) { CheckBox chkExpCol = null; if (Items.Exists(li => li.Parent == tLBIOwner)) { chkExpCol = new CheckBox(Owner) { Width = 12, Height = 12, Tag = tLBIOwner, Parent = lstBox.innerListBox }; chkExpCol.CheckBoxUnchecked = Theme.TreeListBoxExpand; chkExpCol.CheckBoxChecked = Theme.TreeListBoxCollapse; chkExpCol.Checked = tLBIOwner.Expanded; chkExpCol.CheckStateChanged += new EventHandler(chkExpCol_CheckStateChanged); } return chkExpCol; } void chkExpCol_CheckStateChanged(object sender, EventArgs e) { if ((sender as CheckBox).Tag != null && (sender as CheckBox).Tag is TreeListBoxItem) { TreeListBoxItem tLBI = ((sender as CheckBox).Tag as TreeListBoxItem); tLBI.Expanded = !tLBI.Expanded; TranslateToLstBox(); } } private List<ListBoxItem> GetListBoxItems(List<TreeListBoxItem> treeItems, TreeListBoxItem parent, int textXPadding) { List<ListBoxItem> lstItems = new List<ListBoxItem>(); foreach (TreeListBoxItem treeItem in treeItems) { if (treeItem.Parent == parent) { lstItems.Add(new ListBoxItem(treeItem.Value, treeItem.Text, textXPadding, GetExpandCollapseButton(treeItem))); lstItems[lstItems.Count - 1].tag = treeItem; if (treeItem.Expanded) { List<ListBoxItem> lstSub = GetListBoxItems(treeItems, treeItem, textXPadding + textXPadding + lstItems[lstItems.Count - 1].Ctrl.Width); lstItems.AddRange(lstSub); } } } return lstItems; } public void AddItem(TreeListBoxItem item) { Items.Add(item); TranslateToLstBox(); lstBox.ConfigureCoordinatesAndSizes(); } public void RemoveItem(TreeListBoxItem item) { Items.Remove(item); lstBox.Items.Remove(lstBox.Items.Find(li => li.tag == item)); lstBox.ConfigureCoordinatesAndSizes(); } } public class TreeListBoxItem : ListBoxItem { private TreeListBoxItem _parent; public bool Expanded = false; public TreeListBoxItem Parent { get { return _parent; } set { if (_parent != value) _parent = value; } } public TreeListBoxItem(object value, string text, TreeListBoxItem parent, bool expanded) { Value = value; Text = text; Parent = parent; Expanded = expanded; } } }
// 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 ShiftRightLogical128BitLaneInt321() { var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneInt321(); 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 class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ShiftRightLogical128BitLaneInt321 { private struct TestStruct { public Vector128<Int32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld), ref Unsafe.As<Int32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical128BitLaneInt321 testClass) { var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / 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 ImmUnaryOpTest__ShiftRightLogical128BitLaneInt321() { 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]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); } public ImmUnaryOpTest__ShiftRightLogical128BitLaneInt321() { Succeeded = true; 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]), (uint)Unsafe.SizeOf<Vector128<Int32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShiftRightLogical128BitLane( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), 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() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), 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() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), 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() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneInt321(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); 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), (uint)Unsafe.SizeOf<Vector128<Int32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 134217728) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 3 ? result[i] != 0 : result[i] != 134217728)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical128BitLane)}<Int32>(Vector128<Int32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System.Collections.Generic; using System; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal abstract class SourceDelegateMethodSymbol : SourceMethodSymbol { private ImmutableArray<ParameterSymbol> parameters; private readonly TypeSymbol returnType; protected SourceDelegateMethodSymbol( SourceMemberContainerTypeSymbol delegateType, TypeSymbol returnType, DelegateDeclarationSyntax syntax, MethodKind methodKind, DeclarationModifiers declarationModifiers) : base(delegateType, syntax.GetReference(), bodySyntaxReferenceOpt: null, location: syntax.Identifier.GetLocation()) { this.returnType = returnType; this.MakeFlags(methodKind, declarationModifiers, this.returnType.SpecialType == SpecialType.System_Void, isExtensionMethod: false); } private sealed class BeginInvokeMethod : SourceDelegateMethodSymbol { internal void BeginInvokeMethod1( InvokeMethod invoke, TypeSymbol iAsyncResultType, TypeSymbol objectType, TypeSymbol asyncCallbackType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, iAsyncResultType, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); foreach (SourceParameterSymbol p in invoke.Parameters) { var synthesizedParam = new SourceClonedParameterSymbol(originalParam: p, newOwner: this, newOrdinal: p.Ordinal, suppressOptional: true); parameters.Add(synthesizedParam); } int paramCount = invoke.ParameterCount; parameters.Add(new SynthesizedParameterSymbol(this, asyncCallbackType, paramCount, RefKind.None, "callback")); parameters.Add(new SynthesizedParameterSymbol(this, objectType, paramCount + 1, RefKind.None, "object")); InitializeParameters(parameters.ToImmutableAndFree()); } public override string Name { get { return WellKnownMemberNames.DelegateBeginInvokeName; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // BeginInvoke method doesn't have return type attributes // because it doesn't inherit Delegate declaration's return type. // It has a special return type: SpecialType.System.IAsyncResult. return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } } protected void InitializeParameters(ImmutableArray<ParameterSymbol> parameters) { Debug.Assert(this.parameters.IsDefault); this.parameters = parameters; } internal static void AddDelegateMembers( SourceMemberContainerTypeSymbol delegateType, ArrayBuilder<Symbol> symbols, DelegateDeclarationSyntax syntax, DiagnosticBag diagnostics) { Binder binder = delegateType.GetBinder(syntax.ParameterList); TypeSymbol returnType = binder.BindType(syntax.ReturnType, diagnostics); // reuse types to avoid reporting duplicate errors if missing: var voidType = binder.GetSpecialType(SpecialType.System_Void, diagnostics, syntax); var objectType = binder.GetSpecialType(SpecialType.System_Object, diagnostics, syntax); var intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, diagnostics, syntax); if (returnType.IsRestrictedType()) { // Method or delegate cannot return type '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, syntax.ReturnType.Location, returnType); } // A delegate has the following members: (see CLI spec 13.6) // (1) a method named Invoke with the specified signature var invoke = new InvokeMethod(delegateType, returnType, syntax, binder, diagnostics); invoke.CheckDelegateVarianceSafety(diagnostics); symbols.Add(invoke); // (2) a constructor with argument types (object, System.IntPtr) symbols.Add(new Constructor(delegateType, voidType, objectType, intPtrType, syntax)); if (binder.Compilation.GetSpecialType(SpecialType.System_IAsyncResult).TypeKind != TypeKind.Error && binder.Compilation.GetSpecialType(SpecialType.System_AsyncCallback).TypeKind != TypeKind.Error && // WinRT delegates don't have Begin/EndInvoke methods !delegateType.IsCompilationOutputWinMdObj()) { var iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, diagnostics, syntax); var asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, diagnostics, syntax); // (3) BeginInvoke symbols.Add(new BeginInvokeMethod(invoke, iAsyncResultType, objectType, asyncCallbackType, syntax)); // and (4) EndInvoke methods symbols.Add(new EndInvokeMethod(invoke, iAsyncResultType, syntax)); } if (delegateType.DeclaredAccessibility <= Accessibility.Private) { return; } HashSet<DiagnosticInfo> useSiteDiagnostics = null; if (!delegateType.IsNoMoreVisibleThan(invoke.ReturnType, ref useSiteDiagnostics)) { // Inconsistent accessibility: return type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateReturn, delegateType.Locations[0], delegateType, invoke.ReturnType); } foreach (var parameter in invoke.Parameters) { if (!parameter.Type.IsAtLeastAsVisibleAs(delegateType, ref useSiteDiagnostics)) { // Inconsistent accessibility: parameter type '{1}' is less accessible than delegate '{0}' diagnostics.Add(ErrorCode.ERR_BadVisDelegateParam, delegateType.Locations[0], delegateType, parameter.Type); } } diagnostics.Add(delegateType.Locations[0], useSiteDiagnostics); } protected override void MethodChecks(DiagnosticBag diagnostics) { // TODO: move more functionality into here, making these symbols more lazy } public sealed override bool IsVararg { get { return false; } } public sealed override ImmutableArray<ParameterSymbol> Parameters { get { return this.parameters; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public sealed override TypeSymbol ReturnType { get { return this.returnType; } } public sealed override bool IsImplicitlyDeclared { get { return true; } } internal override bool IsExpressionBodied { get { return false; } } internal override bool GenerateDebugInfo { get { return false; } } protected sealed override IAttributeTargetSymbol AttributeOwner { get { return (SourceNamedTypeSymbol)ContainingSymbol; } } internal sealed override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return System.Reflection.MethodImplAttributes.Runtime; } } internal sealed override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { // TODO: This implementation looks strange. It might make sense for the Invoke method, but // not for constructor and other methods. return OneOrMany.Create(((SourceNamedTypeSymbol)ContainingSymbol).GetAttributeDeclarations()); } internal sealed override System.AttributeTargets GetAttributeTarget() { return System.AttributeTargets.Delegate; } private sealed class Constructor : SourceDelegateMethodSymbol { internal Constructor( SourceMemberContainerTypeSymbol delegateType, TypeSymbol voidType, TypeSymbol objectType, TypeSymbol intPtrType, DelegateDeclarationSyntax syntax) : base(delegateType, voidType, syntax, MethodKind.Constructor, DeclarationModifiers.Public) { InitializeParameters(ImmutableArray.Create<ParameterSymbol>( new SynthesizedParameterSymbol(this, objectType, 0, RefKind.None, "object"), new SynthesizedParameterSymbol(this, intPtrType, 1, RefKind.None, "method"))); } public override string Name { get { return WellKnownMemberNames.InstanceConstructorName; } } internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetReturnTypeAttributeDeclarations() { // Constructors don't have return type attributes return OneOrMany.Create(default(SyntaxList<AttributeListSyntax>)); } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of sythesized methods the same as in Dev12 // Dev12 order is not strictly aphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members inone order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } } private sealed class InvokeMethod : SourceDelegateMethodSymbol { internal InvokeMethod( SourceMemberContainerTypeSymbol delegateType, TypeSymbol returnType, DelegateDeclarationSyntax syntax, Binder binder, DiagnosticBag diagnostics) : base(delegateType, returnType, syntax, MethodKind.DelegateInvoke, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { SyntaxToken arglistToken; var parameters = ParameterHelpers.MakeParameters(binder, this, syntax.ParameterList, true, out arglistToken, diagnostics); if (arglistToken.Kind() == SyntaxKind.ArgListKeyword) { // This is a parse-time error in the native compiler; it is a semantic analysis error in Roslyn. // error CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, new SourceLocation(arglistToken)); } InitializeParameters(parameters); } public override string Name { get { return WellKnownMemberNames.DelegateInvokeName; } } internal override LexicalSortKey GetLexicalSortKey() { // associate "Invoke and .ctor" with whole delegate declaration for the sorting purposes // other methods will be associated with delegate's identifier // we want this just to keep the order of sythesized methods the same as in Dev12 // Dev12 order is not strictly aphabetical - .ctor and Invoke go before other members. // there are no real reasons for emitting the members inone order or another, // so we will keep them the same. return new LexicalSortKey(this.syntaxReferenceOpt.GetLocation(), this.DeclaringCompilation); } } private sealed class EndInvokeMethod : SourceDelegateMethodSymbol { internal EndInvokeMethod( InvokeMethod invoke, TypeSymbol iAsyncResultType, DelegateDeclarationSyntax syntax) : base((SourceNamedTypeSymbol)invoke.ContainingType, invoke.ReturnType, syntax, MethodKind.Ordinary, DeclarationModifiers.Virtual | DeclarationModifiers.Public) { var parameters = ArrayBuilder<ParameterSymbol>.GetInstance(); int ordinal = 0; foreach (SourceParameterSymbol p in invoke.Parameters) { if (p.RefKind != RefKind.None) { var synthesizedParam = new SourceClonedParameterSymbol(originalParam: p, newOwner: this, newOrdinal: ordinal++, suppressOptional: true); parameters.Add(synthesizedParam); } } parameters.Add(new SynthesizedParameterSymbol(this, iAsyncResultType, ordinal++, RefKind.None, "__result")); InitializeParameters(parameters.ToImmutableAndFree()); } protected override SourceMethodSymbol BoundAttributesSource { get { // copy return attributes from InvokeMethod return (SourceMethodSymbol)((SourceNamedTypeSymbol)this.ContainingSymbol).DelegateInvokeMethod; } } public override string Name { get { return WellKnownMemberNames.DelegateEndInvokeName; } } } } }
// 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.Security; using System.Text; using System.Threading; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; namespace System.Reflection { internal sealed class RuntimeMethodInfo : MethodInfo, IRuntimeMethodInfo { #region Private Data Members private IntPtr m_handle; private RuntimeTypeCache m_reflectedTypeCache; private string m_name; private string m_toString; private ParameterInfo[] m_parameters; private ParameterInfo m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; private Signature m_signature; private RuntimeType m_declaringType; private object m_keepalive; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags { get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if (ContainsGenericParameters || ReturnType.IsByRef || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this); } m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor internal RuntimeMethodInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { Debug.Assert(!handle.IsNullHandle()); Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_keepalive = keepalive; m_handle = handle.Value; m_reflectedTypeCache = reflectedTypeCache; m_methodAttributes = methodAttributes; } #endregion #region Private Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { get { return new RuntimeMethodHandleInternal(m_handle); } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } private ParameterInfo[] FetchNonReturnParameters() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } private ParameterInfo FetchReturnParameter() { if (m_returnParameter == null) m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature); return m_returnParameter; } #endregion #region Internal Members internal override string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); // serialization == true: use unambiguous (except for assembly name) type names to distinguish between overloads. // serialization == false: use basic format to maintain backward compatibility of MethodInfo.ToString(). TypeNameFormatFlags format = serialization ? TypeNameFormatFlags.FormatSerialization : TypeNameFormatFlags.FormatBasic; if (IsGenericMethod) sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, format)); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } internal override bool CacheEquals(object o) { RuntimeMethodInfo m = o as RuntimeMethodInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } internal Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } internal RuntimeMethodInfo GetParentDefinition() { if (!IsVirtual || m_declaringType.IsInterface) return null; RuntimeType parent = (RuntimeType)m_declaringType.BaseType; if (parent == null) return null; int slot = RuntimeMethodHandle.GetSlot(this); if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot) return null; return (RuntimeMethodInfo)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot)); } // Unlike DeclaringType, this will return a valid type even for global methods internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } internal sealed override int GenericParameterCount => RuntimeMethodHandle.GetGenericParameterCount(this); #endregion #region Object Overrides public override String ToString() { if (m_toString == null) m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig(); return m_toString; } public override int GetHashCode() { // See RuntimeMethodInfo.Equals() below. if (IsGenericMethod) return ValueType.GetHashCodeOfPtr(m_handle); else return base.GetHashCode(); } public override bool Equals(object obj) { if (!IsGenericMethod) return obj == (object)this; // We cannot do simple object identity comparisons for generic methods. // Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo() // retrieve items from and insert items into s_methodInstantiations which is a CerHashtable. RuntimeMethodInfo mi = obj as RuntimeMethodInfo; if (mi == null || !mi.IsGenericMethod) return false; // now we know that both operands are generic methods IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this); IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi); if (handle1.Value.Value != handle2.Value.Value) return false; Type[] lhs = GetGenericArguments(); Type[] rhs = mi.GetGenericArguments(); if (lhs.Length != rhs.Length) return false; for (int i = 0; i < lhs.Length; i++) { if (lhs[i] != rhs[i]) return false; } if (DeclaringType != mi.DeclaringType) return false; if (ReflectedType != mi.ReflectedType) return false; return true; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType as RuntimeType, inherit); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { get { if (m_name == null) m_name = RuntimeMethodHandle.GetName(this); return m_name; } } public override Type DeclaringType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_declaringType; } } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeMethodInfo>(other); public override Type ReflectedType { get { if (m_reflectedTypeCache.IsGlobal) return null; return m_reflectedTypeCache.GetRuntimeType(); } } public override MemberTypes MemberType { get { return MemberTypes.Method; } } public override int MetadataToken { get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } public override bool IsSecurityCritical { get { return true; } } public override bool IsSecuritySafeCritical { get { return false; } } public override bool IsSecurityTransparent { get { return false; } } #endregion #region MethodBase Overrides internal override ParameterInfo[] GetParametersNoCopy() { FetchNonReturnParameters(); return m_parameters; } public override ParameterInfo[] GetParameters() { FetchNonReturnParameters(); if (m_parameters.Length == 0) return m_parameters; ParameterInfo[] ret = new ParameterInfo[m_parameters.Length]; Array.Copy(m_parameters, ret, m_parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } #endregion #region Invocation Logic(On MemberBase) private void CheckConsistency(Object target) { // only test instance methods if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg); else throw new TargetException(SR.RFLCT_Targ_ITargMismatch); } } } private void ThrowNoInvokeException() { // method is ReflectionOnly Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) { throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke); } // method is on a class that contains stack pointers else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) { throw new NotSupportedException(); } // method is vararg else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } // method is generic or on a generic class else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenParam); } // method is abstract class else if (IsAbstract) { throw new MemberAccessException(); } // ByRef return are not allowed in reflection else if (ReturnType.IsByRef) { throw new NotSupportedException(SR.NotSupported_ByRefReturn); } throw new TargetException(); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); return UnsafeInvokeInternal(obj, invokeAttr, parameters, arguments); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal object UnsafeInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture); return UnsafeInvokeInternal(obj, invokeAttr, parameters, arguments); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object UnsafeInvokeInternal(Object obj, BindingFlags invokeAttr, Object[] parameters, Object[] arguments) { bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; if (arguments == null || arguments.Length == 0) return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false, wrapExceptions); else { Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false, wrapExceptions); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] private object[] InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount = (parameters != null) ? parameters.Length : 0; INVOCATION_FLAGS invocationFlags = InvocationFlags; // INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type) // contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot // be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects. if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); if (formalCount != actualCount) throw new TargetParameterCountException(SR.Arg_ParmCnt); if (actualCount != 0) return CheckArguments(parameters, binder, invokeAttr, culture, sig); else return null; } #endregion #region MethodInfo Overrides public override Type ReturnType { get { return Signature.ReturnType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { return ReturnParameter; } } public override ParameterInfo ReturnParameter { get { FetchReturnParameter(); return m_returnParameter as ParameterInfo; } } public override MethodInfo GetBaseDefinition() { if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface) return this; int slot = RuntimeMethodHandle.GetSlot(this); RuntimeType declaringType = (RuntimeType)DeclaringType; RuntimeType baseDeclaringType = declaringType; RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal(); do { int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType); if (cVtblSlots <= slot) break; baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot); baseDeclaringType = declaringType; declaringType = (RuntimeType)declaringType.BaseType; } while (declaringType != null); return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle); } public override Delegate CreateDelegate(Type delegateType) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API existed in v1/v1.1 and only expected to create closed // instance delegates. Constrain the call to BindToMethodInfo to // open delegates only for backwards compatibility. But we'll allow // relaxed signature checking and open static delegates because // there's no ambiguity there (the caller would have to explicitly // pass us a static method or a method with a non-exact signature // and the only change in behavior from v1.1 there is that we won't // fail the call). return CreateDelegateInternal( delegateType, null, DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature, ref stackMark); } public override Delegate CreateDelegate(Type delegateType, Object target) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // This API is new in Whidbey and allows the full range of delegate // flexability (open or closed delegates binding to static or // instance methods with relaxed signature checking). The delegate // can also be closed over null. There's no ambiguity with all these // options since the caller is providing us a specific MethodInfo. return CreateDelegateInternal( delegateType, target, DelegateBindingFlags.RelaxedSignature, ref stackMark); } private Delegate CreateDelegateInternal(Type delegateType, Object firstArgument, DelegateBindingFlags bindingFlags, ref StackCrawlMark stackMark) { // Validate the parameters. if (delegateType == null) throw new ArgumentNullException(nameof(delegateType)); RuntimeType rtType = delegateType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType)); if (!rtType.IsDelegate()) throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(delegateType)); Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark); if (d == null) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return d; } #endregion #region Generics public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) throw new ArgumentNullException(nameof(methodInstantiation)); RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) throw new InvalidOperationException( SR.Format(SR.Arg_NotGenericMethodDefinition, this)); for (int i = 0; i < methodInstantiation.Length; i++) { Type methodInstantiationElem = methodInstantiation[i]; if (methodInstantiationElem == null) throw new ArgumentNullException(); RuntimeType rtMethodInstantiationElem = methodInstantiationElem as RuntimeType; if (rtMethodInstantiationElem == null) { Type[] methodInstantiationCopy = new Type[methodInstantiation.Length]; for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++) methodInstantiationCopy[iCopy] = methodInstantiation[iCopy]; methodInstantiation = methodInstantiationCopy; return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); } methodInstantionRuntimeType[i] = rtMethodInstantiationElem; } RuntimeType[] genericParameters = GetGenericArgumentsInternal(); RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters); MethodInfo ret = null; try { ret = RuntimeType.GetMethodBase(ReflectedTypeInternal, RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo; } catch (VerificationException e) { RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e); throw; } return ret; } internal RuntimeType[] GetGenericArgumentsInternal() { return RuntimeMethodHandle.GetMethodInstantiationInternal(this); } public override Type[] GetGenericArguments() { Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this); if (types == null) { types = Array.Empty<Type>(); } return types; } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } public override bool IsGenericMethod { get { return RuntimeMethodHandle.HasMethodInstantiation(this); } } public override bool IsGenericMethodDefinition { get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); } } public override bool ContainsGenericParameters { get { if (DeclaringType != null && DeclaringType.ContainsGenericParameters) return true; if (!IsGenericMethod) return false; Type[] pis = GetGenericArguments(); for (int i = 0; i < pis.Length; i++) { if (pis[i].ContainsGenericParameters) return true; } return false; } } #endregion #region Legacy Internal internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (method == null) return null; return RuntimeType.GetMethodBase(method); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="EditScript.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Diagnostics; namespace Microsoft.XmlDiffPatch { ////////////////////////////////////////////////////////////////// // EditScriptOperation enum // internal enum EditScriptOperation { None = 0, Match = 1, Add = 2, Remove = 3, ChangeNode = 4, EditScriptReference = 5, EditScriptPostponed = 6, OpenedAdd = 7, OpenedRemove = 8, OpenedMatch = 9, } ////////////////////////////////////////////////////////////////// // EditScript // internal abstract class EditScript { // Fields internal EditScript _nextEditScript; // Constructor internal EditScript( EditScript next) { _nextEditScript = next; } // Properties internal abstract EditScriptOperation Operation { get; } internal EditScript Next { get { return _nextEditScript; } } // Methods internal virtual EditScript GetClosedScript( int currentSourceIndex, int currentTargetIndex ) { Debug.Assert( this as EditScriptOpened == null ); return this; } #if DEBUG internal abstract void Dump(); #endif } ////////////////////////////////////////////////////////////////// // EditScriptEmpty // internal class EditScriptEmpty : EditScript { // Constructor internal EditScriptEmpty() : base( null ) {} // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.None; } } // Methods #if DEBUG internal override void Dump() { Trace.WriteLine( "empty" ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptMatch // internal class EditScriptMatch : EditScript { // Fields internal int _firstSourceIndex; internal int _firstTargetIndex; internal int _length; // Constructor internal EditScriptMatch( int startSourceIndex, int startTargetIndex, int length, EditScript next ) : base ( next ) { Debug.Assert( length > 0 ); Debug.Assert( startSourceIndex > 0 ); Debug.Assert( startTargetIndex > 0 ); _firstSourceIndex = startSourceIndex; _firstTargetIndex = startTargetIndex; _length = length; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.Match; } } // Methods #if DEBUG internal override void Dump() { if ( _length > 1 ) Trace.WriteLine( "match s" + _firstSourceIndex + "-s" + (_firstSourceIndex + _length - 1).ToString() + " to t" + _firstTargetIndex + "-t" + (_firstTargetIndex + _length - 1).ToString() ); else Trace.WriteLine( "match s" + _firstSourceIndex + " to t" + _firstTargetIndex ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptAdd // internal class EditScriptAdd : EditScript { // Fields internal int _startTargetIndex; internal int _endTargetIndex; // Constructor internal EditScriptAdd( int startTargetIndex, int endTargetIndex, EditScript next ) : base ( next ) { Debug.Assert( endTargetIndex - startTargetIndex >= 0 ); Debug.Assert( startTargetIndex > 0 ); Debug.Assert( endTargetIndex > 0 ); _startTargetIndex = startTargetIndex; _endTargetIndex = endTargetIndex; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.Add; } } // Methods #if DEBUG internal override void Dump() { if ( _endTargetIndex - _startTargetIndex > 0 ) Trace.WriteLine( "add t" + _startTargetIndex + "-t" + _endTargetIndex ); else Trace.WriteLine( "add t" + _startTargetIndex ); if (_nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptRemove // internal class EditScriptRemove : EditScript { // Fields internal int _startSourceIndex; internal int _endSourceIndex; // Constructor internal EditScriptRemove( int startSourceIndex, int endSourceIndex, EditScript next ) : base ( next ) { Debug.Assert( endSourceIndex - startSourceIndex >= 0 ); Debug.Assert( startSourceIndex > 0 ); Debug.Assert( endSourceIndex > 0 ); _startSourceIndex = startSourceIndex; _endSourceIndex = endSourceIndex; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.Remove; } } // Methods #if DEBUG internal override void Dump() { if ( _endSourceIndex - _startSourceIndex > 0 ) Trace.WriteLine( "remove s" + _startSourceIndex + "-s" + _endSourceIndex ); else Trace.WriteLine( "remove s" + _startSourceIndex ); if (_nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptChange // internal class EditScriptChange : EditScript { // Fields internal int _sourceIndex, _targetIndex; internal XmlDiffOperation _changeOp; // Constructor internal EditScriptChange( int sourceIndex, int targetIndex, XmlDiffOperation changeOp, EditScript next ) : base( next ) { Debug.Assert( sourceIndex > 0 ); Debug.Assert( targetIndex > 0 ); Debug.Assert( XmlDiff.IsChangeOperation( changeOp) ); _sourceIndex = sourceIndex; _targetIndex = targetIndex; _changeOp = changeOp; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.ChangeNode; } } // Methods #if DEBUG internal override void Dump() { Trace.WriteLine( "change s" + _sourceIndex + " to t" + _targetIndex ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptOpened // internal abstract class EditScriptOpened : EditScript { // Constructor internal EditScriptOpened( EditScript next ) : base ( next ) {} } ////////////////////////////////////////////////////////////////// // EditScriptMatchOpened // internal class EditScriptMatchOpened : EditScriptOpened { // Fields internal int _startSourceIndex; internal int _startTargetIndex; // Constructor internal EditScriptMatchOpened( int startSourceIndex, int startTargetIndex, EditScript next ) : base ( next ) { Debug.Assert( startSourceIndex > 0 ); Debug.Assert( startTargetIndex > 0 ); _startSourceIndex = startSourceIndex; _startTargetIndex = startTargetIndex; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.OpenedMatch; } } // Methods internal override EditScript GetClosedScript( int currentSourceIndex, int currentTargetIndex ) { Debug.Assert( _startSourceIndex - currentSourceIndex == _startTargetIndex - currentTargetIndex ); Debug.Assert( currentSourceIndex - _startSourceIndex >= 0 ); Debug.Assert( currentTargetIndex - _startTargetIndex >= 0 ); return new EditScriptMatch( _startSourceIndex, _startTargetIndex, currentSourceIndex - _startSourceIndex + 1, _nextEditScript ); } #if DEBUG internal override void Dump() { Trace.WriteLine( "opened match: s" + _startSourceIndex + " to t" + _startTargetIndex ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptAddOpened // internal class EditScriptAddOpened : EditScriptOpened { // Fields internal int _startTargetIndex; // Constructor internal EditScriptAddOpened( int startTargetIndex, EditScript next ) : base ( next ) { Debug.Assert( startTargetIndex > 0 ); _startTargetIndex = startTargetIndex; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.OpenedAdd; } } // Methods internal override EditScript GetClosedScript( int currentSourceIndex, int currentTargetIndex ) { Debug.Assert( currentTargetIndex - _startTargetIndex >= 0 ); return new EditScriptAdd( _startTargetIndex, currentTargetIndex, _nextEditScript ); } #if DEBUG internal override void Dump() { Trace.WriteLine( "opened add: t" + _startTargetIndex ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptRemoveOpened // internal class EditScriptRemoveOpened : EditScriptOpened { // Fields internal int _startSourceIndex; // Constructor internal EditScriptRemoveOpened( int startSourceIndex, EditScript next ) : base ( next ) { Debug.Assert( startSourceIndex > 0 ); _startSourceIndex = startSourceIndex; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.OpenedRemove; } } // Methods internal override EditScript GetClosedScript( int currentSourceIndex, int currentTargetIndex ) { Debug.Assert( currentSourceIndex - _startSourceIndex >= 0 ); return new EditScriptRemove( _startSourceIndex, currentSourceIndex, _nextEditScript ); } #if DEBUG internal override void Dump() { Trace.WriteLine( "opened remove: s" + _startSourceIndex ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptReference // internal class EditScriptReference : EditScript { // Fields internal EditScript _editScriptReference; // Constructor internal EditScriptReference( EditScript editScriptReference, EditScript next ) : base( next ) { Debug.Assert( editScriptReference != null ); Debug.Assert( next != null ); _editScriptReference = editScriptReference; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.EditScriptReference; } } // Methods #if DEBUG internal override void Dump() { Trace.WriteLine( "REFERENCE EDIT SCRIPT - start" ); _editScriptReference.Dump(); Trace.WriteLine( "REFERENCE EDIT SCRIPT - end" ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } ////////////////////////////////////////////////////////////////// // EditScriptReference // internal class EditScriptPostponed : EditScript { // Fields internal DiffgramOperation _diffOperation; internal int _startSourceIndex; internal int _endSourceIndex; // Constructor internal EditScriptPostponed( DiffgramOperation diffOperation, int startSourceIndex, int endSourceIndex ) : base( null ) { Debug.Assert( diffOperation != null ); Debug.Assert( startSourceIndex > 0 ); Debug.Assert( endSourceIndex > 0 ); _diffOperation = diffOperation; _startSourceIndex = startSourceIndex; _endSourceIndex = endSourceIndex; } // Properties internal override EditScriptOperation Operation { get { return EditScriptOperation.EditScriptPostponed; } } // Methods #if DEBUG internal override void Dump() { Trace.WriteLine( "postponed edit script: s" + _startSourceIndex + "-s" + _endSourceIndex ); if ( _nextEditScript != null ) _nextEditScript.Dump(); } #endif } };
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Text; using Microsoft.CSharp.RuntimeBinder.Semantics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Errors { internal struct UserStringBuilder { private StringBuilder _strBuilder; private void BeginString() { Debug.Assert(_strBuilder == null || _strBuilder.Length == 0); if(_strBuilder == null) { _strBuilder = new StringBuilder(); } } private string EndString() { Debug.Assert(_strBuilder != null); string s = _strBuilder.ToString(); _strBuilder.Clear(); return s; } private static string ErrSK(SYMKIND sk) { MessageID id; switch (sk) { case SYMKIND.SK_MethodSymbol: id = MessageID.SK_METHOD; break; case SYMKIND.SK_AggregateSymbol: id = MessageID.SK_CLASS; break; case SYMKIND.SK_NamespaceSymbol: id = MessageID.SK_NAMESPACE; break; case SYMKIND.SK_FieldSymbol: id = MessageID.SK_FIELD; break; case SYMKIND.SK_LocalVariableSymbol: id = MessageID.SK_VARIABLE; break; case SYMKIND.SK_PropertySymbol: id = MessageID.SK_PROPERTY; break; case SYMKIND.SK_EventSymbol: id = MessageID.SK_EVENT; break; case SYMKIND.SK_TypeParameterSymbol: id = MessageID.SK_TYVAR; break; default: Debug.Fail("impossible sk"); id = MessageID.SK_UNKNOWN; break; } return ErrId(id); } /* * Create a fill-in string describing a parameter list. * Does NOT include () */ private void ErrAppendParamList(TypeArray @params, bool isParamArray) { if (null == @params) return; for (int i = 0; i < @params.Count; i++) { if (i > 0) { ErrAppendString(", "); } if (isParamArray && i == @params.Count - 1) { ErrAppendString("params "); } // parameter type name ErrAppendType(@params[i], null); } } private void ErrAppendString(string str) { _strBuilder.Append(str); } private void ErrAppendChar(char ch) { _strBuilder.Append(ch); } private void ErrAppendPrintf(string format, params object[] args) { ErrAppendString(string.Format(CultureInfo.InvariantCulture, format, args)); } private void ErrAppendName(Name name) { if (name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL)) { ErrAppendString("this"); } else { ErrAppendString(name.Text); } } private void ErrAppendParentSym(Symbol sym, SubstContext pctx) { ErrAppendParentCore(sym.parent, pctx); } private void ErrAppendParentCore(Symbol parent, SubstContext pctx) { if (parent == null || parent == NamespaceSymbol.Root) { return; } if (pctx != null && !pctx.IsNop && parent is AggregateSymbol agg && 0 != agg.GetTypeVarsAll().Count) { CType pType = TypeManager.SubstType(agg.getThisType(), pctx); ErrAppendType(pType, null); } else { ErrAppendSym(parent, null); } ErrAppendChar('.'); } private void ErrAppendTypeParameters(TypeArray @params, SubstContext pctx) { if (@params != null && @params.Count != 0) { ErrAppendChar('<'); ErrAppendType(@params[0], pctx); for (int i = 1; i < @params.Count; i++) { ErrAppendString(","); ErrAppendType(@params[i], pctx); } ErrAppendChar('>'); } } private void ErrAppendMethod(MethodSymbol meth, SubstContext pctx, bool fArgs) { if (meth.IsExpImpl() && meth.swtSlot) { ErrAppendParentSym(meth, pctx); // Get the type args from the explicit impl type and substitute using pctx (if there is one). SubstContext ctx = new SubstContext(TypeManager.SubstType(meth.swtSlot.GetType(), pctx)); ErrAppendSym(meth.swtSlot.Sym, ctx, fArgs); // args already added return; } MethodKindEnum methodKind = meth.MethKind; switch (methodKind) { case MethodKindEnum.PropAccessor: PropertySymbol prop = meth.getProperty(); // this includes the parent class ErrAppendSym(prop, pctx); // add accessor name if (prop.GetterMethod == meth) { ErrAppendString(".get"); } else { Debug.Assert(meth == prop.SetterMethod); ErrAppendString(".set"); } // args already added return; case MethodKindEnum.EventAccessor: EventSymbol @event = meth.getEvent(); // this includes the parent class ErrAppendSym(@event, pctx); // add accessor name if (@event.methAdd == meth) { ErrAppendString(".add"); } else { Debug.Assert(meth == @event.methRemove); ErrAppendString(".remove"); } // args already added return; } ErrAppendParentSym(meth, pctx); switch (methodKind) { case MethodKindEnum.Constructor: // Use the name of the parent class instead of the name "<ctor>". ErrAppendName(meth.getClass().name); break; case MethodKindEnum.Destructor: // Use the name of the parent class instead of the name "Finalize". ErrAppendChar('~'); goto case MethodKindEnum.Constructor; case MethodKindEnum.ExplicitConv: ErrAppendString("explicit"); goto convOperatorName; case MethodKindEnum.ImplicitConv: ErrAppendString("implicit"); convOperatorName: ErrAppendString(" operator "); // destination type name ErrAppendType(meth.RetType, pctx); break; default: if (meth.isOperator) { // handle user defined operators // map from CLS predefined names to "operator <X>" ErrAppendString("operator "); ErrAppendString(Operators.OperatorOfMethodName(meth.name)); } else if (!meth.IsExpImpl()) { // regular method ErrAppendName(meth.name); } break; } ErrAppendTypeParameters(meth.typeVars, pctx); if (fArgs) { // append argument types ErrAppendChar('('); ErrAppendParamList(TypeManager.SubstTypeArray(meth.Params, pctx), meth.isParamArray); ErrAppendChar(')'); } } private void ErrAppendIndexer(IndexerSymbol indexer, SubstContext pctx) { ErrAppendString("this["); ErrAppendParamList(TypeManager.SubstTypeArray(indexer.Params, pctx), indexer.isParamArray); ErrAppendChar(']'); } private void ErrAppendProperty(PropertySymbol prop, SubstContext pctx) { ErrAppendParentSym(prop, pctx); if (prop.IsExpImpl()) { if (prop.swtSlot.Sym != null) { SubstContext ctx = new SubstContext(TypeManager.SubstType(prop.swtSlot.GetType(), pctx)); ErrAppendSym(prop.swtSlot.Sym, ctx); } else if (prop is IndexerSymbol indexer) { ErrAppendChar('.'); ErrAppendIndexer(indexer, pctx); } } else if (prop is IndexerSymbol indexer) { ErrAppendIndexer(indexer, pctx); } else { ErrAppendName(prop.name); } } private void ErrAppendId(MessageID id) => ErrAppendString(ErrId(id)); /* * Create a fill-in string describing a symbol. */ private void ErrAppendSym(Symbol sym, SubstContext pctx) { ErrAppendSym(sym, pctx, true); } private void ErrAppendSym(Symbol sym, SubstContext pctx, bool fArgs) { switch (sym.getKind()) { case SYMKIND.SK_AggregateSymbol: { // Check for a predefined class with a special "nice" name for // error reported. string text = PredefinedTypes.GetNiceName(sym as AggregateSymbol); if (text != null) { // Found a nice name. ErrAppendString(text); } else { ErrAppendParentSym(sym, pctx); ErrAppendName(sym.name); ErrAppendTypeParameters(((AggregateSymbol)sym).GetTypeVars(), pctx); } break; } case SYMKIND.SK_MethodSymbol: ErrAppendMethod((MethodSymbol)sym, pctx, fArgs); break; case SYMKIND.SK_PropertySymbol: ErrAppendProperty((PropertySymbol)sym, pctx); break; case SYMKIND.SK_EventSymbol: break; case SYMKIND.SK_NamespaceSymbol: if (sym == NamespaceSymbol.Root) { ErrAppendId(MessageID.GlobalNamespace); } else { ErrAppendParentSym(sym, null); ErrAppendName(sym.name); } break; case SYMKIND.SK_FieldSymbol: ErrAppendParentSym(sym, pctx); ErrAppendName(sym.name); break; case SYMKIND.SK_TypeParameterSymbol: if (null == sym.name) { var parSym = (TypeParameterSymbol)sym; // It's a standard type variable. if (parSym.IsMethodTypeParameter()) ErrAppendChar('!'); ErrAppendChar('!'); ErrAppendPrintf("{0}", parSym.GetIndexInTotalParameters()); } else ErrAppendName(sym.name); break; case SYMKIND.SK_LocalVariableSymbol: // Generate symbol name. ErrAppendName(sym.name); break; default: // Shouldn't happen. Debug.Fail($"Bad symbol kind: {sym.getKind()}"); break; } } private void ErrAppendType(CType pType, SubstContext pctx) { if (pctx != null && !pctx.IsNop) { pType = TypeManager.SubstType(pType, pctx); } switch (pType.TypeKind) { case TypeKind.TK_AggregateType: { AggregateType pAggType = (AggregateType)pType; // Check for a predefined class with a special "nice" name for // error reported. string text = PredefinedTypes.GetNiceName(pAggType.OwningAggregate); if (text != null) { // Found a nice name. ErrAppendString(text); } else { if (pAggType.OuterType != null) { ErrAppendType(pAggType.OuterType, null); ErrAppendChar('.'); } else { // In a namespace. ErrAppendParentSym(pAggType.OwningAggregate, null); } ErrAppendName(pAggType.OwningAggregate.name); } ErrAppendTypeParameters(pAggType.TypeArgsThis, null); break; } case TypeKind.TK_TypeParameterType: TypeParameterType tpType = (TypeParameterType)pType; if (null == tpType.Name) { // It's a standard type variable. if (tpType.IsMethodTypeParameter) { ErrAppendChar('!'); } ErrAppendChar('!'); ErrAppendPrintf("{0}", tpType.IndexInTotalParameters); } else { ErrAppendName(tpType.Name); } break; case TypeKind.TK_NullType: // Load the string "<null>". ErrAppendId(MessageID.NULL); break; case TypeKind.TK_MethodGroupType: ErrAppendId(MessageID.MethodGroup); break; case TypeKind.TK_ArgumentListType: ErrAppendString(TokenFacts.GetText(TokenKind.ArgList)); break; case TypeKind.TK_ArrayType: { CType elementType = ((ArrayType)pType).BaseElementType; Debug.Assert(elementType != null, "No element type"); ErrAppendType(elementType, null); for (elementType = pType; elementType is ArrayType arrType; elementType = arrType.ElementType) { int rank = arrType.Rank; // Add [] with (rank-1) commas inside ErrAppendChar('['); // known rank. if (rank == 1) { if (!arrType.IsSZArray) { ErrAppendChar('*'); } } else { for (int i = rank; i > 1; --i) { ErrAppendChar(','); } } ErrAppendChar(']'); } break; } case TypeKind.TK_VoidType: ErrAppendName(NameManager.GetPredefinedName(PredefinedName.PN_VOID)); break; case TypeKind.TK_ParameterModifierType: ParameterModifierType mod = (ParameterModifierType)pType; // add ref or out ErrAppendString(mod.IsOut ? "out " : "ref "); // add base type name ErrAppendType(mod.ParameterType, null); break; case TypeKind.TK_PointerType: // Generate the base type. ErrAppendType(((PointerType)pType).ReferentType, null); { // add the trailing * ErrAppendChar('*'); } break; case TypeKind.TK_NullableType: ErrAppendType(((NullableType)pType).UnderlyingType, null); ErrAppendChar('?'); break; default: // Shouldn't happen. Debug.Fail("Bad type kind"); break; } } // Returns true if the argument could be converted to a string. public bool ErrArgToString(out string psz, ErrArg parg, out bool fUserStrings) { fUserStrings = false; psz = null; bool result = true; switch (parg.eak) { case ErrArgKind.SymKind: psz = ErrSK(parg.sk); break; case ErrArgKind.Type: BeginString(); ErrAppendType(parg.pType, null); psz = EndString(); fUserStrings = true; break; case ErrArgKind.Sym: BeginString(); ErrAppendSym(parg.sym, null); psz = EndString(); fUserStrings = true; break; case ErrArgKind.Name: if (parg.name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL)) { psz = "this"; } else { psz = parg.name.Text; } break; case ErrArgKind.Str: psz = parg.psz; break; case ErrArgKind.SymWithType: { SubstContext ctx = new SubstContext(parg.swtMemo.ats, null); BeginString(); ErrAppendSym(parg.swtMemo.sym, ctx, true); psz = EndString(); fUserStrings = true; break; } case ErrArgKind.MethWithInst: { SubstContext ctx = new SubstContext(parg.mpwiMemo.ats, parg.mpwiMemo.typeArgs); BeginString(); ErrAppendSym(parg.mpwiMemo.sym, ctx, true); psz = EndString(); fUserStrings = true; break; } default: result = false; break; } return result; } private static string ErrId(MessageID id) => ErrorFacts.GetMessage(id); } }
/* * Copyright (C) 2009 The Android Open Source Project * * 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 Android.Content; using Android.Graphics; using Android.OS; using Android.Util; using Android.Views; using Android.Widget; using System; namespace Xamarians.CropImage.Droid { public abstract class ImageViewTouchBase : ImageView { #region Members // This is the base transformation which is used to show the image // initially. The current computation for this shows the image in // it's entirety, letterboxing as needed. One could choose to // show the image as cropped instead. // // This matrix is recomputed when we go from the thumbnail image to // the full size image. protected Matrix baseMatrix = new Matrix(); // This is the supplementary transformation which reflects what // the user has done in terms of zooming and panning. // // This matrix remains the same when we go from the thumbnail image // to the full size image. protected Matrix suppMatrix = new Matrix(); // This is the final matrix which is computed as the concatentation // of the base matrix and the supplementary matrix. private Matrix displayMatrix = new Matrix(); // Temporary buffer used for getting the values out of a matrix. private float[] matrixValues = new float[9]; // The current bitmap being displayed. protected RotateBitmap bitmapDisplayed = new RotateBitmap(null); private int thisWidth = -1; private int thisHeight = -1; const float SCALE_RATE = 1.25F; private float maxZoom; private Handler handler = new Handler(); private Action onLayoutRunnable = null; #endregion #region Constructor public ImageViewTouchBase(Context context) : base(context) { init(); } public ImageViewTouchBase(Context context, IAttributeSet attrs) : base(context, attrs) { init(); } #endregion #region Private helpers private void init() { SetScaleType(ImageView.ScaleType.Matrix); } private void setImageBitmap(Bitmap bitmap, int rotation) { base.SetImageBitmap(bitmap); var d = Drawable; if (d != null) { d.SetDither(true); } Bitmap old = bitmapDisplayed.Bitmap; bitmapDisplayed.Bitmap = bitmap; bitmapDisplayed.Rotation = rotation; } #endregion #region Public methods public void Clear() { SetImageBitmapResetBase(null, true); } /// <summary> /// This function changes bitmap, reset base matrix according to the size /// of the bitmap, and optionally reset the supplementary matrix. /// </summary> public void SetImageBitmapResetBase(Bitmap bitmap, bool resetSupp) { SetImageRotateBitmapResetBase(new RotateBitmap(bitmap), resetSupp); } public void SetImageRotateBitmapResetBase(RotateBitmap bitmap, bool resetSupp) { int viewWidth = Width; if (viewWidth <= 0) { onLayoutRunnable = () => { SetImageRotateBitmapResetBase(bitmap, resetSupp); }; return; } if (bitmap.Bitmap != null) { getProperBaseMatrix(bitmap, baseMatrix); setImageBitmap(bitmap.Bitmap, bitmap.Rotation); } else { baseMatrix.Reset(); base.SetImageBitmap(null); } if (resetSupp) { suppMatrix.Reset(); } ImageMatrix = GetImageViewMatrix(); this.maxZoom = CalculateMaxZoom(); } #endregion #region Overrides protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { this.IvLeft = left; this.IvRight = right; this.IvTop = top; this.IvBottom = bottom; thisWidth = right - left; thisHeight = bottom - top; var r = onLayoutRunnable; if (r != null) { onLayoutRunnable = null; r(); } if (bitmapDisplayed.Bitmap != null) { getProperBaseMatrix(bitmapDisplayed, baseMatrix); ImageMatrix = GetImageViewMatrix(); } } public override bool OnKeyDown(Keycode keyCode, KeyEvent e) { if (keyCode == Keycode.Back && GetScale() > 1.0f) { // If we're zoomed in, pressing Back jumps out to show the entire // image, otherwise Back returns the user to the gallery. ZoomTo(1.0f); return true; } return base.OnKeyDown(keyCode, e); } public override void SetImageBitmap(Bitmap bm) { setImageBitmap(bm, 0); } #endregion #region Properties public int IvLeft { get; private set; } public int IvRight { get; private set; } public int IvTop { get; private set; } public int IvBottom { get; private set; } #endregion #region Protected methods protected float GetValue(Matrix matrix, int whichValue) { matrix.GetValues(matrixValues); return matrixValues[whichValue]; } /// <summary> /// Get the scale factor out of the matrix. /// </summary> protected float GetScale(Matrix matrix) { return GetValue(matrix, Matrix.MscaleX); } protected float GetScale() { return GetScale(suppMatrix); } /// <summary> /// Setup the base matrix so that the image is centered and scaled properly. /// </summary> private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) { float viewWidth = Width; float viewHeight = Height; float w = bitmap.Width; float h = bitmap.Height; int rotation = bitmap.Rotation; matrix.Reset(); // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math.Min(viewWidth / w, 2.0f); float heightScale = Math.Min(viewHeight / h, 2.0f); float scale = Math.Min(widthScale, heightScale); matrix.PostConcat(bitmap.GetRotateMatrix()); matrix.PostScale(scale, scale); matrix.PostTranslate( (viewWidth - w * scale) / 2F, (viewHeight - h * scale) / 2F); } // Combine the base matrix and the supp matrix to make the final matrix. protected Matrix GetImageViewMatrix() { // The final matrix is computed as the concatentation of the base matrix // and the supplementary matrix. displayMatrix.Set(baseMatrix); displayMatrix.PostConcat(suppMatrix); return displayMatrix; } // Sets the maximum zoom, which is a scale relative to the base matrix. It // is calculated to show the image at 400% zoom regardless of screen or // image orientation. If in the future we decode the full 3 megapixel image, // rather than the current 1024x768, this should be changed down to 200%. protected float CalculateMaxZoom() { if (bitmapDisplayed.Bitmap == null) { return 1F; } float fw = (float)bitmapDisplayed.Width / (float)thisWidth; float fh = (float)bitmapDisplayed.Height / (float)thisHeight; float max = Math.Max(fw, fh) * 4; return max; } protected virtual void ZoomTo(float scale, float centerX, float centerY) { if (scale > maxZoom) { scale = maxZoom; } float oldScale = GetScale(); float deltaScale = scale / oldScale; suppMatrix.PostScale(deltaScale, deltaScale, centerX, centerY); ImageMatrix = GetImageViewMatrix(); Center(true, true); } protected void ZoomTo(float scale, float centerX, float centerY, float durationMs) { float incrementPerMs = (scale - GetScale()) / durationMs; float oldScale = GetScale(); long startTime = System.Environment.TickCount; Action anim = null; anim = () => { long now = System.Environment.TickCount; float currentMs = Math.Min(durationMs, now - startTime); float target = oldScale + (incrementPerMs * currentMs); ZoomTo(target, centerX, centerY); if (currentMs < durationMs) { handler.Post(anim); } }; handler.Post(anim); } protected void ZoomTo(float scale) { float cx = Width / 2F; float cy = Height / 2F; ZoomTo(scale, cx, cy); } protected virtual void ZoomIn() { ZoomIn(SCALE_RATE); } protected virtual void ZoomOut() { ZoomOut(SCALE_RATE); } protected virtual void ZoomIn(float rate) { if (GetScale() >= maxZoom) { // Don't let the user zoom into the molecular level. return; } if (bitmapDisplayed.Bitmap == null) { return; } float cx = Width / 2F; float cy = Height / 2F; suppMatrix.PostScale(rate, rate, cx, cy); ImageMatrix = GetImageViewMatrix(); } protected void ZoomOut(float rate) { if (bitmapDisplayed.Bitmap == null) { return; } float cx = Width / 2F; float cy = Height / 2F; // Zoom out to at most 1x. Matrix tmp = new Matrix(suppMatrix); tmp.PostScale(1F / rate, 1F / rate, cx, cy); if (GetScale(tmp) < 1F) { suppMatrix.SetScale(1F, 1F, cx, cy); } else { suppMatrix.PostScale(1F / rate, 1F / rate, cx, cy); } ImageMatrix = GetImageViewMatrix(); Center(true, true); } protected virtual void PostTranslate(float dx, float dy) { suppMatrix.PostTranslate(dx, dy); } protected void PanBy(float dx, float dy) { PostTranslate(dx, dy); ImageMatrix = GetImageViewMatrix(); } /// <summary> /// Center as much as possible in one or both axis. Centering is /// defined as follows: if the image is scaled down below the /// view's dimensions then center it (literally). If the image /// is scaled larger than the view and is translated out of view /// then translate it back into view (i.e. eliminate black bars). /// </summary> protected void Center(bool horizontal, bool vertical) { if (bitmapDisplayed.Bitmap == null) { return; } Matrix m = GetImageViewMatrix(); RectF rect = new RectF(0, 0, bitmapDisplayed.Bitmap.Width, bitmapDisplayed.Bitmap.Height); m.MapRect(rect); float height = rect.Height(); float width = rect.Width(); float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = Height; if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - rect.Top; } else if (rect.Top > 0) { deltaY = -rect.Top; } else if (rect.Bottom < viewHeight) { deltaY = Height - rect.Bottom; } } if (horizontal) { int viewWidth = Width; if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - rect.Left; } else if (rect.Left > 0) { deltaX = -rect.Left; } else if (rect.Right < viewWidth) { deltaX = viewWidth - rect.Right; } } PostTranslate(deltaX, deltaY); ImageMatrix = GetImageViewMatrix(); } #endregion } }
namespace Nancy.Authentication.Forms { using System; using Nancy.Bootstrapper; using Nancy.Cookies; using Nancy.Cryptography; using Nancy.Extensions; using Nancy.Helpers; using Nancy.Security; /// <summary> /// Nancy forms authentication implementation /// </summary> public static class FormsAuthentication { private static string formsAuthenticationCookieName = "_ncfa"; // TODO - would prefer not to hold this here, but the redirect response needs it private static FormsAuthenticationConfiguration currentConfiguration; /// <summary> /// Gets or sets the forms authentication cookie name /// </summary> public static string FormsAuthenticationCookieName { get { return formsAuthenticationCookieName; } set { formsAuthenticationCookieName = value; } } /// <summary> /// Enables forms authentication for the application /// </summary> /// <param name="pipelines">Pipelines to add handlers to (usually "this")</param> /// <param name="configuration">Forms authentication configuration</param> public static void Enable(IPipelines pipelines, FormsAuthenticationConfiguration configuration) { if (pipelines == null) { throw new ArgumentNullException("pipelines"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (!configuration.IsValid) { throw new ArgumentException("Configuration is invalid", "configuration"); } currentConfiguration = configuration; pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration)); if (!configuration.DisableRedirect) { pipelines.AfterRequest.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration)); } } /// <summary> /// Enables forms authentication for a module /// </summary> /// <param name="module">Module to add handlers to (usually "this")</param> /// <param name="configuration">Forms authentication configuration</param> public static void Enable(INancyModule module, FormsAuthenticationConfiguration configuration) { if (module == null) { throw new ArgumentNullException("module"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (!configuration.IsValid) { throw new ArgumentException("Configuration is invalid", "configuration"); } module.RequiresAuthentication(); currentConfiguration = configuration; module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration)); if (!configuration.DisableRedirect) { module.After.AddItemToEndOfPipeline(GetRedirectToLoginHook(configuration)); } } /// <summary> /// Creates a response that sets the authentication cookie and redirects /// the user back to where they came from. /// </summary> /// <param name="context">Current context</param> /// <param name="userIdentifier">User identifier guid</param> /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param> /// <param name="fallbackRedirectUrl">Url to redirect to if none in the querystring</param> /// <returns>Nancy response with redirect.</returns> public static Response UserLoggedInRedirectResponse(NancyContext context, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = null) { var redirectUrl = fallbackRedirectUrl; if (string.IsNullOrEmpty(redirectUrl)) { redirectUrl = context.Request.Url.BasePath; } if (string.IsNullOrEmpty(redirectUrl)) { redirectUrl = "/"; } string redirectQuerystringKey = GetRedirectQuerystringKey(currentConfiguration); if (context.Request.Query[redirectQuerystringKey].HasValue) { var queryUrl = (string)context.Request.Query[redirectQuerystringKey]; if (context.IsLocalUrl(queryUrl)) { redirectUrl = queryUrl; } } var response = context.GetRedirect(redirectUrl); var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration); response.WithCookie(authenticationCookie); return response; } /// <summary> /// Logs the user in. /// </summary> /// <param name="userIdentifier">User identifier guid</param> /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param> /// <returns>Nancy response with status <see cref="HttpStatusCode.OK"/></returns> public static Response UserLoggedInResponse(Guid userIdentifier, DateTime? cookieExpiry = null) { var response = (Response)HttpStatusCode.OK; var authenticationCookie = BuildCookie(userIdentifier, cookieExpiry, currentConfiguration); response.WithCookie(authenticationCookie); return response; } /// <summary> /// Logs the user out and redirects them to a URL /// </summary> /// <param name="context">Current context</param> /// <param name="redirectUrl">URL to redirect to</param> /// <returns>Nancy response</returns> public static Response LogOutAndRedirectResponse(NancyContext context, string redirectUrl) { var response = context.GetRedirect(redirectUrl); var authenticationCookie = BuildLogoutCookie(currentConfiguration); response.WithCookie(authenticationCookie); return response; } /// <summary> /// Logs the user out. /// </summary> /// <returns>Nancy response</returns> public static Response LogOutResponse() { var response = (Response)HttpStatusCode.OK; var authenticationCookie = BuildLogoutCookie(currentConfiguration); response.WithCookie(authenticationCookie); return response; } /// <summary> /// Gets the pre request hook for loading the authenticated user's details /// from the cookie. /// </summary> /// <param name="configuration">Forms authentication configuration to use</param> /// <returns>Pre request hook delegate</returns> private static Func<NancyContext, Response> GetLoadAuthenticationHook(FormsAuthenticationConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("configuration"); } return context => { var userGuid = GetAuthenticatedUserFromCookie(context, configuration); if (userGuid != Guid.Empty) { context.CurrentUser = configuration.UserMapper.GetUserFromIdentifier(userGuid, context); } return null; }; } /// <summary> /// Gets the post request hook for redirecting to the login page /// </summary> /// <param name="configuration">Forms authentication configuration to use</param> /// <returns>Post request hook delegate</returns> private static Action<NancyContext> GetRedirectToLoginHook(FormsAuthenticationConfiguration configuration) { return context => { if (context.Response.StatusCode == HttpStatusCode.Unauthorized) { string redirectQuerystringKey = GetRedirectQuerystringKey(configuration); context.Response = context.GetRedirect( string.Format("{0}?{1}={2}", configuration.RedirectUrl, redirectQuerystringKey, context.ToFullPath("~" + context.Request.Path + HttpUtility.UrlEncode(context.Request.Url.Query)))); } }; } /// <summary> /// Gets the authenticated user GUID from the incoming request cookie if it exists /// and is valid. /// </summary> /// <param name="context">Current context</param> /// <param name="configuration">Current configuration</param> /// <returns>Returns user guid, or Guid.Empty if not present or invalid</returns> private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration) { if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName)) { return Guid.Empty; } var cookieValueEncrypted = context.Request.Cookies[formsAuthenticationCookieName]; if (string.IsNullOrEmpty(cookieValueEncrypted)) { return Guid.Empty; } var cookieValue = DecryptAndValidateAuthenticationCookie(cookieValueEncrypted, configuration); Guid returnGuid; if (String.IsNullOrEmpty(cookieValue) || !Guid.TryParse(cookieValue, out returnGuid)) { return Guid.Empty; } return returnGuid; } /// <summary> /// Build the forms authentication cookie /// </summary> /// <param name="userIdentifier">Authenticated user identifier</param> /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param> /// <param name="configuration">Current configuration</param> /// <returns>Nancy cookie instance</returns> private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration) { var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration); var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry); if(!string.IsNullOrEmpty(configuration.Domain)) { cookie.Domain = configuration.Domain; } if(!string.IsNullOrEmpty(configuration.Path)) { cookie.Path = configuration.Path; } return cookie; } /// <summary> /// Builds a cookie for logging a user out /// </summary> /// <param name="configuration">Current configuration</param> /// <returns>Nancy cookie instance</returns> private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration) { var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1)); if(!string.IsNullOrEmpty(configuration.Domain)) { cookie.Domain = configuration.Domain; } if(!string.IsNullOrEmpty(configuration.Path)) { cookie.Path = configuration.Path; } return cookie; } /// <summary> /// Encrypt and sign the cookie contents /// </summary> /// <param name="cookieValue">Plain text cookie value</param> /// <param name="configuration">Current configuration</param> /// <returns>Encrypted and signed string</returns> private static string EncryptAndSignCookie(string cookieValue, FormsAuthenticationConfiguration configuration) { var encryptedCookie = configuration.CryptographyConfiguration.EncryptionProvider.Encrypt(cookieValue); var hmacBytes = GenerateHmac(encryptedCookie, configuration); var hmacString = Convert.ToBase64String(hmacBytes); return String.Format("{1}{0}", encryptedCookie, hmacString); } /// <summary> /// Generate a hmac for the encrypted cookie string /// </summary> /// <param name="encryptedCookie">Encrypted cookie string</param> /// <param name="configuration">Current configuration</param> /// <returns>Hmac byte array</returns> private static byte[] GenerateHmac(string encryptedCookie, FormsAuthenticationConfiguration configuration) { return configuration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedCookie); } /// <summary> /// Decrypt and validate an encrypted and signed cookie value /// </summary> /// <param name="cookieValue">Encrypted and signed cookie value</param> /// <param name="configuration">Current configuration</param> /// <returns>Decrypted value, or empty on error or if failed validation</returns> public static string DecryptAndValidateAuthenticationCookie(string cookieValue, FormsAuthenticationConfiguration configuration) { var hmacStringLength = Base64Helpers.GetBase64Length(configuration.CryptographyConfiguration.HmacProvider.HmacLength); var encryptedCookie = cookieValue.Substring(hmacStringLength); var hmacString = cookieValue.Substring(0, hmacStringLength); var encryptionProvider = configuration.CryptographyConfiguration.EncryptionProvider; // Check the hmacs, but don't early exit if they don't match var hmacBytes = Convert.FromBase64String(hmacString); var newHmac = GenerateHmac(encryptedCookie, configuration); var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, configuration.CryptographyConfiguration.HmacProvider.HmacLength); var decrypted = encryptionProvider.Decrypt(encryptedCookie); // Only return the decrypted result if the hmac was ok return hmacValid ? decrypted : string.Empty; } /// <summary> /// Gets the redirect query string key from <see cref="FormsAuthenticationConfiguration"/> /// </summary> /// <param name="configuration">The forms authentication configuration.</param> /// <returns>Redirect Querystring key</returns> private static string GetRedirectQuerystringKey(FormsAuthenticationConfiguration configuration) { string redirectQuerystringKey = null; if (configuration != null) { redirectQuerystringKey = configuration.RedirectQuerystringKey; } if(string.IsNullOrWhiteSpace(redirectQuerystringKey)) { redirectQuerystringKey = FormsAuthenticationConfiguration.DefaultRedirectQuerystringKey; } return redirectQuerystringKey; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using QuantConnect.Securities.Option; using QuantConnect.Util; namespace QuantConnect.Data.Market { /// <summary> /// Represents an entire chain of option contracts for a single underying security. /// This type is <see cref="IEnumerable{OptionContract}"/> /// </summary> public class OptionChain : BaseData, IEnumerable<OptionContract> { private readonly Dictionary<Type, Dictionary<Symbol, List<BaseData>>> _auxiliaryData = new Dictionary<Type, Dictionary<Symbol, List<BaseData>>>(); /// <summary> /// Gets the most recent trade information for the underlying. This may /// be a <see cref="Tick"/> or a <see cref="TradeBar"/> /// </summary> public BaseData Underlying { get; internal set; } /// <summary> /// Gets all ticks for every option contract in this chain, keyed by option symbol /// </summary> public Ticks Ticks { get; private set; } /// <summary> /// Gets all trade bars for every option contract in this chain, keyed by option symbol /// </summary> public TradeBars TradeBars { get; private set; } /// <summary> /// Gets all quote bars for every option contract in this chain, keyed by option symbol /// </summary> public QuoteBars QuoteBars { get; private set; } /// <summary> /// Gets all contracts in the chain, keyed by option symbol /// </summary> public OptionContracts Contracts { get; private set; } /// <summary> /// Gets the set of symbols that passed the <see cref="Option.ContractFilter"/> /// </summary> public HashSet<Symbol> FilteredContracts { get; private set; } /// <summary> /// Initializes a new default instance of the <see cref="OptionChain"/> class /// </summary> private OptionChain() { DataType = MarketDataType.OptionChain; } /// <summary> /// Initializes a new instance of the <see cref="OptionChain"/> class /// </summary> /// <param name="canonicalOptionSymbol">The symbol for this chain.</param> /// <param name="time">The time of this chain</param> public OptionChain(Symbol canonicalOptionSymbol, DateTime time) { Time = time; Symbol = canonicalOptionSymbol; DataType = MarketDataType.OptionChain; Ticks = new Ticks(time); TradeBars = new TradeBars(time); QuoteBars = new QuoteBars(time); Contracts = new OptionContracts(time); FilteredContracts = new HashSet<Symbol>(); Underlying = new QuoteBar(); } /// <summary> /// Initializes a new instance of the <see cref="OptionChain"/> class /// </summary> /// <param name="canonicalOptionSymbol">The symbol for this chain.</param> /// <param name="time">The time of this chain</param> /// <param name="underlying">The most recent underlying trade data</param> /// <param name="trades">All trade data for the entire option chain</param> /// <param name="quotes">All quote data for the entire option chain</param> /// <param name="contracts">All contrains for this option chain</param> public OptionChain(Symbol canonicalOptionSymbol, DateTime time, BaseData underlying, IEnumerable<BaseData> trades, IEnumerable<BaseData> quotes, IEnumerable<OptionContract> contracts, IEnumerable<Symbol> filteredContracts) { Time = time; Underlying = underlying; Symbol = canonicalOptionSymbol; DataType = MarketDataType.OptionChain; FilteredContracts = filteredContracts.ToHashSet(); Ticks = new Ticks(time); TradeBars = new TradeBars(time); QuoteBars = new QuoteBars(time); Contracts = new OptionContracts(time); foreach (var trade in trades) { var tick = trade as Tick; if (tick != null) { List<Tick> ticks; if (!Ticks.TryGetValue(tick.Symbol, out ticks)) { ticks = new List<Tick>(); Ticks[tick.Symbol] = ticks; } ticks.Add(tick); continue; } var bar = trade as TradeBar; if (bar != null) { TradeBars[trade.Symbol] = bar; } } foreach (var quote in quotes) { var tick = quote as Tick; if (tick != null) { List<Tick> ticks; if (!Ticks.TryGetValue(tick.Symbol, out ticks)) { ticks = new List<Tick>(); Ticks[tick.Symbol] = ticks; } ticks.Add(tick); continue; } var bar = quote as QuoteBar; if (bar != null) { QuoteBars[quote.Symbol] = bar; } } foreach (var contract in contracts) { Contracts[contract.Symbol] = contract; } } /// <summary> /// Gets the auxiliary data with the specified type and symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <param name="symbol">The symbol of the auxiliary data</param> /// <returns>The last auxiliary data with the specified type and symbol</returns> public T GetAux<T>(Symbol symbol) { List<BaseData> list; Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list)) { return default(T); } return list.OfType<T>().LastOrDefault(); } /// <summary> /// Gets all auxiliary data of the specified type as a dictionary keyed by symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <returns>A dictionary containing all auxiliary data of the specified type</returns> public DataDictionary<T> GetAux<T>() { Dictionary<Symbol, List<BaseData>> d; if (!_auxiliaryData.TryGetValue(typeof(T), out d)) { return new DataDictionary<T>(); } var dictionary = new DataDictionary<T>(); foreach (var kvp in d) { var item = kvp.Value.OfType<T>().LastOrDefault(); if (item != null) { dictionary.Add(kvp.Key, item); } } return dictionary; } /// <summary> /// Gets all auxiliary data of the specified type as a dictionary keyed by symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <returns>A dictionary containing all auxiliary data of the specified type</returns> public Dictionary<Symbol, List<BaseData>> GetAuxList<T>() { Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary)) { return new Dictionary<Symbol, List<BaseData>>(); } return dictionary; } /// <summary> /// Gets a list of auxiliary data with the specified type and symbol /// </summary> /// <typeparam name="T">The type of auxiliary data</typeparam> /// <param name="symbol">The symbol of the auxiliary data</param> /// <returns>The list of auxiliary data with the specified type and symbol</returns> public List<T> GetAuxList<T>(Symbol symbol) { List<BaseData> list; Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list)) { return new List<T>(); } return list.OfType<T>().ToList(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An enumerator that can be used to iterate through the collection. /// </returns> public IEnumerator<OptionContract> GetEnumerator() { return Contracts.Values.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Return a new instance clone of this object, used in fill forward /// </summary> /// <returns>A clone of the current object</returns> public override BaseData Clone() { return new OptionChain { Underlying = Underlying, Ticks = Ticks, Contracts = Contracts, QuoteBars = QuoteBars, TradeBars = TradeBars, FilteredContracts = FilteredContracts, Symbol = Symbol, Time = Time, DataType = DataType, Value = Value }; } /// <summary> /// Adds the specified auxiliary data to this option chain /// </summary> /// <param name="baseData">The auxiliary data to be added</param> internal void AddAuxData(BaseData baseData) { var type = baseData.GetType(); Dictionary<Symbol, List<BaseData>> dictionary; if (!_auxiliaryData.TryGetValue(type, out dictionary)) { dictionary = new Dictionary<Symbol, List<BaseData>>(); _auxiliaryData[type] = dictionary; } List<BaseData> list; if (!dictionary.TryGetValue(baseData.Symbol, out list)) { list = new List<BaseData>(); dictionary[baseData.Symbol] = list; } list.Add(baseData); } } }
// 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 System.Linq.Expressions.Tests { public static class BinaryAddTests { #region Test methods [Fact] public static void CheckByteAddTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteAdd(array[i], array[j]); } } } [Fact] public static void CheckSByteAddTest() { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteAdd(array[i], array[j]); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUShortAddTest(bool useInterpreter) { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortAdd(array[i], array[j], useInterpreter); VerifyUShortAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckShortAddTest(bool useInterpreter) { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortAdd(array[i], array[j], useInterpreter); VerifyShortAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUIntAddTest(bool useInterpreter) { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntAdd(array[i], array[j], useInterpreter); VerifyUIntAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckIntAddTest(bool useInterpreter) { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntAdd(array[i], array[j], useInterpreter); VerifyIntAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckULongAddTest(bool useInterpreter) { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongAdd(array[i], array[j], useInterpreter); VerifyULongAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLongAddTest(bool useInterpreter) { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongAdd(array[i], array[j], useInterpreter); VerifyLongAddOvf(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckFloatAddTest(bool useInterpreter) { float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyFloatAdd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDoubleAddTest(bool useInterpreter) { double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDoubleAdd(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecimalAddTest(bool useInterpreter) { decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDecimalAdd(array[i], array[j], useInterpreter); } } } [Fact] public static void CheckCharAddTest() { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharAdd(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteAdd(byte a, byte b) { Expression aExp = Expression.Constant(a, typeof(byte)); Expression bExp = Expression.Constant(b, typeof(byte)); Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp)); } private static void VerifySByteAdd(sbyte a, sbyte b) { Expression aExp = Expression.Constant(a, typeof(sbyte)); Expression bExp = Expression.Constant(b, typeof(sbyte)); Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp)); } private static void VerifyUShortAdd(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Add( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort)(a + b)), f()); } private static void VerifyUShortAddOvf(ushort a, ushort b, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.AddChecked( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); int expected = a + b; if (expected < 0 || expected > ushort.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyShortAdd(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Add( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal(unchecked((short)(a + b)), f()); } private static void VerifyShortAddOvf(short a, short b, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.AddChecked( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); int expected = a + b; if (expected < short.MinValue || expected > short.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyUIntAdd(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Add( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyUIntAddOvf(uint a, uint b, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.AddChecked( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); long expected = a + (long)b; if (expected < 0 || expected > uint.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyIntAdd(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Add( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyIntAddOvf(int a, int b, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.AddChecked( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); long expected = a + (long)b; if (expected < int.MinValue || expected > int.MaxValue) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(expected, f()); } private static void VerifyULongAdd(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Add( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyULongAddOvf(ulong a, ulong b, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.AddChecked( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); ulong expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyLongAdd(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Add( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(unchecked(a + b), f()); } private static void VerifyLongAddOvf(long a, long b, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.AddChecked( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); long expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyFloatAdd(float a, float b, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Add( Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); float expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyDoubleAdd(double a, double b, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Add( Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); double expected = 0; try { expected = checked(a + b); } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyDecimalAdd(decimal a, decimal b, bool useInterpreter) { Expression<Func<decimal>> e = Expression.Lambda<Func<decimal>>( Expression.Add( Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<decimal> f = e.Compile(useInterpreter); decimal expected = 0; try { expected = a + b; } catch (OverflowException) { Assert.Throws<OverflowException>(() => f()); return; } Assert.Equal(expected, f()); } private static void VerifyCharAdd(char a, char b) { Expression aExp = Expression.Constant(a, typeof(char)); Expression bExp = Expression.Constant(b, typeof(char)); Assert.Throws<InvalidOperationException>(() => Expression.Add(aExp, bExp)); } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.Add(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void CannotReduceChecked() { Expression exp = Expression.AddChecked(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); AssertExtensions.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.Add(null, Expression.Constant(""))); } [Fact] public static void ThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.Add(Expression.Constant(""), null)); } [Fact] public static void CheckedThrowsOnLeftNull() { AssertExtensions.Throws<ArgumentNullException>("left", () => Expression.AddChecked(null, Expression.Constant(""))); } [Fact] public static void CheckedThrowsOnRightNull() { AssertExtensions.Throws<ArgumentNullException>("right", () => Expression.AddChecked(Expression.Constant(""), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.Add(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value)); } [Fact] public static void CheckedThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("left", () => Expression.AddChecked(value, Expression.Constant(1))); } [Fact] public static void CheckedThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); AssertExtensions.Throws<ArgumentException>("right", () => Expression.Add(Expression.Constant(1), value)); } [Fact] public static void ToStringTest() { BinaryExpression e1 = Expression.Add(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a + b)", e1.ToString()); BinaryExpression e2 = Expression.AddChecked(Expression.Parameter(typeof(int), "a"), Expression.Parameter(typeof(int), "b")); Assert.Equal("(a + b)", e2.ToString()); } } }
// Generated by UblXml2CSharp using System.Xml; using UblLarsen.Ubl2; using UblLarsen.Ubl2.Cac; using UblLarsen.Ubl2.Ext; using UblLarsen.Ubl2.Udt; namespace UblLarsen.Test.UblClass { internal class UBLInvoice20Example { public static InvoiceType Create() { var doc = new InvoiceType { UBLVersionID = "2.0", CustomizationID = "urn:oasis:names:specification:ubl:xpath:Invoice-2.0:sbs-1.0-draft", ProfileID = "bpid:urn:oasis:names:draft:bpss:ubl-2-sbs-invoice-notification-draft", ID = "A00095678", CopyIndicator = false, UUID = "849FBBCE-E081-40B4-906C-94C5FF9D1AC3", IssueDate = "2005-06-21", InvoiceTypeCode = "SalesInvoice", Note = new TextType[] { new TextType { Value = "sample" } }, TaxPointDate = "2005-06-21", OrderReference = new OrderReferenceType { ID = "AEG012345", SalesOrderID = "CON0095678", UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20" }, AccountingSupplierParty = new SupplierPartyType { CustomerAssignedAccountID = "CO001", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Consortial" } }, PostalAddress = new AddressType { StreetName = "Busy Street", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "The Roundabout" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Farthing Purchasing Consortium", CompanyID = "175 269 2355", ExemptionReason = new TextType[] { new TextType { Value = "N/A" } }, TaxScheme = new TaxSchemeType { ID = "VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mrs Bouquet", Telephone = "0158 1233714", Telefax = "0158 1233856", ElectronicMail = "bouquet@fpconsortial.co.uk" } } }, AccountingCustomerParty = new CustomerPartyType { CustomerAssignedAccountID = "XFB01", SupplierAssignedAccountID = "GT00978567", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "IYT Corporation" } }, PostalAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Bridgtow District Council", CompanyID = "12356478", ExemptionReason = new TextType[] { new TextType { Value = "Local Authority" } }, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mr Fred Churchill", Telephone = "0127 2653214", Telefax = "0127 2653215", ElectronicMail = "fred@iytcorporation.gov.uk" } } }, Delivery = new DeliveryType[] { new DeliveryType { ActualDeliveryDate = "2005-06-20", ActualDeliveryTime = "11:30:00.0Z", DeliveryAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } } } }, PaymentMeans = new PaymentMeansType[] { new PaymentMeansType { PaymentMeansCode = "20", PaymentDueDate = "2005-07-21", PayeeFinancialAccount = new FinancialAccountType { ID = "12345678", Name = "Farthing Purchasing Consortium", AccountTypeCode = "Current", CurrencyCode = "GBP", FinancialInstitutionBranch = new BranchType { ID = "10-26-58", Name = "Open Bank Ltd, Bridgstow Branch ", FinancialInstitution = new FinancialInstitutionType { ID = "10-26-58", Name = "Open Bank Ltd", Address = new AddressType { StreetName = "City Road", BuildingName = "Banking House", BuildingNumber = "12", CityName = "London", PostalZone = "AQ1 6TH", CountrySubentity = @"London ", AddressLine = new AddressLineType[] { new AddressLineType { Line = "5th Floor" } }, Country = new CountryType { IdentificationCode = "GB" } } }, Address = new AddressType { StreetName = "Busy Street", BuildingName = "The Mall", BuildingNumber = "152", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "West Wing" } }, Country = new CountryType { IdentificationCode = "GB" } } }, Country = new CountryType { IdentificationCode = "GB" } } } }, PaymentTerms = new PaymentTermsType[] { new PaymentTermsType { Note = new TextType[] { new TextType { Value = "Payable within 1 calendar month from the invoice date" } } } }, AllowanceCharge = new AllowanceChargeType[] { new AllowanceChargeType { ChargeIndicator = false, AllowanceChargeReasonCode = "17", MultiplierFactorNumeric = 0.10M, Amount = new AmountType { currencyID = "GBP", Value = 10.00M } } }, TaxTotal = new TaxTotalType[] { new TaxTotalType { TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxEvidenceIndicator = true, TaxSubtotal = new TaxSubtotalType[] { new TaxSubtotalType { TaxableAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxCategory = new TaxCategoryType { ID = "A", TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } } } } }, LegalMonetaryTotal = new MonetaryTotalType { LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxExclusiveAmount = new AmountType { currencyID = "GBP", Value = 90.00M }, AllowanceTotalAmount = new AmountType { currencyID = "GBP", Value = 10.00M }, PayableAmount = new AmountType { currencyID = "GBP", Value = 107.50M } }, InvoiceLine = new InvoiceLineType[] { new InvoiceLineType { ID = "A", InvoicedQuantity = new QuantityType { unitCode = "KGM", Value = 100M }, LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, OrderLineReference = new OrderLineReferenceType[] { new OrderLineReferenceType { LineID = "1", SalesOrderLineID = "A", LineStatusCode = "NoStatus", OrderReference = new OrderReferenceType { ID = "AEG012345", SalesOrderID = "CON0095678", UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20" } } }, TaxTotal = new TaxTotalType[] { new TaxTotalType { TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxEvidenceIndicator = true, TaxSubtotal = new TaxSubtotalType[] { new TaxSubtotalType { TaxableAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxCategory = new TaxCategoryType { ID = "A", Percent = 17.5M, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } } } } }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "Acme beeswax" } }, Name = "beeswax", BuyersItemIdentification = new ItemIdentificationType { ID = "6578489" }, SellersItemIdentification = new ItemIdentificationType { ID = "17589683" }, ItemInstance = new ItemInstanceType[] { new ItemInstanceType { LotIdentification = new LotIdentificationType { LotNumberID = "546378239", ExpiryDate = "2010-01-01" } } } }, Price = new PriceType { PriceAmount = new AmountType { currencyID = "GBP", Value = 1.00M }, BaseQuantity = new QuantityType { unitCode = "KGM", Value = 1M } } } } }; doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[] { new XmlQualifiedName("cbc","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"), new XmlQualifiedName("cac","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"), }); return doc; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.Framework; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Region.CoreModules.World.Permissions; using OpenSim.Tests.Common; using OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups; using System.Threading; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class ScenePresenceCrossingTests : OpenSimTestCase { [TestFixtureSetUp] public void FixtureInit() { // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest; } [TestFixtureTearDown] public void TearDown() { // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple // threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression // tests really shouldn't). Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; } [Test] public void TestCrossOnSameSimulator() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); // TestEventQueueGetModule eqmA = new TestEventQueueGetModule(); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); // IConfig entityTransferConfig = config.AddConfig("EntityTransfer"); // In order to run a single threaded regression test we do not want the entity transfer module waiting // for a callback from the destination scene before removing its avatar data. // entityTransferConfig.Set("wait_for_callback", false); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); // SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA, eqmA); SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB); AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); ScenePresence originalSp = SceneHelpers.AddScenePresence(sceneA, tc, acd); originalSp.AbsolutePosition = new Vector3(128, 32, 10); // originalSp.Flying = true; // Console.WriteLine("First pos {0}", originalSp.AbsolutePosition); // eqmA.ClearEvents(); AgentUpdateArgs moveArgs = new AgentUpdateArgs(); //moveArgs.BodyRotation = Quaternion.CreateFromEulers(Vector3.Zero); moveArgs.BodyRotation = Quaternion.CreateFromEulers(new Vector3(0, 0, (float)-(Math.PI / 2))); moveArgs.ControlFlags = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; moveArgs.SessionID = acd.SessionID; originalSp.HandleAgentUpdate(originalSp.ControllingClient, moveArgs); sceneA.Update(1); // Console.WriteLine("Second pos {0}", originalSp.AbsolutePosition); // FIXME: This is a sufficient number of updates to for the presence to reach the northern border. // But really we want to do this in a more robust way. for (int i = 0; i < 100; i++) { sceneA.Update(1); // Console.WriteLine("Pos {0}", originalSp.AbsolutePosition); } // Need to sort processing of EnableSimulator message on adding scene presences before we can test eqm // messages // Dictionary<UUID, List<TestEventQueueGetModule.Event>> eqmEvents = eqmA.Events; // // Assert.That(eqmEvents.Count, Is.EqualTo(1)); // Assert.That(eqmEvents.ContainsKey(originalSp.UUID), Is.True); // // List<TestEventQueueGetModule.Event> spEqmEvents = eqmEvents[originalSp.UUID]; // // Assert.That(spEqmEvents.Count, Is.EqualTo(1)); // Assert.That(spEqmEvents[0].Name, Is.EqualTo("CrossRegion")); // sceneA should now only have a child agent ScenePresence spAfterCrossSceneA = sceneA.GetScenePresence(originalSp.UUID); Assert.That(spAfterCrossSceneA.IsChildAgent, Is.True); ScenePresence spAfterCrossSceneB = sceneB.GetScenePresence(originalSp.UUID); // Agent remains a child until the client triggers complete movement Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True); TestClient sceneBTc = ((TestClient)spAfterCrossSceneB.ControllingClient); int agentMovementCompleteReceived = 0; sceneBTc.OnReceivedMoveAgentIntoRegion += (ri, pos, look) => agentMovementCompleteReceived++; sceneBTc.CompleteMovement(); Assert.That(agentMovementCompleteReceived, Is.EqualTo(1)); Assert.That(spAfterCrossSceneB.IsChildAgent, Is.False); } /// <summary> /// Test a cross attempt where the user can see into the neighbour but does not have permission to become /// root there. /// </summary> [Test] public void TestCrossOnSameSimulatorNoRootDestPerm() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID userId = TestHelpers.ParseTail(0x1); EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); SceneHelpers sh = new SceneHelpers(); TestScene sceneA = sh.SetupScene("sceneA", TestHelpers.ParseTail(0x100), 1000, 1000); TestScene sceneB = sh.SetupScene("sceneB", TestHelpers.ParseTail(0x200), 1000, 999); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA); // We need to set up the permisions module on scene B so that our later use of agent limit to deny // QueryAccess won't succeed anyway because administrators are always allowed in and the default // IsAdministrator if no permissions module is present is true. SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), new DefaultPermissionsModule(), etmB); AgentCircuitData acd = SceneHelpers.GenerateAgentData(userId); TestClient tc = new TestClient(acd, sceneA); List<TestClient> destinationTestClients = new List<TestClient>(); EntityTransferHelpers.SetupInformClientOfNeighbourTriggersNeighbourClientCreate(tc, destinationTestClients); // Make sure sceneB will not accept this avatar. sceneB.RegionInfo.EstateSettings.PublicAccess = false; ScenePresence originalSp = SceneHelpers.AddScenePresence(sceneA, tc, acd); originalSp.AbsolutePosition = new Vector3(128, 32, 10); AgentUpdateArgs moveArgs = new AgentUpdateArgs(); //moveArgs.BodyRotation = Quaternion.CreateFromEulers(Vector3.Zero); moveArgs.BodyRotation = Quaternion.CreateFromEulers(new Vector3(0, 0, (float)-(Math.PI / 2))); moveArgs.ControlFlags = (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS; moveArgs.SessionID = acd.SessionID; originalSp.HandleAgentUpdate(originalSp.ControllingClient, moveArgs); sceneA.Update(1); // Console.WriteLine("Second pos {0}", originalSp.AbsolutePosition); // FIXME: This is a sufficient number of updates to for the presence to reach the northern border. // But really we want to do this in a more robust way. for (int i = 0; i < 100; i++) { sceneA.Update(1); // Console.WriteLine("Pos {0}", originalSp.AbsolutePosition); } // sceneA agent should still be root ScenePresence spAfterCrossSceneA = sceneA.GetScenePresence(originalSp.UUID); Assert.That(spAfterCrossSceneA.IsChildAgent, Is.False); ScenePresence spAfterCrossSceneB = sceneB.GetScenePresence(originalSp.UUID); // sceneB agent should still be child Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True); // sceneB should ignore unauthorized attempt to upgrade agent to root TestClient sceneBTc = ((TestClient)spAfterCrossSceneB.ControllingClient); int agentMovementCompleteReceived = 0; sceneBTc.OnReceivedMoveAgentIntoRegion += (ri, pos, look) => agentMovementCompleteReceived++; sceneBTc.CompleteMovement(); Assert.That(agentMovementCompleteReceived, Is.EqualTo(0)); Assert.That(spAfterCrossSceneB.IsChildAgent, Is.True); } } }
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> /// Event type: Sports event. /// </summary> public class SportsEvent_Core : TypeCore, IEvent { public SportsEvent_Core() { this._TypeId = 248; this._Id = "SportsEvent"; this._Schema_Org_Url = "http://schema.org/SportsEvent"; string label = ""; GetLabel(out label, "SportsEvent", typeof(SportsEvent_Core)); this._Label = label; this._Ancestors = new int[]{266,98}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{98}; this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218}; } /// <summary> /// A person attending the event. /// </summary> private Attendees_Core attendees; public Attendees_Core Attendees { get { return attendees; } set { attendees = value; SetPropertyInstance(attendees); } } /// <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> /// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>. /// </summary> private Properties.Duration_Core duration; public Properties.Duration_Core Duration { get { return duration; } set { duration = value; SetPropertyInstance(duration); } } /// <summary> /// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>). /// </summary> private EndDate_Core endDate; public EndDate_Core EndDate { get { return endDate; } set { endDate = value; SetPropertyInstance(endDate); } } /// <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> /// 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> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// The main performer or performers of the event\u2014for example, a presenter, musician, or actor. /// </summary> private Performers_Core performers; public Performers_Core Performers { get { return performers; } set { performers = value; SetPropertyInstance(performers); } } /// <summary> /// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>). /// </summary> private StartDate_Core startDate; public StartDate_Core StartDate { get { return startDate; } set { startDate = value; SetPropertyInstance(startDate); } } /// <summary> /// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference. /// </summary> private SubEvents_Core subEvents; public SubEvents_Core SubEvents { get { return subEvents; } set { subEvents = value; SetPropertyInstance(subEvents); } } /// <summary> /// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent. /// </summary> private SuperEvent_Core superEvent; public SuperEvent_Core SuperEvent { get { return superEvent; } set { superEvent = value; SetPropertyInstance(superEvent); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// // Project HWClassLibrary // Copyright (C) 2011 - 2011 Harald Hoyer // // 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 3 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, see <http://www.gnu.org/licenses/>. // // Comments, bugs and suggestions to hahoyer at yahoo.de using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using HWClassLibrary.Debug; using HWClassLibrary.Helper; using JetBrains.Annotations; namespace HWClassLibrary.Debug { /// <summary> /// Summary description for Dumpable. /// </summary> [Dump("Dump")] public class Dumpable { static readonly Stack<MethodDumpTraceItem> _methodDumpTraceSwitches = new Stack<MethodDumpTraceItem>(); /// <summary> /// generate dump string to be shown in debug windows /// </summary> /// <returns> </returns> public virtual string DebuggerDump() { return Tracer.Dump(this); } /// <summary> /// dump string to be shown in debug windows /// </summary> [DisableDump] [UsedImplicitly] public string DebuggerDumpString { get { return DebuggerDump().Replace("\n", "\r\n"); } } /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] public static void NotImplementedFunction(params object[] p) { var os = Tracer.DumpMethodWithData("not implemented", 1, null, p); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method start dump, /// </summary> /// <param name="trace"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void StartMethodDump(bool trace, params object[] p) { StartMethodDump(1, trace); if(IsMethodDumpTraceActive) { var os = Tracer.DumpMethodWithData("", 1, this, p); Tracer.Line(os); Tracer.IndentStart(); } } /// <summary> /// Method start dump, /// </summary> /// <param name="name"> </param> /// <param name="value"> </param> /// <returns> </returns> [DebuggerHidden] public static void Dump(string name, object value) { if(IsMethodDumpTraceActive) { var os = Tracer.DumpData("", 1, new[] {name, value}); Tracer.Line(os); } } /// <summary> /// Method dump, /// </summary> /// <param name="rv"> </param> /// <param name="breakExecution"> </param> /// <returns> </returns> [DebuggerHidden] protected static T ReturnMethodDump<T>(T rv, bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); Tracer.Line(Tracer.MethodHeader(1) + "[returns] " + Tracer.Dump(rv)); if(breakExecution) Tracer.TraceBreak(); } return rv; } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void ReturnVoidMethodDump(bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); Tracer.Line(Tracer.MethodHeader(1) + "[returns]"); if(breakExecution) Tracer.TraceBreak(); } } [DebuggerHidden] protected void BreakExecution() { if(IsMethodDumpTraceActive) Tracer.TraceBreak(); } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void EndMethodDump() { if(!Debugger.IsAttached) return; CheckDumpLevel(1); _methodDumpTraceSwitches.Pop(); } static void CheckDumpLevel(int depth) { if(!Debugger.IsAttached) return; var top = _methodDumpTraceSwitches.Peek(); Tracer.Assert(top.FrameCount == Tracer.CurrentFrameCount(depth + 1)); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void DumpMethodWithBreak(string text, params object[] p) { var os = Tracer.DumpMethodWithData(text, 1, this, p); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected static void DumpDataWithBreak(string text, params object[] p) { var os = Tracer.DumpData(text, 1, p); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void NotImplementedMethod(params object[] p) { if(IsInDump) throw new NotImplementedException(); var os = Tracer.DumpMethodWithData("not implemented", 1, this, p); Tracer.Line(os); Tracer.TraceBreak(); } public string Dump() { var oldIsInDump = _isInDump; _isInDump = true; var result = Dump(oldIsInDump); _isInDump = oldIsInDump; return result; } protected virtual string Dump(bool isRecursion) { var surround = "<recursion>"; if(!isRecursion) surround = DumpData().Surround("{", "}"); return GetType().PrettyName() + surround; } /// <summary> /// Gets a value indicating whether this instance is in dump. /// </summary> /// <value> /// <c>true</c> /// if this instance is in dump; otherwise, /// <c>false</c> /// .</value> /// created 23.09.2006 17:39 [DisableDump] public bool IsInDump { get { return _isInDump; } } bool _isInDump; public static bool? IsMethodDumpTraceInhibited; /// <summary> /// Default dump of data /// </summary> /// <returns> </returns> public virtual string DumpData() { string result; try { result = Tracer.DumpData(this); } catch(Exception) { result = "<not implemented>"; } return result; } public void Dispose() { } static void StartMethodDump(int depth, bool trace) { if(!Debugger.IsAttached) return; var frameCount = Tracer.CurrentFrameCount(depth + 1); _methodDumpTraceSwitches.Push(new MethodDumpTraceItem(frameCount, trace)); } sealed class MethodDumpTraceItem { readonly int _frameCount; readonly bool _trace; public MethodDumpTraceItem(int frameCount, bool trace) { _frameCount = frameCount; _trace = trace; } internal int FrameCount { get { return _frameCount; } } internal bool Trace { get { return _trace; } } } static bool IsMethodDumpTraceActive { get { if (IsMethodDumpTraceInhibited != null) return !IsMethodDumpTraceInhibited.Value; if(!Debugger.IsAttached) return false; //CheckDumpLevel(2); return _methodDumpTraceSwitches.Peek().Trace; } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; using System.Management.Automation.Runspaces; using System.Text; namespace System.Management.Automation { /// <summary> /// Provides information about a function that is stored in session state. /// </summary> public class FunctionInfo : CommandInfo, IScriptCommandInfo { #region ctor /// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ExecutionContext context) : this(name, function, context, null) { } /// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ExecutionContext context, string helpFile) : base(name, CommandTypes.Function, context) { if (function == null) { throw PSTraceSource.NewArgumentNullException(nameof(function)); } _scriptBlock = function; CmdletInfo.SplitCmdletName(name, out _verb, out _noun); this.Module = function.Module; _helpFile = helpFile; } /// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options, ExecutionContext context) : this(name, function, options, context, null) { } /// <summary> /// Creates an instance of the FunctionInfo class with the specified name and ScriptBlock. /// </summary> /// <param name="name"> /// The name of the function. /// </param> /// <param name="function"> /// The ScriptBlock for the function /// </param> /// <param name="options"> /// The options to set on the function. Note, Constant can only be set at creation time. /// </param> /// <param name="context"> /// The execution context for the function. /// </param> /// <param name="helpFile"> /// The name of the help file associated with the function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="function"/> is null. /// </exception> internal FunctionInfo(string name, ScriptBlock function, ScopedItemOptions options, ExecutionContext context, string helpFile) : this(name, function, context, helpFile) { _options = options; } /// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal FunctionInfo(FunctionInfo other) : base(other) { CopyFieldsFromOther(other); } private void CopyFieldsFromOther(FunctionInfo other) { _verb = other._verb; _noun = other._noun; _scriptBlock = other._scriptBlock; _description = other._description; _options = other._options; _helpFile = other._helpFile; } /// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal FunctionInfo(string name, FunctionInfo other) : base(name, other) { CopyFieldsFromOther(other); // Get the verb and noun from the name CmdletInfo.SplitCmdletName(name, out _verb, out _noun); } /// <summary> /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter /// sets based on an argument list (so we can get the dynamic parameters.) /// </summary> internal override CommandInfo CreateGetCommandCopy(object[] arguments) { FunctionInfo copy = new FunctionInfo(this) { IsGetCommandCopy = true, Arguments = arguments }; return copy; } #endregion ctor internal override HelpCategory HelpCategory { get { return HelpCategory.Function; } } /// <summary> /// Gets the ScriptBlock which is the implementation of the function. /// </summary> public ScriptBlock ScriptBlock { get { return _scriptBlock; } } private ScriptBlock _scriptBlock; /// <summary> /// Updates a function. /// </summary> /// <param name="newFunction"> /// The script block that the function should represent. /// </param> /// <param name="force"> /// If true, the script block will be applied even if the filter is ReadOnly. /// </param> /// <param name="options"> /// Any options to set on the new function, null if none. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="newFunction"/> is null. /// </exception> internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options) { Update(newFunction, force, options, null); this.DefiningLanguageMode = newFunction.LanguageMode; } /// <summary/> protected internal virtual void Update(FunctionInfo newFunction, bool force, ScopedItemOptions options, string helpFile) { Update(newFunction.ScriptBlock, force, options, helpFile); } /// <summary> /// Updates a function. /// </summary> /// <param name="newFunction"> /// The script block that the function should represent. /// </param> /// <param name="force"> /// If true, the script block will be applied even if the filter is ReadOnly. /// </param> /// <param name="options"> /// Any options to set on the new function, null if none. /// </param> /// <param name="helpFile"> /// The helpfile for this function. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="newFunction"/> is null. /// </exception> internal void Update(ScriptBlock newFunction, bool force, ScopedItemOptions options, string helpFile) { if (newFunction == null) { throw PSTraceSource.NewArgumentNullException("function"); } if ((_options & ScopedItemOptions.Constant) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Function, "FunctionIsConstant", SessionStateStrings.FunctionIsConstant); throw e; } if (!force && (_options & ScopedItemOptions.ReadOnly) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Function, "FunctionIsReadOnly", SessionStateStrings.FunctionIsReadOnly); throw e; } _scriptBlock = newFunction; this.Module = newFunction.Module; _commandMetadata = null; this._parameterSets = null; this.ExternalCommandMetadata = null; if (options != ScopedItemOptions.Unspecified) { this.Options = options; } _helpFile = helpFile; } /// <summary> /// Returns <see langword="true"/> if this function uses cmdlet binding mode for its parameters; otherwise returns <see langword="false"/>. /// </summary> public bool CmdletBinding { get { return this.ScriptBlock.UsesCmdletBinding; } } /// <summary> /// Gets the name of the default parameter set. /// Returns <see langword="null"/> if this function doesn't use cmdlet parameter binding or if the default parameter set wasn't specified. /// </summary> public string DefaultParameterSet { get { return this.CmdletBinding ? this.CommandMetadata.DefaultParameterSetName : null; } } /// <summary> /// Gets the definition of the function which is the /// ToString() of the ScriptBlock that implements the function. /// </summary> public override string Definition { get { return _scriptBlock.ToString(); } } /// <summary> /// Gets or sets the scope options for the function. /// </summary> /// <exception cref="SessionStateUnauthorizedAccessException"> /// If the trying to set a function that is constant or /// if the value trying to be set is ScopedItemOptions.Constant /// </exception> public ScopedItemOptions Options { get { return CopiedCommand == null ? _options : ((FunctionInfo)CopiedCommand).Options; } set { if (CopiedCommand == null) { // Check to see if the function is constant, if so // throw an exception because the options cannot be changed. if ((_options & ScopedItemOptions.Constant) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Function, "FunctionIsConstant", SessionStateStrings.FunctionIsConstant); throw e; } // Now check to see if the caller is trying to set // the options to constant. This is only allowed at // variable creation if ((value & ScopedItemOptions.Constant) != 0) { // user is trying to set the function to constant after // creating the function. Do not allow this (as per spec). SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( Name, SessionStateCategory.Function, "FunctionCannotBeMadeConstant", SessionStateStrings.FunctionCannotBeMadeConstant); throw e; } // Ensure we are not trying to remove the AllScope option if ((value & ScopedItemOptions.AllScope) == 0 && (_options & ScopedItemOptions.AllScope) != 0) { SessionStateUnauthorizedAccessException e = new SessionStateUnauthorizedAccessException( this.Name, SessionStateCategory.Function, "FunctionAllScopeOptionCannotBeRemoved", SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved); throw e; } _options = value; } else { ((FunctionInfo)CopiedCommand).Options = value; } } } private ScopedItemOptions _options = ScopedItemOptions.None; /// <summary> /// Gets or sets the description associated with the function. /// </summary> public string Description { get { return CopiedCommand == null ? _description : ((FunctionInfo)CopiedCommand).Description; } set { if (CopiedCommand == null) { _description = value; } else { ((FunctionInfo)CopiedCommand).Description = value; } } } private string _description = null; /// <summary> /// Gets the verb of the function. /// </summary> public string Verb { get { return _verb; } } private string _verb = string.Empty; /// <summary> /// Gets the noun of the function. /// </summary> public string Noun { get { return _noun; } } private string _noun = string.Empty; /// <summary> /// Gets the help file path for the function. /// </summary> public string HelpFile { get { return _helpFile; } internal set { _helpFile = value; } } private string _helpFile = string.Empty; /// <summary> /// Returns the syntax of a command. /// </summary> internal override string Syntax { get { StringBuilder synopsis = new StringBuilder(); foreach (CommandParameterSetInfo parameterSet in ParameterSets) { synopsis.AppendLine(); synopsis.AppendLine( string.Format( Globalization.CultureInfo.CurrentCulture, "{0} {1}", Name, parameterSet.ToString())); } return synopsis.ToString(); } } /// <summary> /// True if the command has dynamic parameters, false otherwise. /// </summary> internal override bool ImplementsDynamicParameters { get { return ScriptBlock.HasDynamicParameters; } } /// <summary> /// The command metadata for the function or filter. /// </summary> internal override CommandMetadata CommandMetadata { get { return _commandMetadata ??= new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS()); } } private CommandMetadata _commandMetadata; /// <summary> /// The output type(s) is specified in the script block. /// </summary> public override ReadOnlyCollection<PSTypeName> OutputType { get { return ScriptBlock.OutputType; } } } }
namespace Payplug { using System; using System.Collections.Generic; using Core; using Newtonsoft.Json; /// <summary> /// A DAO which provides a way to query customer resources. /// </summary> public static class Customer { /// <summary> /// Create a customer. /// </summary> /// <seealso cref="CreateRaw">If you want to create a customer using a string of JSON data.</seealso> /// <param name="customer">Data used to create the customer.</param> /// <returns>The created customer.</returns> /// <example> /// <code><![CDATA[ /// var customerData = new Dictionary<string, dynamic> /// { /// {"email", "john.watson@example.net"}, /// {"first_name", "John"}, /// {"last_name", "Watson"}, /// {"address1", "27 Rue Pasteur"}, /// {"address2", null}, /// {"city", "Paris"}, /// {"postcode", "75018"}, /// {"country", "France"}, /// {"metadata", new Dictionary<string, object> /// { /// {"segment", "mass"} /// } /// } /// }; /// var customer = Customer.Create(customerData); /// ]]></code> /// </example> public static Dictionary<string, dynamic> Create(Dictionary<string, object> customer) { if (customer == null) { throw new ArgumentNullException("customer cannot be null"); } var json = JsonConvert.SerializeObject(customer); var response = CreateRaw(json); return JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(response); } /// <summary> /// Retrieve a customer. /// </summary> /// <seealso cref="RetrieveRaw">If you want to retrieve a customer as a string of JSON data.</seealso> /// <param name="customerID">ID of the customer to retrieve.</param> /// <returns>The customer asked.</returns> /// <example> /// <code><![CDATA[ /// var customer = Customer.Retrieve("cus_6ESfofiMiLBjC6"); /// ]]></code> /// </example> public static Dictionary<string, dynamic> Retrieve(string customerID) { if (string.IsNullOrEmpty(customerID)) { throw new ArgumentNullException("customerID cannot be null"); } var response = RetrieveRaw(customerID); return JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(response); } /// <summary> /// Retrieve all customers. /// </summary> /// <seealso cref="ListRaw">If you want to retrieve customers as a string of JSON data.</seealso> /// <param name="page">The page number.</param> /// <param name="per_page">number of customer per page.</param> /// <returns>A collection of customers.</returns> /// <example> /// <code><![CDATA[ /// var customers = Customer.List(); /// var customer = customers["data"][0]; /// ]]></code> /// </example> public static Dictionary<string, dynamic> List(uint? page = null, uint? per_page = null) { var response = ListRaw(page, per_page); return JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(response); } /// <summary> /// Update a customer. /// </summary> /// <seealso cref="UpdateRaw">If you want to update a customer with a string of JSON data.</seealso> /// <param name="customerID">ID of the customer to update.</param> /// <param name="customer">Data used to update the customer as a string of JSON data.</param> /// <returns>The updated customer.</returns> /// <example> /// <code><![CDATA[ /// var customerData = new Dictionary<string, dynamic> /// { /// {"address1", "20 Rue Pasteur"} /// }; /// var customer = Customer.Update("cus_72F7mCcibttCnv", customerData); /// ]]></code> /// </example> public static Dictionary<string, dynamic> Update(string customerID, Dictionary<string, object> customer) { if (string.IsNullOrEmpty(customerID)) { throw new ArgumentNullException("customerID cannot be null"); } if (customer == null) { throw new ArgumentNullException("customer cannot be null"); } var json = JsonConvert.SerializeObject(customer); var response = UpdateRaw(customerID, json); return JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(response); } /// <summary> /// Delete a customer request. /// </summary> /// <param name="customerID">ID of the customer to delete.</param> /// <example> /// <code><![CDATA[ /// Customer.Delete("cus_72F7mCcibttCnv"); /// ]]></code> /// </example> public static void Delete(string customerID) { if (string.IsNullOrEmpty(customerID)) { throw new ArgumentNullException("customerID cannot be null"); } var parameters = new Dictionary<string, string> { { "customer_id", customerID } }; var uri = Routes.Uri(Routes.DeleteCustomer, parameters); Service.Delete(uri); } /// <summary> /// Create a customer request with a string of JSON data. /// </summary> /// <seealso cref="Create">If you want to create a customer request using a Dictionary.</seealso> /// <param name="customer">Data used to create the customer as a string of JSON data.</param> /// <returns>The created customer.</returns> public static string CreateRaw(string customer) { if (string.IsNullOrEmpty(customer)) { throw new ArgumentNullException("customer cannot be null"); } var uri = Routes.Uri(Routes.CreateCustomer); return Service.Post(uri, customer); } /// <summary> /// Retrieve a customer as a string of JSON data. /// </summary> /// <seealso cref="Retrieve">If you want to retrieve a customer as a Dictionary.</seealso> /// <param name="customerID">ID of the customer to retrieve.</param> /// <returns>The customer asked.</returns> public static string RetrieveRaw(string customerID) { if (string.IsNullOrEmpty(customerID)) { throw new ArgumentNullException("customerID cannot be null"); } var parameters = new Dictionary<string, string> { { "customer_id", customerID } }; var uri = Routes.Uri(Routes.RetrieveCustomer, parameters); return Service.Get(uri); } /// <summary> /// Retrieve all customers as a string of JSON data. /// </summary> /// <seealso cref="List">If you want to retrieve customers as a Dictionary.</seealso> /// <param name="page">The page number.</param> /// <param name="per_page">number of payment per page.</param> /// <returns>A collection of customers.</returns> public static string ListRaw(uint? page = null, uint? per_page = null) { var query = new Dictionary<string, string>(); if (page != null) { query.Add("page", page.ToString()); } if (per_page != null) { query.Add("per_page", per_page.ToString()); } var uri = Routes.Uri(Routes.ListCustomers, null, query); return Service.Get(uri); } /// <summary> /// Update a customer with a string of JSON data. /// </summary> /// <seealso cref="Update">If you want to update a customer with a Dictionary.</seealso> /// <param name="customerID">ID of the customer to update.</param> /// <param name="customer">Data used to update the customer as a string of JSON data.</param> /// <returns>The updated customer.</returns> public static string UpdateRaw(string customerID, string customer) { if (string.IsNullOrEmpty(customerID)) { throw new ArgumentNullException("customerID cannot be null"); } if (string.IsNullOrEmpty(customer)) { throw new ArgumentNullException("customer cannot be null"); } var parameters = new Dictionary<string, string> { { "customer_id", customerID } }; var uri = Routes.Uri(Routes.UpdateCustomer, parameters); return Service.Patch(uri, customer); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Models; namespace Microsoft.Azure.Management.DataFactories.Core { public static partial class DataSliceRunOperationsExtensions { /// <summary> /// Gets a Data Slice Run instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='runId'> /// Required. A unique Data Slice Run Id. /// </param> /// <returns> /// The get Data Slice Run operation response. /// </returns> public static DataSliceRunGetResponse Get(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string runId) { return Task.Factory.StartNew((object s) => { return ((IDataSliceRunOperations)s).GetAsync(resourceGroupName, dataFactoryName, runId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a Data Slice Run instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='runId'> /// Required. A unique Data Slice Run Id. /// </param> /// <returns> /// The get Data Slice Run operation response. /// </returns> public static Task<DataSliceRunGetResponse> GetAsync(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string runId) { return operations.GetAsync(resourceGroupName, dataFactoryName, runId, CancellationToken.None); } /// <summary> /// Gets logs for a data slice run /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='dataSliceRunId'> /// Required. A unique data slice run instance id. /// </param> /// <returns> /// The data slice run get logs operation response. /// </returns> public static DataSliceRunGetLogsResponse GetLogs(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string dataSliceRunId) { return Task.Factory.StartNew((object s) => { return ((IDataSliceRunOperations)s).GetLogsAsync(resourceGroupName, dataFactoryName, dataSliceRunId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets logs for a data slice run /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='dataSliceRunId'> /// Required. A unique data slice run instance id. /// </param> /// <returns> /// The data slice run get logs operation response. /// </returns> public static Task<DataSliceRunGetLogsResponse> GetLogsAsync(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string dataSliceRunId) { return operations.GetLogsAsync(resourceGroupName, dataFactoryName, dataSliceRunId, CancellationToken.None); } /// <summary> /// Gets the first page of data slice run instances with the link to /// the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='parameters'> /// Required. Parameters for specifying the filters to list data slice /// runs of the table. /// </param> /// <returns> /// The List data slice runs operation response. /// </returns> public static DataSliceRunListResponse List(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string tableName, DataSliceRunListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDataSliceRunOperations)s).ListAsync(resourceGroupName, dataFactoryName, tableName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of data slice run instances with the link to /// the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='parameters'> /// Required. Parameters for specifying the filters to list data slice /// runs of the table. /// </param> /// <returns> /// The List data slice runs operation response. /// </returns> public static Task<DataSliceRunListResponse> ListAsync(this IDataSliceRunOperations operations, string resourceGroupName, string dataFactoryName, string tableName, DataSliceRunListParameters parameters) { return operations.ListAsync(resourceGroupName, dataFactoryName, tableName, parameters, CancellationToken.None); } /// <summary> /// Gets the next page of run instances with the link to the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next data slice runs page. /// </param> /// <returns> /// The List data slice runs operation response. /// </returns> public static DataSliceRunListResponse ListNext(this IDataSliceRunOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDataSliceRunOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the next page of run instances with the link to the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IDataSliceRunOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next data slice runs page. /// </param> /// <returns> /// The List data slice runs operation response. /// </returns> public static Task<DataSliceRunListResponse> ListNextAsync(this IDataSliceRunOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ using System; using System.Data; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using GemFireXDDBI.DBObjects; using Pivotal.Data.GemFireXD; namespace GemFireXDDBI.DBI { /// <summary> /// Specific implementation of GemFireXD database interface /// </summary> class GemFireXDDbi { public static string DbConnectionString { get; set; } public static int TestConnection() { GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString); connection.Open(); if(connection.State == ConnectionState.Open) { connection.Close(); return 1; } return 0; } public static bool SchemaExists(String schemaName) { bool exists = false; if (Convert.ToInt32(ExecuteScalarStatement(OpenNewConnection(), String.Format( "SELECT COUNT(*) FROM SYS.SYSSCHEMAS WHERE SCHEMANAME = '{0}'", schemaName.ToUpper()))) > 0) exists = true; return exists; } public static bool TableExists(String tableName) { bool exists = false; if (Convert.ToInt32(ExecuteScalarStatement(OpenNewConnection(), String.Format( "SELECT COUNT(*) FROM SYS.SYSTABLES WHERE TABLENAME = '{0}'", tableName.ToUpper()))) > 0) exists = true; return exists; } public static bool IndexExists(String indexName) { bool exists = false; if (Convert.ToInt32(ExecuteScalarStatement(OpenNewConnection(), String.Format( @"SELECT COUNT(*) FROM SYS.SYSCONGLOMERATES A INNER JOIN SYS.SYSKEYS B ON A.CONGLOMERATEID = B.CONGLOMERATEID INNER JOIN SYS.SYSCONSTRAINTS C ON B.CONSTRAINTID = C.CONSTRAINTID WHERE A.ISINDEX = 1 AND C.CONSTRAINTNAME = '{0}'", indexName.ToUpper()))) > 0) exists = true; return exists; } public static DataTable GetTableNames() { string sql = @"SELECT B.SCHEMANAME, A.TABLENAME FROM SYS.SYSTABLES A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID WHERE A.TABLETYPE = 'T' ORDER BY B.SCHEMANAME ASC"; return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetIndexes() { string sql = @"SELECT D.SCHEMANAME, E.TABLENAME, C.CONSTRAINTNAME, F.COLUMNNAME, A.ISINDEX FROM SYS.SYSCONGLOMERATES A INNER JOIN SYS.SYSKEYS B ON A.CONGLOMERATEID = B.CONGLOMERATEID INNER JOIN SYS.SYSCONSTRAINTS C ON B.CONSTRAINTID = C.CONSTRAINTID INNER JOIN SYS.SYSSCHEMAS D ON A.SCHEMAID = D.SCHEMAID INNER JOIN SYS.SYSTABLES E ON E.TABLEID = A.TABLEID INNER JOIN SYS.SYSCOLUMNS F ON F.REFERENCEID = A.TABLEID WHERE A.ISINDEX = 1"; return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetIndex(string indexName) { string[] temp = indexName.Split(new char[] { '.' }); indexName = temp[temp.Length - 1]; string sql = String.Format(@"SELECT D.SCHEMANAME, E.TABLENAME, C.CONSTRAINTNAME, F.COLUMNNAME, A.ISINDEX FROM SYS.SYSCONGLOMERATES A INNER JOIN SYS.SYSKEYS B ON A.CONGLOMERATEID = B.CONGLOMERATEID INNER JOIN SYS.SYSCONSTRAINTS C ON B.CONSTRAINTID = C.CONSTRAINTID INNER JOIN SYS.SYSSCHEMAS D ON A.SCHEMAID = D.SCHEMAID INNER JOIN SYS.SYSTABLES E ON E.TABLEID = A.TABLEID INNER JOIN SYS.SYSCOLUMNS F ON F.REFERENCEID = A.TABLEID WHERE C.CONSTRAINTNAME = '{0}'", indexName.ToUpper()); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetStoredProcedures() { string sql = @"SELECT B.SCHEMANAME, A.ALIAS, ALIASTYPE FROM SYS.SYSALIASES A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID WHERE A.ALIASTYPE = 'P' AND SYSTEMALIAS = 1"; return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetStoredProcedure(string procedureName) { string[] temp = procedureName.Split(new char[] { '.' }); procedureName = temp[temp.Length - 1]; string sql = String.Format( @"SELECT B.SCHEMANAME, A.ALIAS, ALIASTYPE FROM SYS.SYSALIASES A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID WHERE A.ALIASTYPE = 'P' AND SYSTEMALIAS = 1 AND A.ALIAS = '{0}'", procedureName.ToUpper()); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetFunctions() { string sql = @"SELECT B.SCHEMANAME, A.ALIAS, ALIASTYPE FROM SYS.SYSALIASES A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID WHERE A.ALIASTYPE = 'F' AND SYSTEMALIAS = 1"; return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetFunction(string functionName) { string[] temp = functionName.Split(new char[] { '.' }); functionName = temp[temp.Length - 1]; string sql = String.Format( @"SELECT B.SCHEMANAME, A.ALIAS, ALIASTYPE FROM SYS.SYSALIASES A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID WHERE A.ALIASTYPE = 'F' AND SYSTEMALIAS = 1 AND A.ALIAS = '{0}'", functionName.ToUpper()); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetTriggers() { string sql = @"SELECT B.SCHEMANAME, C.TABLENAME, A.TRIGGERNAME, A.TYPE, A.EVENT, A.STATE, A.TRIGGERDEFINITION, A.FIRINGTIME FROM SYS.SYSTRIGGERS A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID INNER JOIN SYS.SYSTABLES C ON A.TABLEID = C.TABLEID "; return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetTrigger(string triggerName) { string[] temp = triggerName.Split(new char[] { '.' }); triggerName = temp[temp.Length - 1]; string sql = String.Format( @"SELECT B.SCHEMANAME, C.TABLENAME, A.TRIGGERNAME, A.TYPE, A.EVENT, A.STATE, A.TRIGGERDEFINITION, A.FIRINGTIME FROM SYS.SYSTRIGGERS A INNER JOIN SYS.SYSSCHEMAS B ON A.SCHEMAID = B.SCHEMAID INNER JOIN SYS.SYSTABLES C ON A.TABLEID = C.TABLEID WHERE TRIGGERNAME = '{0}'", triggerName.ToUpper()); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetViews() { string sql = @"SELECT S.SCHEMANAME, T.TABLENAME, V.VIEWDEFINITION FROM SYS.SYSVIEWS V INNER JOIN SYS.SYSTABLES T ON V.TABLEID = T.TABLEID INNER JOIN SYS.SYSSCHEMAS S ON T.SCHEMAID = S.SCHEMAID WHERE T.TABLETYPE = 'V'"; return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetView(string viewName) { string[] temp = viewName.Split(new char[] { '.' }); viewName = temp[temp.Length - 1]; string sql = String.Format( @"SELECT S.SCHEMANAME, T.TABLENAME, V.VIEWDEFINITION FROM SYS.SYSVIEWS V INNER JOIN SYS.SYSTABLES T ON V.TABLEID = T.TABLEID INNER JOIN SYS.SYSSCHEMAS S ON T.SCHEMAID = S.SCHEMAID WHERE T.TABLETYPE = 'V' AND T.TABLENAME = '{0}'", viewName); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static DataTable GetViewData(string viewName) { string sql = String.Format(@"SELECT * FROM {0}", viewName.ToUpper()); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static int Create(string sql) { using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = sql; connection.Open(); return command.ExecuteNonQuery(); } } } public static int Drop(string sql) { using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = sql; connection.Open(); return command.ExecuteNonQuery(); } } } public static long Insert(string sql) { return Insert(sql, false); } public static long Insert(string sql, bool getId) { int result = 0; using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = sql; connection.Open(); result = command.ExecuteNonQuery(); if (getId) { command.CommandText = "SELECT @@IDENTITY"; result = int.Parse(command.ExecuteScalar().ToString()); } } } return result; } public static int BatchInsert(GFXDClientConnection connection, string sql, DataTable sqlTable, DbTable esqlTable) { GFXDCommand command = null; int result = 0; int batchSize = 10; try { using (command = connection.CreateCommand()) { IDictionary<String, object> refColumns = new Dictionary<String, object>(); if (connection.IsClosed) connection.Open(); command.CommandType = CommandType.Text; command.CommandText = sql; command.Prepare(); Util.Helper.Log(command.CommandText); int batchCount = 0; for (int i = 0; i < sqlTable.Rows.Count; i++) { DataRow row = sqlTable.Rows[i]; for (int j = 0; j < esqlTable.Columns.Count; j++) { GFXDParameter param = command.CreateParameter(); param.Type = esqlTable.Columns[j].FieldType; // Set self-referenced column with null if (esqlTable.Columns[j].FieldName == esqlTable.SelfRefColumn) { refColumns.Add(row[0].ToString(), row[esqlTable.SelfRefColumn].ToString()); param.Value = DBNull.Value; } else param.Value = FormatFieldData(esqlTable.Columns[j].FieldType, row[j]); command.Parameters.Add(param); } command.AddBatch(); if ((++batchCount) == batchSize) { command.ExecuteBatch(); batchCount = 0; } } command.ExecuteBatch(); // Now update self-referenced column with actual value if (!String.IsNullOrEmpty(esqlTable.SelfRefColumn)) { command.CommandText = String.Format("UPDATE {0} SET {1} = ? WHERE {2} = ?", esqlTable.TableFullName, esqlTable.SelfRefColumn, sqlTable.Columns[0].ColumnName); command.Prepare(); batchCount = 0; foreach (String key in refColumns.Keys) { if (String.IsNullOrEmpty((String)refColumns[key]) || ((String)refColumns[key]).ToUpper() == "NULL") continue; command.Parameters.Add(refColumns[key]); command.Parameters.Add(key); command.AddBatch(); if ((++batchCount) == batchSize) { command.ExecuteBatch(); batchCount = 0; } } command.ExecuteBatch(); } } } catch (Exception e) { Util.Helper.Log(e); } return result; } public static int Update(string sql) { using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = sql; connection.Open(); return command.ExecuteNonQuery(); } } } public static int Delete(string sql) { using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = sql; connection.Open(); return command.ExecuteNonQuery(); } } } public static DataTable GetTableData(string tableName) { string sql = String.Format("SELECT * FROM {0} ORDER BY {1} ASC", tableName, GetPKColumnName(tableName)); Util.Helper.Log(sql); return (DataTable)Select(sql, Util.QueryType.DATATABLE); } public static String GetPKColumnName(string tableName) { string[] temp = tableName.Split(new char[] { '.' }); tableName = temp[temp.Length - 1]; string sql = String.Format(@"SELECT C.COLUMNNAME FROM SYS.SYSCOLUMNS C INNER JOIN SYS.SYSTABLES T ON C.REFERENCEID = T.TABLEID WHERE T.TABLENAME = '{0}' AND C.COLUMNNUMBER = 1", tableName.ToUpper()); return (String)ExecuteScalarStatement(OpenConnection(DbConnectionString), sql); } public static object Select(string sql, Util.QueryType type) { using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = sql; if (connection.IsClosed) connection.Open(); if (type == Util.QueryType.SCALAR) return command.ExecuteScalar(); using (GFXDDataAdapter adapter = command.CreateDataAdapter()) { switch (type) { case Util.QueryType.DATAROW: return GetDataRow(connection, adapter); case Util.QueryType.DATATABLE: return GetDataTable(connection, adapter); case Util.QueryType.DATASET: return GetDataSet(connection, adapter); default: return null; } } } } } public static DataTable SelectRandom(String tableName, int numRows) { using (GFXDClientConnection connection = new GFXDClientConnection(DbConnectionString)) { using (GFXDCommand command = connection.CreateCommand()) { command.CommandType = System.Data.CommandType.Text; command.CommandText = String.Format( "SELECT * FROM {0} ORDER BY RANDOM() FETCH FIRST {1} ROWS ONLY", tableName, numRows); using (GFXDDataAdapter adapter = command.CreateDataAdapter()) { return GetDataTable(connection, adapter); } } } } public static object ExecuteScalarStatement(GFXDClientConnection conn, String statement) { GFXDCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = statement; return cmd.ExecuteScalar(); } private static DataRow GetDataRow(GFXDClientConnection connection, GFXDDataAdapter adapter) { DataTable dt = GetDataTable(connection, adapter); DataRow dr = null; if (dt.Rows.Count > 0) dr = dt.Rows[0]; return dr; } private static DataTable GetDataTable(GFXDClientConnection connection, GFXDDataAdapter adapter) { DataTable dt = new DataTable(); adapter.Fill(dt); return dt; } private static DataSet GetDataSet(GFXDClientConnection connection, GFXDDataAdapter adapter) { DataSet ds = new DataSet(); adapter.Fill(ds); return ds; } public static String Escape(String str) { if (String.IsNullOrEmpty(str)) return "NULL"; else return ("'" + str.Trim().Replace("'", "''") + "'"); } public static String Escape(String str, int length) { if (String.IsNullOrEmpty(str)) return "NULL"; else { str = str.Trim(); if (str.Length > length) str = str.Substring(0, length - 1); return ("'" + str.Trim().Replace("'", "''") + "'"); } } public static GFXDClientConnection OpenNewConnection() { return OpenConnection(DbConnectionString); } public static GFXDClientConnection OpenConnection(String connStr) { GFXDClientConnection conn = new GFXDClientConnection(connStr); conn.Open(); return conn; } private static object FormatFieldData(GFXDType type, object data) { if (data.GetType() == typeof(DBNull)) return DBNull.Value; switch (type) { case GFXDType.Binary: case GFXDType.Blob: case GFXDType.VarBinary: case GFXDType.LongVarBinary: return ConvertToBytes(data.ToString()); case GFXDType.Clob: case GFXDType.Char: case GFXDType.LongVarChar: case GFXDType.VarChar: return data.ToString(); case GFXDType.Date: return DateTime.Parse(data.ToString()).ToShortDateString(); case GFXDType.Time: return DateTime.Parse(data.ToString()).ToShortTimeString(); case GFXDType.TimeStamp: return DateTime.Parse(data.ToString()); case GFXDType.Decimal: return Convert.ToDecimal(data); case GFXDType.Double: case GFXDType.Float: return Convert.ToDouble(data); case GFXDType.Short: return Convert.ToInt16(data); case GFXDType.Integer: return Convert.ToInt32(data); case GFXDType.Long: return Convert.ToInt64(data); case GFXDType.Numeric: return Convert.ToInt64(data); case GFXDType.Real: return Convert.ToDecimal(data); case GFXDType.Boolean: return Convert.ToBoolean(data); case GFXDType.Null: return Convert.DBNull; case GFXDType.JavaObject: case GFXDType.Other: default: return new object(); } } public static byte[] ConvertToBytes(string txtString) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); return encoding.GetBytes(txtString); } /// <summary> /// /// </summary> /// <param name="bytes"></param> /// <returns></returns> public static string ConvertToString(byte[] bytes) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); return encoding.GetString(bytes); } public static IList<String> ReservedWords = new List<String>{ "ADD", "ALL", "ALLOCATE", "ALTER", "AND", "ANY", "ARE", "AS", "ASC", "ASSERTION", "AT", "AUTHORIZATION", "AVG", "BEGIN", "BETWEEN", "BIGINT", "BIT", "BOOLEAN", "BOTH", "BY", "CALL", "CASCADE", "CASCADED", "CASE", "CAST", "CHAR", "CHARACTER", "CHECK", "CLOSE", "COALESCE", "COLLATE", "COLLATION", "COLUMN", "COMMIT", "CONNECT", "CONNECTION", "CONSTRAINT", "CONSTRAINTS", "CONTINUE", "CONVERT", "CORRESPONDING", "CREATE", "CURRENT", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "CURRENT_USER", "CURSOR", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DESCRIBE", "DIAGNOSTICS", "DISCONNECT", "DISTINCT", "DOUBLE", "DROP", "ELSE", "END", "END-EXEC", "ESCAPE", "EXCEPT", "EXCEPTION", "EXEC", "EXECUTE", "EXISTS", "EXPLAIN", "EXTERNAL", "FALSE", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN", "FOUND", "FROM", "FULL", "FUNCTION", "GET", "GETCURRENTCONNECTION", "GLOBAL", "GO", "GOTO", "GRANT", "GROUP", "HAVING", "HOUR", "IDENTITY", "IMMEDIATE", "IN", "INDICATOR", "INITIALLY", "INNER", "INOUT", "INPUT", "INSENSITIVE", "INSERT", "INT", "INTEGER", "INTERSECT", "INTO", "IS", "ISOLATION", "JOIN", "KEY", "LAST", "LEFT", "LIKE", "LOWER", "LTRIM", "MATCH", "MAX", "MIN", "MINUTE", "NATIONAL", "NATURAL", "NCHAR", "NVARCHAR", "NEXT", "NO", "NOT", "NULL", "NULLIF", "NUMERIC", "OF", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "OUTER", "OUTPUT", "OVERLAPS", "PAD", "PARTIAL", "PREPARE", "PRESERVE", "PRIMARY", "PRIOR", "PRIVILEGES", "PROCEDURE", "PUBLIC", "READ", "REAL", "REFERENCES", "RELATIVE", "RESTRICT", "REVOKE", "RIGHT", "ROLLBACK", "ROWS", "RTRIM", "SCHEMA", "SCROLL", "SECOND", "SELECT", "SESSION_USER", "SET", "SMALLINT", "SOME", "SPACE", "SQL", "SQLCODE", "SQLERROR", "SQLSTATE", "SUBSTR", "SUBSTRING", "SUM", "SYSTEM_USER", "TABLE", "TEMPORARY", "TIMEZONE_HOUR", "TIMEZONE_MINUTE", "TO", "TRANSACTION", "TRANSLATE", "TRANSLATION", "TRUE", "UNION", "UNIQUE", "UNKNOWN", "UPDATE", "UPPER", "USER", "USING", "VALUES", "VARCHAR", "VARYING", "VIEW", "WHENEVER", "WHERE", "WITH", "WORK", "WRITE", "XML", "XMLEXISTS", "XMLPARSE", "XMLQUERY", "XMLSERIALIZE", "YEAR" }; public static bool IsReservedWord(string word) { return ReservedWords.Contains(word.ToUpper()); } } }
using System; using System.Diagnostics; using System.Drawing; using System.IO; using System.Windows.Forms; using GemBox.Document; namespace WindowsFormsRichTextEditor { public partial class MainForm : Form { public MainForm() { InitializeComponent(); ComponentInfo.SetLicense("FREE-LIMITED-KEY"); } private void btnOpen_Click(object sender, EventArgs e) { var dialog = new OpenFileDialog() { AddExtension = true, Filter = "All Documents (*.docx;*.docm;*.doc;*.dotx;*.dotm;*.dot;*.htm;*.html;*.rtf;*.txt)|*.docx;*.docm;*.dotx;*.dotm;*.doc;*.dot;*.htm;*.html;*.rtf;*.txt|" + "Word Documents (*.docx)|*.docx|" + "Word Macro-Enabled Documents (*.docm)|*.docm|" + "Word 97-2003 Documents (*.doc)|*.doc|" + "Word Templates (*.dotx)|*.dotx|" + "Word Macro-Enabled Templates (*.dotm)|*.dotm|" + "Word 97-2003 Templates (*.dot)|*.dot|" + "Web Pages (*.htm;*.html)|*.htm;*.html|" + "Rich Text Format (*.rtf)|*.rtf|" + "Text Files (*.txt)|*.txt" }; if (dialog.ShowDialog() == DialogResult.OK) using (var stream = new MemoryStream()) { // Convert input file to RTF stream. DocumentModel.Load(dialog.FileName).Save(stream, SaveOptions.RtfDefault); stream.Position = 0; // Load RTF stream into RichTextBox. this.richTextBox.LoadFile(stream, RichTextBoxStreamType.RichText); } } private void btnSave_Click(object sender, EventArgs e) { var dialog = new SaveFileDialog() { AddExtension = true, Filter = "Word Document (*.docx)|*.docx|" + "Word Macro-Enabled Document (*.docm)|*.docm|" + "Word Template (*.dotx)|*.dotx|" + "Word Macro-Enabled Template (*.dotm)|*.dotm|" + "PDF (*.pdf)|*.pdf|" + "XPS Document (*.xps)|*.xps|" + "Web Page (*.htm;*.html)|*.htm;*.html|" + "Single File Web Page (*.mht;*.mhtml)|*.mht;*.mhtml|" + "Rich Text Format (*.rtf)|*.rtf|" + "Plain Text (*.txt)|*.txt|" + "Image (*.png;*.jpg;*.jpeg;*.gif;*.bmp;*.tif;*.tiff;*.wdp)|*.png;*.jpg;*.jpeg;*.gif;*.bmp;*.tif;*.tiff;*.wdp" }; if (dialog.ShowDialog(this) == DialogResult.OK) using (var stream = new MemoryStream()) { // Save RichTextBox content to RTF stream. this.richTextBox.SaveFile(stream, RichTextBoxStreamType.RichText); stream.Position = 0; // Convert RTF stream to output format. DocumentModel.Load(stream, LoadOptions.RtfDefault).Save(dialog.FileName); Process.Start(dialog.FileName); } } private void btnGemBoxCut_Click(object sender, EventArgs e) { this.DoGemBoxCopy(); // Clear selection. this.richTextBox.SelectedRtf = string.Empty; } private void btnGemBoxCopy_Click(object sender, EventArgs e) { this.DoGemBoxCopy(); } private void btnGemBoxPastePrepend_Click(object sender, EventArgs e) { this.DoGemBoxPaste(true); } private void btnGemBoxPasteAppend_Click(object sender, EventArgs e) { this.DoGemBoxPaste(false); } private void btnUndo_Click(object sender, EventArgs e) { if (this.richTextBox.CanUndo) this.richTextBox.Undo(); } private void btnRedo_Click(object sender, EventArgs e) { if (this.richTextBox.CanRedo) this.richTextBox.Redo(); } private void btnCut_Click(object sender, EventArgs e) { this.richTextBox.Cut(); } private void btnCopy_Click(object sender, EventArgs e) { this.richTextBox.Copy(); } private void btnPaste_Click(object sender, EventArgs e) { this.richTextBox.Paste(); } private void btnBold_Click(object sender, EventArgs e) { this.richTextBox.SelectionFont = new Font(this.richTextBox.SelectionFont.FontFamily, this.richTextBox.SelectionFont.Size, this.ToggleFontStyle(this.richTextBox.SelectionFont.Style, FontStyle.Bold)); } private void btnItalic_Click(object sender, EventArgs e) { this.richTextBox.SelectionFont = new Font(this.richTextBox.SelectionFont.FontFamily, this.richTextBox.SelectionFont.Size, this.ToggleFontStyle(this.richTextBox.SelectionFont.Style, FontStyle.Italic)); } private void btnUnderline_Click(object sender, EventArgs e) { this.richTextBox.SelectionFont = new Font(this.richTextBox.SelectionFont.FontFamily, this.richTextBox.SelectionFont.Size, this.ToggleFontStyle(this.richTextBox.SelectionFont.Style, FontStyle.Underline)); } private void btnIncreaseFontSize_Click(object sender, EventArgs e) { this.richTextBox.SelectionFont = new Font(this.richTextBox.SelectionFont.FontFamily, this.richTextBox.SelectionFont.Size + 1, this.richTextBox.SelectionFont.Style); } private void btnDecreaseFontSize_Click(object sender, EventArgs e) { this.richTextBox.SelectionFont = new Font(this.richTextBox.SelectionFont.FontFamily, this.richTextBox.SelectionFont.Size - 1, this.richTextBox.SelectionFont.Style); } private void btnToggleBullets_Click(object sender, EventArgs e) { this.richTextBox.SelectionBullet = !this.richTextBox.SelectionBullet; } private void btnDecreaseIndentation_Click(object sender, EventArgs e) { this.richTextBox.SelectionIndent -= 10; } private void btnIncreaseIndentation_Click(object sender, EventArgs e) { this.richTextBox.SelectionIndent += 10; } private void btnAlignLeft_Click(object sender, EventArgs e) { this.richTextBox.SelectionAlignment = System.Windows.Forms.HorizontalAlignment.Left; } private void btnAlignCenter_Click(object sender, EventArgs e) { this.richTextBox.SelectionAlignment = System.Windows.Forms.HorizontalAlignment.Center; } private void btnAlignRight_Click(object sender, EventArgs e) { this.richTextBox.SelectionAlignment = System.Windows.Forms.HorizontalAlignment.Right; } private void DoGemBoxCopy() { using (var stream = new MemoryStream()) { // Save RichTextBox selection to RTF stream. var writer = new StreamWriter(stream); writer.Write(this.richTextBox.SelectedRtf); writer.Flush(); stream.Position = 0; // Save RTF stream to clipboard. DocumentModel.Load(stream, LoadOptions.RtfDefault).Content.SaveToClipboard(); } } private void DoGemBoxPaste(bool prepend) { using (var stream = new MemoryStream()) { // Save RichTextBox content to RTF stream. var writer = new StreamWriter(stream); writer.Write(this.richTextBox.SelectedRtf); writer.Flush(); stream.Position = 0; // Load document from RTF stream and prepend or append clipboard content to it. var document = DocumentModel.Load(stream, LoadOptions.RtfDefault); var content = document.Content; (prepend ? content.Start : content.End).LoadFromClipboard(); stream.Position = 0; // Save document to RTF stream. document.Save(stream, SaveOptions.RtfDefault); stream.Position = 0; // Load RTF stream into RichTextBox. var reader = new StreamReader(stream); this.richTextBox.SelectedRtf = reader.ReadToEnd(); } } private FontStyle ToggleFontStyle(FontStyle item, FontStyle toggle) { return item ^ toggle; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Rotate { internal class App { public static int s_weightCount = 1; private class BaseNode { private String _BASEPAD_0; private String _BASEPAD_1; private uint _BASEPAD_2; private ushort _BASEPAD_3; private uint _BASEPAD_4; private char _BASEPAD_5; private uint _BASEPAD_6; private ushort _BASEPAD_7; private int _BASEPAD_8; private byte _BASEPAD_9; private uint _BASEPAD_10; private char _BASEPAD_11; private int _BASEPAD_12; private ushort _BASEPAD_13; private uint _BASEPAD_14; private ulong _BASEPAD_15; private int _BASEPAD_16; public BaseNode() { _BASEPAD_0 = "404"; _BASEPAD_1 = "16309"; _BASEPAD_2 = 167; _BASEPAD_3 = 138; _BASEPAD_4 = 99; _BASEPAD_5 = 'I'; _BASEPAD_6 = 172; _BASEPAD_7 = 5; _BASEPAD_8 = 108; _BASEPAD_9 = 46; _BASEPAD_10 = 147; _BASEPAD_11 = 'u'; _BASEPAD_12 = 92; _BASEPAD_13 = 17; _BASEPAD_14 = 209; _BASEPAD_15 = 129; _BASEPAD_16 = 145; } public virtual void VerifyValid() { if (_BASEPAD_0 != "404") throw new Exception("m_BASEPAD_0"); if (_BASEPAD_1 != "16309") throw new Exception("m_BASEPAD_1"); if (_BASEPAD_2 != 167) throw new Exception("m_BASEPAD_2"); if (_BASEPAD_3 != 138) throw new Exception("m_BASEPAD_3"); if (_BASEPAD_4 != 99) throw new Exception("m_BASEPAD_4"); if (_BASEPAD_5 != 'I') throw new Exception("m_BASEPAD_5"); if (_BASEPAD_6 != 172) throw new Exception("m_BASEPAD_6"); if (_BASEPAD_7 != 5) throw new Exception("m_BASEPAD_7"); if (_BASEPAD_8 != 108) throw new Exception("m_BASEPAD_8"); if (_BASEPAD_9 != 46) throw new Exception("m_BASEPAD_9"); if (_BASEPAD_10 != 147) throw new Exception("m_BASEPAD_10"); if (_BASEPAD_11 != 'u') throw new Exception("m_BASEPAD_11"); if (_BASEPAD_12 != 92) throw new Exception("m_BASEPAD_12"); if (_BASEPAD_13 != 17) throw new Exception("m_BASEPAD_13"); if (_BASEPAD_14 != 209) throw new Exception("m_BASEPAD_14"); if (_BASEPAD_15 != 129) throw new Exception("m_BASEPAD_15"); if (_BASEPAD_16 != 145) throw new Exception("m_BASEPAD_16"); } } private class Node : BaseNode { private int _PREPAD_0; private ulong _PREPAD_1; private String _PREPAD_2; private ushort _PREPAD_3; private uint _PREPAD_4; private uint _PREPAD_5; private String _PREPAD_6; private String _PREPAD_7; private ushort _PREPAD_8; private ulong _PREPAD_9; private String _PREPAD_10; private ulong _PREPAD_11; private ushort _PREPAD_12; private uint _PREPAD_13; private int _PREPAD_14; public Node m_leftChild; private char _MID1PAD_0; private int _MID1PAD_1; private char _MID1PAD_2; private int _MID1PAD_3; private ulong _MID1PAD_4; private int _MID1PAD_5; private ushort _MID1PAD_6; private int _MID1PAD_7; private ulong _MID1PAD_8; private byte _MID1PAD_9; private uint _MID1PAD_10; private ulong _MID1PAD_11; private int _MID1PAD_12; private char _MID1PAD_13; private char _MID1PAD_14; public int m_weight; private uint _MID2PAD_0; public Node m_rightChild; private int _AFTERPAD_0; private ulong _AFTERPAD_1; private String _AFTERPAD_2; private String _AFTERPAD_3; private String _AFTERPAD_4; private ushort _AFTERPAD_5; private ulong _AFTERPAD_6; public Node() { m_weight = s_weightCount++; _PREPAD_0 = 13; _PREPAD_1 = 130; _PREPAD_2 = "5130"; _PREPAD_3 = 249; _PREPAD_4 = 58; _PREPAD_5 = 166; _PREPAD_6 = "8200"; _PREPAD_7 = "864"; _PREPAD_8 = 36; _PREPAD_9 = 136; _PREPAD_10 = "21789"; _PREPAD_11 = 63; _PREPAD_12 = 49; _PREPAD_13 = 214; _PREPAD_14 = 100; _MID1PAD_0 = '('; _MID1PAD_1 = 8; _MID1PAD_2 = 'w'; _MID1PAD_3 = 21; _MID1PAD_4 = 19; _MID1PAD_5 = 100; _MID1PAD_6 = 3; _MID1PAD_7 = 50; _MID1PAD_8 = 201; _MID1PAD_9 = 3; _MID1PAD_10 = 172; _MID1PAD_11 = 230; _MID1PAD_12 = 214; _MID1PAD_13 = 'z'; _MID1PAD_14 = ';'; _MID2PAD_0 = 153; _AFTERPAD_0 = 84; _AFTERPAD_1 = 74; _AFTERPAD_2 = "30023"; _AFTERPAD_3 = "31182"; _AFTERPAD_4 = "31631"; _AFTERPAD_5 = 8; _AFTERPAD_6 = 17; } public override void VerifyValid() { base.VerifyValid(); if (_PREPAD_0 != 13) throw new Exception("m_PREPAD_0"); if (_PREPAD_1 != 130) throw new Exception("m_PREPAD_1"); if (_PREPAD_2 != "5130") throw new Exception("m_PREPAD_2"); if (_PREPAD_3 != 249) throw new Exception("m_PREPAD_3"); if (_PREPAD_4 != 58) throw new Exception("m_PREPAD_4"); if (_PREPAD_5 != 166) throw new Exception("m_PREPAD_5"); if (_PREPAD_6 != "8200") throw new Exception("m_PREPAD_6"); if (_PREPAD_7 != "864") throw new Exception("m_PREPAD_7"); if (_PREPAD_8 != 36) throw new Exception("m_PREPAD_8"); if (_PREPAD_9 != 136) throw new Exception("m_PREPAD_9"); if (_PREPAD_10 != "21789") throw new Exception("m_PREPAD_10"); if (_PREPAD_11 != 63) throw new Exception("m_PREPAD_11"); if (_PREPAD_12 != 49) throw new Exception("m_PREPAD_12"); if (_PREPAD_13 != 214) throw new Exception("m_PREPAD_13"); if (_PREPAD_14 != 100) throw new Exception("m_PREPAD_14"); if (_MID1PAD_0 != '(') throw new Exception("m_MID1PAD_0"); if (_MID1PAD_1 != 8) throw new Exception("m_MID1PAD_1"); if (_MID1PAD_2 != 'w') throw new Exception("m_MID1PAD_2"); if (_MID1PAD_3 != 21) throw new Exception("m_MID1PAD_3"); if (_MID1PAD_4 != 19) throw new Exception("m_MID1PAD_4"); if (_MID1PAD_5 != 100) throw new Exception("m_MID1PAD_5"); if (_MID1PAD_6 != 3) throw new Exception("m_MID1PAD_6"); if (_MID1PAD_7 != 50) throw new Exception("m_MID1PAD_7"); if (_MID1PAD_8 != 201) throw new Exception("m_MID1PAD_8"); if (_MID1PAD_9 != 3) throw new Exception("m_MID1PAD_9"); if (_MID1PAD_10 != 172) throw new Exception("m_MID1PAD_10"); if (_MID1PAD_11 != 230) throw new Exception("m_MID1PAD_11"); if (_MID1PAD_12 != 214) throw new Exception("m_MID1PAD_12"); if (_MID1PAD_13 != 'z') throw new Exception("m_MID1PAD_13"); if (_MID1PAD_14 != ';') throw new Exception("m_MID1PAD_14"); if (_MID2PAD_0 != 153) throw new Exception("m_MID2PAD_0"); if (_AFTERPAD_0 != 84) throw new Exception("m_AFTERPAD_0"); if (_AFTERPAD_1 != 74) throw new Exception("m_AFTERPAD_1"); if (_AFTERPAD_2 != "30023") throw new Exception("m_AFTERPAD_2"); if (_AFTERPAD_3 != "31182") throw new Exception("m_AFTERPAD_3"); if (_AFTERPAD_4 != "31631") throw new Exception("m_AFTERPAD_4"); if (_AFTERPAD_5 != 8) throw new Exception("m_AFTERPAD_5"); if (_AFTERPAD_6 != 17) throw new Exception("m_AFTERPAD_6"); } public virtual Node growTree(int maxHeight, String indent) { //Console.WriteLine(indent + m_weight.ToString()); if (maxHeight > 0) { m_leftChild = new Node(); m_leftChild.growTree(maxHeight - 1, indent + " "); m_rightChild = new Node(); m_rightChild.growTree(maxHeight - 1, indent + " "); } else m_leftChild = m_rightChild = null; return this; } public virtual void rotateTree(ref int leftWeight, ref int rightWeight) { //Console.WriteLine("rotateTree(" + m_weight.ToString() + ")"); VerifyValid(); // create node objects for children Node newLeftChild = null, newRightChild = null; if (m_leftChild != null) { newRightChild = new Node(); newRightChild.m_leftChild = m_leftChild.m_leftChild; newRightChild.m_rightChild = m_leftChild.m_rightChild; newRightChild.m_weight = m_leftChild.m_weight; } if (m_rightChild != null) { newLeftChild = new Node(); newLeftChild.m_leftChild = m_rightChild.m_leftChild; newLeftChild.m_rightChild = m_rightChild.m_rightChild; newLeftChild.m_weight = m_rightChild.m_weight; } // replace children m_leftChild = newLeftChild; m_rightChild = newRightChild; for (int I = 0; I < 32; I++) { int[] u = new int[1024]; } // verify all valid if (m_rightChild != null) { if (m_rightChild.m_leftChild != null && m_rightChild.m_rightChild != null) { m_rightChild.m_leftChild.VerifyValid(); m_rightChild.m_rightChild.VerifyValid(); m_rightChild.rotateTree( ref m_rightChild.m_leftChild.m_weight, ref m_rightChild.m_rightChild.m_weight); } else { int minus1 = -1; m_rightChild.rotateTree(ref minus1, ref minus1); } if (leftWeight != m_rightChild.m_weight) { Console.WriteLine("left weight do not match."); throw new Exception(); } } if (m_leftChild != null) { if (m_leftChild.m_leftChild != null && m_leftChild.m_rightChild != null) { m_leftChild.m_leftChild.VerifyValid(); m_leftChild.m_rightChild.VerifyValid(); m_leftChild.rotateTree( ref m_leftChild.m_leftChild.m_weight, ref m_leftChild.m_rightChild.m_weight); } else { int minus1 = -1; m_leftChild.rotateTree(ref minus1, ref minus1); } if (rightWeight != m_leftChild.m_weight) { Console.WriteLine("right weight do not match."); throw new Exception(); } } } } private static int Main() { try { Node root = new Node(); root.growTree(6, "").rotateTree( ref root.m_leftChild.m_weight, ref root.m_rightChild.m_weight); } catch (Exception) { Console.WriteLine("*** FAILED ***"); return 1; } Console.WriteLine("*** PASSED ***"); return 100; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 using System.Threading; using Dbg = System.Management.Automation; namespace System.Management.Automation { /// <summary> /// Defines a drive that exposes a provider path to the user. /// </summary> /// /// <remarks> /// A cmdlet provider may want to derive from this class to provide their /// own public members or to cache information related to the drive. For instance, /// if a drive is a connection to a remote machine and making that connection /// is expensive, then the provider may want keep a handle to the connection as /// a member of their derived <see cref="PSDriveInfo"/> class and use it when /// the provider is invoked. /// </remarks> public class PSDriveInfo : IComparable { /// <summary> /// An instance of the PSTraceSource class used for trace output /// using "SessionState" as the category. /// This is the same category as the SessionState tracer class. /// </summary> [Dbg.TraceSourceAttribute( "PSDriveInfo", "The namespace navigation tracer")] private static Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("PSDriveInfo", "The namespace navigation tracer"); /// <summary> /// Gets or sets the current working directory for the drive. /// </summary> public string CurrentLocation { get { return _currentWorkingDirectory; } set { _currentWorkingDirectory = value; } } // CurrentLocation /// <summary> /// The current working directory for the virtual drive /// as a relative path from Root /// </summary> private string _currentWorkingDirectory; /// <summary> /// Gets the name of the drive /// </summary> public string Name { get { return _name; } } /// <summary> /// The name of the virtual drive /// </summary> private string _name; /// <summary> /// Gets the name of the provider that root path /// of the drive represents. /// </summary> public ProviderInfo Provider { get { return _provider; } } /// <summary> /// The provider information for the provider that implements /// the functionality for the drive. /// </summary> private ProviderInfo _provider; /// <summary> /// Gets the root path of the drive. /// </summary> public string Root { get { return _root; } internal set { _root = value; } } /// <summary> /// Sets the root of the drive. /// </summary> /// /// <param name="path"> /// The root path to set for the drive. /// </param> /// /// <remarks> /// This method can only be called during drive /// creation. A NotSupportedException if this method /// is called outside of drive creation. /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="path"/> is null. /// </exception> /// /// <exception cref="NotSupportedException"> /// If this method gets called any other time except /// during drive creation. /// </exception> /// internal void SetRoot(string path) { if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (!DriveBeingCreated) { NotSupportedException e = PSTraceSource.NewNotSupportedException(); throw e; } _root = path; } // SetRoot /// <summary> /// The root of the virtual drive /// </summary> private string _root; /// <summary> /// Gets or sets the description for the drive. /// </summary> public string Description { get; set; } /// <summary> /// When supported by provider this specifies a maximum drive size. /// </summary> public long? MaximumSize { get; internal set; } /// <summary> /// Gets the credential to use with the drive. /// </summary> public PSCredential Credential { get; } = PSCredential.Empty; /// <summary> /// Determines if the root of the drive can /// be modified during drive creation through /// the SetRoot method. /// </summary> /// /// <value> /// True if the drive is being created and the /// root can be modified through the SetRoot method. /// False otherwise. /// </value> /// internal bool DriveBeingCreated { get; set; } /// <summary> /// True if the drive was automounted by the system, /// false otherwise. /// </summary> /// <value></value> internal bool IsAutoMounted { get; set; } /// <summary> /// True if the drive was automounted by the system, /// and then manually removed by the user. /// </summary> /// internal bool IsAutoMountedManuallyRemoved { get; set; } /// <summary> /// Gets or sets the Persist Switch parameter. /// If this switch parameter is set then the created PSDrive /// would be persisted across PowerShell sessions. /// </summary> internal bool Persist { get; } = false; /// <summary> /// Get or sets the value indicating if the created drive is a network drive. /// </summary> internal bool IsNetworkDrive { get; set; } = false; /// <summary> /// Gets or sets the UNC path of the drive. This property would be populated only /// if the created PSDrive is targeting a network drive or else this property /// would be null. /// </summary> public string DisplayRoot { get; internal set; } = null; /// <summary> /// Gets or sets if the drive-root relative paths on this drive are separated by a /// colon or not. /// /// This is true for all PSDrives on all platforms, except for filesystems on /// non-Windows platforms. /// /// This is not a path separator in the sense of separating paths in a single /// string. /// /// The biggest difference in filesystem handling between PS internally, and Unix /// style systems is, that paths on Windows separate the drive letter from the /// actual path by a colon. The second difference is, that a path that starts with /// a \ or / on Windows is considered to be a relative path (drive-relative in /// that case) where a similar path on a Unix style filesystem would be /// root-relative, which is basically drive-relative for the filesystem, as there /// is only one filesystem drive. /// /// This property indicates, that a path can be checked for that drive-relativity /// by checking for a colon. The main reason for this can be seen in all the /// places that use this property, where PowerShell's code checks/splits/string /// manipulates paths according to the colon character. This happens in many /// places. /// /// The idea here was to introduce a property that allows a code to query if a /// PSDrive expects colon to be such a separator or not. I talked to Jim back then /// about the problem, and this seemed to be a reasonable solution, given that /// there is no other way to know for a PSDrive if paths can be qualified only in /// a certain windows way on all platforms, or need special treatment on platforms /// where colon does not exist as drive separator (regular filesystems on Unix /// platforms are the only exception). /// /// Globally this property can also be only true for one single PSDrive, because /// if there is no drive separator, there is also no drive, and because there is /// no drive there is no way to match against multiple such drives. /// /// Additional data: /// It seems that on single rooted filesystems, only the default /// drive of "/" needs to set this VolumeSeparatedByColon to false /// otherwise, creating new drives from the filesystem should actually /// have this set to true as all the drives will have <string>: except /// for "/" /// /// </summary> public bool VolumeSeparatedByColon { get; internal set; } = true; #region ctor /// <summary> /// Constructs a new instance of the PSDriveInfo using another PSDriveInfo /// as a template. /// </summary> /// /// <param name="driveInfo"> /// An existing PSDriveInfo object that should be copied to this instance. /// </param> /// /// <remarks> /// A protected constructor that derived classes can call with an instance /// of this class. This allows for easy creation of derived PSDriveInfo objects /// which can be created in CmdletProvider's NewDrive method using the PSDriveInfo /// that is passed in. /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="PSDriveInfo"/> is null. /// </exception> protected PSDriveInfo(PSDriveInfo driveInfo) { if (driveInfo == null) { throw PSTraceSource.NewArgumentNullException("driveInfo"); } _name = driveInfo.Name; _provider = driveInfo.Provider; Credential = driveInfo.Credential; _currentWorkingDirectory = driveInfo.CurrentLocation; Description = driveInfo.Description; this.MaximumSize = driveInfo.MaximumSize; DriveBeingCreated = driveInfo.DriveBeingCreated; _hidden = driveInfo._hidden; IsAutoMounted = driveInfo.IsAutoMounted; _root = driveInfo._root; Persist = driveInfo.Persist; this.Trace(); } /// <summary> /// Constructs a drive that maps an MSH Path in /// the shell to a Cmdlet Provider. /// </summary> /// /// <param name="name"> /// The name of the drive. /// </param> /// /// <param name="provider"> /// The name of the provider which implements the functionality /// for the root path of the drive. /// </param> /// /// <param name="root"> /// The root path of the drive. For example, the root of a /// drive in the file system can be c:\windows\system32 /// </param> /// /// <param name="description"> /// The description for the drive. /// </param> /// /// <param name="credential"> /// The credentials under which all operations on the drive should occur. /// If null, the current user credential is used. /// </param> /// /// <throws> /// ArgumentNullException - if <paramref name="name"/>, /// <paramref name="provider"/>, or <paramref name="root"/> /// is null. /// </throws> public PSDriveInfo( string name, ProviderInfo provider, string root, string description, PSCredential credential) { // Verify the parameters if (name == null) { throw PSTraceSource.NewArgumentNullException("name"); } if (provider == null) { throw PSTraceSource.NewArgumentNullException("provider"); } if (root == null) { throw PSTraceSource.NewArgumentNullException("root"); } // Copy the parameters to the local members _name = name; _provider = provider; _root = root; Description = description; if (credential != null) { Credential = credential; } // Set the current working directory to the empty // string since it is relative to the root. _currentWorkingDirectory = String.Empty; Dbg.Diagnostics.Assert( _currentWorkingDirectory != null, "The currentWorkingDirectory cannot be null"); // Trace out the fields this.Trace(); } /// <summary> /// Constructs a drive that maps an MSH Path in /// the shell to a Cmdlet Provider. /// </summary> /// /// <param name="name"> /// The name of the drive. /// </param> /// /// <param name="provider"> /// The name of the provider which implements the functionality /// for the root path of the drive. /// </param> /// /// <param name="root"> /// The root path of the drive. For example, the root of a /// drive in the file system can be c:\windows\system32 /// </param> /// /// <param name="description"> /// The description for the drive. /// </param> /// /// <param name="credential"> /// The credentials under which all operations on the drive should occur. /// If null, the current user credential is used. /// </param> /// <param name="displayRoot"> /// The network path of the drive. This field would be populated only if PSDriveInfo /// is targeting the network drive or else this filed is null for local drives. /// </param> /// /// <throws> /// ArgumentNullException - if <paramref name="name"/>, /// <paramref name="provider"/>, or <paramref name="root"/> /// is null. /// </throws> public PSDriveInfo( string name, ProviderInfo provider, string root, string description, PSCredential credential, string displayRoot) : this(name, provider, root, description, credential) { DisplayRoot = displayRoot; } /// <summary> /// Constructs a drive that maps an MSH Path in /// the shell to a Cmdlet Provider. /// </summary> /// /// <param name="name"> /// The name of the drive. /// </param> /// /// <param name="provider"> /// The name of the provider which implements the functionality /// for the root path of the drive. /// </param> /// /// <param name="root"> /// The root path of the drive. For example, the root of a /// drive in the file system can be c:\windows\system32 /// </param> /// /// <param name="description"> /// The description for the drive. /// </param> /// /// <param name="credential"> /// The credentials under which all operations on the drive should occur. /// If null, the current user credential is used. /// </param> /// <param name="persist"> /// It indicates if the the created PSDrive would be /// persisted across PowerShell sessions. /// </param> /// /// <throws> /// ArgumentNullException - if <paramref name="name"/>, /// <paramref name="provider"/>, or <paramref name="root"/> /// is null. /// </throws> public PSDriveInfo( string name, ProviderInfo provider, string root, string description, PSCredential credential, bool persist) : this(name, provider, root, description, credential) { Persist = persist; } #endregion ctor /// <summary> /// Gets the name of the drive as a string. /// </summary> /// /// <returns> /// Returns a String that is that name of the drive. /// </returns> public override string ToString() { return Name; } /// <summary> /// Gets or sets the hidden property. The hidden property /// determines if the drive should be hidden from the user. /// </summary> /// /// <value> /// True if the drive should be hidden from the user, false /// otherwise. /// </value> /// internal bool Hidden { get { return _hidden; } //get set { _hidden = value; } // set } // Hidden /// <summary> /// Determines if the drive should be hidden from the user. /// </summary> private bool _hidden; /// <summary> /// Sets the name of the drive to a new name. /// </summary> /// /// <param name="newName"> /// The new name for the drive. /// </param> /// /// <remarks> /// This must be internal so that we allow the renaming of drives /// via the Core Command API but not through a reference to the /// drive object. More goes in to renaming a drive than just modifying /// the name in this class. /// </remarks> /// /// <exception cref="ArgumentException"> /// If <paramref name="newName"/> is null or empty. /// </exception> /// internal void SetName(string newName) { if (String.IsNullOrEmpty(newName)) { throw PSTraceSource.NewArgumentException("newName"); } _name = newName; } // SetName /// <summary> /// Sets the provider of the drive to a new provider. /// </summary> /// /// <param name="newProvider"> /// The new provider for the drive. /// </param> /// /// <remarks> /// This must be internal so that we allow the renaming of providers. /// All drives must be associated with the new provider name and can /// be changed using the Core Command API but not through a reference to the /// drive object. More goes in to renaming a provider than just modifying /// the provider in this class. /// </remarks> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="newProvider"/> is null. /// </exception> /// internal void SetProvider(ProviderInfo newProvider) { if (newProvider == null) { throw PSTraceSource.NewArgumentNullException("newProvider"); } _provider = newProvider; } // SetProvider /// <summary> /// Traces the virtual drive /// </summary> internal void Trace() { s_tracer.WriteLine( "A drive was found:"); if (Name != null) { s_tracer.WriteLine( "\tName: {0}", Name); } if (Provider != null) { s_tracer.WriteLine( "\tProvider: {0}", Provider); } if (Root != null) { s_tracer.WriteLine( "\tRoot: {0}", Root); } if (CurrentLocation != null) { s_tracer.WriteLine( "\tCWD: {0}", CurrentLocation); } if (Description != null) { s_tracer.WriteLine( "\tDescription: {0}", Description); } }//Trace /// <summary> /// Compares this instance to the specified drive. /// </summary> /// /// <param name="drive"> /// A PSDriveInfo object to compare. /// </param> /// /// <returns> /// A signed number indicating the relative values of this instance and object specified. /// Return Value: Less than zero Meaning: This instance is less than object. /// Return Value: Zero Meaning: This instance is equal to object. /// Return Value: Greater than zero Meaning: This instance is greater than object or object is a null reference. /// </returns> public int CompareTo(PSDriveInfo drive) { #pragma warning disable 56506 if (drive == null) { throw PSTraceSource.NewArgumentNullException("drive"); } return String.Compare(Name, drive.Name, StringComparison.CurrentCultureIgnoreCase); #pragma warning restore 56506 } /// <summary> /// Compares this instance to the specified object. The object must be a PSDriveInfo. /// </summary> /// /// <param name="obj"> /// An object to compare. /// </param> /// /// <returns> /// A signed number indicating the relative values of this /// instance and object specified. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="obj"/> is not a PSDriveInfo instance. /// </exception> public int CompareTo(object obj) { PSDriveInfo drive = obj as PSDriveInfo; if (drive == null) { ArgumentException e = PSTraceSource.NewArgumentException( "obj", SessionStateStrings.OnlyAbleToComparePSDriveInfo); throw e; } return (CompareTo(drive)); } /// <summary> /// Compares this instance to the specified object. /// </summary> /// /// <param name="obj"> /// An object to compare. /// </param> /// /// <returns> /// True if the drive names are equal, false otherwise. /// </returns> public override bool Equals(object obj) { if (obj is PSDriveInfo) { return CompareTo(obj) == 0; } else { return false; } } /// <summary> /// Compares this instance to the specified object. /// </summary> /// /// <param name="drive"> /// An object to compare. /// </param> /// /// <returns> /// True if the drive names are equal, false otherwise. /// </returns> public bool Equals(PSDriveInfo drive) { return CompareTo(drive) == 0; } /// <summary> /// Equality operator for the drive determines if the drives /// are equal by having the same name. /// </summary> /// /// <param name="drive1"> /// The first object to compare to the second. /// </param> /// /// <param name="drive2"> /// The second object to compare to the first. /// </param> /// /// <returns> /// True if the objects are PSDriveInfo objects and have the same name, /// false otherwise. /// </returns> public static bool operator ==(PSDriveInfo drive1, PSDriveInfo drive2) { Object drive1Object = drive1; Object drive2Object = drive2; if ((drive1Object == null) == (drive2Object == null)) { if (drive1Object != null) { return drive1.Equals(drive2); } return true; } else { return false; } } /// <summary> /// Inequality operator for the drive determines if the drives /// are not equal by using the drive name. /// </summary> /// /// <param name="drive1"> /// The first object to compare to the second. /// </param> /// /// <param name="drive2"> /// The second object to compare to the first. /// </param> /// /// <returns> /// True if the PSDriveInfo objects do not have the same name, /// false otherwise. /// </returns> public static bool operator !=(PSDriveInfo drive1, PSDriveInfo drive2) { return !(drive1 == drive2); } /// <summary> /// Compares the specified drives to determine if drive1 is less than /// drive2. /// </summary> /// /// <param name="drive1"> /// The drive to determine if it is less than the other drive. /// </param> /// /// <param name="drive2"> /// The drive to compare drive1 against. /// </param> /// /// <returns> /// True if the lexical comparison of drive1's name is less than drive2's name. /// </returns> public static bool operator <(PSDriveInfo drive1, PSDriveInfo drive2) { Object drive1Object = drive1; Object drive2Object = drive2; if ((drive1Object == null)) { if (drive2Object == null) { // Since both drives are null, they are equal return false; } else { // Since drive1 is null it is less than drive2 which is not null return true; } } else { if (drive2Object == null) { // Since drive1 is not null and drive2 is, drive1 is greater than drive2 return false; } else { // Since drive1 and drive2 are not null use the CompareTo return drive1.CompareTo(drive2) < 0; } } } // operator < /// <summary> /// Compares the specified drives to determine if drive1 is greater than /// drive2. /// </summary> /// /// <param name="drive1"> /// The drive to determine if it is greater than the other drive. /// </param> /// /// <param name="drive2"> /// The drive to compare drive1 against. /// </param> /// /// <returns> /// True if the lexical comparison of drive1's name is greater than drive2's name. /// </returns> public static bool operator >(PSDriveInfo drive1, PSDriveInfo drive2) { Object drive1Object = drive1; Object drive2Object = drive2; if ((drive1Object == null)) { if (drive2Object == null) { // Since both drives are null, they are equal return false; } else { // Since drive1 is null it is less than drive2 which is not null return false; } } else { if (drive2Object == null) { // Since drive1 is not null and drive2 is, drive1 is greater than drive2 return true; } else { // Since drive1 and drive2 are not null use the CompareTo return drive1.CompareTo(drive2) > 0; } } } // operator > /// <summary> /// Gets the hash code for this instance. /// </summary> /// /// <returns>The result of base.GetHashCode()</returns> /// <!-- Override the base GetHashCode because the compiler complains /// if you don't when you implement operator== and operator!= --> public override int GetHashCode() { return base.GetHashCode(); } private PSNoteProperty _noteProperty; internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { if (_noteProperty == null) { Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); } return _noteProperty; } }//Class PSDriveInfo }
// Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Copyright (c) 2008 Novell, Inc. // // Authors: // Andreia Gaita (avidigal@novell.com) // using System; using System.Collections.Generic; using Gtk; using Bugzz; namespace mockup { public partial class MainWindow: Gtk.Window { Widgets.BugList bugsWidget; Widgets.Detail detailWidget; Widgets.Search searchWidget; Widgets.Settings settingsWidget; Settings settings; BugzzManager bugzzManager; bool suspendLayout; public MainWindow (): base (Gtk.WindowType.Toplevel) { Build (); settings = new Settings (); Loader.Load (settings); Bugzz.LoginData loginData = new LoginData(); Loader.Load (loginData); if (settings.Online) { Console.WriteLine (1); bugzzManager = new BugzzManager (settings.Url, loginData); this.actOnline.Label = Mono.Unix.Catalog.GetString("Online"); } else { Console.WriteLine (2); bugzzManager = new BugzzManager (loginData); this.actOnline.Label = Mono.Unix.Catalog.GetString("Offline"); } ShowAll (); } protected void OnDeleteEvent (object sender, DeleteEventArgs a) { Application.Quit (); a.RetVal = true; } protected virtual void OnToggleSettings (object sender, System.EventArgs e) { if (suspendLayout) return; if (settingsWidget == null) { settingsWidget = new Widgets.Settings (settings); ShowFull (settingsWidget); } else { if (settingsWidget.Visible) { settingsWidget.Cancel (); Hide (settingsWidget); } else { ShowFull (settingsWidget); } } UpdateToggles (); ShowAll (); } protected virtual void OnToggleSearch (object sender, System.EventArgs e) { if (suspendLayout) return; if (searchWidget == null) { searchWidget = new Widgets.Search (this); MoveDown (bugsWidget); ShowTop (searchWidget); } else { if (searchWidget.Visible) { Hide (searchWidget); MoveUp (bugsWidget); } else { MoveDown (bugsWidget); ShowTop (searchWidget); } } UpdateToggles (); ShowAll (); } protected virtual void OnToggleList (object sender, System.EventArgs e) { if (suspendLayout) return; ToggleList (); } public void ToggleList () { if (bugsWidget == null) { bugsWidget = new Widgets.BugList (bugzzManager); ShowBottom (bugsWidget); } else { if (bugsWidget.Visible) { Hide (bugsWidget); } else { ShowBottom (bugsWidget); } } UpdateToggles (); ShowAll (); } public void Search (Query query) { if (bugsWidget == null || !bugsWidget.Visible) ToggleList (); bugsWidget.Load (query); } protected virtual void OnToggleDetail (object sender, System.EventArgs e) { if (suspendLayout) return; if (detailWidget == null) { detailWidget = new Widgets.Detail (); MoveUp (bugsWidget); ShowBottom (detailWidget); } else { if (detailWidget.Visible) { detailWidget.Cancel (); Hide (detailWidget); MoveDown (bugsWidget); } else { MoveUp (bugsWidget); ShowBottom (detailWidget); } } UpdateToggles (); ShowAll (); } protected virtual void OnToggleOnline (object sender, System.EventArgs e) { if (suspendLayout) return; if (settings.Online) { settings.Online = false; this.actOnline.Label = Mono.Unix.Catalog.GetString("Offline"); } else { settings.Online = true; this.actOnline.Label = Mono.Unix.Catalog.GetString("Online"); } } private void Hide (Gtk.Widget widget) { vpane.Remove (widget); widget.Hide (); } private void MoveUp () { Gtk.Widget pre = vpane.Child2; HideBottom (); ShowTop (pre); } private void MoveUp (Gtk.Widget widget) { if (widget == null) return; Gtk.Widget pre = vpane.Child2; if (pre == widget) { HideBottom (); ShowTop (pre); } else { HideTop (); HideBottom (); } } private void MoveDown () { Gtk.Widget pre = vpane.Child1; HideTop (); ShowBottom (pre); } private void MoveDown (Gtk.Widget widget) { if (widget == null) return; Gtk.Widget pre = vpane.Child1; if (pre == widget) { HideTop (); ShowBottom (pre); } else { HideTop (); HideBottom (); } } private void HideTop () { Gtk.Widget pre = vpane.Child1; if (pre != null) { pre.Hide (); vpane.Remove (pre); } } private void HideBottom () { Gtk.Widget pre = vpane.Child2; if (pre != null) { pre.Hide (); vpane.Remove (pre); } } private void ShowBottom (Gtk.Widget widget) { if (widget == null) return; HideBottom (); vpane.Add2 (widget); widget.Show (); if (vpane.Child1 != null) vpane.Position = vpane.Child1.SizeRequest ().Height; } private void ShowTop (Gtk.Widget widget) { if (widget == null) return; HideTop (); vpane.Add1 (widget); widget.Show (); vpane.Position = widget.SizeRequest ().Height; } private void ShowFull (Gtk.Widget widget) { if (widget == null) return; HideBottom (); ShowTop (widget); } private void UpdateToggles () { suspendLayout = true; actBugDetail.Active = detailWidget != null ? detailWidget.Visible : false; actBugList.Active = bugsWidget != null ? bugsWidget.Visible : false; actSearch.Active = searchWidget != null ? searchWidget.Visible : false; actSettings.Active = settingsWidget != null ? settingsWidget.Visible : false; suspendLayout = false; } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Specialized; using System.Collections; using System.Collections.Generic; using System.Text; using gov.va.medora.mdo.dao; using gov.va.medora.mdo.exceptions; namespace gov.va.medora.mdo { public class Patient : Person { const int INPATIENT = 1; const int OUTPATIENT = 2; public string EDIPI { get; set; } string mpiPid; string localPid; StringDictionary sitePids; string vendorPid; string localSiteId; string mpiChecksum; bool locallyAssignedMpiPid; HospitalLocation location; string cwad; bool restricted; string admitTimestamp; bool serviceConnected; int scPercent; bool inpatient; string deceasedDate; KeyValuePair<int, string> confidentiality; bool needsMeansTest; string currentMeansStatus; StringDictionary patientFlags; string cmorSiteId; string activeInsurance; bool hasInsurance; bool testPatient; KeyValuePair<string, string> preferredFacility; string patientType; bool isVeteran; Team team; SiteId[] siteIDs; const string DAO_NAME = "IPatientDao"; public Patient() { } public string MpiPid { get { return mpiPid; } set { mpiPid = value; } } public string LocalPid { get { return localPid; } set { localPid = value; } } public StringDictionary SitePids { get { return sitePids; } set { sitePids = value; } } public string VendorPid { get { return vendorPid; } set { vendorPid = value; } } public string LocalSiteId { get { return localSiteId; } set { localSiteId = value; } } public string MpiChecksum { get { return mpiChecksum; } set { mpiChecksum = value; } } public HospitalLocation Location { get { return location; } set { location = value; } } public string Cwad { get { return cwad; } set { cwad = value; } } public bool IsRestricted { get { return restricted; } set { restricted = value; } } public string AdmitTimestamp { get { return admitTimestamp; } set { admitTimestamp = value; } } public bool IsServiceConnected { get { return serviceConnected; } set { serviceConnected = value; } } public int ScPercent { get { return scPercent; } set { scPercent = value; } } public bool IsInpatient { get { return inpatient; } set { inpatient = value; } } public string DeceasedDate { get { return deceasedDate; } set { deceasedDate = value; } } public KeyValuePair<int, string> Confidentiality { get { return confidentiality; } set { confidentiality = value; } } public bool NeedsMeansTest { get { return needsMeansTest; } set { needsMeansTest = value; } } public StringDictionary PatientFlags { get { return patientFlags; } set { patientFlags = value; } } public string CmorSiteId { get { return cmorSiteId; } set { cmorSiteId = value; } } public string ActiveInsurance { get { return activeInsurance; } set { activeInsurance = value; } } public bool IsTestPatient { get { return testPatient; } set { testPatient = value; } } public string CurrentMeansStatus { get { return currentMeansStatus; } set { currentMeansStatus = value; } } public bool HasInsurance { get { return hasInsurance; } set { hasInsurance = value; } } public KeyValuePair<string, string> PreferredFacility { get { return preferredFacility; } set { preferredFacility = value; } } public string PatientType { get { return patientType; } set { patientType = value; } } public bool IsVeteran { get { return isVeteran; } set { isVeteran = value; } } public bool IsLocallyAssignedMpiPid { get { return locallyAssignedMpiPid; } set { locallyAssignedMpiPid = value; } } public SiteId[] SiteIDs { get { return siteIDs; } set { siteIDs = value; } } public Team Team { get { return team; } set { team = value; } } internal static IPatientDao getDao(AbstractConnection cxn) { if (!cxn.IsConnected) { throw new MdoException(MdoExceptionCode.USAGE_NO_CONNECTION, "Unable to instantiate DAO: unconnected"); } AbstractDaoFactory f = AbstractDaoFactory.getDaoFactory(AbstractDaoFactory.getConstant(cxn.DataSource.Protocol)); return f.getPatientDao(cxn); } public static KeyValuePair<string, string> getPcpForPatient(AbstractConnection cxn, string pid) { return getDao(cxn).getPcpForPatient(pid); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an array with all values /// </summary> public static double[] Values(dquat q) => q.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<double> GetEnumerator(dquat q) => q.GetEnumerator(); /// <summary> /// Returns a string representation of this quaternion using ', ' as a seperator. /// </summary> public static string ToString(dquat q) => q.ToString(); /// <summary> /// Returns a string representation of this quaternion using a provided seperator. /// </summary> public static string ToString(dquat q, string sep) => q.ToString(sep); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format provider for each component. /// </summary> public static string ToString(dquat q, string sep, IFormatProvider provider) => q.ToString(sep, provider); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format for each component. /// </summary> public static string ToString(dquat q, string sep, string format) => q.ToString(sep, format); /// <summary> /// Returns a string representation of this quaternion using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(dquat q, string sep, string format, IFormatProvider provider) => q.ToString(sep, format, provider); /// <summary> /// Returns the number of components (4). /// </summary> public static int Count(dquat q) => q.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(dquat q, dquat rhs) => q.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(dquat q, object obj) => q.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(dquat q) => q.GetHashCode(); /// <summary> /// Returns a bvec4 from component-wise application of IsInfinity (double.IsInfinity(v)). /// </summary> public static bvec4 IsInfinity(dquat v) => dquat.IsInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of IsFinite (!double.IsNaN(v) &amp;&amp; !double.IsInfinity(v)). /// </summary> public static bvec4 IsFinite(dquat v) => dquat.IsFinite(v); /// <summary> /// Returns a bvec4 from component-wise application of IsNaN (double.IsNaN(v)). /// </summary> public static bvec4 IsNaN(dquat v) => dquat.IsNaN(v); /// <summary> /// Returns a bvec4 from component-wise application of IsNegativeInfinity (double.IsNegativeInfinity(v)). /// </summary> public static bvec4 IsNegativeInfinity(dquat v) => dquat.IsNegativeInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of IsPositiveInfinity (double.IsPositiveInfinity(v)). /// </summary> public static bvec4 IsPositiveInfinity(dquat v) => dquat.IsPositiveInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(dquat lhs, dquat rhs) => dquat.Equal(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(dquat lhs, dquat rhs) => dquat.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(dquat lhs, dquat rhs) => dquat.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(dquat lhs, dquat rhs) => dquat.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(dquat lhs, dquat rhs) => dquat.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(dquat lhs, dquat rhs) => dquat.LesserThanEqual(lhs, rhs); /// <summary> /// Returns the inner product (dot product, scalar product) of the two quaternions. /// </summary> public static double Dot(dquat lhs, dquat rhs) => dquat.Dot(lhs, rhs); /// <summary> /// Returns the euclidean length of this quaternion. /// </summary> public static double Length(dquat q) => q.Length; /// <summary> /// Returns the squared euclidean length of this quaternion. /// </summary> public static double LengthSqr(dquat q) => q.LengthSqr; /// <summary> /// Returns a copy of this quaternion with length one (undefined if this has zero length). /// </summary> public static dquat Normalized(dquat q) => q.Normalized; /// <summary> /// Returns a copy of this quaternion with length one (returns zero if length is zero). /// </summary> public static dquat NormalizedSafe(dquat q) => q.NormalizedSafe; /// <summary> /// Returns the represented angle of this quaternion. /// </summary> public static double Angle(dquat q) => q.Angle; /// <summary> /// Returns the represented axis of this quaternion. /// </summary> public static dvec3 Axis(dquat q) => q.Axis; /// <summary> /// Returns the represented yaw angle of this quaternion. /// </summary> public static double Yaw(dquat q) => q.Yaw; /// <summary> /// Returns the represented pitch angle of this quaternion. /// </summary> public static double Pitch(dquat q) => q.Pitch; /// <summary> /// Returns the represented roll angle of this quaternion. /// </summary> public static double Roll(dquat q) => q.Roll; /// <summary> /// Returns the represented euler angles (pitch, yaw, roll) of this quaternion. /// </summary> public static dvec3 EulerAngles(dquat q) => q.EulerAngles; /// <summary> /// Rotates this quaternion from an axis and an angle (in radians). /// </summary> public static dquat Rotated(dquat q, double angle, dvec3 v) => q.Rotated(angle, v); /// <summary> /// Creates a dmat3 that realizes the rotation of this quaternion /// </summary> public static dmat3 ToMat3(dquat q) => q.ToMat3; /// <summary> /// Creates a dmat4 that realizes the rotation of this quaternion /// </summary> public static dmat4 ToMat4(dquat q) => q.ToMat4; /// <summary> /// Returns the conjugated quaternion /// </summary> public static dquat Conjugate(dquat q) => q.Conjugate; /// <summary> /// Returns the inverse quaternion /// </summary> public static dquat Inverse(dquat q) => q.Inverse; /// <summary> /// Returns the cross product between two quaternions. /// </summary> public static dquat Cross(dquat q1, dquat q2) => dquat.Cross(q1, q2); /// <summary> /// Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions). /// </summary> public static dquat Mix(dquat x, dquat y, double a) => dquat.Mix(x, y, a); /// <summary> /// Calculates a proper spherical interpolation between two quaternions (only works for normalized quaternions). /// </summary> public static dquat SLerp(dquat x, dquat y, double a) => dquat.SLerp(x, y, a); /// <summary> /// Applies squad interpolation of these quaternions /// </summary> public static dquat Squad(dquat q1, dquat q2, dquat s1, dquat s2, double h) => dquat.Squad(q1, q2, s1, s2, h); /// <summary> /// Returns a dquat from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static dquat Lerp(dquat min, dquat max, dquat a) => dquat.Lerp(min, max, a); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Write action delegate. /// </summary> /// <param name="obj">Target object.</param> /// <param name="writer">Writer.</param> internal delegate void BinaryReflectiveWriteAction(object obj, IBinaryWriter writer); /// <summary> /// Read action delegate. /// </summary> /// <param name="obj">Target object.</param> /// <param name="reader">Reader.</param> internal delegate void BinaryReflectiveReadAction(object obj, IBinaryReader reader); /// <summary> /// Routines for reflective reads and writes. /// </summary> internal static class BinaryReflectiveActions { /** Method: read enum. */ private static readonly MethodInfo MthdReadEnum = typeof(IBinaryReader).GetMethod("ReadEnum", new[] { typeof(string) }); /** Method: read enum. */ private static readonly MethodInfo MthdReadEnumRaw = typeof (IBinaryRawReader).GetMethod("ReadEnum"); /** Method: read enum array. */ private static readonly MethodInfo MthdReadEnumArray = typeof(IBinaryReader).GetMethod("ReadEnumArray", new[] { typeof(string) }); /** Method: read enum array. */ private static readonly MethodInfo MthdReadEnumArrayRaw = typeof(IBinaryRawReader).GetMethod("ReadEnumArray"); /** Method: read array. */ private static readonly MethodInfo MthdReadObjArray = typeof(IBinaryReader).GetMethod("ReadArray", new[] { typeof(string) }); /** Method: read array. */ private static readonly MethodInfo MthdReadObjArrayRaw = typeof(IBinaryRawReader).GetMethod("ReadArray"); /** Method: read object. */ private static readonly MethodInfo MthdReadObj= typeof(IBinaryReader).GetMethod("ReadObject", new[] { typeof(string) }); /** Method: read object. */ private static readonly MethodInfo MthdReadObjRaw = typeof(IBinaryRawReader).GetMethod("ReadObject"); /** Method: write enum array. */ private static readonly MethodInfo MthdWriteEnumArray = typeof(IBinaryWriter).GetMethod("WriteEnumArray"); /** Method: write enum array. */ private static readonly MethodInfo MthdWriteEnumArrayRaw = typeof(IBinaryRawWriter).GetMethod("WriteEnumArray"); /** Method: write array. */ private static readonly MethodInfo MthdWriteObjArray = typeof(IBinaryWriter).GetMethod("WriteArray"); /** Method: write array. */ private static readonly MethodInfo MthdWriteObjArrayRaw = typeof(IBinaryRawWriter).GetMethod("WriteArray"); /** Method: write object. */ private static readonly MethodInfo MthdWriteObj = typeof(IBinaryWriter).GetMethod("WriteObject"); /** Method: write object. */ private static readonly MethodInfo MthdWriteObjRaw = typeof(IBinaryRawWriter).GetMethod("WriteObject"); /** Method: raw writer */ private static readonly MethodInfo MthdGetRawWriter = typeof(IBinaryWriter).GetMethod("GetRawWriter"); /** Method: raw writer */ private static readonly MethodInfo MthdGetRawReader = typeof(IBinaryReader).GetMethod("GetRawReader"); /// <summary> /// Lookup read/write actions for the given type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> /// <param name="forceTimestamp">Force timestamp serialization for DateTime fields..</param> public static void GetTypeActions(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw, bool forceTimestamp) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); var type = field.FieldType; forceTimestamp = forceTimestamp || field.DeclaringType.GetCustomAttributes(typeof(TimestampAttribute), true).Any(); if (type.IsPrimitive) HandlePrimitive(field, out writeAction, out readAction, raw); else if (type.IsArray) HandleArray(field, out writeAction, out readAction, raw); else HandleOther(field, out writeAction, out readAction, raw, forceTimestamp); } /// <summary> /// Handle primitive type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> /// <exception cref="IgniteException">Unsupported primitive type: + type.Name</exception> private static void HandlePrimitive(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { var type = field.FieldType; if (type == typeof (bool)) { writeAction = raw ? GetRawWriter<bool>(field, (w, o) => w.WriteBoolean(o)) : GetWriter<bool>(field, (f, w, o) => w.WriteBoolean(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadBoolean()) : GetReader(field, (f, r) => r.ReadBoolean(f)); } else if (type == typeof (sbyte)) { writeAction = raw ? GetRawWriter<sbyte>(field, (w, o) => w.WriteByte(unchecked((byte) o))) : GetWriter<sbyte>(field, (f, w, o) => w.WriteByte(f, unchecked((byte) o))); readAction = raw ? GetRawReader(field, r => unchecked ((sbyte) r.ReadByte())) : GetReader(field, (f, r) => unchecked ((sbyte) r.ReadByte(f))); } else if (type == typeof (byte)) { writeAction = raw ? GetRawWriter<byte>(field, (w, o) => w.WriteByte(o)) : GetWriter<byte>(field, (f, w, o) => w.WriteByte(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadByte()) : GetReader(field, (f, r) => r.ReadByte(f)); } else if (type == typeof (short)) { writeAction = raw ? GetRawWriter<short>(field, (w, o) => w.WriteShort(o)) : GetWriter<short>(field, (f, w, o) => w.WriteShort(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadShort()) : GetReader(field, (f, r) => r.ReadShort(f)); } else if (type == typeof (ushort)) { writeAction = raw ? GetRawWriter<ushort>(field, (w, o) => w.WriteShort(unchecked((short) o))) : GetWriter<ushort>(field, (f, w, o) => w.WriteShort(f, unchecked((short) o))); readAction = raw ? GetRawReader(field, r => unchecked((ushort) r.ReadShort())) : GetReader(field, (f, r) => unchecked((ushort) r.ReadShort(f))); } else if (type == typeof (char)) { writeAction = raw ? GetRawWriter<char>(field, (w, o) => w.WriteChar(o)) : GetWriter<char>(field, (f, w, o) => w.WriteChar(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadChar()) : GetReader(field, (f, r) => r.ReadChar(f)); } else if (type == typeof (int)) { writeAction = raw ? GetRawWriter<int>(field, (w, o) => w.WriteInt(o)) : GetWriter<int>(field, (f, w, o) => w.WriteInt(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadInt()) : GetReader(field, (f, r) => r.ReadInt(f)); } else if (type == typeof (uint)) { writeAction = raw ? GetRawWriter<uint>(field, (w, o) => w.WriteInt(unchecked((int) o))) : GetWriter<uint>(field, (f, w, o) => w.WriteInt(f, unchecked((int) o))); readAction = raw ? GetRawReader(field, r => unchecked((uint) r.ReadInt())) : GetReader(field, (f, r) => unchecked((uint) r.ReadInt(f))); } else if (type == typeof (long)) { writeAction = raw ? GetRawWriter<long>(field, (w, o) => w.WriteLong(o)) : GetWriter<long>(field, (f, w, o) => w.WriteLong(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadLong()) : GetReader(field, (f, r) => r.ReadLong(f)); } else if (type == typeof (ulong)) { writeAction = raw ? GetRawWriter<ulong>(field, (w, o) => w.WriteLong(unchecked((long) o))) : GetWriter<ulong>(field, (f, w, o) => w.WriteLong(f, unchecked((long) o))); readAction = raw ? GetRawReader(field, r => unchecked((ulong) r.ReadLong())) : GetReader(field, (f, r) => unchecked((ulong) r.ReadLong(f))); } else if (type == typeof (float)) { writeAction = raw ? GetRawWriter<float>(field, (w, o) => w.WriteFloat(o)) : GetWriter<float>(field, (f, w, o) => w.WriteFloat(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadFloat()) : GetReader(field, (f, r) => r.ReadFloat(f)); } else if (type == typeof (double)) { writeAction = raw ? GetRawWriter<double>(field, (w, o) => w.WriteDouble(o)) : GetWriter<double>(field, (f, w, o) => w.WriteDouble(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDouble()) : GetReader(field, (f, r) => r.ReadDouble(f)); } else throw new IgniteException("Unsupported primitive type: " + type.Name); } /// <summary> /// Handle array type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> private static void HandleArray(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw) { Type elemType = field.FieldType.GetElementType(); if (elemType == typeof (bool)) { writeAction = raw ? GetRawWriter<bool[]>(field, (w, o) => w.WriteBooleanArray(o)) : GetWriter<bool[]>(field, (f, w, o) => w.WriteBooleanArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadBooleanArray()) : GetReader(field, (f, r) => r.ReadBooleanArray(f)); } else if (elemType == typeof (byte)) { writeAction = raw ? GetRawWriter<byte[]>(field, (w, o) => w.WriteByteArray(o)) : GetWriter<byte[]>(field, (f, w, o) => w.WriteByteArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadByteArray()) : GetReader(field, (f, r) => r.ReadByteArray(f)); } else if (elemType == typeof (sbyte)) { writeAction = raw ? GetRawWriter<sbyte[]>(field, (w, o) => w.WriteByteArray((byte[]) (Array) o)) : GetWriter<sbyte[]>(field, (f, w, o) => w.WriteByteArray(f, (byte[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (sbyte[]) (Array) r.ReadByteArray()) : GetReader(field, (f, r) => (sbyte[]) (Array) r.ReadByteArray(f)); } else if (elemType == typeof (short)) { writeAction = raw ? GetRawWriter<short[]>(field, (w, o) => w.WriteShortArray(o)) : GetWriter<short[]>(field, (f, w, o) => w.WriteShortArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadShortArray()) : GetReader(field, (f, r) => r.ReadShortArray(f)); } else if (elemType == typeof (ushort)) { writeAction = raw ? GetRawWriter<ushort[]>(field, (w, o) => w.WriteShortArray((short[]) (Array) o)) : GetWriter<ushort[]>(field, (f, w, o) => w.WriteShortArray(f, (short[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (ushort[]) (Array) r.ReadShortArray()) : GetReader(field, (f, r) => (ushort[]) (Array) r.ReadShortArray(f)); } else if (elemType == typeof (char)) { writeAction = raw ? GetRawWriter<char[]>(field, (w, o) => w.WriteCharArray(o)) : GetWriter<char[]>(field, (f, w, o) => w.WriteCharArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadCharArray()) : GetReader(field, (f, r) => r.ReadCharArray(f)); } else if (elemType == typeof (int)) { writeAction = raw ? GetRawWriter<int[]>(field, (w, o) => w.WriteIntArray(o)) : GetWriter<int[]>(field, (f, w, o) => w.WriteIntArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadIntArray()) : GetReader(field, (f, r) => r.ReadIntArray(f)); } else if (elemType == typeof (uint)) { writeAction = raw ? GetRawWriter<uint[]>(field, (w, o) => w.WriteIntArray((int[]) (Array) o)) : GetWriter<uint[]>(field, (f, w, o) => w.WriteIntArray(f, (int[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (uint[]) (Array) r.ReadIntArray()) : GetReader(field, (f, r) => (uint[]) (Array) r.ReadIntArray(f)); } else if (elemType == typeof (long)) { writeAction = raw ? GetRawWriter<long[]>(field, (w, o) => w.WriteLongArray(o)) : GetWriter<long[]>(field, (f, w, o) => w.WriteLongArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadLongArray()) : GetReader(field, (f, r) => r.ReadLongArray(f)); } else if (elemType == typeof (ulong)) { writeAction = raw ? GetRawWriter<ulong[]>(field, (w, o) => w.WriteLongArray((long[]) (Array) o)) : GetWriter<ulong[]>(field, (f, w, o) => w.WriteLongArray(f, (long[]) (Array) o)); readAction = raw ? GetRawReader(field, r => (ulong[]) (Array) r.ReadLongArray()) : GetReader(field, (f, r) => (ulong[]) (Array) r.ReadLongArray(f)); } else if (elemType == typeof (float)) { writeAction = raw ? GetRawWriter<float[]>(field, (w, o) => w.WriteFloatArray(o)) : GetWriter<float[]>(field, (f, w, o) => w.WriteFloatArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadFloatArray()) : GetReader(field, (f, r) => r.ReadFloatArray(f)); } else if (elemType == typeof (double)) { writeAction = raw ? GetRawWriter<double[]>(field, (w, o) => w.WriteDoubleArray(o)) : GetWriter<double[]>(field, (f, w, o) => w.WriteDoubleArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDoubleArray()) : GetReader(field, (f, r) => r.ReadDoubleArray(f)); } else if (elemType == typeof (decimal?)) { writeAction = raw ? GetRawWriter<decimal?[]>(field, (w, o) => w.WriteDecimalArray(o)) : GetWriter<decimal?[]>(field, (f, w, o) => w.WriteDecimalArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDecimalArray()) : GetReader(field, (f, r) => r.ReadDecimalArray(f)); } else if (elemType == typeof (string)) { writeAction = raw ? GetRawWriter<string[]>(field, (w, o) => w.WriteStringArray(o)) : GetWriter<string[]>(field, (f, w, o) => w.WriteStringArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadStringArray()) : GetReader(field, (f, r) => r.ReadStringArray(f)); } else if (elemType == typeof (Guid?)) { writeAction = raw ? GetRawWriter<Guid?[]>(field, (w, o) => w.WriteGuidArray(o)) : GetWriter<Guid?[]>(field, (f, w, o) => w.WriteGuidArray(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadGuidArray()) : GetReader(field, (f, r) => r.ReadGuidArray(f)); } else if (elemType.IsEnum) { writeAction = raw ? GetRawWriter(field, MthdWriteEnumArrayRaw, elemType) : GetWriter(field, MthdWriteEnumArray, elemType); readAction = raw ? GetRawReader(field, MthdReadEnumArrayRaw, elemType) : GetReader(field, MthdReadEnumArray, elemType); } else { writeAction = raw ? GetRawWriter(field, MthdWriteObjArrayRaw, elemType) : GetWriter(field, MthdWriteObjArray, elemType); readAction = raw ? GetRawReader(field, MthdReadObjArrayRaw, elemType) : GetReader(field, MthdReadObjArray, elemType); } } /// <summary> /// Handle other type. /// </summary> /// <param name="field">The field.</param> /// <param name="writeAction">Write action.</param> /// <param name="readAction">Read action.</param> /// <param name="raw">Raw mode.</param> /// <param name="forceTimestamp">Force timestamp serialization for DateTime fields..</param> private static void HandleOther(FieldInfo field, out BinaryReflectiveWriteAction writeAction, out BinaryReflectiveReadAction readAction, bool raw, bool forceTimestamp) { var type = field.FieldType; var genericDef = type.IsGenericType ? type.GetGenericTypeDefinition() : null; bool nullable = genericDef == typeof (Nullable<>); var nullableType = nullable ? type.GetGenericArguments()[0] : null; if (type == typeof (decimal)) { writeAction = raw ? GetRawWriter<decimal>(field, (w, o) => w.WriteDecimal(o)) : GetWriter<decimal>(field, (f, w, o) => w.WriteDecimal(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDecimal()) : GetReader(field, (f, r) => r.ReadDecimal(f)); } else if (type == typeof (string)) { writeAction = raw ? GetRawWriter<string>(field, (w, o) => w.WriteString(o)) : GetWriter<string>(field, (f, w, o) => w.WriteString(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadString()) : GetReader(field, (f, r) => r.ReadString(f)); } else if (type == typeof (Guid)) { writeAction = raw ? GetRawWriter<Guid>(field, (w, o) => w.WriteGuid(o)) : GetWriter<Guid>(field, (f, w, o) => w.WriteGuid(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadObject<Guid>()) : GetReader(field, (f, r) => r.ReadObject<Guid>(f)); } else if (nullable && nullableType == typeof (Guid)) { writeAction = raw ? GetRawWriter<Guid?>(field, (w, o) => w.WriteGuid(o)) : GetWriter<Guid?>(field, (f, w, o) => w.WriteGuid(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadGuid()) : GetReader(field, (f, r) => r.ReadGuid(f)); } else if (type.IsEnum && !new[] {typeof(long), typeof(ulong)}.Contains(Enum.GetUnderlyingType(type))) { writeAction = raw ? GetRawWriter<object>(field, (w, o) => w.WriteEnum(o), true) : GetWriter<object>(field, (f, w, o) => w.WriteEnum(f, o), true); readAction = raw ? GetRawReader(field, MthdReadEnumRaw) : GetReader(field, MthdReadEnum); } else if (type == typeof(IDictionary) || type == typeof(Hashtable)) { writeAction = raw ? GetRawWriter<IDictionary>(field, (w, o) => w.WriteDictionary(o)) : GetWriter<IDictionary>(field, (f, w, o) => w.WriteDictionary(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadDictionary()) : GetReader(field, (f, r) => r.ReadDictionary(f)); } else if (type == typeof(ICollection) || type == typeof(ArrayList)) { writeAction = raw ? GetRawWriter<ICollection>(field, (w, o) => w.WriteCollection(o)) : GetWriter<ICollection>(field, (f, w, o) => w.WriteCollection(f, o)); readAction = raw ? GetRawReader(field, r => r.ReadCollection()) : GetReader(field, (f, r) => r.ReadCollection(f)); } else if (type == typeof(DateTime) && IsTimestamp(field, forceTimestamp, raw)) { writeAction = GetWriter<DateTime>(field, (f, w, o) => w.WriteTimestamp(f, o)); readAction = GetReader(field, (f, r) => r.ReadObject<DateTime>(f)); } else if (nullableType == typeof(DateTime) && IsTimestamp(field, forceTimestamp, raw)) { writeAction = GetWriter<DateTime?>(field, (f, w, o) => w.WriteTimestamp(f, o)); readAction = GetReader(field, (f, r) => r.ReadTimestamp(f)); } else { writeAction = raw ? GetRawWriter(field, MthdWriteObjRaw) : GetWriter(field, MthdWriteObj); readAction = raw ? GetRawReader(field, MthdReadObjRaw) : GetReader(field, MthdReadObj); } } /// <summary> /// Determines whether specified field should be written as timestamp. /// </summary> private static bool IsTimestamp(FieldInfo field, bool forceTimestamp, bool raw) { if (forceTimestamp) { return true; } Debug.Assert(field != null && field.DeclaringType != null); var fieldName = BinaryUtils.CleanFieldName(field.Name); object[] attrs = null; if (fieldName != field.Name) { // Backing field, check corresponding property var prop = field.DeclaringType.GetProperty(fieldName, field.FieldType); if (prop != null) attrs = prop.GetCustomAttributes(true); } attrs = attrs ?? field.GetCustomAttributes(true); if (attrs.Any(x => x is TimestampAttribute)) { return true; } // Special case for DateTime and query fields. // If a field is marked with [QuerySqlField], write it as TimeStamp so that queries work. // This is not needed in raw mode (queries do not work anyway). // It may cause issues when field has attribute, but is used in a cache without queries, and user // may expect non-UTC dates to work. However, such cases are rare, and there are workarounds. return !raw && attrs.Any(x => x is QuerySqlFieldAttribute); } /// <summary> /// Gets the reader with a specified write action. /// </summary> private static BinaryReflectiveWriteAction GetWriter<T>(FieldInfo field, Expression<Action<string, IBinaryWriter, T>> write, bool convertFieldValToObject = false) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(write != null); // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); Expression fldExpr = Expression.Field(targetParamConverted, field); if (convertFieldValToObject) fldExpr = Expression.Convert(fldExpr, typeof (object)); // Call Writer method var writerParam = Expression.Parameter(typeof(IBinaryWriter)); var fldNameParam = Expression.Constant(BinaryUtils.CleanFieldName(field.Name)); var writeExpr = Expression.Invoke(write, fldNameParam, writerParam, fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the reader with a specified write action. /// </summary> private static BinaryReflectiveWriteAction GetRawWriter<T>(FieldInfo field, Expression<Action<IBinaryRawWriter, T>> write, bool convertFieldValToObject = false) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(write != null); // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); Expression fldExpr = Expression.Field(targetParamConverted, field); if (convertFieldValToObject) fldExpr = Expression.Convert(fldExpr, typeof (object)); // Call Writer method var writerParam = Expression.Parameter(typeof(IBinaryWriter)); var writeExpr = Expression.Invoke(write, Expression.Call(writerParam, MthdGetRawWriter), fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetWriter(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetWriter0(field, method, false, genericArgs); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetRawWriter(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetWriter0(field, method, true, genericArgs); } /// <summary> /// Gets the writer with a specified generic method. /// </summary> private static BinaryReflectiveWriteAction GetWriter0(FieldInfo field, MethodInfo method, bool raw, params Type[] genericArgs) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static Debug.Assert(method != null); if (genericArgs.Length == 0) genericArgs = new[] {field.FieldType}; // Get field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, field.DeclaringType); var fldExpr = Expression.Field(targetParamConverted, field); // Call Writer method var writerParam = Expression.Parameter(typeof (IBinaryWriter)); var writeMethod = method.MakeGenericMethod(genericArgs); var writeExpr = raw ? Expression.Call(Expression.Call(writerParam, MthdGetRawWriter), writeMethod, fldExpr) : Expression.Call(writerParam, writeMethod, Expression.Constant(BinaryUtils.CleanFieldName(field.Name)), fldExpr); // Compile and return return Expression.Lambda<BinaryReflectiveWriteAction>(writeExpr, targetParam, writerParam).Compile(); } /// <summary> /// Gets the reader with a specified read action. /// </summary> private static BinaryReflectiveReadAction GetReader<T>(FieldInfo field, Expression<Func<string, IBinaryReader, T>> read) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static // Call Reader method var readerParam = Expression.Parameter(typeof(IBinaryReader)); var fldNameParam = Expression.Constant(BinaryUtils.CleanFieldName(field.Name)); Expression readExpr = Expression.Invoke(read, fldNameParam, readerParam); if (typeof(T) != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParam, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } /// <summary> /// Gets the reader with a specified read action. /// </summary> private static BinaryReflectiveReadAction GetRawReader<T>(FieldInfo field, Expression<Func<IBinaryRawReader, T>> read) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static // Call Reader method var readerParam = Expression.Parameter(typeof(IBinaryReader)); Expression readExpr = Expression.Invoke(read, Expression.Call(readerParam, MthdGetRawReader)); if (typeof(T) != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParam, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetReader(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetReader0(field, method, false, genericArgs); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetRawReader(FieldInfo field, MethodInfo method, params Type[] genericArgs) { return GetReader0(field, method, true, genericArgs); } /// <summary> /// Gets the reader with a specified generic method. /// </summary> private static BinaryReflectiveReadAction GetReader0(FieldInfo field, MethodInfo method, bool raw, params Type[] genericArgs) { Debug.Assert(field != null); Debug.Assert(field.DeclaringType != null); // non-static if (genericArgs.Length == 0) genericArgs = new[] {field.FieldType}; // Call Reader method var readerParam = Expression.Parameter(typeof (IBinaryReader)); var readMethod = method.MakeGenericMethod(genericArgs); Expression readExpr = raw ? Expression.Call(Expression.Call(readerParam, MthdGetRawReader), readMethod) : Expression.Call(readerParam, readMethod, Expression.Constant(BinaryUtils.CleanFieldName(field.Name))); if (readMethod.ReturnType != field.FieldType) readExpr = Expression.Convert(readExpr, field.FieldType); // Assign field value var targetParam = Expression.Parameter(typeof(object)); var targetParamConverted = Expression.Convert(targetParam, typeof(object)); var assignExpr = Expression.Call(DelegateConverter.GetWriteFieldMethod(field), targetParamConverted, readExpr); // Compile and return return Expression.Lambda<BinaryReflectiveReadAction>(assignExpr, targetParam, readerParam).Compile(); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.Helpers { using System; using System.Runtime.CompilerServices; using TS = Microsoft.Zelig.Runtime.TypeSystem; internal static class BinaryOperations { [TS.WellKnownMethod( "Helpers_BinaryOperations_IntDiv" )] internal static int IntDiv( int left , int right ) { bool fReverse; if(left < 0) { left = unchecked(-left); fReverse = true; } else { fReverse = false; } if(right < 0) { right = unchecked(-right); fReverse = !fReverse; } int res = (int)((uint)left / (uint)right); if(fReverse) { res = -res; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_IntRem" )] internal static int IntRem( int left , int right ) { return left - (left / right) * right; } //--// [TS.WellKnownMethod( "Helpers_BinaryOperations_UintDiv" )] internal static uint UintDiv( uint dividend , uint divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } uint res = 0; int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { res *= 2; if(dividend >= divisor) { dividend -= divisor; res += 1; if(dividend == 0) { res <<= shift; break; } } divisor /= 2; shift--; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_UintRem" )] internal static uint UintRem( uint dividend , uint divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { if(dividend >= divisor) { dividend -= divisor; if(dividend == 0) { break; } } divisor /= 2; shift--; } return dividend; } //--// [TS.WellKnownMethod( "Helpers_BinaryOperations_LongMul" )] internal static long LongMul( long left , long right ) { bool fReverse; if(left < 0) { left = unchecked(-left); fReverse = true; } else { fReverse = false; } if(right < 0) { right = unchecked(-right); fReverse = !fReverse; } ulong leftU = unchecked( (ulong)left ); ulong rightU = unchecked( (ulong)right ); long res = (long)(leftU * rightU); if(fReverse) { res = -res; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_LongDiv" )] internal static long LongDiv( long left , long right ) { bool fReverse; if(left < 0) { left = unchecked(-left); fReverse = true; } else { fReverse = false; } if(right < 0) { right = unchecked(-right); fReverse = !fReverse; } ulong leftU = unchecked( (ulong)left ); ulong rightU = unchecked( (ulong)right ); long res = (long)(leftU / rightU); if(fReverse) { res = -res; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_LongRem" )] internal static long LongRem( long left , long right ) { return left - (left / right) * right; } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_LongShl" )] internal static long LongShl( long left , int shift ) { if(shift == 0) { return left; } else { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { return 0; } else { return (long)(((ulong)(leftLow << (shift - 32))) << 32); } } else { uint resHigh = (leftHigh << shift) | (leftLow >> (32 - shift)); uint resLow = (leftLow << shift); return (long)(((ulong)resHigh << 32) | (ulong)resLow); } } } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_LongShr" )] internal static long LongShr( long left , int shift ) { if(shift == 0) { return left; } else { int leftHigh = (int )(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { // // Just return the sign. // return (long)((int)leftHigh >> 31); } else { return (long)((int)leftHigh >> (shift - 32)); } } else { int resHigh = (leftHigh >> shift); uint resLow = (leftLow >> shift) | ((uint)leftHigh << (32 - shift)); return (long)(((ulong)resHigh << 32) | (ulong)resLow); } } } //--// [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongMul" )] internal static ulong UlongMul( ulong left , ulong right ) { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; uint rightHigh = (uint)(right >> 32); uint rightLow = (uint) right ; uint mid1 = (uint)((ulong)leftLow * (ulong)rightHigh); uint mid2 = (uint)((ulong)leftHigh * (ulong)rightLow ); return ((ulong)leftLow * (ulong)rightLow ) + ((ulong)mid1 << 32 ) + ((ulong)mid2 << 32 ) ; } [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongDiv" )] internal static ulong UlongDiv( ulong dividend , ulong divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } ulong res = 0; int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { res *= 2; if(dividend >= divisor) { dividend -= divisor; res += 1; if(dividend == 0) { res <<= shift; break; } } divisor /= 2; shift--; } return res; } [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongRem" )] internal static ulong UlongRem( ulong dividend , ulong divisor ) { if(divisor == 0) { throw new DivideByZeroException(); } int shift = 0; while(dividend > divisor) { if(MathImpl.IsNegative( divisor )) { break; } divisor *= 2; shift++; } while(shift >= 0) { if(dividend >= divisor) { dividend -= divisor; if(dividend == 0) { break; } } divisor /= 2; shift--; } return dividend; } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongShl" )] internal static ulong UlongShl( ulong left , int shift ) { if(shift == 0) { return left; } else { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { return 0; } else { return ((ulong)(leftLow << (shift - 32))) << 32; } } else { uint resHigh = (leftHigh << shift) | (leftLow >> (32 - shift)); uint resLow = (leftLow << shift); return (((ulong)resHigh << 32) | (ulong)resLow); } } } [Inline] [TS.WellKnownMethod( "Helpers_BinaryOperations_UlongShr" )] internal static ulong UlongShr( ulong left , int shift ) { if(shift == 0) { return left; } else { uint leftHigh = (uint)(left >> 32); uint leftLow = (uint) left ; if(shift >= 32) { if(shift >= 64) { return 0; } else { return (ulong)(leftHigh >> (shift - 32)); } } else { uint resHigh = (leftHigh >> shift); uint resLow = (leftLow >> shift) | (leftHigh << (32 - shift)); return (((ulong)resHigh << 32) | (ulong)resLow); } } } //--// [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatAdd" )] internal static float FloatAdd( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Add( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatSub" )] internal static float FloatSub( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Sub( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatMul" )] internal static float FloatMul( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Mul( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatDiv" )] internal static float FloatDiv( float left , float right ) { FloatImplementation fiLeft = new FloatImplementation( left ); FloatImplementation fiRight = new FloatImplementation( right ); fiLeft.Div( ref fiRight ); return fiLeft.ToFloat(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_FloatRem" )] internal static float FloatRem( float left , float right ) { return left - (int)(left / right) * right; } //--// [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleAdd" )] internal static double DoubleAdd( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Add( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleSub" )] internal static double DoubleSub( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Sub( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleMul" )] internal static double DoubleMul( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Mul( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleDiv" )] internal static double DoubleDiv( double left , double right ) { DoubleImplementation diLeft = new DoubleImplementation( left ); DoubleImplementation diRight = new DoubleImplementation( right ); diLeft.Div( ref diRight ); return diLeft.ToDouble(); } [TS.WellKnownMethod( "SoftFP_BinaryOperations_DoubleRem" )] internal static double DoubleRem( double left , double right ) { return left - (long)(left / right) * right; } } }
/** * Class to represent an Ordnance Survey grid reference * * (c) 2006 Jonathan Stott * * Created on 11-02-2006 * * @author Jonathan Stott * @version 1.0 * @since 1.0 */ using System; namespace SCC.Modules.DotMap.Coord { internal class OSRef { /** * Easting */ private double easting; /** * Northing */ private double northing; /** * Create a new Ordnance Survey grid reference. * * @param easting * the easting in metres * @param northing * the northing in metres * @since 1.0 */ public OSRef(double easting, double northing) { this.easting = easting; this.northing = northing; } /** * Take a string formatted as a six-figure OS grid reference (e.g. "TG514131") * and create a new OSRef object that represents that grid reference. The * first character must be H, N, S, O or T. The second character can be any * uppercase character from A through Z excluding I. * * @param ref * a String representing a six-figure Ordnance Survey grid reference * in the form XY123456 * @throws IllegalArgumentException * if ref is not of the form XY123456 * @since 1.0 */ public OSRef(String osref) { // if (ref.matches("")) char char1 = osref[0]; char char2 = osref[1]; // Thanks to Nick Holloway for pointing out the radix bug here int east = System.Convert.ToInt32(osref.Substring(2, 3)) * 100; int north = System.Convert.ToInt32(osref.Substring(5, 3)) * 100; if (char1 == 'H') { north += 1000000; } else if (char1 == 'N') { north += 500000; } else if (char1 == 'O') { north += 500000; east += 500000; } else if (char1 == 'T') { east += 500000; } int char2ord = char2; if (char2ord > 73) char2ord--; // Adjust for no I double nx = ((char2ord - 65) % 5) * 100000; double ny = (4 - Math.Floor((double)(char2ord - 65) / 5)) * 100000; easting = east + nx; northing = north + ny; } /** * Return a String representation of this OSGB grid reference showing the * easting and northing. * * @return a String represenation of this OSGB grid reference * @since 1.0 */ public String toString() { return "(" + easting + ", " + northing + ")"; } /** * Return a String representation of this OSGB grid reference using the * six-figure notation in the form XY123456 * * @return a String representing this OSGB grid reference in six-figure * notation * @since 1.0 */ public String toSixFigureString() { int hundredkmE = (int)Math.Floor(easting / 100000); int hundredkmN = (int)Math.Floor(northing / 100000); String firstLetter; if (hundredkmN < 5) { if (hundredkmE < 5) { firstLetter = "S"; } else { firstLetter = "T"; } } else if (hundredkmN < 10) { if (hundredkmE < 5) { firstLetter = "N"; } else { firstLetter = "O"; } } else { firstLetter = "H"; } int index = 65 + ((4 - (hundredkmN % 5)) * 5) + (hundredkmE % 5); // int ti = index; if (index >= 73) index++; String secondLetter = Convert.ToString(Convert.ToChar(index)); int e = (int)Math.Floor((easting - (100000 * hundredkmE)) / 100); int n = (int)Math.Floor((northing - (100000 * hundredkmN)) / 100); String es = "" + e; if (e < 100) es = "0" + es; if (e < 10) es = "0" + es; String ns = "" + n; if (n < 100) ns = "0" + ns; if (n < 10) ns = "0" + ns; return firstLetter + secondLetter + es + ns; } /** * Convert this OSGB grid reference to a latitude/longitude pair using the * OSGB36 datum. Note that, the LatLng object may need to be converted to the * WGS84 datum depending on the application. * * @return a LatLng object representing this OSGB grid reference using the * OSGB36 datum * @since 1.0 */ public LatLng toLatLng() { double OSGB_F0 = 0.9996012717; double N0 = -100000.0; double E0 = 400000.0; double phi0 = Util.ToRadians(49.0); double lambda0 = Util.ToRadians(-2.0); double a = RefEll.AIRY_1830.getMaj(); double b = RefEll.AIRY_1830.getMin(); double eSquared = RefEll.AIRY_1830.getEcc(); double phi = 0.0; double lambda = 0.0; double E = this.easting; double N = this.northing; double n = (a - b) / (a + b); double M = 0.0; double phiPrime = ((N - N0) / (a * OSGB_F0)) + phi0; do { M = (b * OSGB_F0) * (((1 + n + ((5.0 / 4.0) * n * n) + ((5.0 / 4.0) * n * n * n)) * (phiPrime - phi0)) - (((3 * n) + (3 * n * n) + ((21.0 / 8.0) * n * n * n)) * Math.Sin(phiPrime - phi0) * Math.Cos(phiPrime + phi0)) + ((((15.0 / 8.0) * n * n) + ((15.0 / 8.0) * n * n * n)) * Math.Sin(2.0 * (phiPrime - phi0)) * Math.Cos(2.0 * (phiPrime + phi0))) - (((35.0 / 24.0) * n * n * n) * Math.Sin(3.0 * (phiPrime - phi0)) * Math.Cos(3.0 * (phiPrime + phi0)))); phiPrime += (N - N0 - M) / (a * OSGB_F0); } while ((N - N0 - M) >= 0.001); double v = a * OSGB_F0 * Math.Pow(1.0 - eSquared * Util.sinSquared(phiPrime), -0.5); double rho = a * OSGB_F0 * (1.0 - eSquared) * Math.Pow(1.0 - eSquared * Util.sinSquared(phiPrime), -1.5); double etaSquared = (v / rho) - 1.0; double VII = Math.Tan(phiPrime) / (2 * rho * v); double VIII = (Math.Tan(phiPrime) / (24.0 * rho * Math.Pow(v, 3.0))) * (5.0 + (3.0 * Util.tanSquared(phiPrime)) + etaSquared - (9.0 * Util.tanSquared(phiPrime) * etaSquared)); double IX = (Math.Tan(phiPrime) / (720.0 * rho * Math.Pow(v, 5.0))) * (61.0 + (90.0 * Util.tanSquared(phiPrime)) + (45.0 * Util.tanSquared(phiPrime) * Util.tanSquared(phiPrime))); double X = Util.sec(phiPrime) / v; double XI = (Util.sec(phiPrime) / (6.0 * v * v * v)) * ((v / rho) + (2 * Util.tanSquared(phiPrime))); double XII = (Util.sec(phiPrime) / (120.0 * Math.Pow(v, 5.0))) * (5.0 + (28.0 * Util.tanSquared(phiPrime)) + (24.0 * Util .tanSquared(phiPrime) * Util.tanSquared(phiPrime))); double XIIA = (Util.sec(phiPrime) / (5040.0 * Math.Pow(v, 7.0))) * (61.0 + (662.0 * Util.tanSquared(phiPrime)) + (1320.0 * Util.tanSquared(phiPrime) * Util .tanSquared(phiPrime)) + (720.0 * Util.tanSquared(phiPrime) * Util.tanSquared(phiPrime) * Util.tanSquared(phiPrime))); phi = phiPrime - (VII * Math.Pow(E - E0, 2.0)) + (VIII * Math.Pow(E - E0, 4.0)) - (IX * Math.Pow(E - E0, 6.0)); lambda = lambda0 + (X * (E - E0)) - (XI * Math.Pow(E - E0, 3.0)) + (XII * Math.Pow(E - E0, 5.0)) - (XIIA * Math.Pow(E - E0, 7.0)); return new LatLng(Util.ToDegrees(phi), Util.ToDegrees(lambda)); } /** * Get the easting. * * @return the easting in metres * @since 1.0 */ public double getEasting() { return easting; } /** * Get the northing. * * @return the northing in metres * @since 1.0 */ public double getNorthing() { return northing; } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using HttpServer.Exceptions; using HttpServer.Sessions; using Xunit; namespace HttpServer.Controllers { /// <summary> /// Used to simply testing of controls. /// </summary> public class ControllerTester { /// <summary> /// Fake host name, default is "http://localhost" /// </summary> public string HostName = "http://localhost"; private static readonly IHttpClientContext TestContext = new MyContext(); /// <summary> /// Session used if null have been specified as argument to one of the class methods. /// </summary> public IHttpSession DefaultSession = new MemorySession("abc"); /// <summary> /// Send a GET request to a controller. /// </summary> /// <param name="controller">Controller receiving the post request.</param> /// <param name="uri">Uri visited.</param> /// <param name="response">Response from the controller.</param> /// <param name="session">Session used during the test. null = <see cref="DefaultSession"/> is used.</param> /// <returns>body posted by the response object</returns> /// <example> /// <code> /// void MyTest() /// { /// ControllerTester tester = new ControllerTester(); /// /// MyController controller = new MyController(); /// IHttpResponse response; /// string text = Get(controller, "/my/hello/1?hello=world", out response, null); /// Assert.Equal("world|1", text); /// } /// </code> /// </example> public string Get(RequestController controller, string uri, out IHttpResponse response, IHttpSession session) { return Invoke(controller, Method.Get, uri, out response, session); } /// <summary> /// Send a POST request to a controller. /// </summary> /// <param name="controller">Controller receiving the post request.</param> /// <param name="uri">Uri visited.</param> /// <param name="form">Form being processed by controller.</param> /// <param name="response">Response from the controller.</param> /// <param name="session">Session used during the test. null = <see cref="DefaultSession"/> is used.</param> /// <returns>body posted by the response object</returns> /// <example> /// <code> /// void MyTest() /// { /// // Create a controller. /// MyController controller = new MyController(); /// /// // build up a form that is used by the controller. /// HttpForm form = new HttpForm(); /// form.Add("user[firstName]", "Jonas"); /// /// // Invoke the request /// ControllerTester tester = new ControllerTester(); /// IHttpResponse response; /// string text = tester.Get(controller, "/user/create/", form, out response, null); /// /// // validate response back from controller. /// Assert.Equal("User 'Jonas' has been created.", text); /// } /// </code> /// </example> public string Post(RequestController controller, string uri, HttpForm form, out IHttpResponse response, IHttpSession session) { return Invoke(controller, Method.Post, uri, form, out response, session); } private string Invoke(RequestController controller, string httpMetod, string uri, out IHttpResponse response, IHttpSession session) { return Invoke(controller, httpMetod, uri, null, out response, session); } // ReSharper disable SuggestBaseTypeForParameter private string Invoke(RequestController controller, string httpMetod, string uri, HttpForm form, out IHttpResponse response, IHttpSession session) // ReSharper restore SuggestBaseTypeForParameter { HttpRequest request = new HttpRequest { HttpVersion = "HTTP/1.1", UriPath = uri, Method = httpMetod, Uri = new Uri(HostName + uri) }; request.AssignForm(form); response = request.CreateResponse(TestContext); if(!controller.Process(request, response, session)) throw new NotFoundException("404 could not find processor for: " + uri); response.Body.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(response.Body); return reader.ReadToEnd(); } [Fact] private void TestGet() { MyController controller = new MyController(); IHttpResponse response; IHttpSession session = DefaultSession; string text = Get(controller, "/my/hello/1?hello=world", out response, session); Assert.Equal("world|1", text); } [Fact] private void TestPost() { MyController controller = new MyController(); IHttpResponse response; IHttpSession session = DefaultSession; HttpForm form = new HttpForm(); form.Add("user[firstName]", "jonas"); string text = Post(controller, "/my/hello/id", form, out response, session); Assert.Equal("jonas", text); } private class MyController : RequestController { //controller method. // ReSharper disable UnusedMemberInPrivateClass public string Hello() // ReSharper restore UnusedMemberInPrivateClass { Assert.False(string.IsNullOrEmpty(Id)); if (Request.Method == Method.Post) return Request.Form["user"]["firstName"].Value; return Request.QueryString["hello"].Value + "|" + Id; } public override object Clone() { return new MyController(); } } private class MyContext : IHttpClientContext { private const bool _secured = false; /// <summary> /// Using SSL or other encryption method. /// </summary> public bool Secured { get { return _secured; } } /// <summary> /// Using SSL or other encryption method. /// </summary> public bool IsSecured { get { return _secured; } } /// <summary> /// Disconnect from client /// </summary> /// <param name="error">error to report in the <see cref="Disconnected"/> event.</param> public void Disconnect(SocketError error) { } /// <summary> /// Send a response. /// </summary> /// <param name="httpVersion">Either HttpHelper.HTTP10 or HttpHelper.HTTP11</param> /// <param name="statusCode">http status code</param> /// <param name="reason">reason for the status code.</param> /// <param name="body">html body contents, can be null or empty.</param> /// <param name="contentType">A content type to return the body as, ie 'text/html' or 'text/plain', defaults to 'text/html' if null or empty</param> /// <exception cref="ArgumentException">If httpVersion is invalid.</exception> public void Respond(string httpVersion, HttpStatusCode statusCode, string reason, string body, string contentType) { } /// <summary> /// Send a response. /// </summary> /// <param name="httpVersion">Either HttpHelper.HTTP10 or HttpHelper.HTTP11</param> /// <param name="statusCode">http status code</param> /// <param name="reason">reason for the status code.</param> public void Respond(string httpVersion, HttpStatusCode statusCode, string reason) { } /// <summary> /// Send a response. /// </summary> /// <exception cref="ArgumentNullException"></exception> public void Respond(string body) { } /// <summary> /// send a whole buffer /// </summary> /// <param name="buffer">buffer to send</param> /// <exception cref="ArgumentNullException"></exception> public void Send(byte[] buffer) { } /// <summary> /// Send data using the stream /// </summary> /// <param name="buffer">Contains data to send</param> /// <param name="offset">Start position in buffer</param> /// <param name="size">number of bytes to send</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentOutOfRangeException"></exception> public void Send(byte[] buffer, int offset, int size) { } public void ShutupWarnings() { Disconnected(this, null); RequestReceived(this, null); } public event EventHandler<DisconnectedEventArgs> Disconnected; public event EventHandler<RequestEventArgs> RequestReceived; } } }
// 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.UInt16.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 { public partial struct UInt16 : IComparable, IFormattable, IConvertible, IComparable<ushort>, IEquatable<ushort> { #region Methods and constructors public int CompareTo(ushort value) { return default(int); } public int CompareTo(Object value) { return default(int); } public bool Equals(ushort obj) { return default(bool); } public override bool Equals(Object obj) { return default(bool); } public override int GetHashCode() { return default(int); } public TypeCode GetTypeCode() { return default(TypeCode); } public static ushort Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider) { Contract.Ensures(System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData == 8); return default(ushort); } public static ushort Parse(string s, IFormatProvider provider) { Contract.Ensures(System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData == 8); return default(ushort); } public static ushort Parse(string s, System.Globalization.NumberStyles style) { Contract.Ensures(System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData == 8); return default(ushort); } public static ushort Parse(string s) { Contract.Ensures(System.Runtime.CompilerServices.RuntimeHelpers.OffsetToStringData == 8); return default(ushort); } bool System.IConvertible.ToBoolean(IFormatProvider provider) { return default(bool); } byte System.IConvertible.ToByte(IFormatProvider provider) { return default(byte); } char System.IConvertible.ToChar(IFormatProvider provider) { return default(char); } DateTime System.IConvertible.ToDateTime(IFormatProvider provider) { return default(DateTime); } Decimal System.IConvertible.ToDecimal(IFormatProvider provider) { return default(Decimal); } double System.IConvertible.ToDouble(IFormatProvider provider) { return default(double); } short System.IConvertible.ToInt16(IFormatProvider provider) { return default(short); } int System.IConvertible.ToInt32(IFormatProvider provider) { return default(int); } long System.IConvertible.ToInt64(IFormatProvider provider) { return default(long); } sbyte System.IConvertible.ToSByte(IFormatProvider provider) { return default(sbyte); } float System.IConvertible.ToSingle(IFormatProvider provider) { return default(float); } Object System.IConvertible.ToType(Type type, IFormatProvider provider) { return default(Object); } ushort System.IConvertible.ToUInt16(IFormatProvider provider) { return default(ushort); } uint System.IConvertible.ToUInt32(IFormatProvider provider) { return default(uint); } ulong System.IConvertible.ToUInt64(IFormatProvider provider) { return default(ulong); } public string ToString(IFormatProvider provider) { return default(string); } public override string ToString() { return default(string); } public string ToString(string format, IFormatProvider provider) { return default(string); } public string ToString(string format) { return default(string); } public static bool TryParse(string s, out ushort result) { result = default(ushort); return default(bool); } public static bool TryParse(string s, System.Globalization.NumberStyles style, IFormatProvider provider, out ushort result) { result = default(ushort); return default(bool); } #endregion #region Fields public static ushort MaxValue; public static ushort MinValue; #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 Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { // The Windows implementation of PipeStream sets the stream's handle during // creation, and as such should always have a handle, but the Unix implementation // sometimes sets the handle not during creation but later during connection. // As such, validation during member access needs to verify a valid handle on // Windows, but can't assume a valid handle on Unix. internal const bool CheckOperationsRequiresSetHandle = false; /// <summary>Characters that can't be used in a pipe's name.</summary> private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars(); /// <summary>Prefix to prepend to all pipe names.</summary> private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); internal static string GetPipePath(string serverName, string pipeName) { if (serverName != "." && serverName != Interop.Sys.GetHostName()) { // Cross-machine pipes are not supported. throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes); } if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { // Match Windows constraint throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0) { // Since pipes are stored as files in the file system, we don't support // pipe names that are actually paths or that otherwise have invalid // filename characters in them. throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars); } // Return the pipe path. The pipe is created directly under %TMPDIR%. We don't bother // putting it into subdirectories, as the pipe will only exist on disk for the // duration between when the server starts listening and the client connects, after // which the pipe will be deleted. return s_pipePrefix + pipeName; } /// <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) { if (safePipeHandle.NamedPipeSocket == null) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO && (status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK) { throw new IOException(SR.IO_InvalidPipeHandle); } } } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> [SecurityCritical] private void InitializeAsyncHandle(SafePipeHandle handle) { // nop } private void UninitializeAsyncHandle() { // nop } private unsafe int ReadCore(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // For named pipes, receive on the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Read syscall as is done // for reading an anonymous pipe. However, for a non-blocking socket, Read could // end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case // is already handled by Socket.Receive, so we use it here. try { return socket.Receive(buffer, offset, count, SocketFlags.None); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, read from the file descriptor. fixed (byte* bufPtr = buffer) { int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr + offset, count)); Debug.Assert(result <= count); return result; } } private unsafe void WriteCore(byte[] buffer, int offset, int count) { DebugAssertReadWriteArgs(buffer, offset, count, _handle); // For named pipes, send to the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Write syscall as is done // for writing to anonymous pipe. However, for a non-blocking socket, Write could // end up returning EWOULDBLOCK rather than blocking waiting for space available. // Such a case is already handled by Socket.Send, so we use it here. try { while (count > 0) { int bytesWritten = socket.Send(buffer, offset, count, SocketFlags.None); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, write the file descriptor. fixed (byte* bufPtr = buffer) { while (count > 0) { int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr + offset, count)); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); Socket socket = InternalHandle.NamedPipeSocket; // If a cancelable token is used, we have a choice: we can either ignore it and use a true async operation // with Socket.ReceiveAsync, or we can use a polling loop on a worker thread to block for short intervals // and check for cancellation in between. We do the latter. if (cancellationToken.CanBeCanceled) { await Task.CompletedTask.ForceAsync(); // queue the remainder of the work to avoid blocking the caller int timeout = 10000; const int MaxTimeoutMicroseconds = 500000; while (true) { cancellationToken.ThrowIfCancellationRequested(); if (socket.Poll(timeout, SelectMode.SelectRead)) { return ReadCore(buffer, offset, count); } timeout = Math.Min(timeout * 2, MaxTimeoutMicroseconds); } } // The token wasn't cancelable, so we can simply use an async receive on the socket. try { return await socket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); try { while (count > 0) { // cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if // cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and // most writes will complete immediately as they simply store data into the socket's buffer. The only time we end // up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation. cancellationToken.ThrowIfCancellationRequested(); int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private IOException GetIOExceptionForSocketException(SocketException e) { if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE { State = PipeState.Broken; } return new IOException(e.Message, e); } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } // For named pipes on sockets, we could potentially partially implement this // via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However, // that would require polling, and it wouldn't actually mean that the other // end has read all of the data, just that the data has left this end's buffer. throw new PlatformNotSupportedException(); } // 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 { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } } // 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 { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } return GetPipeBufferSize(); } } // 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 { [SecurityCritical] [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); } return GetPipeBufferSize(); } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode); } // nop, since it's already the only valid value } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// We want to ensure that only one asynchronous operation is actually in flight /// at a time. The base Stream class ensures this by serializing execution via a /// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due /// to having specialized support for cancellation, we do the same serialization here. /// </summary> private SemaphoreSlim _asyncActiveSemaphore; private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } private static void CreateDirectory(string directoryPath) { int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask); // If successful created, we're done. if (result >= 0) return; // If the directory already exists, consider it a success. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EEXIST) return; // Otherwise, fail. throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true); } /// <summary>Creates an anonymous pipe.</summary> /// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param> /// <param name="reader">The resulting reader end of the pipe.</param> /// <param name="writer">The resulting writer end of the pipe.</param> internal static unsafe void CreateAnonymousPipe( HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer) { // Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations reader = new SafePipeHandle(); writer = new SafePipeHandle(); // Create the OS pipe int* fds = stackalloc int[2]; CreateAnonymousPipe(inheritability, fds); // Store the file descriptors into our safe handles reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]); writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]); } internal int CheckPipeCall(int result) { if (result == -1) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) State = PipeState.Broken; throw Interop.GetExceptionForIoErrno(errorInfo); } return result; } private int GetPipeBufferSize() { if (!Interop.Sys.Fcntl.CanGetSetPipeSz) { throw new PlatformNotSupportedException(); } // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction). // If we don't, just return the buffer size that was passed to the constructor. return _handle != null ? CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) : _outBufferSize; } internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr) { var flags = (inheritability & HandleInheritability.Inheritable) == 0 ? Interop.Sys.PipeFlags.O_CLOEXEC : 0; Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags)); } internal static void ConfigureSocket( Socket s, SafePipeHandle pipeHandle, PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { if (inBufferSize > 0) { s.ReceiveBufferSize = inBufferSize; } if (outBufferSize > 0) { s.SendBufferSize = outBufferSize; } if (inheritability != HandleInheritability.Inheritable) { Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt } switch (direction) { case PipeDirection.In: s.Shutdown(SocketShutdown.Send); break; case PipeDirection.Out: s.Shutdown(SocketShutdown.Receive); break; } } } }
/* * MiniXml.cs - Implementation of the "System.Security.MiniXml" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security { #if CONFIG_PERMISSIONS || CONFIG_POLICY_OBJECTS || CONFIG_REMOTING using System; using System.IO; // This class is used by "SecurityElement" to implement a very // simple XML parser, suitable for processing code access security tags. // It isn't for general-purpose XML parsing (use System.Xml instead). // We cannot use System.Xml directly due to library circularities. internal sealed class MiniXml { // Token types. private enum Token { EOF, StartTag, EndTag, SingletonTag, Text }; // enum Token // Internal state. private String input; private int posn; private Token token; private String value; private String args; // Constructors. public MiniXml(String input) { this.input = (input == null ? String.Empty : input); this.posn = 0; } public MiniXml(TextReader input) { this.input = input.ReadToEnd(); this.posn = 0; } public MiniXml(Stream input) { StreamReader reader = new StreamReader(input); this.input = reader.ReadToEnd(); this.posn = 0; ((IDisposable)reader).Dispose(); } // Read the next token from the input. private void NextToken() { char ch; int start; int level; args = String.Empty; for(;;) { // Skip white space prior to the next token. while(posn < input.Length && Char.IsWhiteSpace(input[posn])) { ++posn; } if(posn >= input.Length) { token = Token.EOF; return; } // What kind of token is this? ch = input[posn]; if(ch == '<') { // Some form of tag. if((posn + 3) < input.Length && input[posn + 1] == '!' && input[posn + 2] == '-' && input[posn + 3] == '-') { // Comment tag. start = input.IndexOf("-->", posn + 4); if(start != -1) { posn = start + 3; } else { posn = input.Length; } } else if((posn + 1) < input.Length && input[posn + 1] == '/') { // End tag. posn += 2; start = posn; while(posn < input.Length && ((ch = input[posn]) != '>' && !Char.IsWhiteSpace(ch))) { ++posn; } value = input.Substring(start, posn - start); while(posn < input.Length && input[posn] != '>') { ++posn; } if(posn < input.Length) { ++posn; } token = Token.EndTag; return; } else if((posn + 8) < input.Length && input[posn + 1] == '!' && input[posn + 2] == '[' && input[posn + 3] == 'C' && input[posn + 4] == 'D' && input[posn + 5] == 'A' && input[posn + 6] == 'T' && input[posn + 7] == 'A' && input[posn + 8] == '[') { // CDATA text block. start = input.IndexOf("]]>", posn + 9); if(start != -1) { value = input.Substring (posn + 9, start - (posn + 9)); posn = start + 3; } else { value = input.Substring(posn + 9); posn = input.Length; } token = Token.Text; return; } else if((posn + 1) < input.Length && (input[posn + 1] == '!' || input[posn + 1] == '?')) { // DTD or XML declaration. level = 1; ++posn; while(posn < input.Length) { ch = input[posn++]; if(ch == '>') { if(--level == 0) { break; } } else if(ch == '<') { ++level; } } } else { // Start or singleton tag. ++posn; start = posn; while(posn < input.Length && ((ch = input[posn]) != '>' && ch != '/' && !Char.IsWhiteSpace(ch))) { ++posn; } value = input.Substring(start, posn - start); start = posn; while(posn < input.Length && input[posn] != '>') { ++posn; } if(input[posn - 1] == '/') { args = input.Substring(start, posn - start - 1); token = Token.SingletonTag; } else { args = input.Substring(start, posn - start); token = Token.StartTag; } if(posn < input.Length) { ++posn; } return; } } else if(ch == '&') { // Ampersand-escaped character. start = posn; ++posn; while(posn < input.Length && input[posn] != ';') { ++posn; } if(posn < input.Length) { ++posn; } value = input.Substring(start, posn - start); if(value == "&lt;") { value = "<"; } else if(value == "&gt;") { value = ">"; } else if(value == "&amp;") { value = "&"; } else if(value == "&quot;") { value = "\""; } else if(value == "&apos;") { value = "'"; } else { value = " "; } token = Token.Text; return; } else { // Start of an ordinary text run. start = posn; ++posn; while(posn < input.Length && ((ch = input[posn]) != '<' && ch != '&')) { ++posn; } while(posn > start && Char.IsWhiteSpace(input[posn - 1])) { --posn; } value = input.Substring(start, posn - start); token = Token.Text; return; } } } // Parse an element tag. private SecurityElement ParseElement() { // Create the new element. SecurityElement element; element = new SecurityElement(value); // Parse and add the attribute arguments. int temp = 0; int start; String name; String avalue; for(;;) { while(temp < args.Length && Char.IsWhiteSpace(args[temp])) { ++temp; } if(temp >= args.Length) { break; } start = temp; while(temp < args.Length && args[temp] != '=') { ++temp; } name = args.Substring(start, temp - start); if(temp < args.Length) { ++temp; } if(temp < args.Length && args[temp] == '"') { ++temp; start = temp; while(temp < args.Length && args[temp] != '"') { ++temp; } avalue = args.Substring(start, temp - start); if(temp < args.Length) { ++temp; } } else if(temp < args.Length && args[temp] == '\'') { ++temp; start = temp; while(temp < args.Length && args[temp] != '\'') { ++temp; } avalue = args.Substring(start, temp - start); if(temp < args.Length) { ++temp; } } else { avalue = String.Empty; } element.AddAttribute(name, avalue); } // Parse the children of this element. if(token == Token.SingletonTag) { NextToken(); } else { NextToken(); while(token != Token.EOF && token != Token.EndTag) { if(token == Token.StartTag || token == Token.SingletonTag) { SecurityElement child; child = ParseElement(); element.AddChild(child); } else if(token == Token.Text) { String prevText = element.Text; if(prevText != null) { element.Text = prevText + value; } else { element.Text = value; } } NextToken(); } } // Return the final element to the caller. return element; } // Parse the input data. public SecurityElement Parse() { // Skip until we find a start or singleton token. do { NextToken(); } while(token != Token.EOF && token != Token.StartTag && token != Token.SingletonTag); if(token == Token.EOF) { return null; } // Parse the element. return ParseElement(); } // Load the contents of an XML file. public static SecurityElement Load(String filename) { try { StreamReader reader = new StreamReader(filename); SecurityElement e = (new MiniXml(reader)).Parse(); reader.Close(); return e; } catch(Exception) { return null; } } }; // class MiniXml #endif // CONFIG_PERMISSIONS || CONFIG_POLICY_OBJECTS || CONFIG_REMOTING }; // namespace System.Security
#region Copyright notice and license // Copyright 2015, Google Inc. // 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message."); readonly Func<TWrite, byte[]> serializer; readonly Func<byte[], TRead> deserializer; protected readonly object myLock = new object(); protected INativeCall call; protected bool disposed; protected bool started; protected bool cancelRequested; protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null. protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null. protected TaskCompletionSource<object> sendStatusFromServerTcs; protected bool readingDone; // True if last read (i.e. read with null payload) was already received. protected bool halfcloseRequested; // True if send close have been initiated. protected bool finished; // True if close has been received from the peer. protected bool initialMetadataSent; protected long streamingWritesCounter; // Number of streaming send operations started so far. public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer) { this.serializer = GrpcPreconditions.CheckNotNull(serializer); this.deserializer = GrpcPreconditions.CheckNotNull(deserializer); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { GrpcPreconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> protected void CancelWithStatus(Status status) { lock (myLock) { cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(INativeCall call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// </summary> protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendAllowedOrEarlyResult(); if (earlyResult != null) { return earlyResult; } call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent); initialMetadataSent = true; streamingWritesCounter++; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// </summary> protected Task<TRead> ReadMessageInternalAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); if (readingDone) { // the last read that returns null or throws an exception is idempotent // and maintains its state. GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads."); return streamingReadTcs.Task; } GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time"); GrpcPreconditions.CheckState(!disposed); call.StartReceiveMessage(HandleReadFinished); streamingReadTcs = new TaskCompletionSource<TRead>(); return streamingReadTcs.Task; } } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.ReleaseResourcesIfPossible")) { if (!disposed && call != null) { bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } } protected abstract bool IsClient { get; } private void ReleaseResources() { if (call != null) { call.Dispose(); } disposed = true; OnAfterReleaseResources(); } protected virtual void OnAfterReleaseResources() { } /// <summary> /// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send /// logic by directly returning the write operation result task. Normally, null is returned. /// </summary> protected abstract Task CheckSendAllowedOrEarlyResult(); protected byte[] UnsafeSerialize(TWrite msg) { using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.UnsafeSerialize")) { return serializer(msg); } } protected Exception TryDeserialize(byte[] payload, out TRead msg) { using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.TryDeserialize")) { try { msg = deserializer(payload); return null; } catch (Exception e) { msg = default(TRead); return e; } } } /// <summary> /// Handles send completion. /// </summary> protected void HandleSendFinished(bool success) { TaskCompletionSource<object> origTcs = null; lock (myLock) { origTcs = streamingWriteTcs; streamingWriteTcs = null; ReleaseResourcesIfPossible(); } if (!success) { origTcs.SetException(new InvalidOperationException("Send failed")); } else { origTcs.SetResult(null); } } /// <summary> /// Handles halfclose (send close from client) completion. /// </summary> protected void HandleSendCloseFromClientFinished(bool success) { TaskCompletionSource<object> origTcs = null; lock (myLock) { origTcs = streamingWriteTcs; streamingWriteTcs = null; ReleaseResourcesIfPossible(); } if (!success) { // TODO(jtattermusch): this method is same as HandleSendFinished (only the error message differs). origTcs.SetException(new InvalidOperationException("Sending close from client has failed.")); } else { origTcs.SetResult(null); } } /// <summary> /// Handles send status from server completion. /// </summary> protected void HandleSendStatusFromServerFinished(bool success) { lock (myLock) { ReleaseResourcesIfPossible(); } if (!success) { sendStatusFromServerTcs.SetException(new InvalidOperationException("Error sending status from server.")); } else { sendStatusFromServerTcs.SetResult(null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, byte[] receivedMessage) { // if success == false, received message will be null. It that case we will // treat this completion as the last read an rely on C core to handle the failed // read (e.g. deliver approriate statusCode on the clientside). TRead msg = default(TRead); var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null; TaskCompletionSource<TRead> origTcs = null; lock (myLock) { origTcs = streamingReadTcs; if (receivedMessage == null) { // This was the last read. readingDone = true; } if (deserializeException != null && IsClient) { readingDone = true; // TODO(jtattermusch): it might be too late to set the status CancelWithStatus(DeserializeResponseFailureStatus); } if (!readingDone) { streamingReadTcs = null; } ReleaseResourcesIfPossible(); } if (deserializeException != null && !IsClient) { origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException)); return; } origTcs.SetResult(msg); } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System.Collections.Generic; using UMA.CharacterSystem; namespace UMA { public class DynamicUMADna : DynamicUMADnaBase { #region Constructor public DynamicUMADna() { } public DynamicUMADna(int typeHash) { base.dnaTypeHash = typeHash; } #endregion #region Properties public override DynamicUMADnaAsset dnaAsset { get { return _dnaAsset; } set { if (value != null) { ValidateValues(value.Names); dnaAssetName = value.name; _dnaAsset = value; } else { dnaAssetName = ""; _dnaAsset = null; } } } public override int Count { get { return Values.Length; } } public override float[] Values { get { if (_values.Length > 0) return _values; else { return new float[0]; } } set { _values = value; } } public override string[] Names { get { if (_names.Length != 0) { if(dnaAsset != null) { //this just checks if the names have changed while the game is actually running if(_names.Length != dnaAsset.Names.Length) { ValidateValues(dnaAsset.Names); } } return _names; } else { return new string[0]; } } } /// <summary> /// This is a placeholder method to conform to the requirements for the DNA template code, results are not valid /// </summary> public static string[] GetNames() { if (Debug.isDebugBuild) Debug.LogWarning("Calling the static GetNames() method of Dynamic DNA, result will be empty"); return new string[0]; } #endregion #region Methods /// <summary> /// Convert a recipes UMADnaHumanoid values to DynamicUMADna values. This will need to be done if the user switches a races converter from a HumanoidDNAConverterBehaviour to a DynamicDNAConverterBehaviour /// </summary> /// <param name="umaDna"></param> public override int ImportUMADnaValues(UMADnaBase umaDna) { int dnaImported = 0; string[] dnaNames = umaDna.Names; for (int i = 0; i < umaDna.Count; i++) { var thisValueName = dnaNames[i]; for (int ii = 0; ii < Names.Length; ii++) { //if (Names[ii].Equals(thisValueName, StringComparison.OrdinalIgnoreCase)) //actually I think they should be exactly equal if (Names[ii] == thisValueName) { Values[ii] = umaDna.Values[i]; dnaImported++; } } } return dnaImported; } /// <summary> /// Regenerates the _names and _values array when a DynamicUMADnaAsset is added matching existing values to the assets names, adding any names that dont exist and removing names that no longer exist /// </summary> /// <param name="requiredNames"></param> void ValidateValues(string[] requiredNames) { List<float> newValues = new List<float>(requiredNames.Length); for (int i = 0; i < requiredNames.Length; i++) { bool valueFound = false; var currentNames = _names.Length > 0 ? _names : new string[0]; for (int ii = 0; ii < currentNames.Length; ii++) { if (currentNames[ii] == requiredNames[i]) { newValues.Insert(i, Values[ii]); valueFound = true; break; } } if (valueFound == false) { newValues.Insert(i, 0.5f); } } _names = requiredNames; _values = newValues.ToArray(); } public override float GetValue(string dnaName, bool failSilently = false) { int idx = -1; //changed to IndexOf because its slightly faster than For loop if (!string.IsNullOrEmpty(dnaName)) idx = System.Array.IndexOf(Names, dnaName); if (idx == -1 && failSilently == false) throw new System.ArgumentOutOfRangeException(); else if (idx == -1 && failSilently == true) return 0.5f; return GetValue(idx); } public override float GetValue(int idx) { if (idx < Count) { return Values[idx]; } throw new System.ArgumentOutOfRangeException(); } public override void SetValue(string dnaName, float value) { int idx = -1; //changed to IndexOf because its slightly faster than For loop if (!string.IsNullOrEmpty(dnaName)) idx = System.Array.IndexOf(Names, dnaName); if (idx == -1) throw new System.ArgumentOutOfRangeException(); SetValue(idx, value); } public override void SetValue(int idx, float value) { if (idx < Count) { _values[idx] = value; return; } throw new System.ArgumentOutOfRangeException(); } /// <summary> /// Method for finding a DynamicUMADnaAsset by name using DynamicAssetLoader. This can happen when a recipe tries to load load an asset based on an instance ID that may have changed or if the Asset is in an AssetBundle and was not available when the dna was loaded /// </summary> /// <param name="dnaAssetName"></param> public override void FindMissingDnaAsset(string dnaAssetName) { InitializeDynamicDNADictionary(); if (DynamicDNADictionary.TryGetValue(dnaAssetName, out _dnaAsset)) return; _dnaAsset = UMAContext.Instance.GetDNA(dnaAssetName); if (!_dnaAsset) { if (Debug.isDebugBuild) Debug.LogWarning("DynamicUMADna could not find DNAAsset " + dnaAssetName + "!"); } } public static DynamicUMADna LoadInstance(string data) { return UnityEngine.JsonUtility.FromJson<DynamicUMADna_Byte>(data).ToDna(); } public static string SaveInstance(DynamicUMADnaBase instance) { return UnityEngine.JsonUtility.ToJson(DynamicUMADna_Byte.FromDna(instance)); } #endregion } // Class to store dynamic settings as name value pairs. // We need this because the DynamicUMADnaAssets values may change and so we need to match any existing values to names even if the array size has changed [System.Serializable] public class DNASettings { public string name; public System.Byte value; public DNASettings() { } public DNASettings(string _name, System.Byte _value) { name = _name; value = _value; } } [System.Serializable] public class DynamicUMADna_Byte { public DynamicUMADnaAsset bDnaAsset; public string bDnaAssetName; public DNASettings[] bDnaSettings; public DynamicUMADna ToDna() { var res = new DynamicUMADna(); //Do names and values first res._names = new string[bDnaSettings.Length]; for (int i = 0; i < bDnaSettings.Length; i++) { res._names[i] = bDnaSettings[i].name; } res._values = new float[bDnaSettings.Length]; for (int ii = 0; ii < bDnaSettings.Length; ii++) { res._values[ii] = bDnaSettings[ii].value * (1f / 255f); } res.dnaAssetName = bDnaAssetName; //Then set the asset using dnaAsset.set so that everything is validated and any new dna gets added with default values //Usually we need to find the asset because the instance id in the recipe will not be the same in different sessions of Unity if ((bDnaAsset == null && bDnaAssetName != "") || (bDnaAssetName != "" && (bDnaAsset != null && bDnaAsset.name != bDnaAssetName))) { res.FindMissingDnaAsset(bDnaAssetName); } else if (bDnaAsset != null) { res.dnaAsset = bDnaAsset; } if (res.dnaAsset != null) { res.SetDnaTypeHash(res.dnaAsset.dnaTypeHash); } else { if (Debug.isDebugBuild) Debug.LogWarning("Deserialized DynamicUMADna with no matching asset!"); } return res; } public static DynamicUMADna_Byte FromDna(DynamicUMADnaBase dna ) { var res = new DynamicUMADna_Byte(); res.bDnaAsset = dna.dnaAsset; if(dna.dnaAsset != null) res.bDnaAssetName = dna.dnaAsset.name; res.bDnaSettings = new DNASettings[dna._values.Length]; for (int i = 0; i < dna._values.Length; i++) { res.bDnaSettings[i] = new DNASettings(dna._names[i], (System.Byte)(dna._values[i] * 255f + 0.5f)); } return res; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// UsageOperations operations. /// </summary> internal partial class UsageOperations : IServiceOperations<ComputeManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal UsageOperations(ComputeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// Gets, for the specified location, the current compute resource usage /// information as well as the limits for compute resources under the /// subscription. /// </summary> /// <param name='location'> /// The location for which resource usage is queried. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Usage>>> ListWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (location != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(location, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "location", "^[-\\w\\._]+$"); } } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/locations/{location}/usages").ToString(); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Usage>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets, for the specified location, the current compute resource usage /// information as well as the limits for compute resources under the /// subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Usage>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Usage>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Usage>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Primitives; using osu.Framework.Screens; using osu.Game.Configuration; using osu.Game.Screens; using osu.Game.Screens.Backgrounds; using osuTK; namespace osu.Game.Graphics.Containers { /// <summary> /// Handles user-defined scaling, allowing application at multiple levels defined by <see cref="ScalingMode"/>. /// </summary> public class ScalingContainer : Container { private Bindable<float> sizeX; private Bindable<float> sizeY; private Bindable<float> posX; private Bindable<float> posY; private Bindable<MarginPadding> safeAreaPadding; private readonly ScalingMode? targetMode; private Bindable<ScalingMode> scalingMode; private readonly Container content; protected override Container<Drawable> Content => content; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; private readonly Container sizableContainer; private BackgroundScreenStack backgroundStack; private RectangleF? customRect; private bool customRectIsRelativePosition; /// <summary> /// Set a custom position and scale which overrides any user specification. /// </summary> /// <param name="rect">A rectangle with positional and sizing information for this container to conform to. <c>null</c> will clear the custom rect and revert to user settings.</param> /// <param name="relativePosition">Whether the position portion of the provided rect is in relative coordinate space or not.</param> public void SetCustomRect(RectangleF? rect, bool relativePosition = false) { customRect = rect; customRectIsRelativePosition = relativePosition; if (IsLoaded) Scheduler.AddOnce(updateSize); } private const float corner_radius = 10; /// <summary> /// Create a new instance. /// </summary> /// <param name="targetMode">The mode which this container should be handling. Handles all modes if null.</param> public ScalingContainer(ScalingMode? targetMode = null) { this.targetMode = targetMode; RelativeSizeAxes = Axes.Both; InternalChild = sizableContainer = new AlwaysInputContainer { RelativeSizeAxes = Axes.Both, RelativePositionAxes = Axes.Both, CornerRadius = corner_radius, Child = content = new ScalingDrawSizePreservingFillContainer(targetMode != ScalingMode.Gameplay) }; } private class ScalingDrawSizePreservingFillContainer : DrawSizePreservingFillContainer { private readonly bool applyUIScale; private Bindable<float> uiScale; public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; public ScalingDrawSizePreservingFillContainer(bool applyUIScale) { this.applyUIScale = applyUIScale; } [BackgroundDependencyLoader] private void load(OsuConfigManager osuConfig) { if (applyUIScale) { uiScale = osuConfig.GetBindable<float>(OsuSetting.UIScale); uiScale.BindValueChanged(scaleChanged, true); } } private void scaleChanged(ValueChangedEvent<float> args) { this.ScaleTo(new Vector2(args.NewValue), 500, Easing.Out); this.ResizeTo(new Vector2(1 / args.NewValue), 500, Easing.Out); } } [BackgroundDependencyLoader] private void load(OsuConfigManager config, ISafeArea safeArea) { scalingMode = config.GetBindable<ScalingMode>(OsuSetting.Scaling); scalingMode.ValueChanged += _ => Scheduler.AddOnce(updateSize); sizeX = config.GetBindable<float>(OsuSetting.ScalingSizeX); sizeX.ValueChanged += _ => Scheduler.AddOnce(updateSize); sizeY = config.GetBindable<float>(OsuSetting.ScalingSizeY); sizeY.ValueChanged += _ => Scheduler.AddOnce(updateSize); posX = config.GetBindable<float>(OsuSetting.ScalingPositionX); posX.ValueChanged += _ => Scheduler.AddOnce(updateSize); posY = config.GetBindable<float>(OsuSetting.ScalingPositionY); posY.ValueChanged += _ => Scheduler.AddOnce(updateSize); safeAreaPadding = safeArea.SafeAreaPadding.GetBoundCopy(); safeAreaPadding.BindValueChanged(_ => Scheduler.AddOnce(updateSize)); } protected override void LoadComplete() { base.LoadComplete(); updateSize(); sizableContainer.FinishTransforms(); } private bool requiresBackgroundVisible => (scalingMode.Value == ScalingMode.Everything || scalingMode.Value == ScalingMode.ExcludeOverlays) && (sizeX.Value != 1 || sizeY.Value != 1); private void updateSize() { const float duration = 500; if (targetMode == ScalingMode.Everything) { // the top level scaling container manages the background to be displayed while scaling. if (requiresBackgroundVisible) { if (backgroundStack == null) { AddInternal(backgroundStack = new BackgroundScreenStack { Colour = OsuColour.Gray(0.1f), Alpha = 0, Depth = float.MaxValue }); backgroundStack.Push(new ScalingBackgroundScreen()); } backgroundStack.FadeIn(duration); } else backgroundStack?.FadeOut(duration); } RectangleF targetRect = new RectangleF(Vector2.Zero, Vector2.One); if (customRect != null) { sizableContainer.RelativePositionAxes = customRectIsRelativePosition ? Axes.Both : Axes.None; targetRect = customRect.Value; } else if (targetMode == null || scalingMode.Value == targetMode) { sizableContainer.RelativePositionAxes = Axes.Both; Vector2 scale = new Vector2(sizeX.Value, sizeY.Value); Vector2 pos = new Vector2(posX.Value, posY.Value) * (Vector2.One - scale); targetRect = new RectangleF(pos, scale); } bool requiresMasking = targetRect.Size != Vector2.One // For the top level scaling container, for now we apply masking if safe areas are in use. // In the future this can likely be removed as more of the actual UI supports overflowing into the safe areas. || (targetMode == ScalingMode.Everything && safeAreaPadding.Value.Total != Vector2.Zero); if (requiresMasking) sizableContainer.Masking = true; sizableContainer.MoveTo(targetRect.Location, duration, Easing.OutQuart); sizableContainer.ResizeTo(targetRect.Size, duration, Easing.OutQuart); // Of note, this will not work great in the case of nested ScalingContainers where multiple are applying corner radius. // Masking and corner radius should likely only be applied at one point in the full game stack to fix this. // An example of how this can occur is when the skin editor is visible and the game screen scaling is set to "Everything". sizableContainer.TransformTo(nameof(CornerRadius), requiresMasking ? corner_radius : 0, duration, requiresMasking ? Easing.OutQuart : Easing.None) .OnComplete(_ => { sizableContainer.Masking = requiresMasking; }); } private class ScalingBackgroundScreen : BackgroundScreenDefault { protected override bool AllowStoryboardBackground => false; public override void OnEntering(IScreen last) { this.FadeInFromZero(4000, Easing.OutQuint); } } private class AlwaysInputContainer : Container { public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true; public AlwaysInputContainer() { RelativeSizeAxes = Axes.Both; } } } }
using BTDB.FieldHandler; using BTDB.IL; using BTDB.ODBLayer; using BTDB.StreamLayer; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace BTDB.EventStoreLayer { class DictionaryTypeDescriptor : ITypeDescriptor, IPersistTypeDescriptor { readonly ITypeDescriptorCallbacks _typeSerializers; Type? _type; Type? _keyType; Type? _valueType; ITypeDescriptor? _keyDescriptor; ITypeDescriptor? _valueDescriptor; string? _name; readonly ITypeConvertorGenerator _convertorGenerator; public DictionaryTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, Type type) { _convertorGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; _type = type; var genericArguments = type.GetGenericArguments(); _keyType = genericArguments[0]; _valueType = genericArguments[1]; } public DictionaryTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, AbstractBufferedReader reader, Func<AbstractBufferedReader, ITypeDescriptor> nestedDescriptorReader) : this(typeSerializers, nestedDescriptorReader(reader), nestedDescriptorReader(reader)) { } DictionaryTypeDescriptor(ITypeDescriptorCallbacks typeSerializers, ITypeDescriptor keyDesc, ITypeDescriptor valueDesc) { _convertorGenerator = typeSerializers.ConvertorGenerator; _typeSerializers = typeSerializers; InitFromKeyValueDescriptors(keyDesc, valueDesc); } void InitFromKeyValueDescriptors(ITypeDescriptor keyDescriptor, ITypeDescriptor valueDescriptor) { if (_keyDescriptor == keyDescriptor && _valueDescriptor == valueDescriptor && _name != null) return; _keyDescriptor = keyDescriptor; _valueDescriptor = valueDescriptor; if ((_keyDescriptor.Name?.Length ?? 0) == 0 || (_valueDescriptor.Name?.Length ?? 0) == 0) return; Sealed = _keyDescriptor.Sealed && _valueDescriptor.Sealed; Name = $"Dictionary<{_keyDescriptor.Name}, {_valueDescriptor.Name}>"; } public bool Equals(ITypeDescriptor other) { return Equals(other, new HashSet<ITypeDescriptor>(ReferenceEqualityComparer<ITypeDescriptor>.Instance)); } public string Name { get { if (_name == null) InitFromKeyValueDescriptors(_keyDescriptor!, _valueDescriptor!); return _name!; } private set => _name = value; } public bool FinishBuildFromType(ITypeDescriptorFactory factory) { var keyDescriptor = factory.Create(_keyType!); if (keyDescriptor == null) return false; var valueDescriptor = factory.Create(_valueType!); if (valueDescriptor == null) return false; InitFromKeyValueDescriptors(keyDescriptor, valueDescriptor); return true; } public void BuildHumanReadableFullName(StringBuilder text, HashSet<ITypeDescriptor> stack, uint indent) { text.Append("Dictionary<"); _keyDescriptor!.BuildHumanReadableFullName(text, stack, indent); text.Append(", "); _valueDescriptor!.BuildHumanReadableFullName(text, stack, indent); text.Append(">"); } public bool Equals(ITypeDescriptor other, HashSet<ITypeDescriptor> stack) { var o = other as DictionaryTypeDescriptor; if (o == null) return false; return _keyDescriptor!.Equals(o._keyDescriptor!, stack) && _valueDescriptor!.Equals(o._valueDescriptor!, stack); } public Type GetPreferredType() { if (_type == null) { _keyType = _typeSerializers.LoadAsType(_keyDescriptor!); _valueType = _typeSerializers.LoadAsType(_valueDescriptor!); _type = typeof(IDictionary<,>).MakeGenericType(_keyType, _valueType); } return _type; } static Type GetInterface(Type type) => type.GetInterface("IOrderedDictionary`2") ?? type.GetInterface("IDictionary`2") ?? type; public Type GetPreferredType(Type targetType) { if (_type == targetType) return _type; var targetIDictionary = GetInterface(targetType); var targetTypeArguments = targetIDictionary.GetGenericArguments(); var keyType = _typeSerializers.LoadAsType(_keyDescriptor!, targetTypeArguments[0]); var valueType = _typeSerializers.LoadAsType(_valueDescriptor!, targetTypeArguments[1]); return targetType.GetGenericTypeDefinition().MakeGenericType(keyType, valueType); } public bool AnyOpNeedsCtx() { return !_keyDescriptor!.StoredInline || !_valueDescriptor!.StoredInline || _keyDescriptor.AnyOpNeedsCtx() || _valueDescriptor.AnyOpNeedsCtx(); } public void GenerateLoad(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx, Action<IILGen> pushDescriptor, Type targetType) { if (targetType == typeof(object)) targetType = GetPreferredType(); var localCount = ilGenerator.DeclareLocal(typeof(int)); var targetIDictionary = GetInterface(targetType); var targetTypeArguments = targetIDictionary.GetGenericArguments(); var keyType = _typeSerializers.LoadAsType(_keyDescriptor!, targetTypeArguments[0]); var valueType = _typeSerializers.LoadAsType(_valueDescriptor!, targetTypeArguments[1]); var dictionaryTypeGenericDefinition = targetType.InheritsOrImplements(typeof(IOrderedDictionary<,>)) ? typeof(OrderedDictionaryWithDescriptor<,>) : typeof(DictionaryWithDescriptor<,>); var dictionaryType = dictionaryTypeGenericDefinition.MakeGenericType(keyType, valueType); if (!targetType.IsAssignableFrom(dictionaryType)) throw new InvalidOperationException(); var localDict = ilGenerator.DeclareLocal(dictionaryType); var loadFinished = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Do(pushReader) .Callvirt(() => default(AbstractBufferedReader).ReadVUInt32()) .ConvI4() .Dup() .LdcI4(1) .Sub() .Stloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .Do(pushDescriptor) .Newobj(dictionaryType.GetConstructor(new[] { typeof(int), typeof(ITypeDescriptor) })!) .Stloc(localDict) .Mark(next) .Ldloc(localCount) .Brfalse(loadFinished) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount) .Ldloc(localDict); _keyDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(0).Callvirt(() => default(ITypeDescriptor).NestedType(0)), keyType, _convertorGenerator); _valueDescriptor.GenerateLoadEx(ilGenerator, pushReader, pushCtx, il => il.Do(pushDescriptor).LdcI4(1).Callvirt(() => default(ITypeDescriptor).NestedType(0)), valueType, _convertorGenerator); ilGenerator .Callvirt(dictionaryType.GetMethod(nameof(IDictionary.Add))!) .Br(next) .Mark(loadFinished) .Ldloc(localDict) .Castclass(targetType); } public ITypeNewDescriptorGenerator? BuildNewDescriptorGenerator() { if (_keyDescriptor!.Sealed && _valueDescriptor!.Sealed) return null; return new TypeNewDescriptorGenerator(this); } class TypeNewDescriptorGenerator : ITypeNewDescriptorGenerator { readonly DictionaryTypeDescriptor _owner; public TypeNewDescriptorGenerator(DictionaryTypeDescriptor owner) { _owner = owner; } public void GenerateTypeIterator(IILGen ilGenerator, Action<IILGen> pushObj, Action<IILGen> pushCtx, Type type) { var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); if (type == typeof(object)) type = _owner.GetPreferredType(); var targetIDictionary = GetInterface(type); var targetTypeArguments = targetIDictionary.GetGenericArguments(); var keyType = _owner._typeSerializers.LoadAsType(_owner._keyDescriptor!, targetTypeArguments[0]); var valueType = _owner._typeSerializers.LoadAsType(_owner._valueDescriptor!, targetTypeArguments[1]); if (_owner._type == null) _owner._type = type; var isDict = type.GetGenericTypeDefinition() == typeof(Dictionary<,>); var typeAsIDictionary = isDict ? type : typeof(IDictionary<,>).MakeGenericType(keyType, valueType); var getEnumeratorMethod = isDict ? typeAsIDictionary.GetMethods() .Single( m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0) : typeAsIDictionary.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator)); var typeAsIEnumerator = getEnumeratorMethod!.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var typeKeyValuePair = currentGetter!.ReturnType; var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var localPair = ilGenerator.DeclareLocal(typeKeyValuePair); ilGenerator .Do(pushObj) .Castclass(typeAsIDictionary) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Do(il => { if (isDict) { il .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!); } else { il .Ldloc(localEnumerator) .Callvirt(() => default(IEnumerator).MoveNext()); } }) .Brfalse(finish) .Do(il => { if (isDict) { il .Ldloca(localEnumerator) .Call(currentGetter); } else { il .Ldloc(localEnumerator) .Callvirt(currentGetter); } }) .Stloc(localPair); if (!_owner._keyDescriptor.Sealed) { ilGenerator .Do(pushCtx) .Ldloca(localPair) .Call(typeKeyValuePair.GetProperty("Key")!.GetGetMethod()!) .Callvirt(() => default(IDescriptorSerializerLiteContext).StoreNewDescriptors(null)); } if (!_owner._valueDescriptor.Sealed) { ilGenerator .Do(pushCtx) .Ldloca(localPair) .Call(typeKeyValuePair.GetProperty("Value")!.GetGetMethod()!) .Callvirt(() => default(IDescriptorSerializerLiteContext).StoreNewDescriptors(null)); } ilGenerator .Br(next) .Mark(finish) .Finally() .Do(il => { if (isDict) { il .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator); } else { il.Ldloc(localEnumerator); } }) .Callvirt(() => default(IDisposable).Dispose()) .EndTry(); } } public ITypeDescriptor? NestedType(int index) { return index switch { 0 => _keyDescriptor, 1 => _valueDescriptor, _ => null }; } public void MapNestedTypes(Func<ITypeDescriptor, ITypeDescriptor> map) { InitFromKeyValueDescriptors(map(_keyDescriptor), map(_valueDescriptor)); } public bool Sealed { get; private set; } public bool StoredInline => true; public bool LoadNeedsHelpWithConversion => false; public void ClearMappingToType() { _type = null; _keyType = null; _valueType = null; } public bool ContainsField(string name) { return false; } public void Persist(AbstractBufferedWriter writer, Action<AbstractBufferedWriter, ITypeDescriptor> nestedDescriptorWriter) { nestedDescriptorWriter(writer, _keyDescriptor); nestedDescriptorWriter(writer, _valueDescriptor); } public void GenerateSave(IILGen ilGenerator, Action<IILGen> pushWriter, Action<IILGen> pushCtx, Action<IILGen> pushValue, Type saveType) { var notnull = ilGenerator.DefineLabel(); var completeFinish = ilGenerator.DefineLabel(); var notDictionary = ilGenerator.DefineLabel(); var keyType = saveType.GetGenericArguments()[0]; var valueType = saveType.GetGenericArguments()[1]; var typeAsIDictionary = typeof(IDictionary<,>).MakeGenericType(keyType, valueType); var typeAsICollection = typeAsIDictionary.GetInterface("ICollection`1"); var localDict = ilGenerator.DeclareLocal(typeAsIDictionary); ilGenerator .Do(pushValue) .Castclass(typeAsIDictionary) .Stloc(localDict) .Ldloc(localDict) .Brtrue(notnull) .Do(pushWriter) .Callvirt(() => default(AbstractBufferedWriter).WriteByteZero()) .Br(completeFinish) .Mark(notnull) .Do(pushWriter) .Ldloc(localDict) .Callvirt(typeAsICollection!.GetProperty(nameof(ICollection.Count))!.GetGetMethod()!) .LdcI4(1) .Add() .Callvirt(() => default(AbstractBufferedWriter).WriteVUInt32(0)); { var typeAsDictionary = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); var getEnumeratorMethod = typeAsDictionary.GetMethods() .Single(m => m.Name == nameof(IEnumerable.GetEnumerator) && m.ReturnType.IsValueType && m.GetParameters().Length == 0); var typeAsIEnumerator = getEnumeratorMethod.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var typeKeyValuePair = currentGetter!.ReturnType; var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var localPair = ilGenerator.DeclareLocal(typeKeyValuePair); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Ldloc(localDict) .Isinst(typeAsDictionary) .Brfalse(notDictionary) .Ldloc(localDict) .Castclass(typeAsDictionary) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloca(localEnumerator) .Call(typeAsIEnumerator.GetMethod(nameof(IEnumerator.MoveNext))!) .Brfalse(finish) .Ldloca(localEnumerator) .Call(currentGetter) .Stloc(localPair); _keyDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Key")!.GetGetMethod()!), keyType); _valueDescriptor!.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Value")!.GetGetMethod()!), valueType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloca(localEnumerator) .Constrained(typeAsIEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Br(completeFinish); } { var getEnumeratorMethod = typeAsIDictionary.GetInterface("IEnumerable`1")!.GetMethod(nameof(IEnumerable.GetEnumerator)); var typeAsIEnumerator = getEnumeratorMethod!.ReturnType; var currentGetter = typeAsIEnumerator.GetProperty(nameof(IEnumerator.Current))!.GetGetMethod(); var typeKeyValuePair = currentGetter!.ReturnType; var localEnumerator = ilGenerator.DeclareLocal(typeAsIEnumerator); var localPair = ilGenerator.DeclareLocal(typeKeyValuePair); var finish = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Mark(notDictionary) .Ldloc(localDict) .Callvirt(getEnumeratorMethod) .Stloc(localEnumerator) .Try() .Mark(next) .Ldloc(localEnumerator) .Callvirt(() => default(IEnumerator).MoveNext()) .Brfalse(finish) .Ldloc(localEnumerator) .Callvirt(currentGetter) .Stloc(localPair); _keyDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Key").GetGetMethod()), keyType); _valueDescriptor.GenerateSaveEx(ilGenerator, pushWriter, pushCtx, il => il.Ldloca(localPair).Call(typeKeyValuePair.GetProperty("Value").GetGetMethod()), valueType); ilGenerator .Br(next) .Mark(finish) .Finally() .Ldloc(localEnumerator) .Callvirt(() => default(IDisposable).Dispose()) .EndTry() .Mark(completeFinish); } } public void GenerateSkip(IILGen ilGenerator, Action<IILGen> pushReader, Action<IILGen> pushCtx) { var localCount = ilGenerator.DeclareLocal(typeof(uint)); var skipFinished = ilGenerator.DefineLabel(); var next = ilGenerator.DefineLabel(); ilGenerator .Do(pushReader) .Callvirt(() => default(AbstractBufferedReader).ReadVUInt32()) .Stloc(localCount) .Ldloc(localCount) .Brfalse(skipFinished) .Mark(next) .Ldloc(localCount) .LdcI4(1) .Sub() .Stloc(localCount) .Ldloc(localCount) .Brfalse(skipFinished); _keyDescriptor.GenerateSkipEx(ilGenerator, pushReader, pushCtx); _valueDescriptor.GenerateSkipEx(ilGenerator, pushReader, pushCtx); ilGenerator .Br(next) .Mark(skipFinished); } public ITypeDescriptor CloneAndMapNestedTypes(ITypeDescriptorCallbacks typeSerializers, Func<ITypeDescriptor, ITypeDescriptor> map) { var keyDesc = map(_keyDescriptor); var valueDesc = map(_valueDescriptor); if (_typeSerializers == typeSerializers && keyDesc == _keyDescriptor && valueDesc == _valueDescriptor) return this; return new DictionaryTypeDescriptor(typeSerializers, keyDesc, valueDesc); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using BTDB.IL; using BTDB.StreamLayer; using System.Diagnostics; namespace BTDB.FieldHandler { public class EnumFieldHandler : IFieldHandler { readonly byte[] _configuration; readonly bool _signed; Type _enumType; public class EnumConfiguration { readonly bool _signed; readonly bool _flags; readonly string[] _names; readonly ulong[] _values; public EnumConfiguration(Type enumType) { _signed = IsSignedEnum(enumType); _flags = IsFlagsEnum(enumType); _names = enumType.GetEnumNames(); var members = enumType.GetMembers(BindingFlags.Static | BindingFlags.Public); Debug.Assert(members.Length == _names.Length); for (int i = 0; i < members.Length; i++) { var a = members[i].GetCustomAttributes<PersistedNameAttribute>().FirstOrDefault(); if (a != null) _names[i] = a.Name; } var undertype = enumType.GetEnumUnderlyingType(); var enumValues = enumType.GetEnumValues(); IEnumerable<ulong> enumValuesUlongs; if (undertype == typeof(int)) enumValuesUlongs = enumValues.Cast<int>().Select(i => (ulong)i); else if (undertype == typeof(uint)) enumValuesUlongs = enumValues.Cast<uint>().Select(i => (ulong)i); else if (undertype == typeof(sbyte)) enumValuesUlongs = enumValues.Cast<sbyte>().Select(i => (ulong)i); else if (undertype == typeof(byte)) enumValuesUlongs = enumValues.Cast<byte>().Select(i => (ulong)i); else if (undertype == typeof(short)) enumValuesUlongs = enumValues.Cast<short>().Select(i => (ulong)i); else if (undertype == typeof(ushort)) enumValuesUlongs = enumValues.Cast<ushort>().Select(i => (ulong)i); else if (undertype == typeof(long)) enumValuesUlongs = enumValues.Cast<long>().Select(i => (ulong)i); else enumValuesUlongs = enumValues.Cast<ulong>(); _values = enumValuesUlongs.ToArray(); } public EnumConfiguration(byte[] configuration) { var reader = new ByteArrayReader(configuration); var header = reader.ReadVUInt32(); _signed = (header & 1) != 0; _flags = (header & 2) != 0; var count = header >> 2; _names = new string[count]; _values = new ulong[count]; for (int i = 0; i < count; i++) Names[i] = reader.ReadString(); if (_signed) { for (int i = 0; i < count; i++) Values[i] = (ulong)reader.ReadVInt64(); } else { for (int i = 0; i < count; i++) Values[i] = reader.ReadVUInt64(); } } public bool Signed { get { return _signed; } } bool Flags { get { return _flags; } } string[] Names { get { return _names; } } ulong[] Values { get { return _values; } } public byte[] ToConfiguration() { var writer = new ByteBufferWriter(); writer.WriteVUInt32((_signed ? 1u : 0) + (Flags ? 2u : 0) + 4u * (uint)Names.Length); foreach (var name in Names) { writer.WriteString(name); } foreach (var value in Values) { if (_signed) writer.WriteVInt64((long)value); else writer.WriteVUInt64(value); } return writer.Data.ToByteArray(); } public Type ToType() { var builder = ILBuilder.Instance; var literals = new Dictionary<string, object>(); for (var i = 0; i < Names.Length; i++) { if (_signed) { literals.Add(Names[i], (long)Values[i]); } else { literals.Add(Names[i], Values[i]); } } return builder.NewEnum("EnumByFieldHandler", _signed ? typeof(long) : typeof(ulong), literals); } public static bool operator ==(EnumConfiguration left, EnumConfiguration right) { if (ReferenceEquals(left, right)) return true; if (ReferenceEquals(left, null)) return false; return left.Equals(right); } public static bool operator !=(EnumConfiguration left, EnumConfiguration right) { return !(left == right); } public bool Equals(EnumConfiguration other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return other._flags.Equals(_flags) && _names.SequenceEqual(other._names) && _values.SequenceEqual(other._values); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof(EnumConfiguration)) return false; return Equals((EnumConfiguration)obj); } public override int GetHashCode() { unchecked { int result = _flags.GetHashCode(); result = (result * 397) ^ _names.GetHashCode(); result = (result * 397) ^ _values.GetHashCode(); return result; } } public bool IsSubsetOf(EnumConfiguration targetCfg) { if (_flags != targetCfg._flags) return false; var targetDict = targetCfg.Names.Zip(targetCfg.Values, (k, v) => new KeyValuePair<string, ulong>(k, v)) .ToDictionary(p => p.Key, p => p.Value); for (int i = 0; i < _names.Length; i++) { ulong targetValue; if (!targetDict.TryGetValue(_names[i], out targetValue)) return false; if (_values[i] != targetValue) return false; } return true; } } public EnumFieldHandler(Type enumType) { if (!IsCompatibleWith(enumType)) throw new ArgumentException("enumType"); _enumType = enumType; var ec = new EnumConfiguration(enumType); _signed = ec.Signed; _configuration = ec.ToConfiguration(); } public EnumFieldHandler(byte[] configuration) { _configuration = configuration; var ec = new EnumConfiguration(configuration); _signed = ec.Signed; } static bool IsSignedEnum(Type enumType) { return SignedFieldHandler.IsCompatibleWith(enumType.GetEnumUnderlyingType()); } static bool IsFlagsEnum(Type type) { return type.GetCustomAttributes(typeof(FlagsAttribute), false).Length != 0; } public static string HandlerName { get { return "Enum"; } } public string Name { get { return HandlerName; } } public byte[] Configuration { get { return _configuration; } } public static bool IsCompatibleWith(Type type) { if (!type.IsEnum) return false; var enumUnderlyingType = type.GetEnumUnderlyingType(); return SignedFieldHandler.IsCompatibleWith(enumUnderlyingType) || UnsignedFieldHandler.IsCompatibleWith(enumUnderlyingType); } public Type HandledType() { return _enumType ?? (_enumType = new EnumConfiguration(_configuration).ToType()); } public bool NeedsCtx() { return false; } public void Load(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx) { pushReaderOrCtx(ilGenerator); Type typeRead; if (_signed) { ilGenerator.Call(() => default(AbstractBufferedReader).ReadVInt64()); typeRead = typeof(long); } else { ilGenerator.Call(() => default(AbstractBufferedReader).ReadVUInt64()); typeRead = typeof(ulong); } new DefaultTypeConvertorGenerator().GenerateConversion(typeRead, _enumType.GetEnumUnderlyingType())(ilGenerator); } public void Skip(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx) { pushReaderOrCtx(ilGenerator); if (_signed) { ilGenerator.Call(() => default(AbstractBufferedReader).SkipVInt64()); } else { ilGenerator.Call(() => default(AbstractBufferedReader).SkipVUInt64()); } } public void Save(IILGen ilGenerator, Action<IILGen> pushWriterOrCtx, Action<IILGen> pushValue) { pushWriterOrCtx(ilGenerator); pushValue(ilGenerator); if (_signed) { ilGenerator .ConvI8() .Call(() => default(AbstractBufferedWriter).WriteVInt64(0)); } else { ilGenerator .ConvU8() .Call(() => default(AbstractBufferedWriter).WriteVUInt64(0)); } } public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler typeHandler) { if (typeHandler == this) return this; var enumTypeHandler = typeHandler as EnumFieldHandler; if (enumTypeHandler != null) { if (_signed == enumTypeHandler._signed && new EnumConfiguration(Configuration).IsSubsetOf(new EnumConfiguration(enumTypeHandler.Configuration))) { return typeHandler; } } if (_enumType == null) { if (_configuration.SequenceEqual(new EnumConfiguration(type).ToConfiguration())) { _enumType = type; } } return this; } public IFieldHandler SpecializeSaveForType(Type type) { return SpecializeLoadForType(type, null); } public bool IsCompatibleWith(Type type, FieldHandlerOptions options) { return IsCompatibleWith(type); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERLevel { /// <summary> /// A09Level11111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="A09Level11111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A08Level1111"/> collection. /// </remarks> [Serializable] public partial class A09Level11111ReChild : BusinessBase<A09Level11111ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int cNarentID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A09Level11111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="A09Level11111ReChild"/> object.</returns> internal static A09Level11111ReChild NewA09Level11111ReChild() { return DataPortal.CreateChild<A09Level11111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="A09Level11111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A09Level11111ReChild"/> object.</returns> internal static A09Level11111ReChild GetA09Level11111ReChild(SafeDataReader dr) { A09Level11111ReChild obj = new A09Level11111ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A09Level11111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private A09Level11111ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A09Level11111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A09Level11111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_Child_Name")); cNarentID2 = dr.GetInt32("CNarentID2"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A09Level11111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddA09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="A09Level11111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateA09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="A09Level11111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A08Level1111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteA09Level11111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_ID", parent.Level_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// // Copyright 2012 Hakan Kjellerstrand // // 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 Google.OrTools.ConstraintSolver; public class DeBruijn { /** * * ToNum(solver, a, num, base) * * channelling between the array a and the number num. * */ private static Constraint ToNum(IntVar[] a, IntVar num, int bbase) { int len = a.Length; IntVar[] tmp = new IntVar[len]; for (int i = 0; i < len; i++) { tmp[i] = (a[i] * (int)Math.Pow(bbase, (len - i - 1))).Var(); } return tmp.Sum() == num; } /** * * Implements "arbitrary" de Bruijn sequences. * See http://www.hakank.org/or-tools/debruijn_binary.py * */ private static void Solve(int bbase, int n, int m) { Solver solver = new Solver("DeBruijn"); // Ensure that the number of each digit in bin_code is // the same. Nice feature, but it can slow things down... bool check_same_gcc = false; // true; // // Decision variables // IntVar[] x = solver.MakeIntVarArray(m, 0, (int)Math.Pow(bbase, n) - 1, "x"); IntVar[,] binary = solver.MakeIntVarMatrix(m, n, 0, bbase - 1, "binary"); // this is the de Bruijn sequence IntVar[] bin_code = solver.MakeIntVarArray(m, 0, bbase - 1, "bin_code"); // occurences of each number in bin_code IntVar[] gcc = solver.MakeIntVarArray(bbase, 0, m, "gcc"); // for the branching IntVar[] all = new IntVar[2 * m + bbase]; for (int i = 0; i < m; i++) { all[i] = x[i]; all[m + i] = bin_code[i]; } for (int i = 0; i < bbase; i++) { all[2 * m + i] = gcc[i]; } // // Constraints // solver.Add(x.AllDifferent()); // converts x <-> binary for (int i = 0; i < m; i++) { IntVar[] t = new IntVar[n]; for (int j = 0; j < n; j++) { t[j] = binary[i, j]; } solver.Add(ToNum(t, x[i], bbase)); } // the de Bruijn condition: // the first elements in binary[i] is the same as the last // elements in binary[i-1] for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { solver.Add(binary[i - 1, j] == binary[i, j - 1]); } } // ... and around the corner for (int j = 1; j < n; j++) { solver.Add(binary[m - 1, j] == binary[0, j - 1]); } // converts binary -> bin_code (de Bruijn sequence) for (int i = 0; i < m; i++) { solver.Add(bin_code[i] == binary[i, 0]); } // extra: ensure that all the numbers in the de Bruijn sequence // (bin_code) has the same occurrences (if check_same_gcc is True // and mathematically possible) solver.Add(bin_code.Distribute(gcc)); if (check_same_gcc && m % bbase == 0) { for (int i = 1; i < bbase; i++) { solver.Add(gcc[i] == gcc[i - 1]); } } // symmetry breaking: // the minimum value of x should be first // solver.Add(x[0] == x.Min()); // // Search // DecisionBuilder db = solver.MakePhase(all, Solver.CHOOSE_MIN_SIZE_LOWEST_MAX, Solver.ASSIGN_MIN_VALUE); solver.NewSearch(db); while (solver.NextSolution()) { Console.Write("x: "); for (int i = 0; i < m; i++) { Console.Write(x[i].Value() + " "); } Console.Write("\nde Bruijn sequence:"); for (int i = 0; i < m; i++) { Console.Write(bin_code[i].Value() + " "); } Console.Write("\ngcc: "); for (int i = 0; i < bbase; i++) { Console.Write(gcc[i].Value() + " "); } Console.WriteLine("\n"); // for debugging etc: show the full binary table /* Console.Write("binary:"); for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { Console.Write(binary[i][j].Value() + " "); } Console.WriteLine(); } Console.WriteLine(); */ } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); Console.WriteLine("WallTime: {0}ms", solver.WallTime()); Console.WriteLine("Failures: {0}", solver.Failures()); Console.WriteLine("Branches: {0} ", solver.Branches()); solver.EndSearch(); } public static void Main(String[] args) { int bbase = 2; int n = 3; int m = 8; if (args.Length > 0) { bbase = Convert.ToInt32(args[0]); } if (args.Length > 1) { n = Convert.ToInt32(args[1]); } if (args.Length > 2) { m = Convert.ToInt32(args[2]); } Solve(bbase, n, m); } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record.CF { using System; using System.Text; using NPOI.HSSF.Record; using NPOI.Util; using NPOI.SS.UserModel; /** * Font Formatting Block of the Conditional Formatting Rule Record. * * @author Dmitriy Kumshayev */ internal class FontFormatting { private byte[] _rawData; private static int OFFSET_FONT_NAME = 0; private static int OFFSET_FONT_HEIGHT = 64; private static int OFFSET_FONT_OPTIONS = 68; private static int OFFSET_FONT_WEIGHT = 72; private static int OFFSET_ESCAPEMENT_TYPE = 74; private static int OFFSET_UNDERLINE_TYPE = 76; private static int OFFSET_FONT_COLOR_INDEX = 80; private static int OFFSET_OPTION_FLAGS = 88; private static int OFFSET_ESCAPEMENT_TYPE_MODIFIED = 92; private static int OFFSET_UNDERLINE_TYPE_MODIFIED = 96; private static int OFFSET_FONT_WEIGHT_MODIFIED = 100; private static int OFFSET_NOT_USED1 = 104; private static int OFFSET_NOT_USED2 = 108; private static int OFFSET_NOT_USED3 = 112; // for some reason Excel always Writes 0x7FFFFFFF at this offset private static int OFFSET_FONT_FORMATING_END = 116; private static int RAW_DATA_SIZE = 118; public static int FONT_CELL_HEIGHT_PRESERVED = unchecked((int)0xFFFFFFFF); // FONT OPTIONS MASKS private static BitField posture = BitFieldFactory.GetInstance(0x00000002); private static BitField outline = BitFieldFactory.GetInstance(0x00000008); private static BitField shadow = BitFieldFactory.GetInstance(0x00000010); private static BitField cancellation = BitFieldFactory.GetInstance(0x00000080); // OPTION FLAGS MASKS private static BitField styleModified = BitFieldFactory.GetInstance(0x00000002); private static BitField outlineModified = BitFieldFactory.GetInstance(0x00000008); private static BitField shadowModified = BitFieldFactory.GetInstance(0x00000010); private static BitField cancellationModified = BitFieldFactory.GetInstance(0x00000080); /** Escapement type - None */ public const short SS_NONE = 0; /** Escapement type - Superscript */ public const short SS_SUPER = 1; /** Escapement type - Subscript */ public const short SS_SUB = 2; /** Underline type - None */ public const byte U_NONE = 0; /** Underline type - Single */ public const byte U_SINGLE = 1; /** Underline type - double */ public const byte U_DOUBLE = 2; /** Underline type - Single Accounting */ public const byte U_SINGLE_ACCOUNTING = 0x21; /** Underline type - double Accounting */ public const byte U_DOUBLE_ACCOUNTING = 0x22; /** Normal boldness (not bold) */ private const short FONT_WEIGHT_NORMAL = 0x190; /** * Bold boldness (bold) */ private const short FONT_WEIGHT_BOLD = 0x2bc; private FontFormatting(byte[] rawData) { _rawData = rawData; } public FontFormatting():this(new byte[RAW_DATA_SIZE]) { FontHeight=-1; IsItalic=false; IsFontWeightModified=false; IsOutlineOn=false; IsShadowOn=false; IsStruckout=false; EscapementType=(FontSuperScript)0; UnderlineType=(FontUnderlineType)0; FontColorIndex=(short)-1; IsFontStyleModified=false; IsFontOutlineModified=false; IsFontShadowModified=false; IsFontCancellationModified=false; IsEscapementTypeModified=false; IsUnderlineTypeModified=false; SetShort(OFFSET_FONT_NAME, 0); SetInt(OFFSET_NOT_USED1, 0x00000001); SetInt(OFFSET_NOT_USED2, 0x00000000); SetInt(OFFSET_NOT_USED3, 0x7FFFFFFF);// for some reason Excel always Writes 0x7FFFFFFF at this offset SetShort(OFFSET_FONT_FORMATING_END, 0x0001); } /** Creates new FontFormatting */ public FontFormatting(RecordInputStream in1):this(new byte[RAW_DATA_SIZE]) { for (int i = 0; i < _rawData.Length; i++) { _rawData[i] =(byte) in1.ReadByte(); } } private short GetShort(int offset) { return LittleEndian.GetShort(_rawData, offset); } private void SetShort(int offset, int value) { LittleEndian.PutShort(_rawData, offset, (short)value); } private int GetInt(int offset) { return LittleEndian.GetInt(_rawData, offset); } private void SetInt(int offset, int value) { LittleEndian.PutInt(_rawData, offset, value); } public byte[] GetRawRecord() { return _rawData; } /** * Gets the height of the font in 1/20th point Units * * @return fontheight (in points/20); or -1 if not modified */ public int FontHeight { get{return GetInt(OFFSET_FONT_HEIGHT);} set { SetInt(OFFSET_FONT_HEIGHT, value); } } private void SetFontOption(bool option, BitField field) { int options = GetInt(OFFSET_FONT_OPTIONS); options = field.SetBoolean(options, option); SetInt(OFFSET_FONT_OPTIONS, options); } private bool GetFontOption(BitField field) { int options = GetInt(OFFSET_FONT_OPTIONS); return field.IsSet(options); } /** * Get whether the font Is to be italics or not * * @return italics - whether the font Is italics or not * @see #GetAttributes() */ public bool IsItalic { get { return GetFontOption(posture); } set { SetFontOption(value, posture); } } public bool IsOutlineOn { get { return GetFontOption(outline); } set { SetFontOption(value, outline); } } public bool IsShadowOn { get { return GetFontOption(shadow); } set { SetFontOption(value, shadow); } } /** * Get whether the font Is to be stricken out or not * * @return strike - whether the font Is stricken out or not * @see #GetAttributes() */ public bool IsStruckout { get { return GetFontOption(cancellation); } set { SetFontOption(value, cancellation); } } /// <summary> /// Get or set the font weight for this font (100-1000dec or 0x64-0x3e8). /// Default Is 0x190 for normal and 0x2bc for bold /// </summary> public short FontWeight { get { return GetShort(OFFSET_FONT_WEIGHT); } set { short bw = value; if (bw < 100) { bw = 100; } if (bw > 1000) { bw = 1000; } SetShort(OFFSET_FONT_WEIGHT, bw); } } /// <summary> ///Get or set whether the font weight is set to bold or not /// </summary> public bool IsBold { get { return FontWeight == FONT_WEIGHT_BOLD; } set { this.FontWeight = (value ? FONT_WEIGHT_BOLD : FONT_WEIGHT_NORMAL); } } /** * Get the type of base or subscript for the font * * @return base or subscript option * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#SS_NONE * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#SS_SUPER * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#SS_SUB */ public FontSuperScript EscapementType { get { return (FontSuperScript)GetShort(OFFSET_ESCAPEMENT_TYPE); } set { SetShort(OFFSET_ESCAPEMENT_TYPE, (short)value); } } /** * Get the type of Underlining for the font * * @return font Underlining type * * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#U_NONE * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#U_SINGLE * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#U_DOUBLE * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#U_SINGLE_ACCOUNTING * @see org.apache.poi.hssf.usermodel.HSSFFontFormatting#U_DOUBLE_ACCOUNTING */ public FontUnderlineType UnderlineType { get { return (FontUnderlineType)GetShort(OFFSET_UNDERLINE_TYPE); } set { SetShort(OFFSET_UNDERLINE_TYPE, (short)value); } } public short FontColorIndex { get { return (short)GetInt(OFFSET_FONT_COLOR_INDEX); } set { SetInt(OFFSET_FONT_COLOR_INDEX, value); } } private bool GetOptionFlag(BitField field) { int optionFlags = GetInt(OFFSET_OPTION_FLAGS); int value = field.GetValue(optionFlags); return value == 0 ? true : false; } private void SetOptionFlag(bool modified, BitField field) { int value = modified ? 0 : 1; int optionFlags = GetInt(OFFSET_OPTION_FLAGS); optionFlags = field.SetValue(optionFlags, value); SetInt(OFFSET_OPTION_FLAGS, optionFlags); } public bool IsFontStyleModified { get { return GetOptionFlag(styleModified); } set { SetOptionFlag(value, styleModified); } } public bool IsFontOutlineModified { get { return GetOptionFlag(outlineModified); } set { SetOptionFlag(value, outlineModified); } } public bool IsFontShadowModified { get { return GetOptionFlag(shadowModified); } set { SetOptionFlag(value, shadowModified); } } public bool IsFontCancellationModified { get { return GetOptionFlag(cancellationModified); } set { SetOptionFlag(value, cancellationModified); } } public bool IsEscapementTypeModified { get { int escapementModified = GetInt(OFFSET_ESCAPEMENT_TYPE_MODIFIED); return escapementModified == 0; } set { int value1 = value ? 0 : 1; SetInt(OFFSET_ESCAPEMENT_TYPE_MODIFIED, value1); } } public bool IsUnderlineTypeModified { get { int underlineModified = GetInt(OFFSET_UNDERLINE_TYPE_MODIFIED); return underlineModified == 0; } set { int value1 = value ? 0 : 1; SetInt(OFFSET_UNDERLINE_TYPE_MODIFIED, value1); } } public bool IsFontWeightModified { get { int fontStyleModified = GetInt(OFFSET_FONT_WEIGHT_MODIFIED); return fontStyleModified == 0; } set { int value1 = value ? 0 : 1; SetInt(OFFSET_FONT_WEIGHT_MODIFIED, value1); } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append(" [Font Formatting]\n"); buffer.Append(" .font height = ").Append(FontHeight).Append(" twips\n"); if (IsFontStyleModified) { buffer.Append(" .font posture = ").Append(IsItalic ? "Italic" : "Normal").Append("\n"); } else { buffer.Append(" .font posture = ]not modified]").Append("\n"); } if (IsFontOutlineModified) { buffer.Append(" .font outline = ").Append(IsOutlineOn).Append("\n"); } else { buffer.Append(" .font outline Is not modified\n"); } if (IsFontShadowModified) { buffer.Append(" .font shadow = ").Append(IsShadowOn).Append("\n"); } else { buffer.Append(" .font shadow Is not modified\n"); } if (IsFontCancellationModified) { buffer.Append(" .font strikeout = ").Append(IsStruckout).Append("\n"); } else { buffer.Append(" .font strikeout Is not modified\n"); } if (IsFontStyleModified) { buffer.Append(" .font weight = "). Append(FontWeight). Append( FontWeight == FONT_WEIGHT_NORMAL ? "(Normal)" : FontWeight == FONT_WEIGHT_BOLD ? "(Bold)" : "0x" + StringUtil.ToHexString(FontWeight)). Append("\n"); } else { buffer.Append(" .font weight = ]not modified]").Append("\n"); } if (IsEscapementTypeModified) { buffer.Append(" .escapement type = ").Append(EscapementType).Append("\n"); } else { buffer.Append(" .escapement type Is not modified\n"); } if (IsUnderlineTypeModified) { buffer.Append(" .underline type = ").Append(UnderlineType).Append("\n"); } else { buffer.Append(" .underline type Is not modified\n"); } buffer.Append(" .color index = ").Append("0x" + StringUtil.ToHexString(FontColorIndex).ToUpper()).Append("\n"); buffer.Append(" [/Font Formatting]\n"); return buffer.ToString(); } public Object Clone() { byte[] rawData = (byte[])_rawData.Clone(); return new FontFormatting(rawData); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace NearestStation.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.HWPF.Model { using NPOI.Util; using System; using System.Text; using NPOI.HWPF.UserModel; /** * Comment me * * @author Ryan Ackley */ public class StyleDescription { private const int PARAGRAPH_STYLE = 1; private const int CHARACTER_STYLE = 2; private int _istd; private int _baseLength; private short _infoshort; private static BitField _sti = BitFieldFactory.GetInstance(0xfff); private static BitField _fScratch = BitFieldFactory.GetInstance(0x1000); private static BitField _fInvalHeight = BitFieldFactory.GetInstance(0x2000); private static BitField _fHasUpe = BitFieldFactory.GetInstance(0x4000); private static BitField _fMassCopy = BitFieldFactory.GetInstance(0x8000); private short _infoshort2; private static BitField _styleTypeCode = BitFieldFactory.GetInstance(0xf); private static BitField _baseStyle = BitFieldFactory.GetInstance(0xfff0); private short _infoshort3; private static BitField _numUPX = BitFieldFactory.GetInstance(0xf); private static BitField _nextStyle = BitFieldFactory.GetInstance(0xfff0); private short _bchUpe; private short _infoshort4; private static BitField _fAutoRedef = BitFieldFactory.GetInstance(0x1); private static BitField _fHidden = BitFieldFactory.GetInstance(0x2); UPX[] _upxs; String _name; ParagraphProperties _pap; CharacterProperties _chp; public StyleDescription() { // _pap = new ParagraphProperties(); // _chp = new CharacterProperties(); } public StyleDescription(byte[] std, int baseLength, int offset, bool word9) { _baseLength = baseLength; int nameStart = offset + baseLength; _infoshort = LittleEndian.GetShort(std, offset); offset += LittleEndianConsts.SHORT_SIZE; _infoshort2 = LittleEndian.GetShort(std, offset); offset += LittleEndianConsts.SHORT_SIZE; _infoshort3 = LittleEndian.GetShort(std, offset); offset += LittleEndianConsts.SHORT_SIZE; _bchUpe = LittleEndian.GetShort(std, offset); offset += LittleEndianConsts.SHORT_SIZE; _infoshort4 = LittleEndian.GetShort(std, offset); offset += LittleEndianConsts.SHORT_SIZE; //first byte(s) of variable length section of std is the length of the //style name and aliases string int nameLength = 0; int multiplier = 1; if (word9) { nameLength = LittleEndian.GetShort(std, nameStart); multiplier = 2; nameStart += LittleEndianConsts.SHORT_SIZE; } else { nameLength = std[nameStart]; } try { _name = Encoding.GetEncoding("UTF-16LE").GetString(std, nameStart, nameLength * multiplier); } catch (EncoderFallbackException) { // ignore } //length then null terminator. int grupxStart = ((nameLength + 1) * multiplier) + nameStart; // the spec only refers to two possible upxs but it mentions // that more may be Added in the future int varoffset = grupxStart; int numUPX = _numUPX.GetValue(_infoshort3); _upxs = new UPX[numUPX]; for (int x = 0; x < numUPX; x++) { int upxSize = LittleEndian.GetShort(std, varoffset); varoffset += LittleEndianConsts.SHORT_SIZE; byte[] upx = new byte[upxSize]; Array.Copy(std, varoffset, upx, 0, upxSize); _upxs[x] = new UPX(upx); varoffset += upxSize; // the upx will always start on a word boundary. if (upxSize % 2 == 1) { ++varoffset; } } } public int GetBaseStyle() { return _baseStyle.GetValue(_infoshort2); } public byte[] GetCHPX() { switch (_styleTypeCode.GetValue(_infoshort2)) { case PARAGRAPH_STYLE: if (_upxs.Length > 1) { return _upxs[1].GetUPX(); } return null; case CHARACTER_STYLE: return _upxs[0].GetUPX(); default: return null; } } public byte[] GetPAPX() { switch (_styleTypeCode.GetValue(_infoshort2)) { case PARAGRAPH_STYLE: return _upxs[0].GetUPX(); default: return null; } } public ParagraphProperties GetPAP() { return _pap; } public CharacterProperties GetCHP() { return _chp; } internal void SetPAP(ParagraphProperties pap) { _pap = pap; } internal void SetCHP(CharacterProperties chp) { _chp = chp; } public String GetName() { return _name; } public byte[] ToArray() { // size Equals _baseLength bytes for known variables plus 2 bytes for name // length plus name length * 2 plus 2 bytes for null plus upx's preceded by // length int size = _baseLength + 2 + ((_name.Length + 1) * 2); // determine the size needed for the upxs. They always fall on word // boundaries. size += _upxs[0].Size + 2; for (int x = 1; x < _upxs.Length; x++) { size += _upxs[x - 1].Size % 2; size += _upxs[x].Size + 2; } byte[] buf = new byte[size]; int offset = 0; LittleEndian.PutShort(buf, offset, _infoshort); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, _infoshort2); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, _infoshort3); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, _bchUpe); offset += LittleEndianConsts.SHORT_SIZE; LittleEndian.PutShort(buf, offset, _infoshort4); offset = _baseLength; char[] letters = _name.ToCharArray(); LittleEndian.PutShort(buf, _baseLength, (short)letters.Length); offset += LittleEndianConsts.SHORT_SIZE; for (int x = 0; x < letters.Length; x++) { LittleEndian.PutShort(buf, offset, (short)letters[x]); offset += LittleEndianConsts.SHORT_SIZE; } // get past the null delimiter for the name. offset += LittleEndianConsts.SHORT_SIZE; for (int x = 0; x < _upxs.Length; x++) { short upxSize = (short)_upxs[x].Size; LittleEndian.PutShort(buf, offset, upxSize); offset += LittleEndianConsts.SHORT_SIZE; Array.Copy(_upxs[x].GetUPX(), 0, buf, offset, upxSize); offset += upxSize + (upxSize % 2); } return buf; } public override bool Equals(Object o) { StyleDescription sd = (StyleDescription)o; if (sd._infoshort == _infoshort && sd._infoshort2 == _infoshort2 && sd._infoshort3 == _infoshort3 && sd._bchUpe == _bchUpe && sd._infoshort4 == _infoshort4 && _name.Equals(sd._name)) { if (!Arrays.Equals(_upxs, sd._upxs)) { return false; } return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.FindSymbols; using OmniSharp.Models; namespace OmniSharp { //TODO: //1. Remove unused using statements //2. Sort using statements //3. Remove redundant using statements //4. Replace code which checks accessibility by Roslyn method if it is made available public class FixUsingsWorker { public static async Task<FixUsingsResponse> AddMissingUsings(string fileName, Document document, SemanticModel semanticModel) { var compilationUnitSyntax = await AddUnambiguousUsings(fileName, document, semanticModel); document = document.WithSyntaxRoot(compilationUnitSyntax); semanticModel = await document.GetSemanticModelAsync(); return await GetAmbiguousUsings(fileName, document, semanticModel, compilationUnitSyntax); } private static async Task<CompilationUnitSyntax> AddUnambiguousUsings(string fileName, Document document, SemanticModel semanticModel) { var root = (await document.GetSyntaxTreeAsync()).GetRoot(); var unresolvedTypes = GetUnresolvedTypes(semanticModel, root); var hasLinq = HasLinqQuerySyntax(semanticModel, root); var compilationUnitSyntax = (CompilationUnitSyntax)root; var usingsToAdd = new HashSet<string>(); var unresolvedSet = new HashSet<string>(); var candidateUsings = new List<ISymbol>(); if (compilationUnitSyntax != null) { usingsToAdd.UnionWith(GetUsings(root)); foreach (var unresolvedType in unresolvedTypes) { candidateUsings = GetCandidateUsings(document, unresolvedType); //If there is only one candidate - add it to the usings list if (candidateUsings.Count() == 1) { var candidateNameSpace = candidateUsings[0].ContainingNamespace.ToString(); var candidateName = SyntaxFactory.ParseName(candidateNameSpace); var usingToAdd = SyntaxFactory.UsingDirective(candidateName).NormalizeWhitespace() .WithTrailingTrivia(SyntaxFactory.Whitespace(Environment.NewLine)); var usingToAddText = usingToAdd.GetText().ToString(); if (!usingsToAdd.Contains(usingToAddText.Trim())) { compilationUnitSyntax = compilationUnitSyntax.AddUsings(usingToAdd); usingsToAdd.Add(usingToAddText.Trim()); } } } //Handle linq with query syntax var linqName = SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("System"), SyntaxFactory.IdentifierName("Linq")); var linqUsingText = "using " + linqName.ToString() + ";"; if (hasLinq && !usingsToAdd.Contains(linqUsingText)) { var linq = SyntaxFactory.UsingDirective(linqName).NormalizeWhitespace() .WithTrailingTrivia(SyntaxFactory.Whitespace(Environment.NewLine)); compilationUnitSyntax = compilationUnitSyntax.AddUsings(linq); usingsToAdd.Add(linqName.GetText().ToString().Trim()); } } return compilationUnitSyntax; } private static async Task<FixUsingsResponse> GetAmbiguousUsings(string fileName, Document document, SemanticModel semanticModel, CompilationUnitSyntax compilationUnitSyntax) { var root = (await document.GetSyntaxTreeAsync()).GetRoot(); var unresolvedTypes = GetUnresolvedTypes(semanticModel, root); var usingsToAdd = new HashSet<string>(); var unresolvedSet = new HashSet<string>(); var candidateUsings = new List<ISymbol>(); var ambiguous = new List<QuickFix>(); if (compilationUnitSyntax != null) { usingsToAdd.UnionWith(GetUsings(root)); foreach (var unresolvedType in unresolvedTypes) { candidateUsings = GetCandidateUsings(document, unresolvedType); //Set the symbol as an ambiguous match foreach (var candidateUsing in candidateUsings) { var unresolvedText = unresolvedType.Identifier.ValueText; if (!unresolvedSet.Contains(unresolvedText)) { var unresolvedLocation = unresolvedType.GetLocation().GetLineSpan().StartLinePosition; ambiguous.Add(new QuickFix { Line = unresolvedLocation.Line + 1, Column = unresolvedLocation.Character + 1, FileName = fileName, Text = "`" + unresolvedText + "`" + " is ambiguous" }); unresolvedSet.Add(unresolvedText); } } } } return new FixUsingsResponse(compilationUnitSyntax.GetText().ToString(), ambiguous); } private static IEnumerable<SimpleNameSyntax> GetUnresolvedTypes(SemanticModel semanticModel, SyntaxNode syntaxNode) { return syntaxNode.DescendantNodes() .OfType<SimpleNameSyntax>() .Where(x => semanticModel.GetSymbolInfo(x).Symbol == null && semanticModel.GetSymbolInfo(x).CandidateReason != CandidateReason.OverloadResolutionFailure); } private static bool HasLinqQuerySyntax(SemanticModel semanticModel, SyntaxNode syntaxNode) { return syntaxNode.DescendantNodes() .Where(x => x.Kind() == SyntaxKind.QueryExpression || x.Kind() == SyntaxKind.QueryBody || x.Kind() == SyntaxKind.FromClause || x.Kind() == SyntaxKind.LetClause || x.Kind() == SyntaxKind.JoinClause || x.Kind() == SyntaxKind.JoinClause || x.Kind() == SyntaxKind.JoinIntoClause || x.Kind() == SyntaxKind.WhereClause || x.Kind() == SyntaxKind.OrderByClause || x.Kind() == SyntaxKind.AscendingOrdering || x.Kind() == SyntaxKind.DescendingOrdering || x.Kind() == SyntaxKind.SelectClause || x.Kind() == SyntaxKind.GroupClause || x.Kind() == SyntaxKind.QueryContinuation).Any(); } private static HashSet<string> GetUsings(SyntaxNode root) { var usings = new HashSet<string>(); root.DescendantNodes().OfType<UsingDirectiveSyntax>() .ToList().ForEach(x => { if (!usings.Contains(x.ToString().Trim())) { usings.Add(x.ToString().Trim()); } }); return usings; } private static List<ISymbol> GetCandidateUsings(Document document, SimpleNameSyntax unresolvedType) { var candidateUsings = new List<ISymbol>(); //Get all candidate usings by type var candidateUsingsTypes = SymbolFinder.FindDeclarationsAsync(document.Project, unresolvedType.Identifier.ValueText, false, SymbolFilter.Type, CancellationToken.None).Result.Where(c => c.DeclaredAccessibility == Accessibility.Public); var candidateUsingsAll = candidateUsingsTypes .Where(s => HasValidContainer(s) && !IsExcluded(s)) .ToList(); //Get all candidate usings by member var candidateUsingsMembers = SymbolFinder.FindDeclarationsAsync(document.Project, unresolvedType.Identifier.ValueText, false, SymbolFilter.Member, CancellationToken.None).Result.Where(c => c.DeclaredAccessibility == Accessibility.Public); candidateUsingsAll.AddRange(candidateUsingsMembers .Where(s => !IsExcluded(s)) .ToList()); //Dedup candidate usings and handle Linq separately foreach (var candidateUsing in candidateUsingsAll) { if (!candidateUsings.Any(c => c.ContainingNamespace.ToString() == candidateUsing.ContainingNamespace.ToString())) { if (candidateUsing.ContainingNamespace.ToString() == "System.Linq") { candidateUsings.Clear(); candidateUsings.Add(candidateUsing); break; } else { candidateUsings.Add(candidateUsing); } } } return candidateUsings; } private static bool HasValidContainer(ISymbol symbol) { var container = symbol.ContainingSymbol; return container is INamespaceSymbol || (container is INamedTypeSymbol && !((INamedTypeSymbol)container).IsGenericType); } private static bool IsExcluded(ISymbol symbol) { //Exclude method symbols and enum containing types. //Add any additional exclusions here var containingType = symbol.ContainingType; return (containingType != null && containingType.TypeKind == TypeKind.Enum); } } }
// // Copyright (C) DataStax 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.Linq; using Cassandra.Requests; using Cassandra.Serialization; namespace Cassandra { /// <summary> /// <para>Represents a prepared statement with the parameter values set, ready for execution.</para> /// A <see cref="BoundStatement"/> can be created from a <see cref="PreparedStatement"/> instance using the /// <c>Bind()</c> method and can be executed using a <see cref="ISession"/> instance. /// <seealso cref="Cassandra.PreparedStatement"/> /// </summary> public class BoundStatement : Statement { private readonly PreparedStatement _preparedStatement; private RoutingKey _routingKey; private readonly Serializer _serializer; private readonly string _keyspace; /// <summary> /// Gets the prepared statement on which this BoundStatement is based. /// </summary> public PreparedStatement PreparedStatement { get { return _preparedStatement; } } /// <summary> /// Gets the routing key for this bound query. <p> This method will return a /// non-<c>null</c> value if: <ul> <li>either all the TableColumns composing the /// partition key are bound variables of this <c>BoundStatement</c>. The /// routing key will then be built using the values provided for these partition /// key TableColumns.</li> <li>or the routing key has been set through /// <c>PreparedStatement.SetRoutingKey</c> for the /// <see cref="PreparedStatement"/> this statement has been built from.</li> </ul> /// Otherwise, <c>null</c> is returned.</p> <p> Note that if the routing key /// has been set through <link>PreparedStatement.SetRoutingKey</link>, that value /// takes precedence even if the partition key is part of the bound variables.</p> /// </summary> public override RoutingKey RoutingKey { get { return _routingKey; } } /// <summary> /// Returns the keyspace this query operates on, based on the <see cref="PreparedStatement"/> metadata. /// <para> /// The keyspace returned is used as a hint for token-aware routing. /// </para> /// </summary> public override string Keyspace { get { return _keyspace; } } /// <summary> /// Initializes a new instance of the Cassandra.BoundStatement class /// </summary> public BoundStatement() { //Default constructor for client test and mocking frameworks } /// <summary> /// Creates a new <c>BoundStatement</c> from the provided prepared /// statement. /// </summary> /// <param name="statement"> the prepared statement from which to create a <c>BoundStatement</c>.</param> public BoundStatement(PreparedStatement statement) { _preparedStatement = statement; _routingKey = statement.RoutingKey; if (statement.Metadata != null) { _keyspace = statement.Metadata.Keyspace; } SetConsistencyLevel(statement.ConsistencyLevel); if (statement.IsIdempotent != null) { SetIdempotence(statement.IsIdempotent.Value); } } internal BoundStatement(PreparedStatement statement, Serializer serializer) : this(statement) { _serializer = serializer; } /// <summary> /// Set the routing key for this query. This method allows to manually /// provide a routing key for this BoundStatement. It is thus optional since the routing /// key is only an hint for token aware load balancing policy but is never /// mandatory. /// </summary> /// <param name="routingKeyComponents"> the raw (binary) values to compose the routing key.</param> public BoundStatement SetRoutingKey(params RoutingKey[] routingKeyComponents) { _routingKey = RoutingKey.Compose(routingKeyComponents); return this; } internal override void SetValues(object[] values) { values = ValidateValues(values); base.SetValues(values); } /// <summary> /// Validate values using prepared statement metadata, /// returning a new instance of values to be used as parameters. /// </summary> private object[] ValidateValues(object[] values) { if (_serializer == null) { throw new DriverInternalError("Serializer can not be null"); } if (values == null) { return null; } if (PreparedStatement.Metadata == null || PreparedStatement.Metadata.Columns == null || PreparedStatement.Metadata.Columns.Length == 0) { return values; } var paramsMetadata = PreparedStatement.Metadata.Columns; if (values.Length > paramsMetadata.Length) { throw new ArgumentException( string.Format("Provided {0} parameters to bind, expected {1}", values.Length, paramsMetadata.Length)); } for (var i = 0; i < values.Length; i++) { var p = paramsMetadata[i]; var value = values[i]; if (!_serializer.IsAssignableFrom(p, value)) { throw new InvalidTypeException( String.Format("It is not possible to encode a value of type {0} to a CQL type {1}", value.GetType(), p.TypeCode)); } } if (values.Length < paramsMetadata.Length && _serializer.ProtocolVersion.SupportsUnset()) { //Set the result of the unspecified parameters to Unset var completeValues = new object[paramsMetadata.Length]; values.CopyTo(completeValues, 0); for (var i = values.Length; i < paramsMetadata.Length; i++) { completeValues[i] = Unset.Value; } values = completeValues; } return values; } internal override IQueryRequest CreateBatchRequest(ProtocolVersion protocolVersion) { // Use the default query options as the individual options of the query will be ignored var options = QueryProtocolOptions.CreateForBatchItem(this); return new ExecuteRequest(protocolVersion, PreparedStatement.Id, PreparedStatement.Metadata, IsTracing, options); } internal void CalculateRoutingKey(bool useNamedParameters, int[] routingIndexes, string[] routingNames, object[] valuesByPosition, object[] rawValues) { if (_routingKey != null) { //The routing key was specified by the user return; } if (routingIndexes != null) { var keys = new RoutingKey[routingIndexes.Length]; for (var i = 0; i < routingIndexes.Length; i++) { var index = routingIndexes[i]; var key = _serializer.Serialize(valuesByPosition[index]); if (key == null) { //The partition key can not be null //Get out and let any node reply a Response Error return; } keys[i] = new RoutingKey(key); } SetRoutingKey(keys); return; } if (routingNames != null && useNamedParameters) { var keys = new RoutingKey[routingNames.Length]; var routingValues = Utils.GetValues(routingNames, rawValues[0]).ToArray(); if (routingValues.Length != keys.Length) { //The routing names are not valid return; } for (var i = 0; i < routingValues.Length; i++) { var key = _serializer.Serialize(routingValues[i]); if (key == null) { //The partition key can not be null return; } keys[i] = new RoutingKey(key); } SetRoutingKey(keys); } } } }
using System; namespace ChainUtils.BouncyCastle.Asn1.Pkcs { public abstract class PkcsObjectIdentifiers { // // pkcs-1 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } // public const string Pkcs1 = "1.2.840.113549.1.1"; public static readonly DerObjectIdentifier RsaEncryption = new DerObjectIdentifier(Pkcs1 + ".1"); public static readonly DerObjectIdentifier MD2WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".2"); public static readonly DerObjectIdentifier MD4WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".3"); public static readonly DerObjectIdentifier MD5WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".4"); public static readonly DerObjectIdentifier Sha1WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".5"); public static readonly DerObjectIdentifier SrsaOaepEncryptionSet = new DerObjectIdentifier(Pkcs1 + ".6"); public static readonly DerObjectIdentifier IdRsaesOaep = new DerObjectIdentifier(Pkcs1 + ".7"); public static readonly DerObjectIdentifier IdMgf1 = new DerObjectIdentifier(Pkcs1 + ".8"); public static readonly DerObjectIdentifier IdPSpecified = new DerObjectIdentifier(Pkcs1 + ".9"); public static readonly DerObjectIdentifier IdRsassaPss = new DerObjectIdentifier(Pkcs1 + ".10"); public static readonly DerObjectIdentifier Sha256WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".11"); public static readonly DerObjectIdentifier Sha384WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".12"); public static readonly DerObjectIdentifier Sha512WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".13"); public static readonly DerObjectIdentifier Sha224WithRsaEncryption = new DerObjectIdentifier(Pkcs1 + ".14"); // // pkcs-3 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 3 } // public const string Pkcs3 = "1.2.840.113549.1.3"; public static readonly DerObjectIdentifier DhKeyAgreement = new DerObjectIdentifier(Pkcs3 + ".1"); // // pkcs-5 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } // public const string Pkcs5 = "1.2.840.113549.1.5"; public static readonly DerObjectIdentifier PbeWithMD2AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".1"); public static readonly DerObjectIdentifier PbeWithMD2AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".4"); public static readonly DerObjectIdentifier PbeWithMD5AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".3"); public static readonly DerObjectIdentifier PbeWithMD5AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".6"); public static readonly DerObjectIdentifier PbeWithSha1AndDesCbc = new DerObjectIdentifier(Pkcs5 + ".10"); public static readonly DerObjectIdentifier PbeWithSha1AndRC2Cbc = new DerObjectIdentifier(Pkcs5 + ".11"); public static readonly DerObjectIdentifier IdPbeS2 = new DerObjectIdentifier(Pkcs5 + ".13"); public static readonly DerObjectIdentifier IdPbkdf2 = new DerObjectIdentifier(Pkcs5 + ".12"); // // encryptionAlgorithm OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) 3 } // public const string EncryptionAlgorithm = "1.2.840.113549.3"; public static readonly DerObjectIdentifier DesEde3Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".7"); public static readonly DerObjectIdentifier RC2Cbc = new DerObjectIdentifier(EncryptionAlgorithm + ".2"); // // object identifiers for digests // public const string DigestAlgorithm = "1.2.840.113549.2"; // // md2 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 2} // public static readonly DerObjectIdentifier MD2 = new DerObjectIdentifier(DigestAlgorithm + ".2"); // // md4 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 4} // public static readonly DerObjectIdentifier MD4 = new DerObjectIdentifier(DigestAlgorithm + ".4"); // // md5 OBJECT IDENTIFIER ::= // {iso(1) member-body(2) US(840) rsadsi(113549) DigestAlgorithm(2) 5} // public static readonly DerObjectIdentifier MD5 = new DerObjectIdentifier(DigestAlgorithm + ".5"); public static readonly DerObjectIdentifier IdHmacWithSha1 = new DerObjectIdentifier(DigestAlgorithm + ".7"); public static readonly DerObjectIdentifier IdHmacWithSha224 = new DerObjectIdentifier(DigestAlgorithm + ".8"); public static readonly DerObjectIdentifier IdHmacWithSha256 = new DerObjectIdentifier(DigestAlgorithm + ".9"); public static readonly DerObjectIdentifier IdHmacWithSha384 = new DerObjectIdentifier(DigestAlgorithm + ".10"); public static readonly DerObjectIdentifier IdHmacWithSha512 = new DerObjectIdentifier(DigestAlgorithm + ".11"); // // pkcs-7 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 } // public const string Pkcs7 = "1.2.840.113549.1.7"; public static readonly DerObjectIdentifier Data = new DerObjectIdentifier(Pkcs7 + ".1"); public static readonly DerObjectIdentifier SignedData = new DerObjectIdentifier(Pkcs7 + ".2"); public static readonly DerObjectIdentifier EnvelopedData = new DerObjectIdentifier(Pkcs7 + ".3"); public static readonly DerObjectIdentifier SignedAndEnvelopedData = new DerObjectIdentifier(Pkcs7 + ".4"); public static readonly DerObjectIdentifier DigestedData = new DerObjectIdentifier(Pkcs7 + ".5"); public static readonly DerObjectIdentifier EncryptedData = new DerObjectIdentifier(Pkcs7 + ".6"); // // pkcs-9 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } // public const string Pkcs9 = "1.2.840.113549.1.9"; public static readonly DerObjectIdentifier Pkcs9AtEmailAddress = new DerObjectIdentifier(Pkcs9 + ".1"); public static readonly DerObjectIdentifier Pkcs9AtUnstructuredName = new DerObjectIdentifier(Pkcs9 + ".2"); public static readonly DerObjectIdentifier Pkcs9AtContentType = new DerObjectIdentifier(Pkcs9 + ".3"); public static readonly DerObjectIdentifier Pkcs9AtMessageDigest = new DerObjectIdentifier(Pkcs9 + ".4"); public static readonly DerObjectIdentifier Pkcs9AtSigningTime = new DerObjectIdentifier(Pkcs9 + ".5"); public static readonly DerObjectIdentifier Pkcs9AtCounterSignature = new DerObjectIdentifier(Pkcs9 + ".6"); public static readonly DerObjectIdentifier Pkcs9AtChallengePassword = new DerObjectIdentifier(Pkcs9 + ".7"); public static readonly DerObjectIdentifier Pkcs9AtUnstructuredAddress = new DerObjectIdentifier(Pkcs9 + ".8"); public static readonly DerObjectIdentifier Pkcs9AtExtendedCertificateAttributes = new DerObjectIdentifier(Pkcs9 + ".9"); public static readonly DerObjectIdentifier Pkcs9AtSigningDescription = new DerObjectIdentifier(Pkcs9 + ".13"); public static readonly DerObjectIdentifier Pkcs9AtExtensionRequest = new DerObjectIdentifier(Pkcs9 + ".14"); public static readonly DerObjectIdentifier Pkcs9AtSmimeCapabilities = new DerObjectIdentifier(Pkcs9 + ".15"); public static readonly DerObjectIdentifier Pkcs9AtFriendlyName = new DerObjectIdentifier(Pkcs9 + ".20"); public static readonly DerObjectIdentifier Pkcs9AtLocalKeyID = new DerObjectIdentifier(Pkcs9 + ".21"); [Obsolete("Use X509Certificate instead")] public static readonly DerObjectIdentifier X509CertType = new DerObjectIdentifier(Pkcs9 + ".22.1"); public const string CertTypes = Pkcs9 + ".22"; public static readonly DerObjectIdentifier X509Certificate = new DerObjectIdentifier(CertTypes + ".1"); public static readonly DerObjectIdentifier SdsiCertificate = new DerObjectIdentifier(CertTypes + ".2"); public const string CrlTypes = Pkcs9 + ".23"; public static readonly DerObjectIdentifier X509Crl = new DerObjectIdentifier(CrlTypes + ".1"); public static readonly DerObjectIdentifier IdAlgPwriKek = new DerObjectIdentifier(Pkcs9 + ".16.3.9"); // // SMIME capability sub oids. // public static readonly DerObjectIdentifier PreferSignedData = new DerObjectIdentifier(Pkcs9 + ".15.1"); public static readonly DerObjectIdentifier CannotDecryptAny = new DerObjectIdentifier(Pkcs9 + ".15.2"); public static readonly DerObjectIdentifier SmimeCapabilitiesVersions = new DerObjectIdentifier(Pkcs9 + ".15.3"); // // other SMIME attributes // public static readonly DerObjectIdentifier IdAAReceiptRequest = new DerObjectIdentifier(Pkcs9 + ".16.2.1"); // // id-ct OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1)} // public const string IdCT = "1.2.840.113549.1.9.16.1"; public static readonly DerObjectIdentifier IdCTAuthData = new DerObjectIdentifier(IdCT + ".2"); public static readonly DerObjectIdentifier IdCTTstInfo = new DerObjectIdentifier(IdCT + ".4"); public static readonly DerObjectIdentifier IdCTCompressedData = new DerObjectIdentifier(IdCT + ".9"); public static readonly DerObjectIdentifier IdCTAuthEnvelopedData = new DerObjectIdentifier(IdCT + ".23"); public static readonly DerObjectIdentifier IdCTTimestampedData = new DerObjectIdentifier(IdCT + ".31"); // // id-cti OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) cti(6)} // public const string IdCti = "1.2.840.113549.1.9.16.6"; public static readonly DerObjectIdentifier IdCtiEtsProofOfOrigin = new DerObjectIdentifier(IdCti + ".1"); public static readonly DerObjectIdentifier IdCtiEtsProofOfReceipt = new DerObjectIdentifier(IdCti + ".2"); public static readonly DerObjectIdentifier IdCtiEtsProofOfDelivery = new DerObjectIdentifier(IdCti + ".3"); public static readonly DerObjectIdentifier IdCtiEtsProofOfSender = new DerObjectIdentifier(IdCti + ".4"); public static readonly DerObjectIdentifier IdCtiEtsProofOfApproval = new DerObjectIdentifier(IdCti + ".5"); public static readonly DerObjectIdentifier IdCtiEtsProofOfCreation = new DerObjectIdentifier(IdCti + ".6"); // // id-aa OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) attributes(2)} // public const string IdAA = "1.2.840.113549.1.9.16.2"; public static readonly DerObjectIdentifier IdAAContentHint = new DerObjectIdentifier(IdAA + ".4"); // See RFC 2634 public static readonly DerObjectIdentifier IdAAMsgSigDigest = new DerObjectIdentifier(IdAA + ".5"); public static readonly DerObjectIdentifier IdAAContentReference = new DerObjectIdentifier(IdAA + ".10"); /* * id-aa-encrypKeyPref OBJECT IDENTIFIER ::= {id-aa 11} * */ public static readonly DerObjectIdentifier IdAAEncrypKeyPref = new DerObjectIdentifier(IdAA + ".11"); public static readonly DerObjectIdentifier IdAASigningCertificate = new DerObjectIdentifier(IdAA + ".12"); public static readonly DerObjectIdentifier IdAASigningCertificateV2 = new DerObjectIdentifier(IdAA + ".47"); public static readonly DerObjectIdentifier IdAAContentIdentifier = new DerObjectIdentifier(IdAA + ".7"); // See RFC 2634 /* * RFC 3126 */ public static readonly DerObjectIdentifier IdAASignatureTimeStampToken = new DerObjectIdentifier(IdAA + ".14"); public static readonly DerObjectIdentifier IdAAEtsSigPolicyID = new DerObjectIdentifier(IdAA + ".15"); public static readonly DerObjectIdentifier IdAAEtsCommitmentType = new DerObjectIdentifier(IdAA + ".16"); public static readonly DerObjectIdentifier IdAAEtsSignerLocation = new DerObjectIdentifier(IdAA + ".17"); public static readonly DerObjectIdentifier IdAAEtsSignerAttr = new DerObjectIdentifier(IdAA + ".18"); public static readonly DerObjectIdentifier IdAAEtsOtherSigCert = new DerObjectIdentifier(IdAA + ".19"); public static readonly DerObjectIdentifier IdAAEtsContentTimestamp = new DerObjectIdentifier(IdAA + ".20"); public static readonly DerObjectIdentifier IdAAEtsCertificateRefs = new DerObjectIdentifier(IdAA + ".21"); public static readonly DerObjectIdentifier IdAAEtsRevocationRefs = new DerObjectIdentifier(IdAA + ".22"); public static readonly DerObjectIdentifier IdAAEtsCertValues = new DerObjectIdentifier(IdAA + ".23"); public static readonly DerObjectIdentifier IdAAEtsRevocationValues = new DerObjectIdentifier(IdAA + ".24"); public static readonly DerObjectIdentifier IdAAEtsEscTimeStamp = new DerObjectIdentifier(IdAA + ".25"); public static readonly DerObjectIdentifier IdAAEtsCertCrlTimestamp = new DerObjectIdentifier(IdAA + ".26"); public static readonly DerObjectIdentifier IdAAEtsArchiveTimestamp = new DerObjectIdentifier(IdAA + ".27"); [Obsolete("Use 'IdAAEtsSigPolicyID' instead")] public static readonly DerObjectIdentifier IdAASigPolicyID = IdAAEtsSigPolicyID; [Obsolete("Use 'IdAAEtsCommitmentType' instead")] public static readonly DerObjectIdentifier IdAACommitmentType = IdAAEtsCommitmentType; [Obsolete("Use 'IdAAEtsSignerLocation' instead")] public static readonly DerObjectIdentifier IdAASignerLocation = IdAAEtsSignerLocation; [Obsolete("Use 'IdAAEtsOtherSigCert' instead")] public static readonly DerObjectIdentifier IdAAOtherSigCert = IdAAEtsOtherSigCert; // // id-spq OBJECT IDENTIFIER ::= {iso(1) member-body(2) usa(840) // rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) id-spq(5)} // public const string IdSpq = "1.2.840.113549.1.9.16.5"; public static readonly DerObjectIdentifier IdSpqEtsUri = new DerObjectIdentifier(IdSpq + ".1"); public static readonly DerObjectIdentifier IdSpqEtsUNotice = new DerObjectIdentifier(IdSpq + ".2"); // // pkcs-12 OBJECT IDENTIFIER ::= { // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } // public const string Pkcs12 = "1.2.840.113549.1.12"; public const string BagTypes = Pkcs12 + ".10.1"; public static readonly DerObjectIdentifier KeyBag = new DerObjectIdentifier(BagTypes + ".1"); public static readonly DerObjectIdentifier Pkcs8ShroudedKeyBag = new DerObjectIdentifier(BagTypes + ".2"); public static readonly DerObjectIdentifier CertBag = new DerObjectIdentifier(BagTypes + ".3"); public static readonly DerObjectIdentifier CrlBag = new DerObjectIdentifier(BagTypes + ".4"); public static readonly DerObjectIdentifier SecretBag = new DerObjectIdentifier(BagTypes + ".5"); public static readonly DerObjectIdentifier SafeContentsBag = new DerObjectIdentifier(BagTypes + ".6"); public const string Pkcs12PbeIds = Pkcs12 + ".1"; public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".1"); public static readonly DerObjectIdentifier PbeWithShaAnd40BitRC4 = new DerObjectIdentifier(Pkcs12PbeIds + ".2"); public static readonly DerObjectIdentifier PbeWithShaAnd3KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".3"); public static readonly DerObjectIdentifier PbeWithShaAnd2KeyTripleDesCbc = new DerObjectIdentifier(Pkcs12PbeIds + ".4"); public static readonly DerObjectIdentifier PbeWithShaAnd128BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".5"); public static readonly DerObjectIdentifier PbewithShaAnd40BitRC2Cbc = new DerObjectIdentifier(Pkcs12PbeIds + ".6"); public static readonly DerObjectIdentifier IdAlgCms3DesWrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.6"); public static readonly DerObjectIdentifier IdAlgCmsRC2Wrap = new DerObjectIdentifier("1.2.840.113549.1.9.16.3.7"); } }
// 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.Xml; using System.Configuration; using System.Windows.Forms; using System.Collections; using System.Text; using WebsitePanel.Setup.Actions; namespace WebsitePanel.Setup { public class Server : BaseSetup { public static object Install(object obj) { return InstallBase(obj, "1.0.1"); } internal static object InstallBase(object obj, string minimalInstallerVersion) { Hashtable args = Utils.GetSetupParameters(obj); //check CS version string shellVersion = Utils.GetStringSetupParameter(args, Global.Parameters.ShellVersion); var shellMode = Utils.GetStringSetupParameter(args, Global.Parameters.ShellMode); Version version = new Version(shellVersion); // var setupVariables = new SetupVariables { SetupAction = SetupActions.Install, IISVersion = Global.IISVersion }; // InitInstall(args, setupVariables); //Unattended setup LoadSetupVariablesFromSetupXml(setupVariables.SetupXml, setupVariables); // var sam = new ServerActionManager(setupVariables); // Prepare installation defaults sam.PrepareDistributiveDefaults(); // Silent Installer Mode if (shellMode.Equals(Global.SilentInstallerShell, StringComparison.OrdinalIgnoreCase)) { if (version < new Version(minimalInstallerVersion)) { Utils.ShowConsoleErrorMessage(Global.Messages.InstallerVersionIsObsolete, minimalInstallerVersion); // return false; } try { var success = true; // setupVariables.ServerPassword = Utils.GetStringSetupParameter(args, Global.Parameters.ServerPassword); // sam.ActionError += new EventHandler<ActionErrorEventArgs>((object sender, ActionErrorEventArgs e) => { Utils.ShowConsoleErrorMessage(e.ErrorMessage); // Log.WriteError(e.ErrorMessage); // success = false; }); // sam.Start(); // return success; } catch (Exception ex) { Log.WriteError("Failed to install the component", ex); // return false; } } else { if (version < new Version(minimalInstallerVersion)) { MessageBox.Show(String.Format(Global.Messages.InstallerVersionIsObsolete, minimalInstallerVersion), "Setup Wizard", MessageBoxButtons.OK, MessageBoxIcon.Warning); // return DialogResult.Cancel; } var form = new InstallerForm(); var wizard = form.Wizard; wizard.SetupVariables = setupVariables; // wizard.ActionManager = sam; //create wizard pages var introPage = new IntroductionPage(); var licPage = new LicenseAgreementPage(); // var page1 = new ConfigurationCheckPage(); page1.Checks.AddRange(new ConfigurationCheck[] { new ConfigurationCheck(CheckTypes.OperationSystem, "Operating System Requirement"){ SetupVariables = setupVariables }, new ConfigurationCheck(CheckTypes.IISVersion, "IIS Requirement"){ SetupVariables = setupVariables }, new ConfigurationCheck(CheckTypes.ASPNET, "ASP.NET Requirement"){ SetupVariables = setupVariables } }); // var page2 = new InstallFolderPage(); var page3 = new WebPage(); var page4 = new UserAccountPage(); var page5 = new ServerPasswordPage(); var page6 = new ExpressInstallPage2(); var page7 = new FinishPage(); // wizard.Controls.AddRange(new Control[] { introPage, licPage, page1, page2, page3, page4, page5, page6, page7 }); wizard.LinkPages(); wizard.SelectedPage = introPage; //show wizard IWin32Window owner = args["ParentForm"] as IWin32Window; return form.ShowModal(owner); } } public static object Uninstall(object obj) { Hashtable args = Utils.GetSetupParameters(obj); // string shellVersion = Utils.GetStringSetupParameter(args, Global.Parameters.ShellVersion); // var setupVariables = new SetupVariables { ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId), SetupAction = SetupActions.Uninstall, IISVersion = Global.IISVersion }; // AppConfig.LoadConfiguration(); InstallerForm form = new InstallerForm(); Wizard wizard = form.Wizard; wizard.SetupVariables = setupVariables; AppConfig.LoadComponentSettings(wizard.SetupVariables); IntroductionPage page1 = new IntroductionPage(); ConfirmUninstallPage page2 = new ConfirmUninstallPage(); UninstallPage page3 = new UninstallPage(); page2.UninstallPage = page3; FinishPage page4 = new FinishPage(); wizard.Controls.AddRange(new Control[] { page1, page2, page3, page4 }); wizard.LinkPages(); wizard.SelectedPage = page1; //show wizard IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window; return form.ShowModal(owner); } public static object Setup(object obj) { var args = Utils.GetSetupParameters(obj); var shellVersion = Utils.GetStringSetupParameter(args, Global.Parameters.ShellVersion); // var setupVariables = new SetupVariables { ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId), SetupAction = SetupActions.Setup, IISVersion = Global.IISVersion, ConfigurationFile = "web.config" }; // AppConfig.LoadConfiguration(); InstallerForm form = new InstallerForm(); Wizard wizard = form.Wizard; // wizard.SetupVariables = setupVariables; // AppConfig.LoadComponentSettings(wizard.SetupVariables); WebPage page1 = new WebPage(); ServerPasswordPage page2 = new ServerPasswordPage(); ExpressInstallPage page3 = new ExpressInstallPage(); //create install actions InstallAction action = new InstallAction(ActionTypes.UpdateWebSite); action.Description = "Updating web site..."; page3.Actions.Add(action); action = new InstallAction(ActionTypes.UpdateServerPassword); action.Description = "Updating server password..."; page3.Actions.Add(action); action = new InstallAction(ActionTypes.UpdateConfig); action.Description = "Updating system configuration..."; page3.Actions.Add(action); FinishPage page4 = new FinishPage(); wizard.Controls.AddRange(new Control[] { page1, page2, page3, page4 }); wizard.LinkPages(); wizard.SelectedPage = page1; //show wizard IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window; return form.ShowModal(owner); } public static object Update(object obj) { Hashtable args = Utils.GetSetupParameters(obj); var setupVariables = new SetupVariables { ComponentId = Utils.GetStringSetupParameter(args, Global.Parameters.ComponentId), SetupAction = SetupActions.Update, BaseDirectory = Utils.GetStringSetupParameter(args, Global.Parameters.BaseDirectory), UpdateVersion = Utils.GetStringSetupParameter(args, "UpdateVersion"), InstallerFolder = Utils.GetStringSetupParameter(args, Global.Parameters.InstallerFolder), Installer = Utils.GetStringSetupParameter(args, Global.Parameters.Installer), InstallerType = Utils.GetStringSetupParameter(args, Global.Parameters.InstallerType), InstallerPath = Utils.GetStringSetupParameter(args, Global.Parameters.InstallerPath) }; AppConfig.LoadConfiguration(); InstallerForm form = new InstallerForm(); Wizard wizard = form.Wizard; // wizard.SetupVariables = setupVariables; // AppConfig.LoadComponentSettings(wizard.SetupVariables); IntroductionPage introPage = new IntroductionPage(); LicenseAgreementPage licPage = new LicenseAgreementPage(); ExpressInstallPage page2 = new ExpressInstallPage(); //create install currentScenario InstallAction action = new InstallAction(ActionTypes.Backup); action.Description = "Backing up..."; page2.Actions.Add(action); action = new InstallAction(ActionTypes.DeleteFiles); action.Description = "Deleting files..."; action.Path = "setup\\delete.txt"; page2.Actions.Add(action); action = new InstallAction(ActionTypes.CopyFiles); action.Description = "Copying files..."; page2.Actions.Add(action); action = new InstallAction(ActionTypes.UpdateConfig); action.Description = "Updating system configuration..."; page2.Actions.Add(action); FinishPage page3 = new FinishPage(); wizard.Controls.AddRange(new Control[] { introPage, licPage, page2, page3 }); wizard.LinkPages(); wizard.SelectedPage = introPage; //show wizard IWin32Window owner = args[Global.Parameters.ParentForm] as IWin32Window; return form.ShowModal(owner); } } }
//--------------------------------------------------------------------- // <copyright file="UriWriter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Translates resource bound expression trees into URIs. // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services.Client { #region Namespaces. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; #endregion Namespaces. /// <summary> /// Translates resource bound expression trees into URIs. /// </summary> internal class UriWriter : DataServiceALinqExpressionVisitor { /// <summary>Data context used to generate type names for types.</summary> private readonly DataServiceContext context; /// <summary>stringbuilder for constructed URI</summary> private readonly StringBuilder uriBuilder; /// <summary>the data service version for the uri</summary> private Version uriVersion; /// <summary>the leaf resourceset for the URI being written</summary> private ResourceSetExpression leafResourceSet; /// <summary> /// Private constructor for creating UriWriter /// </summary> /// <param name='context'>Data context used to generate type names for types.</param> private UriWriter(DataServiceContext context) { Debug.Assert(context != null, "context != null"); this.context = context; this.uriBuilder = new StringBuilder(); this.uriVersion = Util.DataServiceVersion1; } /// <summary> /// Translates resource bound expression tree to a URI. /// </summary> /// <param name='context'>Data context used to generate type names for types.</param> /// <param name="addTrailingParens">flag to indicate whether generated URI should include () if leaf is ResourceSet</param> /// <param name="e">The expression to translate</param> /// <param name="uri">uri</param> /// <param name="version">version for query</param> internal static void Translate(DataServiceContext context, bool addTrailingParens, Expression e, out Uri uri, out Version version) { var writer = new UriWriter(context); writer.leafResourceSet = addTrailingParens ? (e as ResourceSetExpression) : null; writer.Visit(e); uri = Util.CreateUri(context.BaseUriWithSlash, Util.CreateUri(writer.uriBuilder.ToString(), UriKind.Relative)); version = writer.uriVersion; } /// <summary> /// MethodCallExpression visit method /// </summary> /// <param name="m">The MethodCallExpression expression to visit</param> /// <returns>The visited MethodCallExpression expression </returns> internal override Expression VisitMethodCall(MethodCallExpression m) { throw Error.MethodNotSupported(m); } /// <summary> /// UnaryExpression visit method /// </summary> /// <param name="u">The UnaryExpression expression to visit</param> /// <returns>The visited UnaryExpression expression </returns> internal override Expression VisitUnary(UnaryExpression u) { throw new NotSupportedException(Strings.ALinq_UnaryNotSupported(u.NodeType.ToString())); } /// <summary> /// BinaryExpression visit method /// </summary> /// <param name="b">The BinaryExpression expression to visit</param> /// <returns>The visited BinaryExpression expression </returns> internal override Expression VisitBinary(BinaryExpression b) { throw new NotSupportedException(Strings.ALinq_BinaryNotSupported(b.NodeType.ToString())); } /// <summary> /// ConstantExpression visit method /// </summary> /// <param name="c">The ConstantExpression expression to visit</param> /// <returns>The visited ConstantExpression expression </returns> internal override Expression VisitConstant(ConstantExpression c) { throw new NotSupportedException(Strings.ALinq_ConstantNotSupported(c.Value)); } /// <summary> /// TypeBinaryExpression visit method /// </summary> /// <param name="b">The TypeBinaryExpression expression to visit</param> /// <returns>The visited TypeBinaryExpression expression </returns> internal override Expression VisitTypeIs(TypeBinaryExpression b) { throw new NotSupportedException(Strings.ALinq_TypeBinaryNotSupported); } /// <summary> /// ConditionalExpression visit method /// </summary> /// <param name="c">The ConditionalExpression expression to visit</param> /// <returns>The visited ConditionalExpression expression </returns> internal override Expression VisitConditional(ConditionalExpression c) { throw new NotSupportedException(Strings.ALinq_ConditionalNotSupported); } /// <summary> /// ParameterExpression visit method /// </summary> /// <param name="p">The ParameterExpression expression to visit</param> /// <returns>The visited ParameterExpression expression </returns> internal override Expression VisitParameter(ParameterExpression p) { throw new NotSupportedException(Strings.ALinq_ParameterNotSupported); } /// <summary> /// MemberExpression visit method /// </summary> /// <param name="m">The MemberExpression expression to visit</param> /// <returns>The visited MemberExpression expression </returns> internal override Expression VisitMemberAccess(MemberExpression m) { throw new NotSupportedException(Strings.ALinq_MemberAccessNotSupported(m.Member.Name)); } /// <summary> /// LambdaExpression visit method /// </summary> /// <param name="lambda">The LambdaExpression to visit</param> /// <returns>The visited LambdaExpression</returns> internal override Expression VisitLambda(LambdaExpression lambda) { throw new NotSupportedException(Strings.ALinq_LambdaNotSupported); } /// <summary> /// NewExpression visit method /// </summary> /// <param name="nex">The NewExpression to visit</param> /// <returns>The visited NewExpression</returns> internal override NewExpression VisitNew(NewExpression nex) { throw new NotSupportedException(Strings.ALinq_NewNotSupported); } /// <summary> /// MemberInitExpression visit method /// </summary> /// <param name="init">The MemberInitExpression to visit</param> /// <returns>The visited MemberInitExpression</returns> internal override Expression VisitMemberInit(MemberInitExpression init) { throw new NotSupportedException(Strings.ALinq_MemberInitNotSupported); } /// <summary> /// ListInitExpression visit method /// </summary> /// <param name="init">The ListInitExpression to visit</param> /// <returns>The visited ListInitExpression</returns> internal override Expression VisitListInit(ListInitExpression init) { throw new NotSupportedException(Strings.ALinq_ListInitNotSupported); } /// <summary> /// NewArrayExpression visit method /// </summary> /// <param name="na">The NewArrayExpression to visit</param> /// <returns>The visited NewArrayExpression</returns> internal override Expression VisitNewArray(NewArrayExpression na) { throw new NotSupportedException(Strings.ALinq_NewArrayNotSupported); } /// <summary> /// InvocationExpression visit method /// </summary> /// <param name="iv">The InvocationExpression to visit</param> /// <returns>The visited InvocationExpression</returns> internal override Expression VisitInvocation(InvocationExpression iv) { throw new NotSupportedException(Strings.ALinq_InvocationNotSupported); } /// <summary> /// NavigationPropertySingletonExpression visit method. /// </summary> /// <param name="npse">NavigationPropertySingletonExpression expression to visit</param> /// <returns>Visited NavigationPropertySingletonExpression expression</returns> internal override Expression VisitNavigationPropertySingletonExpression(NavigationPropertySingletonExpression npse) { this.Visit(npse.Source); this.uriBuilder.Append(UriHelper.FORWARDSLASH).Append(this.ExpressionToString(npse.MemberExpression)); this.VisitQueryOptions(npse); return npse; } /// <summary> /// ResourceSetExpression visit method. /// </summary> /// <param name="rse">ResourceSetExpression expression to visit</param> /// <returns>Visited ResourceSetExpression expression</returns> internal override Expression VisitResourceSetExpression(ResourceSetExpression rse) { if ((ResourceExpressionType)rse.NodeType == ResourceExpressionType.ResourceNavigationProperty) { this.Visit(rse.Source); this.uriBuilder.Append(UriHelper.FORWARDSLASH).Append(this.ExpressionToString(rse.MemberExpression)); } else { this.uriBuilder.Append(UriHelper.FORWARDSLASH).Append((string)((ConstantExpression)rse.MemberExpression).Value); } if (rse.KeyPredicate != null) { this.uriBuilder.Append(UriHelper.LEFTPAREN); if (rse.KeyPredicate.Count == 1) { this.uriBuilder.Append(this.ExpressionToString(rse.KeyPredicate.Values.First())); } else { bool addComma = false; foreach (var kvp in rse.KeyPredicate) { if (addComma) { this.uriBuilder.Append(UriHelper.COMMA); } this.uriBuilder.Append(kvp.Key.Name); this.uriBuilder.Append(UriHelper.EQUALSSIGN); this.uriBuilder.Append(this.ExpressionToString(kvp.Value)); addComma = true; } } this.uriBuilder.Append(UriHelper.RIGHTPAREN); } else if (rse == this.leafResourceSet) { // if resourceset is on the leaf, append () this.uriBuilder.Append(UriHelper.LEFTPAREN); this.uriBuilder.Append(UriHelper.RIGHTPAREN); } if (rse.CountOption == CountOption.ValueOnly) { // append $count segment: /$count this.uriBuilder.Append(UriHelper.FORWARDSLASH).Append(UriHelper.DOLLARSIGN).Append(UriHelper.COUNT); this.EnsureMinimumVersion(2, 0); } this.VisitQueryOptions(rse); return rse; } /// <summary> /// Visit Query options for Resource /// </summary> /// <param name="re">Resource Expression with query options</param> internal void VisitQueryOptions(ResourceExpression re) { bool needAmpersand = false; if (re.HasQueryOptions) { this.uriBuilder.Append(UriHelper.QUESTIONMARK); ResourceSetExpression rse = re as ResourceSetExpression; if (rse != null) { IEnumerator options = rse.SequenceQueryOptions.GetEnumerator(); while (options.MoveNext()) { if (needAmpersand) { this.uriBuilder.Append(UriHelper.AMPERSAND); } Expression e = ((Expression)options.Current); ResourceExpressionType et = (ResourceExpressionType)e.NodeType; switch (et) { case ResourceExpressionType.SkipQueryOption: this.VisitQueryOptionExpression((SkipQueryOptionExpression)e); break; case ResourceExpressionType.TakeQueryOption: this.VisitQueryOptionExpression((TakeQueryOptionExpression)e); break; case ResourceExpressionType.OrderByQueryOption: this.VisitQueryOptionExpression((OrderByQueryOptionExpression)e); break; case ResourceExpressionType.FilterQueryOption: this.VisitQueryOptionExpression((FilterQueryOptionExpression)e); break; default: Debug.Assert(false, "Unexpected expression type " + (int)et); break; } needAmpersand = true; } } if (re.ExpandPaths.Count > 0) { if (needAmpersand) { this.uriBuilder.Append(UriHelper.AMPERSAND); } this.VisitExpandOptions(re.ExpandPaths); needAmpersand = true; } if (re.Projection != null && re.Projection.Paths.Count > 0) { if (needAmpersand) { this.uriBuilder.Append(UriHelper.AMPERSAND); } this.VisitProjectionPaths(re.Projection.Paths); needAmpersand = true; } if (re.CountOption == CountOption.InlineAll) { if (needAmpersand) { this.uriBuilder.Append(UriHelper.AMPERSAND); } this.VisitCountOptions(); needAmpersand = true; } if (re.CustomQueryOptions.Count > 0) { if (needAmpersand) { this.uriBuilder.Append(UriHelper.AMPERSAND); } this.VisitCustomQueryOptions(re.CustomQueryOptions); needAmpersand = true; } } } /// <summary> /// SkipQueryOptionExpression visit method. /// </summary> /// <param name="sqoe">SkipQueryOptionExpression expression to visit</param> internal void VisitQueryOptionExpression(SkipQueryOptionExpression sqoe) { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONSKIP); this.uriBuilder.Append(UriHelper.EQUALSSIGN); this.uriBuilder.Append(this.ExpressionToString(sqoe.SkipAmount)); } /// <summary> /// TakeQueryOptionExpression visit method. /// </summary> /// <param name="tqoe">TakeQueryOptionExpression expression to visit</param> internal void VisitQueryOptionExpression(TakeQueryOptionExpression tqoe) { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONTOP); this.uriBuilder.Append(UriHelper.EQUALSSIGN); this.uriBuilder.Append(this.ExpressionToString(tqoe.TakeAmount)); } /// <summary> /// FilterQueryOptionExpression visit method. /// </summary> /// <param name="fqoe">FilterQueryOptionExpression expression to visit</param> internal void VisitQueryOptionExpression(FilterQueryOptionExpression fqoe) { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONFILTER); this.uriBuilder.Append(UriHelper.EQUALSSIGN); this.uriBuilder.Append(this.ExpressionToString(fqoe.Predicate)); } /// <summary> /// OrderByQueryOptionExpression visit method. /// </summary> /// <param name="oboe">OrderByQueryOptionExpression expression to visit</param> internal void VisitQueryOptionExpression(OrderByQueryOptionExpression oboe) { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONORDERBY); this.uriBuilder.Append(UriHelper.EQUALSSIGN); int ii = 0; while (true) { var selector = oboe.Selectors[ii]; this.uriBuilder.Append(this.ExpressionToString(selector.Expression)); if (selector.Descending) { this.uriBuilder.Append(UriHelper.SPACE); this.uriBuilder.Append(UriHelper.OPTIONDESC); } if (++ii == oboe.Selectors.Count) { break; } this.uriBuilder.Append(UriHelper.COMMA); } } /// <summary> /// VisitExpandOptions visit method. /// </summary> /// <param name="paths">Expand Paths</param> internal void VisitExpandOptions(List<string> paths) { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONEXPAND); this.uriBuilder.Append(UriHelper.EQUALSSIGN); int ii = 0; while (true) { this.uriBuilder.Append(paths[ii]); if (++ii == paths.Count) { break; } this.uriBuilder.Append(UriHelper.COMMA); } } /// <summary> /// ProjectionPaths visit method. /// </summary> /// <param name="paths">Projection Paths</param> internal void VisitProjectionPaths(List<string> paths) { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONSELECT); this.uriBuilder.Append(UriHelper.EQUALSSIGN); int ii = 0; while (true) { string path = paths[ii]; this.uriBuilder.Append(path); if (++ii == paths.Count) { break; } this.uriBuilder.Append(UriHelper.COMMA); } this.EnsureMinimumVersion(2, 0); } /// <summary> /// VisitCountOptions visit method. /// </summary> internal void VisitCountOptions() { this.uriBuilder.Append(UriHelper.DOLLARSIGN); this.uriBuilder.Append(UriHelper.OPTIONCOUNT); this.uriBuilder.Append(UriHelper.EQUALSSIGN); this.uriBuilder.Append(UriHelper.COUNTALL); this.EnsureMinimumVersion(2, 0); } /// <summary> /// VisitCustomQueryOptions visit method. /// </summary> /// <param name="options">Custom query options</param> internal void VisitCustomQueryOptions(Dictionary<ConstantExpression, ConstantExpression> options) { List<ConstantExpression> keys = options.Keys.ToList(); List<ConstantExpression> values = options.Values.ToList(); int ii = 0; while (true) { this.uriBuilder.Append(keys[ii].Value); this.uriBuilder.Append(UriHelper.EQUALSSIGN); this.uriBuilder.Append(values[ii].Value); if (keys[ii].Value.ToString().Equals(UriHelper.DOLLARSIGN + UriHelper.OPTIONCOUNT, StringComparison.OrdinalIgnoreCase)) { this.EnsureMinimumVersion(2, 0); } if (++ii == keys.Count) { break; } this.uriBuilder.Append(UriHelper.AMPERSAND); } } /// <summary>Serializes an expression to a string.</summary> /// <param name="expression">Expression to serialize</param> /// <returns>The serialized expression.</returns> private string ExpressionToString(Expression expression) { return ExpressionWriter.ExpressionToString(this.context, expression); } /// <summary> /// Ensure that the translated uri has the required minimum version associated with it /// </summary> /// <param name="major">The major number for the version. </param> /// <param name="minor">The minor number for the version. </param> private void EnsureMinimumVersion(int major, int minor) { if (major > this.uriVersion.Major || (major == this.uriVersion.Major && minor > this.uriVersion.Minor)) { this.uriVersion = new Version(major, minor); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.LineSeparator { [ExportLanguageService(typeof(ILineSeparatorService), LanguageNames.CSharp), Shared] internal class CSharpLineSeparatorService : ILineSeparatorService { /// <summary> /// Given a tree returns line separator spans. /// The operation may take fairly long time on a big tree so it is cancelable. /// </summary> public async Task<IEnumerable<TextSpan>> GetLineSeparatorsAsync( Document document, TextSpan textSpan, CancellationToken cancellationToken) { var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var node = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); var spans = new List<TextSpan>(); var blocks = node.Traverse<SyntaxNode>(textSpan, IsSeparableContainer); foreach (var block in blocks) { if (cancellationToken.IsCancellationRequested) { return SpecializedCollections.EmptyEnumerable<TextSpan>(); } var typeBlock = block as TypeDeclarationSyntax; if (typeBlock != null) { ProcessNodeList(typeBlock.Members, spans, cancellationToken); continue; } var namespaceBlock = block as NamespaceDeclarationSyntax; if (namespaceBlock != null) { ProcessUsings(namespaceBlock.Usings, spans, cancellationToken); ProcessNodeList(namespaceBlock.Members, spans, cancellationToken); continue; } var progBlock = block as CompilationUnitSyntax; if (progBlock != null) { ProcessUsings(progBlock.Usings, spans, cancellationToken); ProcessNodeList(progBlock.Members, spans, cancellationToken); } } return spans; } /// <summary>Node types that are interesting for line separation.</summary> private static bool IsSeparableBlock(SyntaxNode node) { if (SyntaxFacts.IsTypeDeclaration(node.Kind())) { return true; } switch (node.Kind()) { case SyntaxKind.NamespaceDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: return true; default: return false; } } /// <summary>Node types that may contain separable blocks.</summary> private static bool IsSeparableContainer(SyntaxNode node) { return node is TypeDeclarationSyntax || node is NamespaceDeclarationSyntax || node is CompilationUnitSyntax; } private static bool IsBadType(SyntaxNode node) { var typeDecl = node as TypeDeclarationSyntax; if (typeDecl != null) { if (typeDecl.OpenBraceToken.IsMissing || typeDecl.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadEnum(SyntaxNode node) { var enumDecl = node as EnumDeclarationSyntax; if (enumDecl != null) { if (enumDecl.OpenBraceToken.IsMissing || enumDecl.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadMethod(SyntaxNode node) { var methodDecl = node as MethodDeclarationSyntax; if (methodDecl != null) { if (methodDecl.Body != null && (methodDecl.Body.OpenBraceToken.IsMissing || methodDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadProperty(SyntaxNode node) { var propDecl = node as PropertyDeclarationSyntax; if (propDecl != null) { if (propDecl.AccessorList.OpenBraceToken.IsMissing || propDecl.AccessorList.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadEvent(SyntaxNode node) { var eventDecl = node as EventDeclarationSyntax; if (eventDecl != null) { if (eventDecl.AccessorList.OpenBraceToken.IsMissing || eventDecl.AccessorList.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadIndexer(SyntaxNode node) { var indexerDecl = node as IndexerDeclarationSyntax; if (indexerDecl != null) { if (indexerDecl.AccessorList.OpenBraceToken.IsMissing || indexerDecl.AccessorList.CloseBraceToken.IsMissing) { return true; } } return false; } private static bool IsBadConstructor(SyntaxNode node) { var constructorDecl = node as ConstructorDeclarationSyntax; if (constructorDecl != null) { if (constructorDecl.Body != null && (constructorDecl.Body.OpenBraceToken.IsMissing || constructorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadDestructor(SyntaxNode node) { var destructorDecl = node as DestructorDeclarationSyntax; if (destructorDecl != null) { if (destructorDecl.Body != null && (destructorDecl.Body.OpenBraceToken.IsMissing || destructorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadOperator(SyntaxNode node) { var operatorDecl = node as OperatorDeclarationSyntax; if (operatorDecl != null) { if (operatorDecl.Body != null && (operatorDecl.Body.OpenBraceToken.IsMissing || operatorDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadConversionOperator(SyntaxNode node) { var conversionDecl = node as ConversionOperatorDeclarationSyntax; if (conversionDecl != null) { if (conversionDecl.Body != null && (conversionDecl.Body.OpenBraceToken.IsMissing || conversionDecl.Body.CloseBraceToken.IsMissing)) { return true; } } return false; } private static bool IsBadNode(SyntaxNode node) { if (node is IncompleteMemberSyntax) { return true; } if (IsBadType(node) || IsBadEnum(node) || IsBadMethod(node) || IsBadProperty(node) || IsBadEvent(node) || IsBadIndexer(node) || IsBadConstructor(node) || IsBadDestructor(node) || IsBadOperator(node) || IsBadConversionOperator(node)) { return true; } return false; } private static void ProcessUsings(SyntaxList<UsingDirectiveSyntax> usings, List<TextSpan> spans, CancellationToken cancellationToken) { Contract.ThrowIfNull(spans); if (usings.Any()) { AddLineSeparatorSpanForNode(usings.Last(), spans, cancellationToken); } } /// <summary> /// If node is separable and not the last in its container => add line separator after the node /// If node is separable and not the first in its container => ensure separator before the node /// last separable node in Program needs separator after it. /// </summary> private static void ProcessNodeList<T>(SyntaxList<T> children, List<TextSpan> spans, CancellationToken cancellationToken) where T : SyntaxNode { Contract.ThrowIfNull(spans); if (children.Count == 0) { // nothing to separate return; } // first child needs no separator var seenSeparator = true; for (int i = 0; i < children.Count - 1; i++) { cancellationToken.ThrowIfCancellationRequested(); var cur = children[i]; if (!IsSeparableBlock(cur)) { seenSeparator = false; } else { if (!seenSeparator) { var prev = children[i - 1]; AddLineSeparatorSpanForNode(prev, spans, cancellationToken); } AddLineSeparatorSpanForNode(cur, spans, cancellationToken); seenSeparator = true; } } // last child may need separator only before it var lastChild = children.Last(); if (IsSeparableBlock(lastChild)) { if (!seenSeparator) { var nextToLast = children[children.Count - 2]; AddLineSeparatorSpanForNode(nextToLast, spans, cancellationToken); } if (lastChild.IsParentKind(SyntaxKind.CompilationUnit)) { AddLineSeparatorSpanForNode(lastChild, spans, cancellationToken); } } } private static void AddLineSeparatorSpanForNode(SyntaxNode node, List<TextSpan> spans, CancellationToken cancellationToken) { if (IsBadNode(node)) { return; } var span = GetLineSeparatorSpanForNode(node); if (IsLegalSpanForLineSeparator(node.SyntaxTree, span, cancellationToken)) { spans.Add(span); } } private static bool IsLegalSpanForLineSeparator(SyntaxTree syntaxTree, TextSpan textSpan, CancellationToken cancellationToken) { // A span is a legal location for a line separator if the following line // contains only whitespace or the span is the last line in the buffer. var line = syntaxTree.GetText(cancellationToken).Lines.IndexOf(textSpan.End); if (line == syntaxTree.GetText(cancellationToken).Lines.Count - 1) { return true; } if (string.IsNullOrWhiteSpace(syntaxTree.GetText(cancellationToken).Lines[line + 1].ToString())) { return true; } return false; } private static TextSpan GetLineSeparatorSpanForNode(SyntaxNode node) { // we only want to underline the node with a long line // for this purpose the last token is as good as the whole node, but has // simpler and typically single line geometry (so it will be easier to find "bottom") return node.GetLastToken().Span; } } }
// 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.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Text.Internal; using System.Text.Unicode; namespace System.Text.Encodings.Web { /// <summary> /// Represents a type used to do JavaScript encoding/escaping. /// </summary> public abstract class JavaScriptEncoder : TextEncoder { /// <summary> /// Returns a default built-in instance of <see cref="JavaScriptEncoder"/>. /// </summary> public static JavaScriptEncoder Default { get { return DefaultJavaScriptEncoder.Singleton; } } /// <summary> /// Returns a built-in instance of <see cref="JavaScriptEncoder"/> that is less strict about what gets encoded. /// </summary> /// <remarks> /// <para> /// Unlike the <see cref="Default"/>, this encoder instance does not escape HTML-senstive characters like &lt;, &gt;, &amp;, etc. and hence must be used cautiously /// (for example, if the output data is within a response whose content-type is known with a charset set to UTF-8). /// </para> /// <para> /// Unlike the <see cref="Default"/>, the quotation mark is encoded as \" rather than \u0022. /// </para> /// <para> /// Unlike the <see cref="Default"/> (which only allows <see cref="UnicodeRanges.BasicLatin"/>), using this encoder instance allows <see cref="UnicodeRanges.All"/> to go through unescaped. /// </para> /// <para> /// Unlike the <see cref="Default"/>, this encoder instance allows some other characters to go through unescaped (for example, '+'), and hence must be used cautiously. /// </para> /// </remarks> public static JavaScriptEncoder UnsafeRelaxedJsonEscaping { get { return UnsafeRelaxedJavaScriptEncoder.s_singleton; } } /// <summary> /// Creates a new instance of JavaScriptEncoder with provided settings. /// </summary> /// <param name="settings">Settings used to control how the created <see cref="JavaScriptEncoder"/> encodes, primarily which characters to encode.</param> /// <returns>A new instance of the <see cref="JavaScriptEncoder"/>.</returns> public static JavaScriptEncoder Create(TextEncoderSettings settings) { return new DefaultJavaScriptEncoder(settings); } /// <summary> /// Creates a new instance of JavaScriptEncoder specifying character to be encoded. /// </summary> /// <param name="allowedRanges">Set of characters that the encoder is allowed to not encode.</param> /// <returns>A new instance of the <see cref="JavaScriptEncoder"/>.</returns> /// <remarks>Some characters in <paramref name="allowedRanges"/> might still get encoded, i.e. this parameter is just telling the encoder what ranges it is allowed to not encode, not what characters it must not encode.</remarks> public static JavaScriptEncoder Create(params UnicodeRange[] allowedRanges) { return new DefaultJavaScriptEncoder(allowedRanges); } } internal sealed class DefaultJavaScriptEncoder : JavaScriptEncoder { private readonly AllowedCharactersBitmap _allowedCharacters; internal static readonly DefaultJavaScriptEncoder Singleton = new DefaultJavaScriptEncoder(new TextEncoderSettings(UnicodeRanges.BasicLatin)); public DefaultJavaScriptEncoder(TextEncoderSettings filter) { if (filter == null) { throw new ArgumentNullException(nameof(filter)); } _allowedCharacters = filter.GetAllowedCharacters(); // Forbid codepoints which aren't mapped to characters or which are otherwise always disallowed // (includes categories Cc, Cs, Co, Cn, Zs [except U+0020 SPACE], Zl, Zp) _allowedCharacters.ForbidUndefinedCharacters(); // Forbid characters that are special in HTML. // Even though this is a not HTML encoder, // it's unfortunately common for developers to // forget to HTML-encode a string once it has been JS-encoded, // so this offers extra protection. DefaultHtmlEncoder.ForbidHtmlCharacters(_allowedCharacters); // '\' (U+005C REVERSE SOLIDUS) must always be escaped in Javascript / ECMAScript / JSON. // '/' (U+002F SOLIDUS) is not Javascript / ECMAScript / JSON-sensitive so doesn't need to be escaped. _allowedCharacters.ForbidCharacter('\\'); // '`' (U+0060 GRAVE ACCENT) is ECMAScript-sensitive (see ECMA-262). _allowedCharacters.ForbidCharacter('`'); } public DefaultJavaScriptEncoder(params UnicodeRange[] allowedRanges) : this(new TextEncoderSettings(allowedRanges)) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool WillEncode(int unicodeScalar) { if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) return true; return !_allowedCharacters.IsUnicodeScalarAllowed(unicodeScalar); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe override int FindFirstCharacterToEncode(char* text, int textLength) { if (text == null) { throw new ArgumentNullException(nameof(text)); } return _allowedCharacters.FindFirstCharacterToEncode(text, textLength); } // The worst case encoding is 6 output chars per input char: [input] U+FFFF -> [output] "\uFFFF" // We don't need to worry about astral code points since they're represented as encoded // surrogate pairs in the output. public override int MaxOutputCharactersPerInputCharacter { get { return 12; } // "\uFFFF\uFFFF" is the longest encoded form } private static readonly char[] s_b = new char[] { '\\', 'b' }; private static readonly char[] s_t = new char[] { '\\', 't' }; private static readonly char[] s_n = new char[] { '\\', 'n' }; private static readonly char[] s_f = new char[] { '\\', 'f' }; private static readonly char[] s_r = new char[] { '\\', 'r' }; private static readonly char[] s_back = new char[] { '\\', '\\' }; // Writes a scalar value as a JavaScript-escaped character (or sequence of characters). // See ECMA-262, Sec. 7.8.4, and ECMA-404, Sec. 9 // http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4 // http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf public unsafe override bool TryEncodeUnicodeScalar(int unicodeScalar, char* buffer, int bufferLength, out int numberOfCharactersWritten) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } // ECMA-262 allows encoding U+000B as "\v", but ECMA-404 does not. // Both ECMA-262 and ECMA-404 allow encoding U+002F SOLIDUS as "\/" // (in ECMA-262 this character is a NonEscape character); however, we // don't encode SOLIDUS by default unless the caller has provided an // explicit bitmap which does not contain it. In this case we'll assume // that the caller didn't want a SOLIDUS written to the output at all, // so it should be written using "\u002F" encoding. // HTML-specific characters (including apostrophe and quotes) will // be written out as numeric entities for defense-in-depth. // See UnicodeEncoderBase ctor comments for more info. if (!WillEncode(unicodeScalar)) { return TryWriteScalarAsChar(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } char[] toCopy; switch (unicodeScalar) { case '\b': toCopy = s_b; break; case '\t': toCopy = s_t; break; case '\n': toCopy = s_n; break; case '\f': toCopy = s_f; break; case '\r': toCopy = s_r; break; case '\\': toCopy = s_back; break; default: return TryWriteEncodedScalarAsNumericEntity(unicodeScalar, buffer, bufferLength, out numberOfCharactersWritten); } return TryCopyCharacters(toCopy, buffer, bufferLength, out numberOfCharactersWritten); } private static unsafe bool TryWriteEncodedScalarAsNumericEntity(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { Debug.Assert(buffer != null && length >= 0); if (UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar)) { // Convert this back to UTF-16 and write out both characters. char leadingSurrogate, trailingSurrogate; UnicodeHelpers.GetUtf16SurrogatePairFromAstralScalarValue(unicodeScalar, out leadingSurrogate, out trailingSurrogate); int leadingSurrogateCharactersWritten; if (TryWriteEncodedSingleCharacter(leadingSurrogate, buffer, length, out leadingSurrogateCharactersWritten) && TryWriteEncodedSingleCharacter(trailingSurrogate, buffer + leadingSurrogateCharactersWritten, length - leadingSurrogateCharactersWritten, out numberOfCharactersWritten) ) { numberOfCharactersWritten += leadingSurrogateCharactersWritten; return true; } else { numberOfCharactersWritten = 0; return false; } } else { // This is only a single character. return TryWriteEncodedSingleCharacter(unicodeScalar, buffer, length, out numberOfCharactersWritten); } } // Writes an encoded scalar value (in the BMP) as a JavaScript-escaped character. private static unsafe bool TryWriteEncodedSingleCharacter(int unicodeScalar, char* buffer, int length, out int numberOfCharactersWritten) { Debug.Assert(buffer != null && length >= 0); Debug.Assert(!UnicodeHelpers.IsSupplementaryCodePoint(unicodeScalar), "The incoming value should've been in the BMP."); if (length < 6) { numberOfCharactersWritten = 0; return false; } // Encode this as 6 chars "\uFFFF". *buffer = '\\'; buffer++; *buffer = 'u'; buffer++; *buffer = HexUtil.Int32LsbToHexDigit(unicodeScalar >> 12); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)((unicodeScalar >> 8) & 0xFU)); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)((unicodeScalar >> 4) & 0xFU)); buffer++; *buffer = HexUtil.Int32LsbToHexDigit((int)(unicodeScalar & 0xFU)); buffer++; numberOfCharactersWritten = 6; return true; } } }
using TreeGecko.Library.Common.Helpers; using TreeGecko.Library.Common.Interfaces; using TreeGecko.Library.Common.Objects; using TreeGecko.Library.Geospatial.Helpers; using TreeGecko.Library.Geospatial.Extensions; namespace TreeGecko.Library.Geospatial.Objects { public class GeoBox : GeoPolygon, ITGSerializable { public GeoPoint Center { get; private set; } public GeoPoint TopLeft { get; private set; } public GeoPoint TopRight { get; private set; } public GeoPoint BottomRight { get; private set; } public GeoPoint BottomLeft { get; private set; } public GeoPoint East { get; private set; } public GeoPoint West { get; private set; } public GeoPoint North { get; private set; } public GeoPoint South { get; private set; } public GeoBox() { } public GeoBox(double _east, double _west, double _north, double _south) { GeoPoint topLeft = new GeoPoint(_west, _north); GeoPoint bottomRight = new GeoPoint(_east, _south); Setup(topLeft, bottomRight); } private void Setup(GeoPoint _topLeft, GeoPoint _bottomRight) { if (_topLeft != null && _bottomRight != null) { GeoPoint topRight = new GeoPoint(_bottomRight.X, _topLeft.Y); GeoPoint bottomLeft = new GeoPoint(_topLeft.X, _bottomRight.Y); TopLeft = _topLeft; TopRight = topRight; BottomLeft = bottomLeft; BottomRight = _bottomRight; SetPoints(); SetCenter(); CalculatePoints(); } } public GeoBox(GeoPoint _topLeft, GeoPoint _bottomRight) { Setup(_topLeft, _bottomRight); } private void SetPoints() { Points.Add(TopLeft); Points.Add(TopRight); Points.Add(BottomRight); Points.Add(BottomLeft); } /// <summary> /// Sets the center. /// </summary> private void SetCenter() { Center = new GeoPoint((TopRight.X + TopLeft.X)/2, (TopRight.Y + BottomRight.Y)/2); } /// <summary> /// Initializes a new instance of the <see cref="GeoBox"/> class. /// </summary> /// <param name='_center'> /// Center. /// </param> /// <param name='_width'> /// Width. /// </param> /// <param name='_height'> /// Height. /// </param> public GeoBox(GeoPoint _center, GeoDistance _width, GeoDistance _height) { Center = _center; East = PositionHelper.GetPointToEast(_center, _width); West = PositionHelper.GetPointToWest(_center, _width); North = PositionHelper.GetPointToNorth(_center, _height); South = PositionHelper.GetPointToSouth(_center, _height); CalculateCorners(); } /// <summary> /// Calculates the points. /// </summary> private void CalculateCorners() { if (East != null && West != null && North != null && South != null) { TopLeft = new GeoPoint(West.X, North.Y); TopRight = new GeoPoint(East.X, North.Y); BottomLeft = new GeoPoint(West.X, South.Y); BottomRight = new GeoPoint(East.X, South.Y); SetPoints(); } } private void CalculatePoints() { if (TopLeft != null && TopRight != null && BottomLeft != null && BottomRight != null) { East = new GeoPoint(TopRight.X, (TopRight.Y + BottomRight.Y)/2); West = new GeoPoint(TopLeft.X, (TopLeft.Y + BottomLeft.Y)/2); North = new GeoPoint((TopLeft.X + TopRight.X)/2, TopLeft.Y); South = new GeoPoint((BottomLeft.X + BottomRight.X)/2, BottomLeft.Y); } } public TGSerializedObject GetTGSerializedObject() { TGSerializedObject obj = new TGSerializedObject { TGObjectType = ReflectionHelper.GetTypeName(GetType()) }; obj.Add("TopLeft", TopLeft); obj.Add("TopRight", TopRight); obj.Add("BottomRight", BottomRight); obj.Add("BottomLeft", BottomLeft); CalculatePoints(); return obj; } public void LoadFromTGSerializedObject(TGSerializedObject _tg) { TopLeft = _tg.GetITGSerializableObject<GeoPoint>("TopLeft"); TopRight = _tg.GetITGSerializableObject<GeoPoint>("TopRight"); BottomRight = _tg.GetITGSerializableObject<GeoPoint>("BottomRight"); BottomLeft = _tg.GetITGSerializableObject<GeoPoint>("BottomLeft"); SetPoints(); SetCenter(); } public string TGObjectType { get { return ReflectionHelper.GetTypeName(GetType()); } } /// <summary> /// Deltas the latitude. /// </summary> /// <returns> /// The latitude. /// </returns> public double DeltaLatitude() { if (TopLeft != null && BottomLeft != null) { return TopLeft.Y - BottomLeft.Y; } return 0; } /// <summary> /// Deltas the longitude. /// </summary> /// <returns> /// The longitude. /// </returns> public double DeltaLongitude() { if (TopRight != null && TopLeft != null) { return TopRight.X - TopLeft.X; } return 0; } /// <summary> /// Minimums the latitude. /// </summary> /// <returns> /// The latitude. /// </returns> public double MinLatitude() { if (BottomLeft != null) { return BottomLeft.Y; } return 0; } /// <summary> /// Maxs the latitude. /// </summary> /// <returns> /// The latitude. /// </returns> public double MaxLatitude() { if (TopRight != null) { return TopRight.Y; } return 0; } /// <summary> /// Minimums the longitude. /// </summary> /// <returns> /// The longitude. /// </returns> public double MinLongitude() { if (TopLeft != null) { return TopLeft.X; } return 0; } /// <summary> /// Maxs the longitude. /// </summary> /// <returns> /// The longitude. /// </returns> public double MaxLongitude() { if (TopRight != null) { return TopRight.X; } return 0; } public bool Contains(GeoPoint _point) { if (_point != null) { if (East != null && West != null && South != null && North != null) { if (_point.X > West.X && _point.X < East.X && _point.Y > South.Y && _point.Y < North.Y) { return true; } } } return false; } } }
//--------------------------------------------------------------------------------------- // Copyright 2014 North Carolina State University // // Center for Educational Informatics // http://www.cei.ncsu.edu/ // // 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. // // 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.Linq; using System.Collections.Generic; namespace IntelliMedia.Utilities { public interface IParameters { T GetValueAs<T>(string name); } // Ensures parameter is available as a specific type public abstract class Operand { public abstract bool HasValue(IParameters parameters); public abstract object GetValue(IParameters parameters); public bool HasValue<T>(IParameters parameters) { if (HasValue(parameters)) { if (GetValue(parameters) is T) { return true; } else { object value = null; return GetValue(parameters).ValueByParsing(typeof(T), out value); } } return false; } public T GetValue<T>(IParameters parameters) { object value = GetValue(parameters); if (!(value is T)) { if (!value.ValueByParsing(typeof(T), out value)) { throw new Exception(String.Format("Operand unable to convert '{0}'", typeof(T).Name)); } } return (T)value; } } public class Constant : Operand { public object Value { get; set; } #region IOperand implementation public override bool HasValue(IParameters parameters) { return true; } public override object GetValue(IParameters parameters) { return Value; } #endregion } public interface IOperandTimeline { IEnumerable<Operand> GetWindow(double leftSeconds, Operand current, string requiredName, double rightSeconds); IEnumerable<Operand> Before(double seconds, Operand current, string requiredName = null); IEnumerable<Operand> After(double seconds, Operand current, string requiredName = null); } public abstract class Operator : Operand { public const string ResultName = "OperatorResult"; public Operand Lhs { get; set; } public Operand Rhs { get; set; } public abstract bool Test(IParameters parameters); #region IOperand implementation public override bool HasValue(IParameters parameters) { return true; } public override object GetValue(IParameters parameters) { return new bool?(Test(parameters)); } #endregion } public class EqualOperator : Operator { #region implemented abstract members of Operator public override bool Test(IParameters parameters) { return (Lhs.HasValue(parameters) && Rhs.HasValue(parameters) && object.Equals(Lhs.GetValue(parameters), Rhs.GetValue(parameters))); } #endregion } public class NotEqualOperator : Operator { #region implemented abstract members of Operator public override bool Test(IParameters parameters) { return (Lhs.HasValue(parameters) && Rhs.HasValue(parameters) && !object.Equals(Lhs.GetValue(parameters), Rhs.GetValue(parameters))); } #endregion } public class AndOperator : Operator { #region implemented abstract members of Operator public override bool Test(IParameters parameters) { return (Lhs.HasValue(parameters) && Rhs.HasValue(parameters) && ((Lhs.GetValue(parameters) as bool?) == true) && ((Rhs.GetValue(parameters) as bool?) == true)); } #endregion } public class NotOperator : Operator { #region implemented abstract members of Operator public override bool Test(IParameters parameters) { Contract.Argument("Lhs must be null for unary operator", "Lhs", Lhs == null); return (Rhs.HasValue(parameters) && ((Rhs.GetValue(parameters) as bool?) == false)); } #endregion } public class OrOperator : Operator { #region implemented abstract members of Operator public override bool Test(IParameters parameters) { return ((Lhs.HasValue(parameters) || Rhs.HasValue(parameters)) && (((Lhs.GetValue(parameters) as bool?) == true) || ((Rhs.GetValue(parameters) as bool?) == true))); } #endregion } public abstract class ComparableOperator : Operator { protected abstract bool CompareTo(IComparable comparable, object rhs); #region implemented abstract members of Operator public override bool Test(IParameters parameters) { IComparable comparable = Lhs.GetValue(parameters) as IComparable; if (comparable != null) { return CompareTo(comparable, Rhs.GetValue(parameters)); } else if (!Lhs.HasValue(parameters)) { return true; } throw new Exception("LessThanOperator left hand side does not implement IComparable"); } #endregion } public class LessThanOperator : ComparableOperator { #region implemented abstract members of ComparableOperator protected override bool CompareTo(IComparable comparable, object rhs) { int result = comparable.CompareTo(rhs); return result < 0; } #endregion } public class LessThanOrEqualToOperator : ComparableOperator { #region implemented abstract members of ComparableOperator protected override bool CompareTo(IComparable comparable, object rhs) { int result = comparable.CompareTo(rhs); return result <= 0; } #endregion } public class GreaterThanOperator : ComparableOperator { #region implemented abstract members of ComparableOperator protected override bool CompareTo(IComparable comparable, object rhs) { int result = comparable.CompareTo(rhs); return result > 0; } #endregion } public class GreaterThanOrEqualToOperator : ComparableOperator { #region implemented abstract members of ComparableOperator protected override bool CompareTo(IComparable comparable, object rhs) { int result = comparable.CompareTo(rhs); return result >= 0; } #endregion } /* public class Condition { public enum Operator { Equal, NotEqual, Contains, RateOfChangeGreaterThan, Duration } public string Name { get; set; } public Operator Comparison { get; set; } public string Value { get; set; } public double WindowSizeSecs { get; set; } public bool IsContinuous { get { return Comparison == Operator.RateOfChangeGreaterThan; } } public bool Test(IOperand operand, IOperandTimeline timeline = null) { if (operand[Name] == null) { return false; } switch (Comparison) { case Condition.Operator.Equal: if (object.Equals(Value, operand[Name])) { return true; } break; case Condition.Operator.NotEqual: if (!object.Equals(Value, operand[Name])) { return true; } break; case Condition.Operator.Contains: string contextValue = operand[Name] as String; if (contextValue != null && contextValue.Contains(Value)) { return true; } break; case Condition.Operator.RateOfChangeGreaterThan: IEnumerable<IOperand> window = timeline.GetWindow(WindowSizeSecs / 2, operand, Name, WindowSizeSecs / 2); if (window != null && window.First() != null) { object start = window.First()[Name]; object end = window.Last()[Name]; if (start != null && end != null) { double valueStart = Convert.ToDouble(start); double valueEnd = Convert.ToDouble(end); double rateOfChange = (valueEnd - valueStart) / WindowSizeSecs; if (rateOfChange > Convert.ToDouble(Value)) { return true; } } } break; case Condition.Operator.Duration: if (Convert.ToDouble(operand[Name]) >= Convert.ToDouble(Value)) { return true; } break; default: throw new Exception("Unsupported filter condition: " + Comparison.ToString()); } return false; } } */ }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace VisualCCommon { /// <summary> /// Meta data class for this package /// </summary> abstract class MetaData : Bam.Core.PackageMetaData, C.IToolchainDiscovery { /// <summary> /// Dictionary of key, object pairs that are the metadata. /// </summary> protected System.Collections.Generic.Dictionary<string, object> Meta = new System.Collections.Generic.Dictionary<string, object>(); /// <summary> /// Indexer into the metadata /// </summary> /// <param name="index">String index to use</param> /// <returns>Indexed result</returns> public override object this[string index] => this.Meta[index]; /// <summary> /// Does the meta data contain an index. /// </summary> /// <param name="index">String index to query</param> /// <returns>True if the meta data contains the index.</returns> public override bool Contains( string index) { return this.Meta.ContainsKey(index); } private void Findvswhere() { #if D_NUGET_NUGET_CLIENT && D_NUGET_VSWHERE var nugetHomeDir = NuGet.Common.NuGetEnvironment.GetFolderPath(NuGet.Common.NuGetFolderPath.NuGetHome); var nugetPackageDir = System.IO.Path.Combine(nugetHomeDir, "packages"); var repo = new NuGet.Repositories.NuGetv3LocalRepository(nugetPackageDir); var vswhereInstalls = repo.FindPackagesById("vswhere"); if (!vswhereInstalls.Any()) { // this should not happen as package restoration should handle this throw new Bam.Core.Exception("Unable to locate any NuGet package for vswhere"); } var visualCCommon = Bam.Core.Graph.Instance.Packages.First(item => item.Name.Equals("VisualCCommon", System.StringComparison.Ordinal)); var requiredVSWhere = visualCCommon.NuGetPackages.First(item => item.Identifier.Equals("vswhere", System.StringComparison.Ordinal)); var requestedVSWhere = vswhereInstalls.First(item => item.Version.ToNormalizedString().Equals(requiredVSWhere.Version, System.StringComparison.Ordinal)); var vswhere_tools_dir = System.IO.Path.Combine(requestedVSWhere.ExpandedPath, "tools"); var vswhere_exe_path = System.IO.Path.Combine(vswhere_tools_dir, "vswhere.exe"); if (!System.IO.File.Exists(vswhere_exe_path)) { throw new Bam.Core.Exception($"Unable to locate vswhere.exe from NuGet package at '{vswhere_exe_path}'"); } this.VswherePath = vswhere_exe_path; #endif } /// <summary> /// Get the vswhere install path /// </summary> /// <returns>Installation path</returns> protected string Vswhere_getinstallpath() { var package_version = Bam.Core.Graph.Instance.Packages.First(item => item.Name == "VisualC").Version; var major_version = System.Convert.ToInt32(package_version.Split('.').First()); try { var args = new System.Text.StringBuilder(); var legacy = major_version < 15; if (Bam.Core.CommandLineProcessor.Evaluate(new Options.DiscoverPrereleases())) { args.Append("-prerelease "); } args.Append("-property installationPath -version "); if (legacy) { // note the [] around the version to specify only that version args.Append($"[{major_version}] -legacy"); } else { // note the [) around the version and version+1 to consider only the minor-releases of that version args.Append($"[{major_version},{major_version + 1})"); } var installpath = Bam.Core.OSUtilities.RunExecutable( this.VswherePath, args.ToString() ).StandardOutput; if (System.String.IsNullOrEmpty(installpath)) { throw new Bam.Core.Exception( $"Unable to locate installation directory for Visual Studio major version {major_version} using '{this.VswherePath} {args.ToString()}'" ); } Bam.Core.Log.Info($"Using VisualStudio {major_version} installed at {installpath}"); return installpath; } catch (Bam.Core.RunExecutableException) { throw new Bam.Core.Exception( $"Unable to locate installation directory for Visual Studio major version {major_version}" ); } } private System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray> Execute_vcvars( C.EBit depth, bool hasNative64BitTools, Bam.Core.StringArray inherited_envvars, System.Collections.Generic.Dictionary<string, Bam.Core.StringArray> required_envvars ) { var startinfo = new System.Diagnostics.ProcessStartInfo { FileName = @"c:\Windows\System32\cmd.exe" }; startinfo.EnvironmentVariables.Clear(); if (null != inherited_envvars) { foreach (var inherited in inherited_envvars) { startinfo.EnvironmentVariables.Add(inherited, System.Environment.GetEnvironmentVariable(inherited)); } } if (null != required_envvars) { foreach (System.Collections.Generic.KeyValuePair<string, Bam.Core.StringArray> required in required_envvars) { if (startinfo.EnvironmentVariables.ContainsKey(required.Key)) { var existing_value = startinfo.EnvironmentVariables[required.Key]; var updated_value = $"{System.Environment.ExpandEnvironmentVariables(required.Value.ToString(';'))};{existing_value}"; startinfo.EnvironmentVariables[required.Key] = updated_value; } else { startinfo.EnvironmentVariables.Add(required.Key, System.Environment.ExpandEnvironmentVariables(required.Value.ToString(';'))); } } } startinfo.UseShellExecute = false; startinfo.RedirectStandardInput = true; startinfo.RedirectStandardOutput = true; startinfo.RedirectStandardError = true; string vcvarsall_command() { var command_and_args = new System.Text.StringBuilder(); command_and_args.Append("vcvarsall.bat "); switch (depth) { case C.EBit.ThirtyTwo: // amd64_x86 seems to be troublesome in terms of finding dependent DLLs, so ignore it command_and_args.Append("x86 "); break; case C.EBit.SixtyFour: { if (Bam.Core.OSUtilities.Is64BitHosting && hasNative64BitTools) { command_and_args.Append("amd64 "); } else { command_and_args.Append("x86_amd64 "); } } break; } // VisualC packages define their 'default' WindowsSDK package to function with // if this is different to what is being used, append the version fo the vcvarsall.bat command var visualC = Bam.Core.Graph.Instance.Packages.First(item => item.Name.Equals("VisualC", System.StringComparison.Ordinal)); var defaultWindowsSDKVersion = visualC.Dependents.First(item => item.Item1.Equals("WindowsSDK", System.StringComparison.Ordinal)).Item2; var windowsSDK = Bam.Core.Graph.Instance.Packages.FirstOrDefault(item => item.Name.Equals("WindowsSDK", System.StringComparison.Ordinal)); if (null != windowsSDK) { if (windowsSDK.Version != defaultWindowsSDKVersion) { command_and_args.Append($"{windowsSDK.Version} "); } else { var option_type = System.Type.GetType("WindowsSDK.Options.WindowsSDK10Version", throwOnError: false); if (null != option_type) { if (System.Activator.CreateInstance(option_type) is Bam.Core.IStringCommandLineArgument option_type_instance) { var win10Option = Bam.Core.CommandLineProcessor.Evaluate(option_type_instance); if (null != win10Option) { command_and_args.Append($"{win10Option} "); } } } } } return command_and_args.ToString(); } var environment_generator_cmdline = System.String.Empty; // allow the WindowsSDK to provide an alternative mechanism for generating // and environment in which to execute VisualC and WindowsSDK tools var windowssdk_meta = Bam.Core.Graph.Instance.PackageMetaData<WindowsSDK.MetaData>("WindowsSDK"); if (windowssdk_meta.Contains("setenvdir") && windowssdk_meta.Contains("setenvcmd")) { startinfo.WorkingDirectory = windowssdk_meta["setenvdir"] as string; environment_generator_cmdline = windowssdk_meta["setenvcmd"] as string; switch (depth) { case C.EBit.ThirtyTwo: environment_generator_cmdline += " /x86"; break; case C.EBit.SixtyFour: environment_generator_cmdline += " /x64"; break; } } else { startinfo.WorkingDirectory = System.IO.Path.Combine(this.InstallDir.ToString(), this.Subpath_to_vcvars); environment_generator_cmdline = vcvarsall_command(); } // allow the WindowsSDK to override the VisualStudio project's PlatformToolset if (windowssdk_meta.Contains("PlatformToolset")) { var vc_meta = Bam.Core.Graph.Instance.PackageMetaData<VisualC.MetaData>("VisualC"); vc_meta.PlatformToolset = windowssdk_meta["PlatformToolset"] as string; } var arguments = new System.Text.StringBuilder(); arguments.Append($"/C {environment_generator_cmdline} && SET"); startinfo.Arguments = arguments.ToString(); var process = new System.Diagnostics.Process(); process.StartInfo = startinfo; // if you don't async read the output, then the process will never finish // as the buffer is filled up // EOLs will also be trimmed from these, so always append whole lines var stdout = new System.Text.StringBuilder(); process.OutputDataReceived += (sender, args) => stdout.AppendLine(args.Data); var stderr = new System.Text.StringBuilder(); process.ErrorDataReceived += (sender, args) => stderr.AppendLine(args.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.StandardInput.Close(); process.WaitForExit(); if (process.ExitCode != 0) { throw new Bam.Core.Exception($"{environment_generator_cmdline} failed: {stderr.ToString()}"); } var env = new System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray>(); var lines = stdout.ToString().Split( new[] { System.Environment.NewLine }, System.StringSplitOptions.RemoveEmptyEntries ); foreach (var line in lines) { Bam.Core.Log.DebugMessage($"{environment_generator_cmdline}->{line}"); var equals_index = line.IndexOf('='); if (-1 == equals_index) { continue; } var key = line.Remove(equals_index); var value = line.Remove(0, equals_index + 1); if (System.String.IsNullOrEmpty(key) || System.String.IsNullOrEmpty(value)) { continue; } var splitValue = value.Split(new[] { ';' }); var valueArray = new Bam.Core.TokenizedStringArray(); foreach (var v in splitValue) { valueArray.Add(Bam.Core.TokenizedString.CreateVerbatim(v)); } env.Add(key, valueArray); } Bam.Core.Log.Info( $@"Generating {(int)depth}-bit build environment using '{startinfo.WorkingDirectory}\{environment_generator_cmdline.TrimEnd()}'" ); foreach (System.Collections.Generic.KeyValuePair<string, Bam.Core.TokenizedStringArray> entry in env) { Bam.Core.Log.DebugMessage($"\t{entry.Key} = {entry.Value.ToString(';')}"); } return env; } /// <summary> /// Get the environment variables to apply to tools /// </summary> /// <param name="depth">Bit depth of tool</param> /// <param name="hasNative64BitTools">Does the toolchain have native 64-bit tools?</param> /// <param name="inherited_envvars">Optional, array of environment variables to inherit from the system. Default is null.</param> /// <param name="required_envvars">Optional, dictionary of environment variables to set. Default is null.</param> protected void Get_tool_environment_variables( C.EBit depth, bool hasNative64BitTools, Bam.Core.StringArray inherited_envvars = null, System.Collections.Generic.Dictionary<string, Bam.Core.StringArray> required_envvars = null) { // for 'reg' used in vcvarsall subroutines if (null == required_envvars) { required_envvars = new System.Collections.Generic.Dictionary<string, Bam.Core.StringArray>(); } if (required_envvars.ContainsKey("PATH")) { var existing = required_envvars["PATH"]; existing.AddUnique("%WINDIR%\\System32"); required_envvars["PATH"] = existing; } else { required_envvars.Add("PATH", new Bam.Core.StringArray { "%WINDIR%\\System32" }); } // VsDevCmd.bat in VS2019+ tries to invoke powershell.exe to send telemetry // which can cause non-interactive continuous integration to halt indefinitely // because a dialog is opened if powershell cannot be found // disabling telemetry avoids this issue required_envvars.Add("VSCMD_SKIP_SENDTELEMETRY", new Bam.Core.StringArray { "1" }); // for WindowsSDK-7.1 if (null == inherited_envvars) { inherited_envvars = new Bam.Core.StringArray(); } inherited_envvars.AddUnique("PROCESSOR_ARCHITECTURE"); var env = this.Execute_vcvars( depth, hasNative64BitTools, inherited_envvars, required_envvars ); this.Meta.Add(EnvironmentKey(depth), env); } /// <summary> /// Get or set the installation directory for VisualStudio /// </summary> public Bam.Core.TokenizedString InstallDir { get { return this.Meta["InstallDir"] as Bam.Core.TokenizedString; } protected set { this.Meta["InstallDir"] = value; } } static private string EnvironmentKey( C.EBit depth) { switch (depth) { case C.EBit.ThirtyTwo: return "Environment32"; case C.EBit.SixtyFour: return "Environment64"; default: throw new Bam.Core.Exception($"Unknown bit depth, {depth.ToString()}"); } } /// <summary> /// Get the environment variables for the given bitdepth /// </summary> /// <param name="depth">Bit depth</param> /// <returns>Environment variable dictionary</returns> public System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray> Environment( C.EBit depth) { var environmentKey = EnvironmentKey(depth); if (!this.Meta.ContainsKey(environmentKey)) { return new System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray>(); } return this.Meta[environmentKey] as System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray>; } private string VswherePath { get; set; } /// <summary> /// Get the toolchain version /// </summary> public C.ToolchainVersion ToolchainVersion { get { return this.Meta["ToolchainVersion"] as C.ToolchainVersion; } private set { this.Meta["ToolchainVersion"] = value; } } /// <summary> /// Get the sub-path to where vcvars.bat resides /// </summary> protected abstract string Subpath_to_vcvars { get; } /// <summary> /// Whether there are native 64-bit tools available /// </summary> protected virtual bool HasNative64BitTools => true; private static bool report_WindowsSDK_done = false; private static void Report_WindowsSDK( System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray> env, C.EBit depth) { // only need to report it once, not for each environment if (report_WindowsSDK_done) { return; } report_WindowsSDK_done = true; var report = new System.Text.StringBuilder(); report.Append("Using WindowsSDK "); if (env.ContainsKey("WindowsSDKVersion")) { // the WindowsSDKVersion environment variable has a trailing back slash var version = env["WindowsSDKVersion"].ToString(); version = version.TrimEnd(System.IO.Path.DirectorySeparatorChar); report.Append($"version {version} "); } var winsdk_installdir = System.String.Empty; if (env.ContainsKey("WindowsSdkDir")) { // WindowsSDK 7.0A, 8.1 has this form winsdk_installdir = env["WindowsSdkDir"].ToString(); } else if (env.ContainsKey("WindowsSDKDir")) { // WindowsSDK 7.1 has this form winsdk_installdir = env["WindowsSDKDir"].ToString(); } else { throw new Bam.Core.Exception( $"Unable to locate WindowsSDK installation directory environment variable for {(int)depth}-bit builds" ); } report.Append($"installed at {winsdk_installdir} "); if (env.ContainsKey("UniversalCRTSdkDir") && env.ContainsKey("UCRTVersion")) { var ucrt_installdir = env["UniversalCRTSdkDir"].ToString(); if (ucrt_installdir != winsdk_installdir) { report.Append($"with UniversalCRT SDK {env["UCRTVersion"].ToString()} installed at {ucrt_installdir} "); } } Bam.Core.Log.Info(report.ToString()); } private C.ToolchainVersion GetCompilerVersion() { var temp_file = System.IO.Path.GetTempFileName(); System.IO.File.WriteAllText(temp_file, "_MSC_VER"); var result = Bam.Core.OSUtilities.RunExecutable( System.IO.Path.Combine( System.IO.Path.Combine( this.InstallDir.ToString(), this.Subpath_to_vcvars ), "vcvarsall.bat" ), $"x86 && cl /EP /nologo {temp_file}" ); var mscver = result.StandardOutput.Split(System.Environment.NewLine.ToCharArray()).Reverse().First(); return VisualCCommon.ToolchainVersion.FromMSCVer(System.Convert.ToInt32(mscver)); } void C.IToolchainDiscovery.Discover( C.EBit? depth) { if (null == this.VswherePath) { this.Findvswhere(); } if (!this.Meta.ContainsKey("InstallDir")) { var install_dir = this.Vswhere_getinstallpath(); if (install_dir.Contains(System.Environment.NewLine)) { throw new Bam.Core.Exception( $"Multiple install directories were detected for VisualStudio:{System.Environment.NewLine}{install_dir}" ); } this.InstallDir = Bam.Core.TokenizedString.CreateVerbatim(install_dir); } var bitdepth = depth.Value; if (!this.Meta.ContainsKey(EnvironmentKey(bitdepth))) { this.Get_tool_environment_variables( bitdepth, this.HasNative64BitTools ); Report_WindowsSDK(this.Environment(bitdepth), bitdepth); } if (!this.Meta.ContainsKey("ToolchainVersion")) { this.ToolchainVersion = this.GetCompilerVersion(); } var runtimeChoice = Bam.Core.CommandLineProcessor.Evaluate(new Options.Runtime()); if (runtimeChoice.Any()) { switch (runtimeChoice.First().First()) { case "MD": this.RuntimeLibrary = ERuntimeLibrary.MultiThreadedDLL; break; case "MDd": this.RuntimeLibrary = ERuntimeLibrary.MultiThreadedDebugDLL; break; case "MT": this.RuntimeLibrary = ERuntimeLibrary.MultiThreaded; break; case "MTd": this.RuntimeLibrary = ERuntimeLibrary.MultiThreadedDebug; break; default: throw new Bam.Core.Exception($"Unknown runtime library type: {runtimeChoice.First().First()}"); } } if (!this.Meta.ContainsKey("RuntimeLibrary")) { this.RuntimeLibrary = ERuntimeLibrary.MultiThreadedDLL; } } /// <summary> /// Get or set the runtime library to use /// </summary> public ERuntimeLibrary RuntimeLibrary { get { return (ERuntimeLibrary)this.Meta["RuntimeLibrary"]; } set { this.Meta["RuntimeLibrary"] = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using System.Linq; #if MS_IO_REDIST using Microsoft.IO.Enumeration; namespace Microsoft.IO #else using System.IO.Enumeration; namespace System.IO #endif { public sealed partial class DirectoryInfo : FileSystemInfo { public DirectoryInfo(string path) { Init(originalPath: path, fullPath: Path.GetFullPath(path), isNormalized: true); } internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false) { Init(originalPath, fullPath, fileName, isNormalized); } private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false) { // Want to throw the original argument name OriginalPath = originalPath ?? throw new ArgumentNullException("path"); fullPath = fullPath ?? originalPath; fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath); _name = fileName ?? (PathInternal.IsRoot(fullPath.AsSpan()) ? fullPath.AsSpan() : Path.GetFileName(PathInternal.TrimEndingDirectorySeparator(fullPath.AsSpan()))).ToString(); FullPath = fullPath; } public DirectoryInfo Parent { get { // FullPath might end in either "parent\child" or "parent\child\", and in either case we want // the parent of child, not the child. Trim off an ending directory separator if there is one, // but don't mangle the root. string parentName = Path.GetDirectoryName(PathInternal.IsRoot(FullPath.AsSpan()) ? FullPath : PathInternal.TrimEndingDirectorySeparator(FullPath)); return parentName != null ? new DirectoryInfo(parentName, isNormalized: true) : null; } } public DirectoryInfo CreateSubdirectory(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Argument_PathEmpty, nameof(path)); if (Path.IsPathRooted(path)) throw new ArgumentException(SR.Arg_Path2IsRooted, nameof(path)); string newPath = Path.GetFullPath(Path.Combine(FullPath, path)); ReadOnlySpan<char> trimmedNewPath = PathInternal.TrimEndingDirectorySeparator(newPath.AsSpan()); ReadOnlySpan<char> trimmedCurrentPath = PathInternal.TrimEndingDirectorySeparator(FullPath.AsSpan()); // We want to make sure the requested directory is actually under the subdirectory. if (trimmedNewPath.StartsWith(trimmedCurrentPath, PathInternal.StringComparison) // Allow the exact same path, but prevent allowing "..\FooBar" through when the directory is "Foo" && ((trimmedNewPath.Length == trimmedCurrentPath.Length) || PathInternal.IsDirectorySeparator(newPath[trimmedCurrentPath.Length]))) { FileSystem.CreateDirectory(newPath); return new DirectoryInfo(newPath); } // We weren't nested throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, FullPath), nameof(path)); } public void Create() => FileSystem.CreateDirectory(FullPath); // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() => GetFiles("*", enumerationOptions: EnumerationOptions.Compatible); // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (i.e. "*.txt"). public FileInfo[] GetFiles(string searchPattern) => GetFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption) => GetFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public FileInfo[] GetFiles(string searchPattern, EnumerationOptions enumerationOptions) => ((IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions)).ToArray(); // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() => GetFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible); // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (i.e. "*.txt"). public FileSystemInfo[] GetFileSystemInfos(string searchPattern) => GetFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption) => GetFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public FileSystemInfo[] GetFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) => InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions).ToArray(); // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() => GetDirectories("*", enumerationOptions: EnumerationOptions.Compatible); // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (i.e. "System*" could match the System & System32 directories). public DirectoryInfo[] GetDirectories(string searchPattern) => GetDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption) => GetDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public DirectoryInfo[] GetDirectories(string searchPattern, EnumerationOptions enumerationOptions) => ((IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions)).ToArray(); public IEnumerable<DirectoryInfo> EnumerateDirectories() => EnumerateDirectories("*", enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern) => EnumerateDirectories(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption) => EnumerateDirectories(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, EnumerationOptions enumerationOptions) => (IEnumerable<DirectoryInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Directories, enumerationOptions); public IEnumerable<FileInfo> EnumerateFiles() => EnumerateFiles("*", enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileInfo> EnumerateFiles(string searchPattern) => EnumerateFiles(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption) => EnumerateFiles(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, EnumerationOptions enumerationOptions) => (IEnumerable<FileInfo>)InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Files, enumerationOptions); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() => EnumerateFileSystemInfos("*", enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern) => EnumerateFileSystemInfos(searchPattern, enumerationOptions: EnumerationOptions.Compatible); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption) => EnumerateFileSystemInfos(searchPattern, EnumerationOptions.FromSearchOption(searchOption)); public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, EnumerationOptions enumerationOptions) => InternalEnumerateInfos(FullPath, searchPattern, SearchTarget.Both, enumerationOptions); internal static IEnumerable<FileSystemInfo> InternalEnumerateInfos( string path, string searchPattern, SearchTarget searchTarget, EnumerationOptions options) { Debug.Assert(path != null); if (searchPattern == null) throw new ArgumentNullException(nameof(searchPattern)); FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options); switch (searchTarget) { case SearchTarget.Directories: return FileSystemEnumerableFactory.DirectoryInfos(path, searchPattern, options); case SearchTarget.Files: return FileSystemEnumerableFactory.FileInfos(path, searchPattern, options); case SearchTarget.Both: return FileSystemEnumerableFactory.FileSystemInfos(path, searchPattern, options); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } public DirectoryInfo Root => new DirectoryInfo(Path.GetPathRoot(FullPath)); public void MoveTo(string destDirName) { if (destDirName == null) throw new ArgumentNullException(nameof(destDirName)); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName)); string destination = Path.GetFullPath(destDirName); string destinationWithSeparator = PathInternal.EnsureTrailingSeparator(destination); string sourceWithSeparator = PathInternal.EnsureTrailingSeparator(FullPath); if (string.Equals(sourceWithSeparator, destinationWithSeparator, PathInternal.StringComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); string sourceRoot = Path.GetPathRoot(sourceWithSeparator); string destinationRoot = Path.GetPathRoot(destinationWithSeparator); if (!string.Equals(sourceRoot, destinationRoot, PathInternal.StringComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); // Windows will throw if the source file/directory doesn't exist, we preemptively check // to make sure our cross platform behavior matches NetFX behavior. if (!Exists && !FileSystem.FileExists(FullPath)) throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath)); if (FileSystem.DirectoryExists(destination)) throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator)); FileSystem.MoveDirectory(FullPath, destination); Init(originalPath: destDirName, fullPath: destinationWithSeparator, fileName: _name, isNormalized: true); // Flush any cached information about the directory. Invalidate(); } public override void Delete() => FileSystem.RemoveDirectory(FullPath, recursive: false); public void Delete(bool recursive) => FileSystem.RemoveDirectory(FullPath, recursive); } }
// 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.Threading.Tasks; using System.IO; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Http.Headers; using System.Diagnostics.Contracts; using System.Text; namespace System.Net.Http { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Represents a multipart/* content. Even if a collection of HttpContent is stored, " + "suffix Collection is not appropriate.")] public class MultipartContent : HttpContent, IEnumerable<HttpContent> { #region Fields private const string crlf = "\r\n"; private List<HttpContent> _nestedContent; private string _boundary; // Temp context for serialization. private int _nextContentIndex; private Stream _outputStream; private TaskCompletionSource<Object> _tcs; #endregion Fields #region Construction public MultipartContent() : this("mixed", GetDefaultBoundary()) { } public MultipartContent(string subtype) : this(subtype, GetDefaultBoundary()) { } public MultipartContent(string subtype, string boundary) { if (string.IsNullOrWhiteSpace(subtype)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(subtype)); } Contract.EndContractBlock(); ValidateBoundary(boundary); _boundary = boundary; string quotedBoundary = boundary; if (!quotedBoundary.StartsWith("\"", StringComparison.Ordinal)) { quotedBoundary = "\"" + quotedBoundary + "\""; } MediaTypeHeaderValue contentType = new MediaTypeHeaderValue("multipart/" + subtype); contentType.Parameters.Add(new NameValueHeaderValue(nameof(boundary), quotedBoundary)); Headers.ContentType = contentType; _nestedContent = new List<HttpContent>(); } private static void ValidateBoundary(string boundary) { // NameValueHeaderValue is too restrictive for boundary. // Instead validate it ourselves and then quote it. if (string.IsNullOrWhiteSpace(boundary)) { throw new ArgumentException(SR.net_http_argument_empty_string, nameof(boundary)); } // RFC 2046 Section 5.1.1 // boundary := 0*69<bchars> bcharsnospace // bchars := bcharsnospace / " " // bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?" if (boundary.Length > 70) { throw new ArgumentOutOfRangeException(nameof(boundary), boundary, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70)); } // Cannot end with space. if (boundary.EndsWith(" ", StringComparison.Ordinal)) { throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary)); } Contract.EndContractBlock(); string allowedMarks = @"'()+_,-./:=? "; foreach (char ch in boundary) { if (('0' <= ch && ch <= '9') || // Digit. ('a' <= ch && ch <= 'z') || // alpha. ('A' <= ch && ch <= 'Z') || // ALPHA. (allowedMarks.IndexOf(ch) >= 0)) // Marks. { // Valid. } else { throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), nameof(boundary)); } } } private static string GetDefaultBoundary() { return Guid.NewGuid().ToString(); } public virtual void Add(HttpContent content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } Contract.EndContractBlock(); _nestedContent.Add(content); } #endregion Construction #region Dispose protected override void Dispose(bool disposing) { if (disposing) { foreach (HttpContent content in _nestedContent) { content.Dispose(); } _nestedContent.Clear(); } base.Dispose(disposing); } #endregion Dispose #region IEnumerable<HttpContent> Members public IEnumerator<HttpContent> GetEnumerator() { return _nestedContent.GetEnumerator(); } #endregion #region IEnumerable Members Collections.IEnumerator Collections.IEnumerable.GetEnumerator() { return _nestedContent.GetEnumerator(); } #endregion #region Serialization // for-each content // write "--" + boundary // for-each content header // write header: header-value // write content.CopyTo[Async] // write "--" + boundary + "--" // Can't be canceled directly by the user. If the overall request is canceled // then the stream will be closed an an exception thrown. protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { Debug.Assert(stream != null); Debug.Assert(_outputStream == null, "Opperation already in progress"); Debug.Assert(_tcs == null, "Opperation already in progress"); Debug.Assert(_nextContentIndex == 0, "Opperation already in progress"); // Keep a local copy in case the operation completes and cleans up synchronously. TaskCompletionSource<Object> localTcs = new TaskCompletionSource<Object>(); _tcs = localTcs; _outputStream = stream; _nextContentIndex = 0; // Start Boundary, chain everything else. EncodeStringToStreamAsync(_outputStream, "--" + _boundary + crlf) .ContinueWithStandard(WriteNextContentHeadersAsync); return localTcs.Task; } private void WriteNextContentHeadersAsync(Task task) { if (task.IsFaulted) { HandleAsyncException("WriteNextContentHeadersAsync", task.Exception.GetBaseException()); return; } try { // Base case, no more content, finish. if (_nextContentIndex >= _nestedContent.Count) { WriteTerminatingBoundaryAsync(); return; } string internalBoundary = crlf + "--" + _boundary + crlf; StringBuilder output = new StringBuilder(); if (_nextContentIndex == 0) { // First time, don't write dividing boundary. } else { output.Append(internalBoundary); } HttpContent content = _nestedContent[_nextContentIndex]; // Headers foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { output.Append(headerPair.Key + ": " + string.Join(", ", headerPair.Value) + crlf); } output.Append(crlf); // Extra CRLF to end headers (even if there are no headers). EncodeStringToStreamAsync(_outputStream, output.ToString()) .ContinueWithStandard(WriteNextContentAsync); } catch (Exception ex) { HandleAsyncException("WriteNextContentHeadersAsync", ex); } } private void WriteNextContentAsync(Task task) { if (task.IsFaulted) { HandleAsyncException("WriteNextContentAsync", task.Exception.GetBaseException()); return; } try { HttpContent content = _nestedContent[_nextContentIndex]; _nextContentIndex++; // Next call will operate on the next content object. content.CopyToAsync(_outputStream) .ContinueWithStandard(WriteNextContentHeadersAsync); } catch (Exception ex) { HandleAsyncException("WriteNextContentAsync", ex); } } // Final step, write the footer boundary. private void WriteTerminatingBoundaryAsync() { try { EncodeStringToStreamAsync(_outputStream, crlf + "--" + _boundary + "--" + crlf) .ContinueWithStandard(task => { if (task.IsFaulted) { HandleAsyncException("WriteTerminatingBoundaryAsync", task.Exception.GetBaseException()); return; } TaskCompletionSource<object> lastTcs = CleanupAsync(); lastTcs.TrySetResult(null); // This was the final opperation. }); } catch (Exception ex) { HandleAsyncException("WriteTerminatingBoundaryAsync", ex); } } private static Task EncodeStringToStreamAsync(Stream stream, string input) { byte[] buffer = HttpRuleParser.DefaultHttpEncoding.GetBytes(input); return stream.WriteAsync(buffer, 0, buffer.Length); } private TaskCompletionSource<object> CleanupAsync() { Contract.Requires(_tcs != null, "Operation already cleaned up"); TaskCompletionSource<object> toReturn = _tcs; _outputStream = null; _nextContentIndex = 0; _tcs = null; return toReturn; } private void HandleAsyncException(string method, Exception ex) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, method, ex); TaskCompletionSource<object> lastTcs = CleanupAsync(); lastTcs.TrySetException(ex); } protected internal override bool TryComputeLength(out long length) { long currentLength = 0; long internalBoundaryLength = GetEncodedLength(crlf + "--" + _boundary + crlf); // Start Boundary. currentLength += GetEncodedLength("--" + _boundary + crlf); bool first = true; foreach (HttpContent content in _nestedContent) { if (first) { first = false; // First boundary already written. } else { // Internal Boundary. currentLength += internalBoundaryLength; } // Headers. foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers) { currentLength += GetEncodedLength(headerPair.Key + ": " + string.Join(", ", headerPair.Value) + crlf); } currentLength += crlf.Length; // Content. long tempContentLength = 0; if (!content.TryComputeLength(out tempContentLength)) { length = 0; return false; } currentLength += tempContentLength; } // Terminating boundary. currentLength += GetEncodedLength(crlf + "--" + _boundary + "--" + crlf); length = currentLength; return true; } private static int GetEncodedLength(string input) { return HttpRuleParser.DefaultHttpEncoding.GetByteCount(input); } #endregion Serialization } }
using System; using System.Threading.Tasks; using System.Web; using System.Net; using System.Text; using System.IO; using System.Threading; using System.Collections.Generic; using System.Security.Cryptography; using System.ComponentModel; using SteamBot.SteamGroups; using SteamKit2; using SteamTrade; using SteamKit2.Internal; using SteamTrade.TradeOffer; using System.Globalization; using System.Text.RegularExpressions; namespace SteamBot { public class Bot : IDisposable { #region Bot delegates public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); #endregion #region Private readonly variables private readonly SteamUser.LogOnDetails logOnDetails; private readonly string schemaLang; private readonly string logFile; private readonly Dictionary<SteamID, UserHandler> userHandlers; private readonly Log.LogLevel consoleLogLevel; private readonly Log.LogLevel fileLogLevel; private readonly UserHandlerCreator createHandler; private readonly bool isProccess; private readonly BackgroundWorker botThread; #endregion #region Private variables private Task<Inventory> myInventoryTask; private TradeManager tradeManager; private TradeOfferManager tradeOfferManager; private int tradePollingInterval; private int tradeOfferPollingIntervalSecs; private string myUserNonce; private string myUniqueId; private bool cookiesAreInvalid = true; private List<SteamID> friends; private bool disposed = false; private string consoleInput; private Thread tradeOfferThread; #endregion #region Public readonly variables /// <summary> /// Userhandler class bot is running. /// </summary> public readonly string BotControlClass; /// <summary> /// The display name of bot to steam. /// </summary> public readonly string DisplayName; /// <summary> /// The chat response from the config file. /// </summary> public readonly string ChatResponse; /// <summary> /// An array of admins for bot. /// </summary> public readonly IEnumerable<SteamID> Admins; public readonly SteamClient SteamClient; public readonly SteamUser SteamUser; public readonly SteamFriends SteamFriends; public readonly SteamTrading SteamTrade; public readonly SteamGameCoordinator SteamGameCoordinator; public readonly SteamNotifications SteamNotifications; /// <summary> /// The amount of time the bot will trade for. /// </summary> public readonly int MaximumTradeTime; /// <summary> /// The amount of time the bot will wait between user interactions with trade. /// </summary> public readonly int MaximumActionGap; /// <summary> /// The api key of bot. /// </summary> public readonly string ApiKey; public readonly SteamWeb SteamWeb; /// <summary> /// The prefix shown before bot's display name. /// </summary> public readonly string DisplayNamePrefix; /// <summary> /// The instance of the Logger for the bot. /// </summary> public readonly Log Log; #endregion #region Public variables public string AuthCode; public bool IsRunning; /// <summary> /// Is bot fully Logged in. /// Set only when bot did successfully Log in. /// </summary> public bool IsLoggedIn { get; private set; } /// <summary> /// The current trade the bot is in. /// </summary> public Trade CurrentTrade { get; private set; } /// <summary> /// The current game bot is in. /// Default: 0 = No game. /// </summary> public int CurrentGame { get; private set; } public SteamAuth.SteamGuardAccount SteamGuardAccount; #endregion public IEnumerable<SteamID> FriendsList { get { CreateFriendsListIfNecessary(); return friends; } } public Inventory MyInventory { get { myInventoryTask.Wait(); return myInventoryTask.Result; } } /// <summary> /// Compatibility sanity. /// </summary> [Obsolete("Refactored to be Log instead of log")] public Log log { get { return Log; } } public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false) { userHandlers = new Dictionary<SteamID, UserHandler>(); logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; tradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; tradeOfferPollingIntervalSecs = (config.TradeOfferPollingIntervalSecs == 0 ? 30 : config.TradeOfferPollingIntervalSecs); schemaLang = config.SchemaLang != null && config.SchemaLang.Length == 2 ? config.SchemaLang.ToLower() : "en"; Admins = config.Admins; ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; isProccess = process; try { if( config.LogLevel != null ) { consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName); } else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); consoleLogLevel = Log.LogLevel.Info; } try { fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true); } catch (ArgumentException) { Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName); fileLogLevel = Log.LogLevel.Info; } logFile = config.LogFile; Log = new Log(logFile, DisplayName, consoleLogLevel, fileLogLevel); createHandler = handlerCreator; BotControlClass = config.BotControlClass; SteamWeb = new SteamWeb(); // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; Log.Debug ("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamClient.AddHandler(new SteamNotifications()); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); SteamNotifications = SteamClient.GetHandler<SteamNotifications>(); botThread = new BackgroundWorker { WorkerSupportsCancellation = true }; botThread.DoWork += BackgroundWorkerOnDoWork; botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; } ~Bot() { Dispose(false); } private void CreateFriendsListIfNecessary() { if (friends != null) return; friends = new List<SteamID>(); for (int i = 0; i < SteamFriends.GetFriendCount(); i++) friends.Add(SteamFriends.GetFriendByIndex(i)); } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <remarks> /// THIS NEVER RETURNS. /// </remarks> /// <returns><c>true</c>. See remarks</returns> public bool StartBot() { IsRunning = true; Log.Info("Connecting..."); if (!botThread.IsBusy) botThread.RunWorkerAsync(); SteamClient.Connect(); Log.Success("Done Loading Bot!"); return true; // never get here } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; Log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); botThread.CancelAsync(); while (botThread.IsBusy) Thread.Yield(); userHandlers.Clear(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade (SteamID other) { if (CurrentTrade != null || CheckCookies() == false) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade (GetUserHandler (CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade (); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.TryGetOffer(offerId, out tradeOffer); } public void HandleBotCommand(string command) { try { if (command == "linkauth") { LinkMobileAuth(); } else if (command == "getauth") { try { Log.Success("Generated Steam Guard code: " + SteamGuardAccount.GenerateSteamGuardCode()); } catch (NullReferenceException) { Log.Error("Unable to generate Steam Guard code."); } } else if (command == "unlinkauth") { if (SteamGuardAccount == null) { Log.Error("Mobile authenticator is not active on this bot."); } else if (SteamGuardAccount.DeactivateAuthenticator()) { Log.Success("Deactivated authenticator on this account."); } else { Log.Error("Failed to deactivate authenticator on this account."); } } else { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed Log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } protected void SpawnTradeOfferPollingThread() { if (tradeOfferThread == null) { tradeOfferThread = new Thread(TradeOfferPollingFunction); tradeOfferThread.Start(); } } protected void CancelTradeOfferPollingThread() { tradeOfferThread = null; } protected void TradeOfferPollingFunction() { while (tradeOfferThread == Thread.CurrentThread) { try { tradeOfferManager.EnqueueUpdatedOffers(); } catch (Exception e) { Log.Error("Error while polling trade offers: " + e); } Thread.Sleep(tradeOfferPollingIntervalSecs*1000); } } public void HandleInput(string input) { consoleInput = input; } public string WaitForInput() { consoleInput = null; while (true) { if (consoleInput != null) { return consoleInput; } Thread.Sleep(5); } } bool HandleTradeSessionStart (SteamID other) { if (CurrentTrade != null) return false; try { tradeManager.InitializeTrade(SteamUser.SteamID, other); CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. /*string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); Log.Info ("Bot sent other: {0}", response); CurrentTrade = null;*/ return false; } } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } void HandleSteamMessage(ICallbackMsg msg) { Log.Debug(msg.ToString()); #region Login msg.Handle<SteamClient.ConnectedCallback> (callback => { Log.Debug ("Connection Callback: {0}", callback.Result); if (callback.Result == EResult.OK) { UserLogOn(); } else { Log.Error ("Failed to connect to Steam Community, trying again..."); SteamClient.Connect (); } }); msg.Handle<SteamUser.LoggedOnCallback> (callback => { Log.Debug("Logged On Callback: {0}", callback.Result); if (callback.Result == EResult.OK) { myUserNonce = callback.WebAPIUserNonce; } else { Log.Error("Login Error: {0}", callback.Result); } if (callback.Result == EResult.AccountLogonDeniedNeedTwoFactorCode) { var mobileAuthCode = GetMobileAuthCode(); if (string.IsNullOrEmpty(mobileAuthCode)) { Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot."); } else { logOnDetails.TwoFactorCode = mobileAuthCode; Log.Success("Generated 2FA code."); } } else if (callback.Result == EResult.TwoFactorCodeMismatch) { SteamAuth.TimeAligner.AlignTime(); logOnDetails.TwoFactorCode = SteamGuardAccount.GenerateSteamGuardCode(); Log.Success("Regenerated 2FA code."); } else if (callback.Result == EResult.AccountLogonDenied) { Log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } else if (callback.Result == EResult.InvalidLoginAuthCode) { Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); msg.Handle<SteamUser.LoginKeyCallback> (callback => { myUniqueId = callback.UniqueID.ToString(); UserWebLogOn(); if (Trade.CurrentSchema == null) { Log.Info ("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema (ApiKey, schemaLang); Log.Success ("Schema Downloaded!"); } SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName); SteamFriends.SetPersonaState (EPersonaState.Online); Log.Success ("Steam Bot Logged In Completely!"); GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); msg.Handle<SteamUser.WebAPIUserNonceCallback>(webCallback => { Log.Debug("Received new WebAPIUserNonce."); if (webCallback.Result == EResult.OK) { myUserNonce = webCallback.Nonce; UserWebLogOn(); } else { Log.Error("WebAPIUserNonce Error: " + webCallback.Result); } }); msg.Handle<SteamUser.UpdateMachineAuthCallback>( authCallback => OnUpdateMachineAuthCallback(authCallback) ); #endregion #region Friends msg.Handle<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { switch (friend.SteamID.AccountType) { case EAccountType.Clan: if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } break; default: CreateFriendsListIfNecessary(); if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); RemoveUserHandler(friend.SteamID); } else if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnFriendAdd()) { if (!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); } SteamFriends.AddFriend(friend.SteamID); } else { if(friends.Contains(friend.SteamID)) { friends.Remove(friend.SteamID); } SteamFriends.RemoveFriend(friend.SteamID); RemoveUserHandler(friend.SteamID); } } break; } } }); msg.Handle<SteamFriends.FriendMsgCallback> (callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { Log.Info ("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName (callback.Sender), callback.Message ); GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type); } }); #endregion #region Group Chat msg.Handle<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading msg.Handle<SteamTrading.SessionStartCallback> (callback => { bool started = HandleTradeSessionStart (callback.OtherClient); if (!started) Log.Error ("Could not start the trade session."); else Log.Debug ("SteamTrading.SessionStartCallback handled successfully. Trade Opened."); }); msg.Handle<SteamTrading.TradeProposedCallback> (callback => { if (CheckCookies() == false) { SteamTrade.RespondToTrade(callback.TradeID, false); return; } try { tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient); } catch (WebException we) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade error: " + we.Message); SteamTrade.RespondToTrade(callback.TradeID, false); return; } catch (Exception) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade declined. Could not correctly fetch your backpack."); SteamTrade.RespondToTrade(callback.TradeID, false); return; } //if (tradeManager.OtherInventory.IsPrivate) //{ // SteamFriends.SendChatMessage(callback.OtherClient, // EChatEntryType.ChatMsg, // "Trade declined. Your backpack cannot be private."); // SteamTrade.RespondToTrade (callback.TradeID, false); // return; //} if (CurrentTrade == null && GetUserHandler (callback.OtherClient).OnTradeRequest ()) SteamTrade.RespondToTrade (callback.TradeID, true); else SteamTrade.RespondToTrade (callback.TradeID, false); }); msg.Handle<SteamTrading.TradeResultCallback> (callback => { if (callback.Response == EEconTradeResponse.Accepted) { Log.Debug("Trade Status: {0}", callback.Response); Log.Info ("Trade Accepted!"); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { Log.Warn("Trade failed: {0}", callback.Response); CloseTrade (); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect msg.Handle<SteamUser.LoggedOffCallback> (callback => { IsLoggedIn = false; Log.Warn("Logged off Steam. Reason: {0}", callback.Result); CancelTradeOfferPollingThread(); }); msg.Handle<SteamClient.DisconnectedCallback> (callback => { if(IsLoggedIn) { IsLoggedIn = false; CloseTrade(); Log.Warn("Disconnected from Steam Network!"); CancelTradeOfferPollingThread(); } SteamClient.Connect (); }); #endregion #region Notifications msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //Log.Info("received CommentNotificationCallback"); //Log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //Log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //Log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); }); #endregion } string GetMobileAuthCode() { var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username)); if (File.Exists(authFile)) { SteamGuardAccount = Newtonsoft.Json.JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(File.ReadAllText(authFile)); return SteamGuardAccount.GenerateSteamGuardCode(); } return string.Empty; } /// <summary> /// Link a mobile authenticator to bot account, using SteamTradeOffersBot as the authenticator. /// Called from bot manager console. Usage: "exec [index] linkauth" /// If successful, 2FA will be required upon the next login. /// Use "exec [index] getauth" if you need to get a Steam Guard code for the account. /// To deactivate the authenticator, use "exec [index] unlinkauth". /// </summary> void LinkMobileAuth() { new Thread(() => { var login = new SteamAuth.UserLogin(logOnDetails.Username, logOnDetails.Password); var loginResult = login.DoLogin(); if (loginResult == SteamAuth.LoginResult.NeedEmail) { while (loginResult == SteamAuth.LoginResult.NeedEmail) { Log.Interface("Enter Steam Guard code from email (type \"input [index] [code]\"):"); var emailCode = WaitForInput(); login.EmailCode = emailCode; loginResult = login.DoLogin(); } } if (loginResult == SteamAuth.LoginResult.LoginOkay) { Log.Info("Linking mobile authenticator..."); var authLinker = new SteamAuth.AuthenticatorLinker(login.Session); var addAuthResult = authLinker.AddAuthenticator(); if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { while (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.MustProvidePhoneNumber) { Log.Interface("Enter phone number with country code, e.g. +1XXXXXXXXXXX (type \"input [index] [number]\"):"); var phoneNumber = WaitForInput(); authLinker.PhoneNumber = phoneNumber; addAuthResult = authLinker.AddAuthenticator(); } } if (addAuthResult == SteamAuth.AuthenticatorLinker.LinkResult.AwaitingFinalization) { SteamGuardAccount = authLinker.LinkedAccount; try { var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username)); Directory.CreateDirectory(Path.Combine(System.Windows.Forms.Application.StartupPath, "authfiles")); File.WriteAllText(authFile, Newtonsoft.Json.JsonConvert.SerializeObject(SteamGuardAccount)); Log.Interface("Enter SMS code (type \"input [index] [code]\"):"); var smsCode = WaitForInput(); var authResult = authLinker.FinalizeAddAuthenticator(smsCode); if (authResult == SteamAuth.AuthenticatorLinker.FinalizeResult.Success) { Log.Success("Linked authenticator."); } else { Log.Error("Error linking authenticator: " + authResult); } } catch (IOException) { Log.Error("Failed to save auth file. Aborting authentication."); } } else { Log.Error("Error adding authenticator: " + addAuthResult); } } else { if (loginResult == SteamAuth.LoginResult.Need2FA) { Log.Error("Mobile authenticator has already been linked!"); } else { Log.Error("Error performing mobile login: " + loginResult); } } }).Start(); } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } void UserWebLogOn() { do { IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce); if(!IsLoggedIn) { Log.Warn("Authentication failed, retrying in 2s..."); Thread.Sleep(2000); } } while(!IsLoggedIn); Log.Success("User Authenticated!"); tradeManager = new TradeManager(ApiKey, SteamWeb); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximumActionGap, tradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; tradeOfferManager = new TradeOfferManager(ApiKey, SteamWeb); SubscribeTradeOffer(tradeOfferManager); cookiesAreInvalid = false; // Success, check trade offers which we have received while we were offline SpawnTradeOfferPollingThread(); } /// <summary> /// Checks if sessionId and token cookies are still valid. /// Sets cookie flag if they are invalid. /// </summary> /// <returns>true if cookies are valid; otherwise false</returns> bool CheckCookies() { // We still haven't re-authenticated if (cookiesAreInvalid) return false; try { if (!SteamWeb.VerifyCookies()) { // Cookies are no longer valid Log.Warn("Cookies are invalid. Need to re-authenticate."); cookiesAreInvalid = true; SteamUser.RequestWebAPIUserNonce(); return false; } } catch { // Even if exception is caught, we should still continue. Log.Warn("Cookie check failed. http://steamcommunity.com is possibly down."); } return true; } public UserHandler GetUserHandler(SteamID sid) { if (!userHandlers.ContainsKey(sid)) userHandlers[sid] = createHandler(this, sid); return userHandlers[sid]; } void RemoveUserHandler(SteamID sid) { if (userHandlers.ContainsKey(sid)) userHandlers.Remove(sid); } static byte [] SHAHash (byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash( input ); sha.Clear(); return output; } void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) { byte[] hash = SHAHash (machineAuth.Data); Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = machineAuth.JobID, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse (authResponse); } /// <summary> /// Gets the bot's inventory and stores it in MyInventory. /// </summary> /// <example> This sample shows how to find items in the bot's inventory from a user handler. /// <code> /// Bot.GetInventory(); // Get the inventory first /// foreach (var item in Bot.MyInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // Bot has a key in its inventory /// } /// } /// </code> /// </example> public void GetInventory() { myInventoryTask = Task.Factory.StartNew((Func<Inventory>) FetchBotsInventory); } public void TradeOfferRouter(TradeOffer offer) { GetUserHandler(offer.PartnerSteamId).OnTradeOfferUpdated(offer); } public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnTradeOfferUpdated += TradeOfferRouter; } //todo: should unsubscribe eventually... public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnTradeOfferUpdated -= TradeOfferRouter; } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade (Trade trade, UserHandler handler) { trade.OnAwaitingConfirmation += handler._OnTradeAwaitingConfirmation; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; trade.OnStatusError += handler.OnStatusError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnUserAddItem += handler.OnTradeAddItem; trade.OnUserRemoveItem += handler.OnTradeRemoveItem; trade.OnMessage += handler.OnTradeMessageHandler; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade (UserHandler handler, Trade trade) { trade.OnAwaitingConfirmation -= handler._OnTradeAwaitingConfirmation; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; trade.OnStatusError -= handler.OnStatusError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnUserAddItem -= handler.OnTradeAddItem; trade.OnUserRemoveItem -= handler.OnTradeRemoveItem; trade.OnMessage -= handler.OnTradeMessageHandler; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } /// <summary> /// Fetch the Bot's inventory and log a warning if it's private /// </summary> private Inventory FetchBotsInventory() { var inventory = Inventory.FetchInventory(SteamUser.SteamID, ApiKey, SteamWeb); if(inventory.IsPrivate) { Log.Warn("The bot's backpack is private! If your bot adds any items it will fail! Your bot's backpack should be Public."); } return inventory; } public void AcceptAllMobileTradeConfirmations() { if (SteamGuardAccount == null) { Log.Warn("Bot account does not have 2FA enabled."); } else { SteamGuardAccount.Session.SteamLogin = SteamWeb.Token; SteamGuardAccount.Session.SteamLoginSecure = SteamWeb.TokenSecure; try { foreach (var confirmation in SteamGuardAccount.FetchConfirmations()) { if (SteamGuardAccount.AcceptConfirmation(confirmation)) { Log.Success("Confirmed {0}. (Confirmation ID #{1})", confirmation.ConfirmationDescription, confirmation.ConfirmationID); } } } catch (SteamAuth.SteamGuardAccount.WGTokenInvalidException) { Log.Error("Invalid session when trying to fetch trade confirmations."); } } } /// <summary> /// Get duration of escrow in days. Call this before sending a trade offer. /// Credit to: https://www.reddit.com/r/SteamBot/comments/3w8j7c/code_getescrowduration_for_c/ /// </summary> /// <param name="steamId">Steam ID of user you want to send a trade offer to</param> /// <param name="token">User's trade token. Can be an empty string if user is on bot's friends list.</param> /// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception> /// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(SteamID steamId, string token) { var url = "https://steamcommunity.com/tradeoffer/new/"; var data = new System.Collections.Specialized.NameValueCollection(); data.Add("partner", steamId.AccountID.ToString()); if (!string.IsNullOrEmpty(token)) { data.Add("token", token); } var resp = SteamWeb.Fetch(url, "GET", data, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } /// <summary> /// Get duration of escrow in days. Call this after receiving a trade offer. /// </summary> /// <param name="tradeOfferId">The ID of the trade offer</param> /// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception> /// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception> /// <returns>TradeOfferEscrowDuration</returns> public TradeOfferEscrowDuration GetEscrowDuration(string tradeOfferId) { var url = "http://steamcommunity.com/tradeoffer/" + tradeOfferId; var resp = SteamWeb.Fetch(url, "GET", null, false); if (string.IsNullOrWhiteSpace(resp)) { throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration."); } return ParseEscrowResponse(resp); } private TradeOfferEscrowDuration ParseEscrowResponse(string resp) { var myM = Regex.Match(resp, @"g_daysMyEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); var theirM = Regex.Match(resp, @"g_daysTheirEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase); if (!myM.Groups["days"].Success || !theirM.Groups["days"].Success) { var steamErrorM = Regex.Match(resp, @"<div id=""error_msg"">([^>]+)<\/div>", RegexOptions.IgnoreCase); if (steamErrorM.Groups.Count > 1) { var steamError = Regex.Replace(steamErrorM.Groups[1].Value.Trim(), @"\t|\n|\r", ""); ; throw new TradeOfferEscrowDurationParseException(steamError); } else { throw new TradeOfferEscrowDurationParseException(string.Empty); } } return new TradeOfferEscrowDuration() { DaysMyEscrow = int.Parse(myM.Groups["days"].Value), DaysTheirEscrow = int.Parse(theirM.Groups["days"].Value) }; } public class TradeOfferEscrowDuration { public int DaysMyEscrow { get; set; } public int DaysTheirEscrow { get; set; } } public class TradeOfferEscrowDurationParseException : Exception { public TradeOfferEscrowDurationParseException() : base() { } public TradeOfferEscrowDurationParseException(string message) : base(message) { } } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); Log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { ICallbackMsg msg; while (!botThread.CancellationPending) { try { msg = SteamClient.GetCallback(true); if (msg != null) { HandleSteamMessage(msg); } if(tradeOfferManager != null) { tradeOfferManager.HandleNextPendingTradeOfferUpdate(); } Thread.Sleep(1); } catch (WebException e) { Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { Log.Error("Unhandled exception occurred in bot: " + e); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #endregion public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) return; StopBot(); if (disposing) Log.Dispose(); disposed = true; } } }
/// <summary> /// /// </summary> using UnityEngine; using System; using System.Collections; using System.Collections.Generic; //[RequireComponent(typeof(Animator))] //Name of class must be name of file as well [RequireComponent(typeof(FacialAnimationPlayer_Animator))] [RequireComponent(typeof(HeadController))] [RequireComponent(typeof(GazeController_IK))] [RequireComponent(typeof(SaccadeController))] public class MecanimCharacter : ICharacter { #region Constants #endregion #region Variables [SerializeField] string m_StartingPosture = ""; [SerializeField] int m_BaseLayerIndex = 0; [SerializeField] int m_UpperBodyLayerIndex = 1; [SerializeField] int m_FaceLayerIndex = 2; protected Animator animator; protected FacialAnimationPlayer m_FacialAnimator; protected HeadController m_HeadController; protected GazeController m_GazeController; protected SaccadeController m_SaccadeController; #endregion #region Properties public override string CharacterName { get { return name; } } public override AudioSource Voice { get { return GetComponentInChildren<AudioSource>(); } } public int BaseLayerIndex { get { return m_BaseLayerIndex; } } public int UpperBodyLayerIndex { get { return m_UpperBodyLayerIndex; } } public int FaceLayerIndex { get { return m_FaceLayerIndex; } } #endregion #region Functions // Use this for initialization void Awake() { animator = GetComponentInChildren<Animator>(); if (animator == null) { Debug.LogError("MecanimCharacter " + name + " doesn't have an Animator component"); } else { // the animator needs this component in order to signal when it receives unity driver function messages // such as OnAvatarIK and OnStateIK AnimatorMessenger messenger = animator.GetComponent<AnimatorMessenger>(); if (messenger == null) { messenger = animator.gameObject.AddComponent<AnimatorMessenger>(); } messenger.SetMessengerTarget(this); } m_FacialAnimator = GetComponent<FacialAnimationPlayer>(); m_HeadController = GetComponent<HeadController>(); m_GazeController = GetComponent<GazeController>(); m_SaccadeController = GetComponent<SaccadeController>(); if (!string.IsNullOrEmpty(m_StartingPosture)) { animator.Play(m_StartingPosture, m_BaseLayerIndex); } } public void SetFloatParam(string paramName, float paramData) { animator.SetFloat(paramName, paramData); } public void SetBoolParam(string paramName, bool paramData) { animator.SetBool(paramName, paramData); } public void SetIntParam(string paramName, int paramData) { animator.SetInteger(paramName, paramData); } public void MoveToPoint(Vector3 point, Quaternion rot) { animator.SetFloat("Speed", 1); //animator.SetFloat("Direction", h, DirectionDampTime, Time.deltaTime); //animator.MatchTarget(point, rot, AvatarTarget.Root, 1.0f); } IEnumerator DoMoveToPoint() { yield break; } public void PlayPosture(string postureName) { PlayPosture(postureName, 0); } public override void PlayPosture(string postureName, float startTime) { if (animator == null) { Debug.LogError("null animator: " + name); } animator.CrossFadeInFixedTime(postureName, 0.5f, m_BaseLayerIndex); } public override void PlayAnim(string animName) { PlayAnim(animName, m_UpperBodyLayerIndex); } public void PlayAnim(string animName, int layer) { if (animator == null) { Debug.LogError("null animator: " + name); } animator.CrossFadeInFixedTime(animName, 0.5f, layer); } public override void PlayAnim(string animName, float readyTime, float strokeStartTime, float emphasisTime, float strokeTime, float relaxTime) { PlayAnim(animName); } public void PlayAnim(string animName, float startDelay) { StartCoroutine(PlayAnimDelayed(startDelay, animName)); } IEnumerator PlayAnimDelayed(float delay, string animName) { yield return new WaitForSeconds(delay); animator.CrossFadeInFixedTime(animName, 0.5f, m_UpperBodyLayerIndex); } public override void PlayXml(string xml) { BMLEventHandler bmlHandler = GetComponent<BMLEventHandler>(); if (bmlHandler != null) { bmlHandler.LoadXMLString(CharacterName, xml); } else { Debug.LogError("PlayXml function failed on character " + name + ". Add BMLEventHandler to the gameobject."); } } public override void PlayXml(AudioSpeechFile xml) { PlayXml(xml.ConvertedXml); } public void PlayAU(int au, string side, float weight, float time) { //animator.SetFloat(au, } public override void PlayViseme(string viseme, float weight) { animator.SetFloat(viseme, weight); } public override void PlayViseme(string viseme, float weight, float totalTime, float blendTime) { m_FacialAnimator.RampViseme(viseme, weight, 0, totalTime, blendTime); } public void SetVisemeWeightMultiplier(float multiplier) { m_FacialAnimator.VisemeWeightMultiplier = multiplier; } public override void PlayAudio(AudioSpeechFile speechFile) { // often times, the facial curves need to start before the audio starts playing // find the most negative curve start time and wait that long before playing the audio //float audioWaitTime = speechFile.UtteranceTiming.GetEarliestCurveTime(); AudioSource src = Voice; if (src != null) { src.clip = speechFile.m_AudioClip; //src.PlayDelayed(Mathf.Abs(audioWaitTime)); src.Play(); } m_FacialAnimator.Play(speechFile.UtteranceTiming); } public void PlayAudio(List<TtsReader.WordTiming> timings) { m_FacialAnimator.Play(timings); } public void SetGazeTarget(GameObject gazeTarget) { if (gazeTarget != null) { m_GazeController.SetGazeTarget(gazeTarget); } } GameObject FindGazeTarget(string gazeAt) { GameObject gazeTarget = GameObject.Find(gazeAt); if (gazeTarget == null) { Debug.LogError("Could not find gaze target " + gazeAt); } return gazeTarget; } public override void Gaze(string gazeAt) { GameObject gazeTarget = FindGazeTarget(gazeAt); if (gazeTarget != null) { SetGazeTarget(gazeTarget); } } public override void Gaze(string gazeAt, float headSpeed) { GameObject gazeTarget = FindGazeTarget(gazeAt); if (gazeTarget != null) { SetGazeTargetWithSpeed(gazeTarget, headSpeed, 0, 0); } } public override void Gaze(string gazeAt, float headSpeed, float eyeSpeed, CharacterDefines.GazeJointRange jointRange) { GameObject gazeTarget = FindGazeTarget(gazeAt); if (gazeTarget != null) { float bodySpeed = ((jointRange & CharacterDefines.GazeJointRange.CHEST) == CharacterDefines.GazeJointRange.CHEST) ? GazeController.DefaultBodyGazeSpeed : 0; SetGazeTargetWithSpeed(gazeTarget, headSpeed, eyeSpeed, bodySpeed); } } public override void Gaze(string gazeAt, string targetBone, CharacterDefines.GazeDirection gazeDirection, CharacterDefines.GazeJointRange jointRange, float angle, float headSpeed, float eyeSpeed, float fadeOut, string gazeHandleName, float duration) { Gaze(gazeAt, headSpeed, eyeSpeed, jointRange); if (duration > 0) { StopGazeLater(duration, fadeOut); } } public void StopGazeLater(float secondsToWait) { StartCoroutine(StopGazeLaterCR(secondsToWait, GazeController.DefaultFadeOutTime)); } public void StopGazeLater(float secondsToWait, float fadeOutTime) { StartCoroutine(StopGazeLaterCR(secondsToWait, fadeOutTime)); } IEnumerator StopGazeLaterCR(float secondsToWait, float fadeOutTime) { yield return new WaitForSeconds(secondsToWait); StopGaze(fadeOutTime); } public void SetGazeTargetWithSpeed(GameObject gazeTarget, float headSpeed, float eyesSpeed, float bodySpeed) { m_GazeController.SetGazeTargetWithSpeed(gazeTarget, headSpeed, eyesSpeed, bodySpeed); } public void SetGazeTargetWithTime(GameObject gazeTarget, float headFadeInTime, float eyesFadeInTime, float bodyFadeInTime) { m_GazeController.SetGazeTargetWithDuration(gazeTarget, headFadeInTime, eyesFadeInTime, bodyFadeInTime); } public void SetGazeWeights(float head, float eyes, float body) { m_GazeController.HeadGazeWeight = head; m_GazeController.EyeGazeWeight = eyes; m_GazeController.BodyGazeWeight = body; } public override void StopGaze() { m_GazeController.StopGaze(); } public override void StopGaze(float fadeoutTime) { m_GazeController.StopGaze(fadeoutTime); } public void UpdateGaze() { m_GazeController.UpdateGaze(); } public override void Nod(float amount, float numTimes, float duration) { m_HeadController.NodHead(amount, numTimes, duration); } public override void Shake(float amount, float numTimes, float duration) { m_HeadController.ShakeHead(amount, numTimes, duration); } public void Tilt(float amount, float numTimes, float duration) { m_HeadController.TiltHead(amount, numTimes, duration); } public override void Saccade(CharacterDefines.SaccadeType type, bool finish, float duration) { SetSaccadeBehaviour(type); } public override void StopSaccade() { m_SaccadeController.SetBehaviourMode(CharacterDefines.SaccadeType.End); } public override void Saccade(CharacterDefines.SaccadeType type, bool finish, float duration, float angleLimit, float direction, float magnitude) { SetSaccadeBehaviour(type); m_SaccadeController.Perform(direction, magnitude, duration); } public void Saccade(float direction, float magnitude, float duration) { m_SaccadeController.Perform(direction, magnitude, duration); } public void SetSaccadeBehaviour(CharacterDefines.SaccadeType mode) { m_SaccadeController.SetBehaviourMode(mode); } public override void Transform(float x, float y, float z) { transform.position = new Vector3(x, y, z); } public override void Transform(float y, float p) { transform.position = new Vector3(transform.position.x, y, transform.position.z); Vector3 currRot = transform.rotation.eulerAngles; transform.rotation = Quaternion.Euler(currRot.x, p, currRot.z); } public override void Transform(float x, float y, float z, float h, float p, float r) { Transform(x, y, z); transform.rotation = Quaternion.Euler(p, h, r); } public override void Transform(Transform trans) { transform.position = trans.position; transform.rotation = trans.rotation; } public override void Transform(Vector3 pos, Quaternion rot) { transform.position = pos; transform.rotation = rot; } public override void Rotate(float h) { Vector3 currRot = transform.rotation.eulerAngles; transform.rotation = Quaternion.Euler(currRot.x, h, currRot.z); } #endregion }
using System.Collections.Generic; using System.Data.Entity.Design.PluralizationServices; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; // ReSharper disable RedundantNameQualifier // ReSharper disable UnusedMember.Global namespace Sawczyn.EFDesigner.EFModel.EditingOnly { public partial class GeneratedTextTransformation { #region Template // EFDesigner v3.0.8.0 // Copyright (c) 2017-2021 Michael Sawczyn // https://github.com/msawczyn/EFDesigner public abstract class EFCoreModelGenerator : EFModelGenerator { protected EFCoreModelGenerator(GeneratedTextTransformation host) : base(host) { } public static string[] SpatialTypes { get { return new[] { "Geometry" , "GeometryPoint" , "GeometryLineString" , "GeometryPolygon" , "GeometryCollection" , "GeometryMultiPoint" , "GeometryMultiLineString" , "GeometryMultiPolygon" }; } } public override void Generate(Manager manager) { // Entities string fileNameMarker = string.IsNullOrEmpty(modelRoot.FileNameMarker) ? string.Empty : $".{modelRoot.FileNameMarker}"; foreach (ModelClass modelClass in modelRoot.Classes.Where(e => e.GenerateCode)) { ClearIndent(); manager.StartNewFile(Path.Combine(modelClass.EffectiveOutputDirectory, $"{modelClass.Name}{fileNameMarker}.cs")); WriteClass(modelClass); } // Enums foreach (ModelEnum modelEnum in modelRoot.Enums.Where(e => e.GenerateCode)) { ClearIndent(); manager.StartNewFile(Path.Combine(modelEnum.EffectiveOutputDirectory, $"{modelEnum.Name}{fileNameMarker}.cs")); WriteEnum(modelEnum); } // Context ClearIndent(); manager.StartNewFile(Path.Combine(modelRoot.ContextOutputDirectory, $"{modelRoot.EntityContainerName}{fileNameMarker}.cs")); WriteDbContext(); // Context factory if (modelRoot.GenerateDbContextFactory) { ClearIndent(); manager.StartNewFile(Path.Combine(modelRoot.ContextOutputDirectory, $"{modelRoot.EntityContainerName}Factory{fileNameMarker}.cs")); WriteDbContextFactory(); } } protected void WriteDbContextFactory() { Output("using System;"); Output("using System.Collections.Generic;"); Output("using System.Linq;"); Output("using System.Text;"); Output("using System.Threading.Tasks;"); NL(); Output("using Microsoft.EntityFrameworkCore;"); Output("using Microsoft.EntityFrameworkCore.Design;"); NL(); BeginNamespace(modelRoot.Namespace); Output("/// <summary>"); Output("/// A factory for creating derived DbContext instances. Implement this interface to enable design-time services for context "); Output("/// types that do not have a public default constructor. At design-time, derived DbContext instances can be created in order "); Output("/// to enable specific design-time experiences such as Migrations. Design-time services will automatically discover "); Output("/// implementations of this interface that are in the startup assembly or the same assembly as the derived context."); Output("/// </summary>"); Output($"public partial class {modelRoot.EntityContainerName}DesignTimeFactory: IDesignTimeDbContextFactory<{modelRoot.EntityContainerName}>"); Output("{"); Output("/// <summary>"); Output("/// Partial method to allow post-creation configuration of the DbContext after it's created"); Output("/// but before it's returned."); Output("/// </summary>"); Output($"partial void Initialize({modelRoot.EntityContainerName} dbContext);"); NL(); Output("/// <summary>Creates a new instance of a derived context.</summary>"); Output("/// <param name=\"args\"> Arguments provided by the design-time service. </param>"); Output($"/// <returns> An instance of <see cref=\"{modelRoot.Namespace}.{modelRoot.EntityContainerName}\" />.</returns>"); Output($"public {modelRoot.EntityContainerName} CreateDbContext(string[] args)"); Output("{"); Output($"DbContextOptionsBuilder<{modelRoot.EntityContainerName}> optionsBuilder = new DbContextOptionsBuilder<{modelRoot.EntityContainerName}>();"); NL(); Output($"// Please provide the {modelRoot.EntityContainerName}.ConfigureOptions(optionsBuilder) in the partial class as"); Output("// public static void ConfigureOptions(DbContextOptionsBuilder optionsBuilder) {{ ... }}"); Output("// If you have custom initialization for the context, you can then consolidate the code by defining the CustomInit partial as"); Output("// partial void CustomInit(DbContextOptionsBuilder optionsBuilder) => ConfigureOptions(optionsBuilder);"); Output($"{modelRoot.EntityContainerName}.ConfigureOptions(optionsBuilder);"); Output($"{modelRoot.EntityContainerName} result = new {modelRoot.EntityContainerName}(optionsBuilder.Options);"); Output($"Initialize(result);"); NL(); Output($"return result;"); Output("}"); Output("}"); NL(); Output("/// <summary>"); Output("/// Defines a factory for creating derived DbContext instances."); Output("/// </summary>"); Output("/// <remarks>"); Output("/// See <see href=\"https://aka.ms/efcore-docs-dbcontext-factory\">Using DbContextFactory</see> for more information."); Output("/// </remarks>"); Output($"public partial class {modelRoot.EntityContainerName}Factory: IDbContextFactory<{modelRoot.EntityContainerName}>"); Output("{"); Output("/// <summary>"); Output("/// Partial method to allow post-creation configuration of the DbContext after it's created"); Output("/// but before it's returned."); Output("/// </summary>"); Output($"partial void Initialize({modelRoot.EntityContainerName} dbContext);"); NL(); Output("/// <summary>"); Output("/// <para>"); Output("/// Creates a new <see cref=\"T:Microsoft.EntityFrameworkCore.DbContext\" /> instance."); Output("/// </para>"); Output("/// <para>"); Output("/// The caller is responsible for disposing the context; it will not be disposed by any dependency injection container."); Output("/// </para>"); Output("/// </summary>"); Output("/// <returns>A new context instance.</returns>"); Output($"public {modelRoot.EntityContainerName} CreateDbContext()"); Output("{"); Output($"DbContextOptionsBuilder<{modelRoot.EntityContainerName}> optionsBuilder = new DbContextOptionsBuilder<{modelRoot.EntityContainerName}>();"); NL(); Output($"// Please provide the {modelRoot.EntityContainerName}.ConfigureOptions(optionsBuilder) in the partial class as"); Output("// public static void ConfigureOptions(DbContextOptionsBuilder optionsBuilder) {{ ... }}"); Output("// If you have custom initialization for the context, you can then consolidate the code by defining the CustomInit partial as"); Output("// partial void CustomInit(DbContextOptionsBuilder optionsBuilder) => ConfigureOptions(optionsBuilder);"); Output($"{modelRoot.EntityContainerName}.ConfigureOptions(optionsBuilder);"); Output($"{modelRoot.EntityContainerName} result = new {modelRoot.EntityContainerName}(optionsBuilder.Options);"); Output($"Initialize(result);"); NL(); Output($"return result;"); Output("}"); Output("}"); EndNamespace(modelRoot.Namespace); } protected override List<string> GetAdditionalUsingStatements() { List<string> result = new List<string>(); List<string> attributeTypes = modelRoot.Classes.SelectMany(c => c.Attributes).Select(a => a.Type).Distinct().ToList(); if (attributeTypes.Intersect(modelRoot.SpatialTypes).Any()) result.Add("using NetTopologySuite.Geometries;"); return result; } protected virtual void ConfigureModelClasses(List<string> segments, ModelClass[] classesWithTables, List<string> foreignKeyColumns, List<Association> visited) { foreach (ModelClass modelClass in modelRoot.Classes.OrderBy(x => x.Name)) { segments.Clear(); foreignKeyColumns.Clear(); NL(); if (modelClass.IsDependentType) { segments.Add($"modelBuilder.Owned<{modelClass.FullName}>()"); Output(segments); continue; } segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()"); foreach (ModelAttribute transient in modelClass.Attributes.Where(x => !x.Persistent)) segments.Add($"Ignore(t => t.{transient.Name})"); //if (modelRoot.InheritanceStrategy == CodeStrategy.TablePerConcreteType && modelClass.Superclass != null) // segments.Add("Map(x => x.MapInheritedProperties())"); if (classesWithTables.Contains(modelClass)) { if (modelClass.IsQueryType) { Output($"// There is no storage defined for {modelClass.Name} because its IsQueryType value is"); Output($"// set to 'true'. Please provide the {modelRoot.FullName}.Get{modelClass.Name}SqlQuery() method in the partial class."); Output("// "); Output($"// private string Get{modelClass.Name}SqlQuery()"); Output("// {"); Output($"// return the defining SQL query that pulls all the properties for {modelClass.FullName}"); Output("// }"); segments.Add($"ToSqlQuery(Get{modelClass.Name}SqlQuery())"); } else ConfigureTable(segments, modelClass); } if (segments.Count > 1 || modelClass.IsDependentType) Output(segments); // attribute level ConfigureModelAttributes(segments, modelClass); bool hasDefinedConcurrencyToken = modelClass.AllAttributes.Any(x => x.IsConcurrencyToken); if (!hasDefinedConcurrencyToken && modelClass.EffectiveConcurrency == ConcurrencyOverride.Optimistic) Output($@"modelBuilder.Entity<{modelClass.FullName}>().Property<byte[]>(""Timestamp"").IsConcurrencyToken();"); // Navigation endpoints are distingished as Source and Target. They are also distinguished as Principal // and Dependent. So how do these map to each other? Short answer: they don't - they're orthogonal concepts. // Source and Target are accidents of where the user started drawing the association, and help define where the // properties are in unidirectional associations. Principal and Dependent define where the foreign keys go in // the persistence mechanism. // What matters to code generation is the Principal and Dependent classifications, so we focus on those. // In the case of 1-1 or 0/1-0/1, it's situational, so the user has to tell us. // In all other cases, we can tell by the cardinalities of the associations. // navigation properties List<string> declaredShadowProperties = new List<string>(); if (!modelClass.IsDependentType) { ConfigureUnidirectionalAssociations(modelClass, visited, foreignKeyColumns, declaredShadowProperties); ConfigureBidirectionalAssociations(modelClass, visited, foreignKeyColumns, declaredShadowProperties); } } } protected virtual void ConfigureTable(List<string> segments, ModelClass modelClass) { string tableName = string.IsNullOrEmpty(modelClass.TableName) ? modelClass.Name : modelClass.TableName; string schema = string.IsNullOrEmpty(modelClass.DatabaseSchema) || modelClass.DatabaseSchema == modelClass.ModelRoot.DatabaseSchema ? string.Empty : $", \"{modelClass.DatabaseSchema}\""; segments.Add($"ToTable(\"{tableName}\"{schema})"); // primary key code segments must be output last, since HasKey returns a different type List<ModelAttribute> identityAttributes = modelClass.IdentityAttributes.ToList(); if (identityAttributes.Count == 1) segments.Add($"HasKey(t => t.{identityAttributes[0].Name})"); else if (identityAttributes.Count > 1) segments.Add($"HasKey(t => new {{ t.{string.Join(", t.", identityAttributes.Select(ia => ia.Name))} }})"); } protected virtual void ConfigureModelAttributes(List<string> segments, ModelClass modelClass) { foreach (ModelAttribute modelAttribute in modelClass.Attributes.Where(x => x.Persistent && !SpatialTypes.Contains(x.Type))) { segments.Clear(); segments.AddRange(GatherModelAttributeSegments(modelAttribute)); if (segments.Any()) { segments.Insert(0, $"modelBuilder.Entity<{modelClass.FullName}>()"); segments.Insert(1, $"Property(t => t.{modelAttribute.Name})"); Output(segments); } if (modelAttribute.Indexed && !modelAttribute.IsIdentity) { segments.Clear(); segments.Add($"modelBuilder.Entity<{modelClass.FullName}>().HasIndex(t => t.{modelAttribute.Name})"); if (modelAttribute.IndexedUnique) segments.Add("IsUnique()"); Output(segments); } } } protected virtual List<string> GatherModelAttributeSegments(ModelAttribute modelAttribute) { List<string> segments = new List<string>(); if (modelAttribute.MaxLength != null && modelAttribute.MaxLength > 0) segments.Add($"HasMaxLength({modelAttribute.MaxLength})"); if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName)) segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")"); if (!modelAttribute.AutoProperty) { segments.Add($"HasField(\"{modelAttribute.BackingFieldName}\")"); segments.Add($"UsePropertyAccessMode(PropertyAccessMode.{modelAttribute.PropertyAccessMode})"); } if (!string.IsNullOrEmpty(modelAttribute.ColumnType) && modelAttribute.ColumnType.ToLowerInvariant() != "default") { if (modelAttribute.ColumnType.ToLowerInvariant() == "varchar" || modelAttribute.ColumnType.ToLowerInvariant() == "nvarchar" || modelAttribute.ColumnType.ToLowerInvariant() == "char") segments.Add($"HasColumnType(\"{modelAttribute.ColumnType}({(modelAttribute.MaxLength > 0 ? modelAttribute.MaxLength.ToString() : "max")})\")"); else segments.Add($"HasColumnType(\"{modelAttribute.ColumnType}\")"); } if (modelAttribute.IsConcurrencyToken) segments.Add("IsRowVersion()"); if (modelAttribute.IsIdentity) { segments.Add(modelAttribute.IdentityType == IdentityType.AutoGenerated ? "ValueGeneratedOnAdd()" : "ValueGeneratedNever()"); } if (modelAttribute.Required) segments.Add("IsRequired()"); return segments; } protected virtual void WriteDbContext() { List<string> segments = new List<string>(); ModelClass[] classesWithTables = null; // Note: TablePerConcreteType not yet available, but it doesn't hurt for it to be here since they shouldn't make it past the designer's validations switch (modelRoot.InheritanceStrategy) { case CodeStrategy.TablePerType: case CodeStrategy.TablePerConcreteType: classesWithTables = modelRoot.Classes .Where(mc => (!mc.IsDependentType || !string.IsNullOrEmpty(mc.TableName)) && mc.GenerateCode) .OrderBy(x => x.Name) .ToArray(); break; //case CodeStrategy.TablePerConcreteType: // classesWithTables = modelRoot.Classes // .Where(mc => (!mc.IsDependentType || !string.IsNullOrEmpty(mc.TableName)) // && !mc.IsAbstract // && mc.GenerateCode) // .OrderBy(x => x.Name) // .ToArray(); // break; case CodeStrategy.TablePerHierarchy: classesWithTables = modelRoot.Classes .Where(mc => (!mc.IsDependentType || !string.IsNullOrEmpty(mc.TableName)) && mc.Superclass == null && mc.GenerateCode) .OrderBy(x => x.Name) .ToArray(); break; } Output("using System;"); Output("using System.Collections.Generic;"); Output("using System.Linq;"); Output("using System.ComponentModel.DataAnnotations.Schema;"); Output("using Microsoft.EntityFrameworkCore;"); NL(); BeginNamespace(modelRoot.Namespace); WriteDbContextComments(); string baseClass = string.IsNullOrWhiteSpace(modelRoot.BaseClass) ? "Microsoft.EntityFrameworkCore.DbContext" : modelRoot.BaseClass; Output($"{modelRoot.EntityContainerAccess.ToString().ToLower()} partial class {modelRoot.EntityContainerName} : {baseClass}"); Output("{"); if (classesWithTables?.Any() == true) WriteDbSets(); WriteContextConstructors(); if (!modelRoot.GenerateDbContextFactory) WriteOnConfiguring(segments); WriteOnModelCreate(segments, classesWithTables); Output("}"); EndNamespace(modelRoot.Namespace); } protected void WriteDbSets() { Output("#region DbSets"); PluralizationService pluralizationService = ModelRoot.PluralizationService; foreach (ModelClass modelClass in modelRoot.Classes.Where(x => !x.IsDependentType).OrderBy(x => x.Name)) { string dbSetName; if (!string.IsNullOrEmpty(modelClass.DbSetName)) dbSetName = modelClass.DbSetName; else { dbSetName = pluralizationService?.IsSingular(modelClass.Name) == true ? pluralizationService.Pluralize(modelClass.Name) : modelClass.Name; } if (!string.IsNullOrEmpty(modelClass.Summary)) { NL(); Output("/// <summary>"); WriteCommentBody($"Repository for {modelClass.FullName} - {modelClass.Summary}"); Output("/// </summary>"); } Output($"{modelRoot.DbSetAccess.ToString().ToLower()} virtual Microsoft.EntityFrameworkCore.DbSet<{modelClass.FullName}> {dbSetName} {{ get; set; }}"); } NL(); Output("#endregion DbSets"); NL(); } protected void WriteContextConstructors() { if (!string.IsNullOrEmpty(modelRoot.ConnectionString) || !string.IsNullOrEmpty(modelRoot.ConnectionStringName)) { string connectionString = string.IsNullOrEmpty(modelRoot.ConnectionString) ? $"Name={modelRoot.ConnectionStringName}" : modelRoot.ConnectionString; Output("/// <summary>"); Output("/// Default connection string"); Output("/// </summary>"); Output($"public static string ConnectionString {{ get; set; }} = @\"{connectionString}\";"); NL(); } Output("/// <summary>"); Output("/// <para>"); Output("/// Initializes a new instance of the <see cref=\"T:Microsoft.EntityFrameworkCore.DbContext\" /> class using the specified options."); Output("/// The <see cref=\"M:Microsoft.EntityFrameworkCore.DbContext.OnConfiguring(Microsoft.EntityFrameworkCore.DbContextOptionsBuilder)\" /> method will still be called to allow further"); Output("/// configuration of the options."); Output("/// </para>"); Output("/// </summary>"); Output("/// <param name=\"options\">The options for this context.</param>"); Output($"public {modelRoot.EntityContainerName}(DbContextOptions<{modelRoot.EntityContainerName}> options) : base(options)"); Output("{"); Output("}"); NL(); Output("partial void CustomInit(DbContextOptionsBuilder optionsBuilder);"); NL(); } protected void WriteOnConfiguring(List<string> segments) { Output("/// <inheritdoc />"); Output("protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)"); Output("{"); segments.Clear(); if (modelRoot.GetEntityFrameworkPackageVersionNum() >= 2.1 && modelRoot.LazyLoadingEnabled) segments.Add("UseLazyLoadingProxies()"); if (segments.Any()) { segments.Insert(0, "optionsBuilder"); Output(segments); NL(); } Output("CustomInit(optionsBuilder);"); Output("}"); NL(); } protected virtual void WriteOnModelCreate(List<string> segments, ModelClass[] classesWithTables) { Output("partial void OnModelCreatingImpl(ModelBuilder modelBuilder);"); Output("partial void OnModelCreatedImpl(ModelBuilder modelBuilder);"); NL(); Output("/// <summary>"); Output("/// Override this method to further configure the model that was discovered by convention from the entity types"); Output("/// exposed in <see cref=\"T:Microsoft.EntityFrameworkCore.DbSet`1\" /> properties on your derived context. The resulting model may be cached"); Output("/// and re-used for subsequent instances of your derived context."); Output("/// </summary>"); Output("/// <remarks>"); Output("/// If a model is explicitly set on the options for this context (via <see cref=\"M:Microsoft.EntityFrameworkCore.DbContextOptionsBuilder.UseModel(Microsoft.EntityFrameworkCore.Metadata.IModel)\" />)"); Output("/// then this method will not be run."); Output("/// </remarks>"); Output("/// <param name=\"modelBuilder\">"); Output("/// The builder being used to construct the model for this context. Databases (and other extensions) typically"); Output("/// define extension methods on this object that allow you to configure aspects of the model that are specific"); Output("/// to a given database."); Output("/// </param>"); Output("protected override void OnModelCreating(ModelBuilder modelBuilder)"); Output("{"); Output("base.OnModelCreating(modelBuilder);"); Output("OnModelCreatingImpl(modelBuilder);"); NL(); if (!string.IsNullOrEmpty(modelRoot.DatabaseSchema)) Output($"modelBuilder.HasDefaultSchema(\"{modelRoot.DatabaseSchema}\");"); List<Association> visited = new List<Association>(); List<string> foreignKeyColumns = new List<string>(); ConfigureModelClasses(segments, classesWithTables, foreignKeyColumns, visited); NL(); Output("OnModelCreatedImpl(modelBuilder);"); Output("}"); } [SuppressMessage("ReSharper", "RedundantNameQualifier")] protected virtual void ConfigureBidirectionalAssociations(ModelClass modelClass , List<Association> visited , List<string> foreignKeyColumns , List<string> declaredShadowProperties) { WriteBidirectionalNonDependentAssociations(modelClass, visited, foreignKeyColumns); WriteBidirectionalDependentAssociations(modelClass, $"modelBuilder.Entity<{modelClass.FullName}>()", visited); } protected virtual void WriteBidirectionalDependentAssociations(ModelClass sourceInstance, string baseSegment, List<Association> visited) { // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach (BidirectionalAssociation association in Association.GetLinksToTargets(sourceInstance) .OfType<BidirectionalAssociation>() .Where(x => x.Persistent && x.Target.IsDependentType)) { if (visited.Contains(association)) continue; visited.Add(association); List<string> segments = new List<string>(); string separator = sourceInstance.ModelRoot.ShadowKeyNamePattern == ShadowKeyPattern.TableColumn ? string.Empty : "_"; switch (association.TargetMultiplicity) // realized by property on source { case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany: { segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add($"ToTable(\"{(string.IsNullOrEmpty(association.Target.TableName) ? association.Target.Name : association.Target.TableName)}\")"); Output(segments); segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add($"WithOwner(\"{association.SourcePropertyName}\")"); segments.Add($"HasForeignKey(\"{association.SourcePropertyName}{separator}Id\")"); Output(segments); segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add($"Property<{modelRoot.DefaultIdentityType}>(\"Id\")"); Output(segments); segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add("HasKey(\"Id\")"); Output(segments); WriteBidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsMany(p => p.{association.TargetPropertyName})", visited); break; } case Sawczyn.EFDesigner.EFModel.Multiplicity.One: { segments.Add(baseSegment); segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})"); segments.Add($"WithOwner(p => p.{association.SourcePropertyName})"); Output(segments); if (!string.IsNullOrEmpty(association.Target.TableName)) { segments.Add(baseSegment); segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})"); segments.Add($"ToTable(\"{association.Target.TableName}\")"); Output(segments); } foreach (ModelAttribute modelAttribute in association.Target.AllAttributes) { segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})"); if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName)) segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")"); if (modelAttribute.Required) segments.Add("IsRequired()"); if (segments.Count > 1) Output(segments); segments.Clear(); } WriteBidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited); break; } case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne: { segments.Add(baseSegment); segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})"); segments.Add($"WithOwner(p => p.{association.SourcePropertyName})"); Output(segments); if (!string.IsNullOrEmpty(association.Target.TableName)) { segments.Add(baseSegment); segments.Add($"OwnsOne(p => p.{association.TargetPropertyName})"); segments.Add($"ToTable(\"{association.Target.TableName}\")"); Output(segments); } foreach (ModelAttribute modelAttribute in association.Target.AllAttributes) { segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})"); if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName)) segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")"); if (modelAttribute.Required) segments.Add("IsRequired()"); if (segments.Count > 1) Output(segments); segments.Clear(); } WriteBidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited); break; } } } } protected virtual void WriteBidirectionalNonDependentAssociations(ModelClass modelClass, List<Association> visited, List<string> foreignKeyColumns) { // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach (BidirectionalAssociation association in Association.GetLinksToTargets(modelClass) .OfType<BidirectionalAssociation>() .Where(x => x.Persistent && !x.Target.IsDependentType)) { if (visited.Contains(association)) continue; visited.Add(association); List<string> segments = new List<string>(); bool required = false; segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()"); switch (association.TargetMultiplicity) // realized by property on source { case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany: segments.Add($"HasMany<{association.Target.FullName}>(p => p.{association.TargetPropertyName})"); break; case Sawczyn.EFDesigner.EFModel.Multiplicity.One: segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})"); required = (modelClass == association.Principal); break; case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne: segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})"); break; } switch (association.SourceMultiplicity) // realized by property on target, but no property on target { case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany: segments.Add($"WithMany(p => p.{association.SourcePropertyName})"); if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany) { string tableMap = string.IsNullOrEmpty(association.JoinTableName) ? $"{association.Target.Name}_{association.SourcePropertyName}_x_{association.Source.Name}_{association.TargetPropertyName}" : association.JoinTableName; segments.Add($"UsingEntity(x => x.ToTable(\"{tableMap}\"))"); } break; case Sawczyn.EFDesigner.EFModel.Multiplicity.One: segments.Add($"WithOne(p => p.{association.SourcePropertyName})"); required = (modelClass == association.Principal); break; case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne: segments.Add($"WithOne(p => p.{association.SourcePropertyName})"); break; } string foreignKeySegment = CreateForeignKeySegment(association, foreignKeyColumns); if (!string.IsNullOrEmpty(foreignKeySegment)) segments.Add(foreignKeySegment); WriteSourceDeleteBehavior(association, segments); if (required && (association.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One || association.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One)) segments.Add("IsRequired()"); Output(segments); } } protected virtual void WriteTargetDeleteBehavior(UnidirectionalAssociation association, List<string> segments) { if (!association.Source.IsDependentType && !association.Target.IsDependentType && (association.TargetRole == EndpointRole.Principal || association.SourceRole == EndpointRole.Principal)) { DeleteAction deleteAction = association.SourceRole == EndpointRole.Principal ? association.SourceDeleteAction : association.TargetDeleteAction; switch (deleteAction) { case DeleteAction.None: segments.Add("OnDelete(DeleteBehavior.Restrict)"); break; case DeleteAction.Cascade: segments.Add("OnDelete(DeleteBehavior.Cascade)"); break; } } } protected virtual void WriteSourceDeleteBehavior(BidirectionalAssociation association, List<string> segments) { if (!association.Source.IsDependentType && !association.Target.IsDependentType && (association.TargetRole == EndpointRole.Principal || association.SourceRole == EndpointRole.Principal)) { DeleteAction deleteAction = association.SourceRole == EndpointRole.Principal ? association.SourceDeleteAction : association.TargetDeleteAction; switch (deleteAction) { case DeleteAction.None: segments.Add("OnDelete(DeleteBehavior.Restrict)"); break; case DeleteAction.Cascade: segments.Add("OnDelete(DeleteBehavior.Cascade)"); break; } } } [SuppressMessage("ReSharper", "RedundantNameQualifier")] protected virtual void ConfigureUnidirectionalAssociations(ModelClass modelClass , List<Association> visited , List<string> foreignKeyColumns , List<string> declaredShadowProperties) { WriteUnidirectionalNonDependentAssociations(modelClass, visited, foreignKeyColumns); WriteUnidirectionalDependentAssociations(modelClass, $"modelBuilder.Entity<{modelClass.FullName}>()", visited); } protected virtual void WriteUnidirectionalDependentAssociations(ModelClass sourceInstance, string baseSegment, List<Association> visited) { // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach (UnidirectionalAssociation association in Association.GetLinksToTargets(sourceInstance) .OfType<UnidirectionalAssociation>() .Where(x => x.Persistent && x.Target.IsDependentType)) { if (visited.Contains(association)) continue; visited.Add(association); List<string> segments = new List<string>(); string separator = sourceInstance.ModelRoot.ShadowKeyNamePattern == ShadowKeyPattern.TableColumn ? string.Empty : "_"; switch (association.TargetMultiplicity) // realized by property on source { case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany: { segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add($"WithOwner(\"{association.Source.Name}_{association.TargetPropertyName}\")"); segments.Add($"HasForeignKey(\"{association.Source.Name}_{association.TargetPropertyName}{separator}Id\")"); Output(segments); segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add($"Property<{modelRoot.DefaultIdentityType}>(\"Id\")"); Output(segments); segments.Add(baseSegment); segments.Add($"OwnsMany(p => p.{association.TargetPropertyName})"); segments.Add("HasKey(\"Id\")"); Output(segments); WriteUnidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsMany(p => p.{association.TargetPropertyName})", visited); break; } case Sawczyn.EFDesigner.EFModel.Multiplicity.One: { foreach (ModelAttribute modelAttribute in association.Target.AllAttributes) { segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})"); if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName)) segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")"); if (modelAttribute.Required) segments.Add("IsRequired()"); Output(segments); } WriteUnidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited); break; } case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne: { foreach (ModelAttribute modelAttribute in association.Target.AllAttributes) { segments.Add($"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName}).Property(p => p.{modelAttribute.Name})"); if (modelAttribute.ColumnName != modelAttribute.Name && !string.IsNullOrEmpty(modelAttribute.ColumnName)) segments.Add($"HasColumnName(\"{modelAttribute.ColumnName}\")"); if (modelAttribute.Required) segments.Add("IsRequired()"); Output(segments); } WriteUnidirectionalDependentAssociations(association.Target, $"{baseSegment}.OwnsOne(p => p.{association.TargetPropertyName})", visited); break; } } } } protected virtual void WriteUnidirectionalNonDependentAssociations(ModelClass modelClass, List<Association> visited, List<string> foreignKeyColumns) { // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach (UnidirectionalAssociation association in Association.GetLinksToTargets(modelClass) .OfType<UnidirectionalAssociation>() .Where(x => x.Persistent && !x.Target.IsDependentType)) { if (visited.Contains(association)) continue; visited.Add(association); List<string> segments = new List<string>(); bool required = false; segments.Add($"modelBuilder.Entity<{modelClass.FullName}>()"); switch (association.TargetMultiplicity) // realized by property on source { case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany: segments.Add($"HasMany<{association.Target.FullName}>(p => p.{association.TargetPropertyName})"); break; case Sawczyn.EFDesigner.EFModel.Multiplicity.One: segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})"); required = (modelClass == association.Principal); break; case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne: segments.Add($"HasOne<{association.Target.FullName}>(p => p.{association.TargetPropertyName})"); break; } switch (association.SourceMultiplicity) // realized by property on target, but no property on target { case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany: segments.Add("WithMany()"); if (association.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany) { string tableMap = string.IsNullOrEmpty(association.JoinTableName) ? $"{association.Target.Name}_x_{association.Source.Name}_{association.TargetPropertyName}" : association.JoinTableName; segments.Add($"UsingEntity(x => x.ToTable(\"{tableMap}\"))"); } break; case Sawczyn.EFDesigner.EFModel.Multiplicity.One: segments.Add("WithOne()"); required = (modelClass == association.Principal); break; case Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne: segments.Add("WithOne()"); break; } string foreignKeySegment = CreateForeignKeySegment(association, foreignKeyColumns); if (!string.IsNullOrEmpty(foreignKeySegment)) segments.Add(foreignKeySegment); else if (association.Is(Sawczyn.EFDesigner.EFModel.Multiplicity.One, Sawczyn.EFDesigner.EFModel.Multiplicity.One) || association.Is(Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne, Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroOne)) segments.Add($"HasForeignKey<{association.Dependent.FullName}>()"); WriteTargetDeleteBehavior(association, segments); if (required && (association.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One || association.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One)) segments.Add("IsRequired()"); Output(segments); } } [SuppressMessage("ReSharper", "RedundantNameQualifier")] protected virtual string CreateForeignKeySegment(Association association, List<string> foreignKeyColumns) { List<string> foreignKeys = GetForeignKeys(association, foreignKeyColumns).ToList(); if (!foreignKeys.Any()) // only happens if many-to-many return null; // 1-1, 1-0/1 and 0/1-0/1 bool dependentClassDesignationRequired = association.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany && association.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.ZeroMany; string result = string.Join(",", foreignKeys); if (foreignKeys.First().StartsWith("\"")) { // foreign keys are shadow properties result = dependentClassDesignationRequired ? $"HasForeignKey(\"{association.Dependent.Name}\", {result})" : $"HasForeignKey({result})"; } else { // foreign keys are real properties result = foreignKeys.Count == 1 ? $"k => {result}" : $"k => new {{ {result} }}"; result = dependentClassDesignationRequired ? $"HasForeignKey<{association.Dependent.FullName}>({result})" : $"HasForeignKey({result})"; } return result; } protected virtual IEnumerable<string> GetForeignKeys(Association association, List<string> foreignKeyColumns) { // final collection of foreign key property names, real or shadow // shadow properties will be double quoted, real properties won't IEnumerable<string> result = new List<string>(); // foreign key definitions always go in the table representing the Dependent end of the association // if there is no dependent end (i.e., many-to-many), there are no foreign keys ModelClass principal = association.Principal; ModelClass dependent = association.Dependent; if (principal != null && dependent != null) { if (string.IsNullOrWhiteSpace(association.FKPropertyName)) result = principal.AllIdentityAttributes.Select(identity => $"\"{CreateShadowPropertyName(association, foreignKeyColumns, identity)}\"").ToList(); else { // defined properties result = association.FKPropertyName.Split(',').Select(prop => "k." + prop.Trim()).ToList(); foreignKeyColumns.AddRange(result); } } return result; } } #endregion Template } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Linq; using System.Text; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Intermediate; namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X { public static class NamespaceDirective { private static readonly char[] Separators = new char[] { '\\', '/' }; public static readonly DirectiveDescriptor Directive = DirectiveDescriptor.CreateDirective( "namespace", DirectiveKind.SingleLine, builder => { builder.AddNamespaceToken( Resources.NamespaceDirective_NamespaceToken_Name, Resources.NamespaceDirective_NamespaceToken_Description); builder.Usage = DirectiveUsage.FileScopedSinglyOccurring; builder.Description = Resources.NamespaceDirective_Description; }); public static void Register(RazorProjectEngineBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AddDirective(Directive); builder.Features.Add(new Pass()); } // internal for testing internal class Pass : IntermediateNodePassBase, IRazorDirectiveClassifierPass { protected override void ExecuteCore(RazorCodeDocument codeDocument, DocumentIntermediateNode documentNode) { if (documentNode.DocumentKind != RazorPageDocumentClassifierPass.RazorPageDocumentKind && documentNode.DocumentKind != MvcViewDocumentClassifierPass.MvcViewDocumentKind) { // Not a page. Skip. return; } var visitor = new Visitor(); visitor.Visit(documentNode); var directive = visitor.LastNamespaceDirective; if (directive == null) { // No namespace set. Skip. return; } var @namespace = visitor.FirstNamespace; if (@namespace == null) { // No namespace node. Skip. return; } @namespace.Content = GetNamespace(codeDocument.Source.FilePath, directive); } } // internal for testing. // // This code does a best-effort attempt to compute a namespace 'suffix' - the path difference between // where the @namespace directive appears and where the current document is on disk. // // In the event that these two source either don't have FileNames set or don't follow a coherent hierarchy, // we will just use the namespace verbatim. internal static string GetNamespace(string source, DirectiveIntermediateNode directive) { var directiveSource = NormalizeDirectory(directive.Source?.FilePath); var baseNamespace = directive.Tokens.FirstOrDefault()?.Content; if (string.IsNullOrEmpty(baseNamespace)) { // The namespace directive was incomplete. return string.Empty; } if (string.IsNullOrEmpty(source) || directiveSource == null) { // No sources, can't compute a suffix. return baseNamespace; } // We're specifically using OrdinalIgnoreCase here because Razor treats all paths as case-insensitive. if (!source.StartsWith(directiveSource, StringComparison.OrdinalIgnoreCase) || source.Length <= directiveSource.Length) { // The imports are not from the directory hierarchy, can't compute a suffix. return baseNamespace; } // OK so that this point we know that the 'imports' file containing this directive is in the directory // hierarchy of this soure file. This is the case where we can append a suffix to the baseNamespace. // // Everything so far has just been defensiveness on our part. var builder = new StringBuilder(baseNamespace); var segments = source.Substring(directiveSource.Length).Split(Separators); // Skip the last segment because it's the FileName. for (var i = 0; i < segments.Length - 1; i++) { builder.Append('.'); builder.Append(CSharpIdentifier.SanitizeClassName(segments[i])); } return builder.ToString(); } // We want to normalize the path of the file containing the '@namespace' directive to just the containing // directory with a trailing separator. // // Not using Path.GetDirectoryName here because it doesn't meet these requirements, and we want to handle // both 'view engine' style paths and absolute paths. // // We also don't normalize the separators here. We expect that all documents are using a consistent style of path. // // If we can't normalize the path, we just return null so it will be ignored. private static string NormalizeDirectory(string path) { if (string.IsNullOrEmpty(path)) { return null; } var lastSeparator = path.LastIndexOfAny(Separators); if (lastSeparator == -1) { return null; } // Includes the separator return path.Substring(0, lastSeparator + 1); } private class Visitor : IntermediateNodeWalker { public ClassDeclarationIntermediateNode FirstClass { get; private set; } public NamespaceDeclarationIntermediateNode FirstNamespace { get; private set; } // We want the last one, so get them all and then . public DirectiveIntermediateNode LastNamespaceDirective { get; private set; } public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateNode node) { if (FirstNamespace == null) { FirstNamespace = node; } base.VisitNamespaceDeclaration(node); } public override void VisitClassDeclaration(ClassDeclarationIntermediateNode node) { if (FirstClass == null) { FirstClass = node; } base.VisitClassDeclaration(node); } public override void VisitDirective(DirectiveIntermediateNode node) { if (node.Directive == Directive) { LastNamespaceDirective = node; } base.VisitDirective(node); } } #region Obsolete [Obsolete("This method is obsolete and will be removed in a future version.")] public static void Register(IRazorEngineBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AddDirective(Directive); builder.Features.Add(new Pass()); } #endregion } }
#region License //============================================================================= // Vici Core - Productivity Library for .NET 3.5 // // Copyright (c) 2008-2012 Philippe Leybaert // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //============================================================================= #endregion using System; using NUnit.Framework; using Vici.Core.Parser; namespace Vici.Core.Test { [TestFixture] public class Tokenizer_Fixture { [Test] public void TestStringLiteral() { Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(new StringLiteralMatcher()); tokenizer.AddTokenMatcher(new WhiteSpaceMatcher()); tokenizer.AddTokenMatcher(new CharMatcher('+')); Token[] tokens = tokenizer.Tokenize("\"test1\" + \"test2\""); Assert.AreEqual(5, tokens.Length); Assert.AreEqual("\"test1\"", tokens[0].Text); Assert.AreEqual("\"test2\"", tokens[4].Text); tokens = tokenizer.Tokenize("\"test1\" + \"test\\\"2\""); Assert.AreEqual(5, tokens.Length); Assert.AreEqual("\"test1\"", tokens[0].Text); Assert.AreEqual("\"test\\\"2\"", tokens[4].Text); } [Test] public void NumericLiterals() { Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(new IntegerLiteralMatcher()); tokenizer.AddTokenMatcher(new DecimalLiteralMatcher()); tokenizer.AddTokenMatcher(new WhiteSpaceMatcher()); Token[] tokens; tokens = tokenizer.Tokenize("10 10.0"); Assert.AreEqual(3,tokens.Length); Assert.AreEqual("10",tokens[0].Text); Assert.AreEqual("10.0",tokens[2].Text); tokens = tokenizer.Tokenize("10m 10ul"); Assert.AreEqual(3, tokens.Length); Assert.AreEqual("10m", tokens[0].Text); Assert.AreEqual("10ul", tokens[2].Text); tokens = tokenizer.Tokenize("10f 10l"); Assert.AreEqual(3, tokens.Length); Assert.AreEqual("10f", tokens[0].Text); Assert.AreEqual("10l", tokens[2].Text); } [Test] public void TestFallback() { ITokenMatcher matcher1 = new CharMatcher('('); ITokenMatcher matcher2 = new CharMatcher(')'); ITokenMatcher matcher3 = new StringMatcher("(test)"); ITokenMatcher matcher4 = new AnyCharMatcher("abcdefghijklmnopqrstuvwxyz"); Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(matcher1); tokenizer.AddTokenMatcher(matcher2); tokenizer.AddTokenMatcher(matcher3); tokenizer.AddTokenMatcher(matcher4); Token[] tokens = tokenizer.Tokenize("(test)(x)"); Assert.AreEqual(4,tokens.Length); } [Test] public void TestAnySequence() { ITokenMatcher matcher = new CompositeMatcher( new AnyCharMatcher("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_"), new SequenceOfAnyCharMatcher("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789") ); ITokenMatcher alphaMatcher = new SequenceOfAnyCharMatcher("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789"); Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(matcher); tokenizer.AddTokenMatcher(new WhiteSpaceMatcher()); tokenizer.AddTokenMatcher(new CharMatcher('.')); Token[] tokens = tokenizer.Tokenize("Math.Max"); Assert.AreEqual(3,tokens.Length); Assert.AreEqual("Math",tokens[0].Text); Assert.AreEqual(".", tokens[1].Text); Assert.AreEqual("Max", tokens[2].Text); } [Test] //[ExpectedException(typeof(UnknownTokenException))] public void BadToken() { try { Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(new IntegerLiteralMatcher()); tokenizer.AddTokenMatcher(new WhiteSpaceMatcher()); tokenizer.Tokenize("5 A"); Assert.Fail(); } catch(UnknownTokenException ex) { } } [Test] public void BadTokenPosition() { Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(new IntegerLiteralMatcher()); tokenizer.AddTokenMatcher(new WhiteSpaceMatcher()); try { tokenizer.Tokenize("5 A"); } catch (UnknownTokenException ex) { Assert.AreEqual(3, ex.Position.Column); Assert.AreEqual(1, ex.Position.Line); Assert.AreEqual("A", ex.Token); } try { tokenizer.Tokenize("5 4\r\n2\r\n X\r\n5"); } catch (UnknownTokenException ex) { Assert.AreEqual(4, ex.Position.Column); Assert.AreEqual(3, ex.Position.Line); Assert.AreEqual("X",ex.Token); } } [Test] public void StartsAndEndsWithToken() { Tokenizer tokenizer = new Tokenizer(); tokenizer.AddTokenMatcher(new StartsAndEndsWithMatcher("<!--","-->",'"')); tokenizer.AddTokenMatcher(new WhiteSpaceMatcher()); Token[] tokens; tokens = tokenizer.Tokenize("<!--test--> <!-- test 2 -->"); Assert.AreEqual(3,tokens.Length); tokens = tokenizer.Tokenize("<!--test \"-->\"--> <!-- test 2 -->"); Assert.AreEqual(3, tokens.Length); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; using Orleans.AzureUtils; using Orleans.Providers; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Serialization; namespace Orleans.Storage { /// <summary> /// Simple storage provider for writing grain state data to Azure table storage. /// </summary> /// <remarks> /// <para> /// Required configuration params: <c>DataConnectionString</c> /// </para> /// <para> /// Optional configuration params: /// <c>TableName</c> -- defaults to <c>OrleansGrainState</c> /// <c>DeleteStateOnClear</c> -- defaults to <c>false</c> /// </para> /// </remarks> /// <example> /// Example configuration for this storage provider in OrleansConfiguration.xml file: /// <code> /// &lt;OrleansConfiguration xmlns="urn:orleans"> /// &lt;Globals> /// &lt;StorageProviders> /// &lt;Provider Type="Orleans.Storage.AzureTableStorage" Name="AzureStore" /// DataConnectionString="UseDevelopmentStorage=true" /// DeleteStateOnClear="true" /// /> /// &lt;/StorageProviders> /// </code> /// </example> public class AzureTableStorage : IStorageProvider, IRestExceptionDecoder { internal const string DataConnectionStringPropertyName = "DataConnectionString"; internal const string TableNamePropertyName = "TableName"; internal const string DeleteOnClearPropertyName = "DeleteStateOnClear"; internal const string UseJsonFormatPropertyName = "UseJsonFormat"; internal const string TableNameDefaultValue = "OrleansGrainState"; private string dataConnectionString; private string tableName; private string serviceId; private GrainStateTableDataManager tableDataManager; private bool isDeleteStateOnClear; private static int counter; private readonly int id; // each property can hold 64KB of data and each entity can take 1MB in total, so 15 full properties take // 15 * 64 = 960 KB leaving room for the primary key, timestamp etc private const int MAX_DATA_CHUNK_SIZE = 64 * 1024; private const int MAX_STRING_PROPERTY_LENGTH = 32 * 1024; private const int MAX_DATA_CHUNKS_COUNT = 15; private const string BINARY_DATA_PROPERTY_NAME = "Data"; private const string STRING_DATA_PROPERTY_NAME = "StringData"; private bool useJsonFormat; private Newtonsoft.Json.JsonSerializerSettings jsonSettings; private SerializationManager serializationManager; /// <summary> Name of this storage provider instance. </summary> /// <see cref="IProvider.Name"/> public string Name { get; private set; } /// <summary> Logger used by this storage provider instance. </summary> /// <see cref="IStorageProvider.Log"/> public Logger Log { get; private set; } /// <summary> Default constructor </summary> public AzureTableStorage() { tableName = TableNameDefaultValue; id = Interlocked.Increment(ref counter); } /// <summary> Initialization function for this storage provider. </summary> /// <see cref="IProvider.Init"/> public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { Name = name; serviceId = providerRuntime.ServiceId.ToString(); this.serializationManager = providerRuntime.ServiceProvider.GetRequiredService<SerializationManager>(); if (!config.Properties.ContainsKey(DataConnectionStringPropertyName) || string.IsNullOrWhiteSpace(config.Properties[DataConnectionStringPropertyName])) throw new ArgumentException("DataConnectionString property not set"); dataConnectionString = config.Properties["DataConnectionString"]; if (config.Properties.ContainsKey(TableNamePropertyName)) tableName = config.Properties[TableNamePropertyName]; isDeleteStateOnClear = config.Properties.ContainsKey(DeleteOnClearPropertyName) && "true".Equals(config.Properties[DeleteOnClearPropertyName], StringComparison.OrdinalIgnoreCase); Log = providerRuntime.GetLogger("Storage.AzureTableStorage." + id); var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}", Name, serviceId, tableName, isDeleteStateOnClear); if (config.Properties.ContainsKey(UseJsonFormatPropertyName)) useJsonFormat = "true".Equals(config.Properties[UseJsonFormatPropertyName], StringComparison.OrdinalIgnoreCase); var grainFactory = providerRuntime.ServiceProvider.GetRequiredService<IGrainFactory>(); this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.serializationManager, grainFactory), config); initMsg = String.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat); Log.Info((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, initMsg); Log.Info((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(dataConnectionString)); tableDataManager = new GrainStateTableDataManager(tableName, dataConnectionString, Log); return tableDataManager.InitTableAsync(); } // Internal method to initialize for testing internal void InitLogger(Logger logger) { Log = logger; } /// <summary> Shutdown this storage provider. </summary> /// <see cref="IProvider.Close"/> public Task Close() { tableDataManager = null; return Task.CompletedTask; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IStorageProvider.ReadStateAsync"/> public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_ReadingData, "Reading: GrainType={0} Pk={1} Grainid={2} from Table={3}", grainType, pk, grainReference, tableName); string partitionKey = pk; string rowKey = grainType; GrainStateRecord record = await tableDataManager.Read(partitionKey, rowKey).ConfigureAwait(false); if (record != null) { var entity = record.Entity; if (entity != null) { var loadedState = ConvertFromStorageFormat(entity); grainState.State = loadedState ?? Activator.CreateInstance(grainState.State.GetType()); grainState.ETag = record.ETag; } } // Else leave grainState in previous default condition } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IStorageProvider.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Writing: GrainType={0} Pk={1} Grainid={2} ETag={3} to Table={4}", grainType, pk, grainReference, grainState.ETag, tableName); var entity = new DynamicTableEntity(pk, grainType); ConvertToStorageFormat(grainState.State, entity); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; try { await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference, tableName, grainState.ETag).ConfigureAwait(false); grainState.ETag = record.ETag; } catch (Exception exc) { Log.Error((int)AzureProviderErrorCode.AzureTableProvider_WriteError, $"Error Writing: GrainType={grainType} Grainid={grainReference} ETag={grainState.ETag} to Table={tableName} Exception={exc.Message}", exc); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IStorageProvider.ClearStateAsync"/> public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainReference); if (Log.IsVerbose3) Log.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_WritingData, "Clearing: GrainType={0} Pk={1} Grainid={2} ETag={3} DeleteStateOnClear={4} from Table={5}", grainType, pk, grainReference, grainState.ETag, isDeleteStateOnClear, tableName); var entity = new DynamicTableEntity(pk, grainType); var record = new GrainStateRecord { Entity = entity, ETag = grainState.ETag }; string operation = "Clearing"; try { if (isDeleteStateOnClear) { operation = "Deleting"; await DoOptimisticUpdate(() => tableDataManager.Delete(record), grainType, grainReference, tableName, grainState.ETag).ConfigureAwait(false); } else { await DoOptimisticUpdate(() => tableDataManager.Write(record), grainType, grainReference, tableName, grainState.ETag).ConfigureAwait(false); } grainState.ETag = record.ETag; // Update in-memory data to the new ETag } catch (Exception exc) { Log.Error((int)AzureProviderErrorCode.AzureTableProvider_DeleteError, string.Format("Error {0}: GrainType={1} Grainid={2} ETag={3} from Table={4} Exception={5}", operation, grainType, grainReference, grainState.ETag, tableName, exc.Message), exc); throw; } } private static async Task DoOptimisticUpdate(Func<Task> updateOperation, string grainType, GrainReference grainReference, string tableName, string currentETag) { try { await updateOperation.Invoke().ConfigureAwait(false); } catch (StorageException ex) when (ex.IsPreconditionFailed()) { throw new TableStorageUpdateConditionNotSatisfiedException(grainType, grainReference, tableName, "Unknown", currentETag, ex); } } /// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat(object grainState, DynamicTableEntity entity) { int dataSize; IEnumerable<EntityProperty> properties; string basePropertyName; if (useJsonFormat) { // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm string data = Newtonsoft.Json.JsonConvert.SerializeObject(grainState, jsonSettings); if (Log.IsVerbose3) Log.Verbose3("Writing JSON data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); // each Unicode character takes 2 bytes dataSize = data.Length * 2; properties = SplitStringData(data).Select(t => new EntityProperty(t)); basePropertyName = STRING_DATA_PROPERTY_NAME; } else { // Convert to binary format byte[] data = this.serializationManager.SerializeToByteArray(grainState); if (Log.IsVerbose3) Log.Verbose3("Writing binary data size = {0} for grain id = Partition={1} / Row={2}", data.Length, entity.PartitionKey, entity.RowKey); dataSize = data.Length; properties = SplitBinaryData(data).Select(t => new EntityProperty(t)); basePropertyName = BINARY_DATA_PROPERTY_NAME; } CheckMaxDataSize(dataSize, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT); foreach (var keyValuePair in properties.Zip(GetPropertyNames(basePropertyName), (property, name) => new KeyValuePair<string, EntityProperty>(name, property))) { entity.Properties.Add(keyValuePair); } } private void CheckMaxDataSize(int dataSize, int maxDataSize) { if (dataSize > maxDataSize) { var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, maxDataSize); Log.Error(0, msg); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } private static IEnumerable<string> SplitStringData(string stringData) { var startIndex = 0; while (startIndex < stringData.Length) { var chunkSize = Math.Min(MAX_STRING_PROPERTY_LENGTH, stringData.Length - startIndex); yield return stringData.Substring(startIndex, chunkSize); startIndex += chunkSize; } } private static IEnumerable<byte[]> SplitBinaryData(byte[] binaryData) { var startIndex = 0; while (startIndex < binaryData.Length) { var chunkSize = Math.Min(MAX_DATA_CHUNK_SIZE, binaryData.Length - startIndex); var chunk = new byte[chunkSize]; Array.Copy(binaryData, startIndex, chunk, 0, chunkSize); yield return chunk; startIndex += chunkSize; } } private static IEnumerable<string> GetPropertyNames(string basePropertyName) { yield return basePropertyName; for (var i = 1; i < MAX_DATA_CHUNKS_COUNT; ++i) { yield return basePropertyName + i; } } private static IEnumerable<byte[]> ReadBinaryDataChunks(DynamicTableEntity entity) { foreach (var binaryDataPropertyName in GetPropertyNames(BINARY_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(binaryDataPropertyName, out dataProperty)) { switch (dataProperty.PropertyType) { // if TablePayloadFormat.JsonNoMetadata is used case EdmType.String: var stringValue = dataProperty.StringValue; if (!string.IsNullOrEmpty(stringValue)) { yield return Convert.FromBase64String(stringValue); } break; // if any payload type providing metadata is used case EdmType.Binary: var binaryValue = dataProperty.BinaryValue; if (binaryValue != null && binaryValue.Length > 0) { yield return binaryValue; } break; } } } } private static byte[] ReadBinaryData(DynamicTableEntity entity) { var dataChunks = ReadBinaryDataChunks(entity).ToArray(); var dataSize = dataChunks.Select(d => d.Length).Sum(); var result = new byte[dataSize]; var startIndex = 0; foreach (var dataChunk in dataChunks) { Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length); startIndex += dataChunk.Length; } return result; } private static IEnumerable<string> ReadStringDataChunks(DynamicTableEntity entity) { foreach (var stringDataPropertyName in GetPropertyNames(STRING_DATA_PROPERTY_NAME)) { EntityProperty dataProperty; if (entity.Properties.TryGetValue(stringDataPropertyName, out dataProperty)) { var data = dataProperty.StringValue; if (!string.IsNullOrEmpty(data)) { yield return data; } } } } private static string ReadStringData(DynamicTableEntity entity) { return string.Join(string.Empty, ReadStringDataChunks(entity)); } /// <summary> /// Deserialize from Azure storage format /// </summary> /// <param name="entity">The Azure table entity the stored data</param> internal object ConvertFromStorageFormat(DynamicTableEntity entity) { var binaryData = ReadBinaryData(entity); var stringData = ReadStringData(entity); object dataValue = null; try { if (binaryData.Length > 0) { // Rehydrate dataValue = this.serializationManager.DeserializeFromByteArray<object>(binaryData); } else if (!string.IsNullOrEmpty(stringData)) { dataValue = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(stringData, jsonSettings); } // Else, no data found } catch (Exception exc) { var sb = new StringBuilder(); if (binaryData.Length > 0) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData); } else if (!string.IsNullOrEmpty(stringData)) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData); } if (dataValue != null) { sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType()); } Log.Error(0, sb.ToString(), exc); throw new AggregateException(sb.ToString(), exc); } return dataValue; } private string GetKeyString(GrainReference grainReference) { var key = String.Format("{0}_{1}", serviceId, grainReference.ToKeyString()); return AzureStorageUtils.SanitizeTableProperty(key); } internal class GrainStateRecord { public string ETag { get; set; } public DynamicTableEntity Entity { get; set; } } private class GrainStateTableDataManager { public string TableName { get; private set; } private readonly AzureTableDataManager<DynamicTableEntity> tableManager; private readonly Logger logger; public GrainStateTableDataManager(string tableName, string storageConnectionString, Logger logger) { this.logger = logger; TableName = tableName; tableManager = new AzureTableDataManager<DynamicTableEntity>(tableName, storageConnectionString); } public Task InitTableAsync() { return tableManager.InitTableAsync(); } public async Task<GrainStateRecord> Read(string partitionKey, string rowKey) { if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Reading, "Reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); try { Tuple<DynamicTableEntity, string> data = await tableManager.ReadSingleTableEntryAsync(partitionKey, rowKey).ConfigureAwait(false); if (data == null || data.Item1 == null) { if (logger.IsVerbose2) logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading: PartitionKey={0} RowKey={1} from Table={2}", partitionKey, rowKey, TableName); return null; } DynamicTableEntity stateEntity = data.Item1; var record = new GrainStateRecord { Entity = stateEntity, ETag = data.Item2 }; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_DataRead, "Read: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", stateEntity.PartitionKey, stateEntity.RowKey, TableName, record.ETag); return record; } catch (Exception exc) { if (AzureStorageUtils.TableStorageDataNotFound(exc)) { if (logger.IsVerbose2) logger.Verbose2((int)AzureProviderErrorCode.AzureTableProvider_DataNotFound, "DataNotFound reading (exception): PartitionKey={0} RowKey={1} from Table={2} Exception={3}", partitionKey, rowKey, TableName, LogFormatter.PrintException(exc)); return null; // No data } throw; } } public async Task Write(GrainStateRecord record) { var entity = record.Entity; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Writing: PartitionKey={0} RowKey={1} to Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); string eTag = String.IsNullOrEmpty(record.ETag) ? await tableManager.CreateTableEntryAsync(entity).ConfigureAwait(false) : await tableManager.UpdateTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = eTag; } public async Task Delete(GrainStateRecord record) { var entity = record.Entity; if (logger.IsVerbose3) logger.Verbose3((int)AzureProviderErrorCode.AzureTableProvider_Storage_Writing, "Deleting: PartitionKey={0} RowKey={1} from Table={2} with ETag={3}", entity.PartitionKey, entity.RowKey, TableName, record.ETag); await tableManager.DeleteTableEntryAsync(entity, record.ETag).ConfigureAwait(false); record.ETag = null; } } /// <summary> Decodes Storage exceptions.</summary> public bool DecodeException(Exception e, out HttpStatusCode httpStatusCode, out string restStatus, bool getRESTErrors = false) { return AzureStorageUtils.EvaluateException(e, out httpStatusCode, out restStatus, getRESTErrors); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; namespace XSerializer { internal sealed class DictionaryJsonSerializer : IJsonSerializerInternal { private static readonly ConcurrentDictionary<Tuple<Type, bool, JsonMappings>, DictionaryJsonSerializer> _cache = new ConcurrentDictionary<Tuple<Type, bool, JsonMappings>, DictionaryJsonSerializer>(); private static readonly ConcurrentDictionary<Type, Func<object, object>> _getKeyFuncCache = new ConcurrentDictionary<Type, Func<object, object>>(); private static readonly ConcurrentDictionary<Type, Func<object, object>> _getValueFuncCache = new ConcurrentDictionary<Type, Func<object, object>>(); private readonly Action<JsonWriter, object, IJsonSerializeOperationInfo> _write; private readonly IJsonSerializerInternal _keySerializer; private readonly IJsonSerializerInternal _valueSerializer; private readonly Func<object> _createDictionary; private readonly Func<string, IJsonSerializeOperationInfo, object> _deserializeKey; private readonly Action<object, object, object> _addToDictionary; private readonly bool _encrypt; private readonly JsonMappings _mappings; private DictionaryJsonSerializer(Type type, bool encrypt, JsonMappings mappings) { _encrypt = encrypt; _mappings = mappings; Type keyType; if (type.IsAssignableToGenericIDictionary()) { var genericArguments = type.GetGenericArguments(); keyType = genericArguments[0]; if (typeof(IDictionary<string, object>).IsAssignableFrom(type)) { _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings); _write = GetIDictionaryOfStringToObjectWriteAction(); } else if (type.IsAssignableToGenericIDictionaryOfStringToAnything()) { _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings); _write = GetIDictionaryOfStringToAnythingWriteAction(); } else { _keySerializer = JsonSerializerFactory.GetSerializer(genericArguments[0], _encrypt, _mappings); _valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings); _write = GetIDictionaryOfAnythingToAnythingWriteAction(); } } else { keyType = typeof(object); _keySerializer = JsonSerializerFactory.GetSerializer(typeof(object), _encrypt, _mappings); _valueSerializer = _keySerializer; _write = GetIDictionaryOfAnythingToAnythingWriteAction(); } if (type.IsInterface) { if (type.IsGenericIDictionary()) { type = typeof(Dictionary<,>).MakeGenericType( type.GetGenericArguments()[0], type.GetGenericArguments()[1]); } else if (type == typeof(IDictionary)) { type = typeof(Dictionary<object, object>); } else { throw new NotSupportedException(type.FullName); } } _createDictionary = GetCreateDictionaryFunc(type); _deserializeKey = GetDeserializeKeyFunc(keyType); _addToDictionary = GetAddToDictionaryAction(type); } public static DictionaryJsonSerializer Get(Type type, bool encrypt, JsonMappings mappings) { return _cache.GetOrAdd(Tuple.Create(type, encrypt, mappings), t => new DictionaryJsonSerializer(t.Item1, t.Item2, t.Item3)); } public void SerializeObject(JsonWriter writer, object instance, IJsonSerializeOperationInfo info) { _write(writer, instance, info); } public object DeserializeObject(JsonReader reader, IJsonSerializeOperationInfo info) { if (!reader.ReadContent()) { throw new XSerializerException("Unexpected end of input while attempting to parse '{' character."); } if (reader.NodeType == JsonNodeType.Null) { return null; } if (_encrypt) { var toggler = new DecryptReadsToggler(reader); toggler.Toggle(); try { return Read(reader, info); } finally { toggler.Revert(); } } return Read(reader, info); } private object Read(JsonReader reader, IJsonSerializeOperationInfo info) { var dictionary = _createDictionary(); foreach (var keyString in reader.ReadProperties()) { var key = _deserializeKey(keyString, info); var value = _valueSerializer.DeserializeObject(reader, info); var jsonNumber = value as JsonNumber; if (jsonNumber != null) { value = jsonNumber.DoubleValue; } _addToDictionary(dictionary, key, value); } return dictionary; } private static Func<object> GetCreateDictionaryFunc(Type type) { var constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new ArgumentException("No default constructor for type: " + type + ".", "type"); } Expression invokeConstructor = Expression.New(constructor); if (type.IsValueType) // Boxing is necessary { invokeConstructor = Expression.Convert(invokeConstructor, typeof(object)); } var lambda = Expression.Lambda<Func<object>>(invokeConstructor); return lambda.Compile(); } private Func<string, IJsonSerializeOperationInfo, object> GetDeserializeKeyFunc(Type type) { if (type == typeof(string)) { return (keyString, info) => keyString; } var serializer = JsonSerializerFactory.GetSerializer(type, _encrypt, _mappings); return (keyString, info) => { try { using (var stringReader = new StringReader(keyString)) { using (var reader = new JsonReader(stringReader, info)) { return serializer.DeserializeObject(reader, info); } } } catch (XSerializerException) { return keyString; } }; } private static Action<object, object, object> GetAddToDictionaryAction(Type type) { var addMethod = type.GetMethods(BindingFlags.Public | BindingFlags.Instance).First(IsAddMethod); var keyType = addMethod.GetParameters()[0].ParameterType; var valueType = addMethod.GetParameters()[1].ParameterType; var dictionaryParameter = Expression.Parameter(typeof(object), "dictionary"); var keyParameter = Expression.Parameter(typeof(object), "key"); var valueParameter = Expression.Parameter(typeof(object), "value"); Expression key = keyParameter; if (keyType != typeof(object)) { key = Expression.Convert(keyParameter, keyType); } Expression value = valueParameter; if (valueType != typeof(object)) { value = Expression.Convert(valueParameter, valueType); } var call = Expression.Call( Expression.Convert(dictionaryParameter, type), addMethod, new[] { key, value }); var lambda = Expression.Lambda<Action<object, object, object>>(call, dictionaryParameter, keyParameter, valueParameter); return lambda.Compile(); } private static bool IsAddMethod(MethodInfo methodInfo) { if (methodInfo.Name == "Add") { var parameters = methodInfo.GetParameters(); if (parameters.Length == 2) // TODO: Better condition (check parameter type, etc.) { return true; } } return false; } private Action<JsonWriter, object, IJsonSerializeOperationInfo> GetIDictionaryOfStringToObjectWriteAction() { return (writer, instance, info) => { if (_encrypt) { var toggler = new EncryptWritesToggler(writer); toggler.Toggle(); WriteIDictionaryOfStringToObject(writer, instance, info); toggler.Revert(); } else { WriteIDictionaryOfStringToObject(writer, instance, info); } }; } private void WriteIDictionaryOfStringToObject(JsonWriter writer, object instance, IJsonSerializeOperationInfo info) { writer.WriteOpenObject(); var dictionary = (IDictionary<string, object>)instance; var first = true; foreach (var item in dictionary) { if (first) { first = false; } else { writer.WriteItemSeparator(); } writer.WriteValue(item.Key); writer.WriteNameValueSeparator(); _valueSerializer.SerializeObject(writer, item.Value, info); } writer.WriteCloseObject(); } private Action<JsonWriter, object, IJsonSerializeOperationInfo> GetIDictionaryOfStringToAnythingWriteAction() { return (writer, instance, info) => { if (_encrypt) { var toggler = new EncryptWritesToggler(writer); toggler.Toggle(); WriteIDictionaryOfStringToAnything(writer, instance, info); toggler.Revert(); } else { WriteIDictionaryOfStringToAnything(writer, instance, info); } }; } private void WriteIDictionaryOfStringToAnything(JsonWriter writer, object instance, IJsonSerializeOperationInfo info) { writer.WriteOpenObject(); var dictionary = (IEnumerable)instance; var first = true; Func<object, object> getKeyFunc = null; Func<object, object> getValueFunc = null; foreach (var item in dictionary) { if (first) { first = false; var itemType = item.GetType(); getKeyFunc = _getKeyFuncCache.GetOrAdd(itemType, GetGetKeyFunc); getValueFunc = _getValueFuncCache.GetOrAdd(itemType, GetGetValueFunc); } else { writer.WriteItemSeparator(); } writer.WriteValue((string)getKeyFunc(item)); writer.WriteNameValueSeparator(); _valueSerializer.SerializeObject(writer, getValueFunc(item), info); } writer.WriteCloseObject(); } private Action<JsonWriter, object, IJsonSerializeOperationInfo> GetIDictionaryOfAnythingToAnythingWriteAction() { return (writer, instance, info) => { if (_encrypt) { var toggler = new EncryptWritesToggler(writer); toggler.Toggle(); WriteIDictionaryOfAnythingToAnything(writer, instance, info); toggler.Revert(); } else { WriteIDictionaryOfAnythingToAnything(writer, instance, info); } }; } private void WriteIDictionaryOfAnythingToAnything(JsonWriter writer, object instance, IJsonSerializeOperationInfo info) { writer.WriteOpenObject(); var dictionary = (IEnumerable)instance; var first = true; Func<object, object> getKeyFunc = null; Func<object, object> getValueFunc = null; foreach (var item in dictionary) { if (first) { first = false; var itemType = item.GetType(); getKeyFunc = _getKeyFuncCache.GetOrAdd(itemType, GetGetKeyFunc); getValueFunc = _getValueFuncCache.GetOrAdd(itemType, GetGetValueFunc); } else { writer.WriteItemSeparator(); } var key = getKeyFunc(item); var keyString = key as string; if (keyString != null) { writer.WriteValue(keyString); } else { var sb = new StringBuilder(); using (var stringWriter = new StringWriterWithEncoding(sb, Encoding.UTF8)) { using (var keyWriter = new JsonWriter(stringWriter, info)) { _keySerializer.SerializeObject(keyWriter, key, info); } } writer.WriteValue((sb.ToString())); } writer.WriteNameValueSeparator(); _valueSerializer.SerializeObject(writer, getValueFunc(item), info); } writer.WriteCloseObject(); } private static Func<object, object> GetGetKeyFunc(Type keyValuePairType) { var parameter = Expression.Parameter(typeof(object), "keyValuePair"); var propertyInfo = keyValuePairType.GetProperty("Key"); Expression body = Expression.Property( Expression.Convert(parameter, keyValuePairType), propertyInfo); if (propertyInfo.PropertyType.IsValueType) { body = Expression.Convert(body, typeof(object)); } var lambda = Expression.Lambda<Func<object, object>>(body, new[] { parameter }); return lambda.Compile(); } private static Func<object, object> GetGetValueFunc(Type keyValuePairType) { var parameter = Expression.Parameter(typeof(object), "keyValuePair"); var propertyInfo = keyValuePairType.GetProperty("Value"); Expression body = Expression.Property( Expression.Convert(parameter, keyValuePairType), propertyInfo); if (propertyInfo.PropertyType.IsValueType) { body = Expression.Convert(body, typeof(object)); } var lambda = Expression.Lambda<Func<object, object>>(body, new[] { parameter }); return lambda.Compile(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Net; using System.Xml; using System.Collections.Specialized; using System.Collections.Generic; using System.Reflection; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Console; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.AssetService { public class ScatteredAssetService : AssetServiceBase, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The following fields implement and control the operation of the /// distributed asset serving stuff. All of these can be configured /// in the .ini file. See ScatteredAssetServerInit for details. /// </summary> internal List<RemoteAssetServer> RemoteServerList = new List<RemoteAssetServer>(); internal static string RRS_PORT = "9999"; internal const int AC_VERSION = 1; // Serialization compatability version internal bool DUMP = false; // Generate dump of transfer data streams internal string m_port = RRS_PORT; // port that this server listens on internal string m_prefix = "/rrs/assetserver"; // path that accepts requests internal string m_register = "/rrs/register"; // path that accepts server regs internal string m_rafile = "interop.txt"; // default static config file internal string m_server = String.Empty; // grid server uri internal string m_uri = String.Empty; // grid server uri internal BaseHttpServer m_httpServer; // RAS server instance public ScatteredAssetService(IConfigSource config) : base(config) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Initializing scattered asset service "); IConfig assetConfig = config.Configs["AssetService"]; MainConsole.Instance.Commands.AddCommand("kfs", false, "show digest", "show digest <ID>", "Show asset digest", HandleShowDigest); MainConsole.Instance.Commands.AddCommand("kfs", false, "delete asset", "delete asset <ID>", "Delete asset from database", HandleDeleteAsset); if (assetConfig == null) return; // Load the scattered extensions. Must be done before loading starts. ScatteredAssetServerInit(assetConfig); // Load "standard" assets if (m_AssetLoader != null) { string loaderArgs = assetConfig.GetString("AssetLoaderArgs", String.Empty); m_log.InfoFormat("[SCATTERED ASSET SERVICE] Loading default asset set from {0}", loaderArgs); m_AssetLoader.ForEachDefaultXmlAsset(loaderArgs, delegate(AssetBase a) { Store(a); }); m_log.Info("[SCATTERED ASSET SERVICE] Local asset service enabled"); } } // Synchronous GET request public AssetBase Get(string id) { AssetBase asset = null; UUID assetID; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY Sync.Get <{0}>", id); if(m_Database != null) { if (UUID.TryParse(id, out assetID)) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Sync.Get Searching Region database for <{0}>", id); asset = m_Database.GetAsset(assetID); } } if((asset == null) && (m_server != String.Empty)) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Sync.Get Searching GRID database for <{0}>", id); asset = SynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", m_uri, 0); } if (asset == null) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Sync.Get Searching scattered databases for <{0}>", id); asset = lookElseWhere(id); } if(asset == null) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Sync.Get Failed to resolve <{0}>", id); } m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT Sync.Get <{0}>", id); return asset; } public AssetMetadata GetMetadata(string id) { AssetBase asset = null; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY Request metadata for <{0}>", id); asset = Get(id); m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT Request metadata for <{0}>", id); if(asset != null) return asset.Metadata; else return null; } public byte[] GetData(string id) { AssetBase asset = null; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY Request content for <{0}>", id); asset = Get(id); m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT Request content for <{0}>", id); if(asset != null) return asset.Data; else return null; } // Asynchronous GET request - call handler public bool Get(string id, Object sender, AssetRetrieved handler) { AssetBase asset = null; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY ASync Request content for <{0}>", id); asset = Get(id); handler(id, sender, asset); m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT ASync Request content for <{0}>", id); return true; } public string Store(AssetBase asset) { UUID assetID; string newID = String.Empty; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY Store <{0}>", asset.ID); //if(asset.Temporary) //{ // m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT <{0}> is temporary, not stored anywhere", asset.ID); // return asset.ID; //} // If the local data base exists, and the ID is // a valid UUID. Look to see if the asset // already exists. If it does, then store it // and return the newly assigned asset ID. if (m_Database != null) { if (UUID.TryParse(asset.ID, out assetID)) { if (m_Database.ExistsAsset(assetID)) { asset.FullID = UUID.Random(); asset.ID = asset.FullID.ToString(); } m_log.DebugFormat("[SCATTERED ASSET SERVICE] Storing {0} locally", asset.ID); m_Database.StoreAsset(asset); newID = asset.ID; } } if(! asset.Local && m_server != String.Empty) { try { newID = SynchronousRestObjectRequester. MakeRequest<AssetBase, string>("POST", m_uri, asset); m_log.DebugFormat("[SCATTERED ASSET SERVICE] Stored {0} on GRID asset server", asset.ID); } catch (Exception e) { m_log.WarnFormat("[SCATTERED ASSET SERVICE] Failed to forward {0} to server. Reason: {1}", asset.ID, e.Message); newID = asset.ID; } } m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT Store <{0}/{1}>", asset.ID, newID); return newID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY Conditionally update content of {0}", id); asset = Get(id); if (asset == null) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] {0} does not already exist", id); AssetMetadata metadata = GetMetadata(id); if (metadata == null) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT Failed to create metadata for {0}", id); return false; } asset = new AssetBase(); asset.Metadata = metadata; } asset.Data = data; id = Store(asset); m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT Conditionally update content of <{0}>", asset.ID); return (id != String.Empty); } public bool Delete(string id) { AssetBase asset; m_log.DebugFormat("[SCATTERED ASSET SERVICE] ENTRY {0} delete requested", id); asset = Get(id); if(asset != null) { // Just from the local database, if it is there if (asset != null && (asset.Local || asset.Temporary)) { m_log.WarnFormat("[SCATTERED ASSET SERVICE] <{0}> local deletion not supported"); } else if(m_server != String.Empty) { if (SynchronousRestObjectRequester. MakeRequest<int, bool>("DELETE", m_uri, 0)) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT <{0}> server deletion complete"); return true; } } } m_log.DebugFormat("[SCATTERED ASSET SERVICE] EXIT {0} delete failed", id); return false; } void HandleShowDigest(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: show digest <ID>"); return; } AssetBase asset = Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } int i; MainConsole.Instance.Output(String.Format("Name: {0}", asset.Name)); MainConsole.Instance.Output(String.Format("Description: {0}", asset.Description)); MainConsole.Instance.Output(String.Format("Type: {0}", asset.Type)); MainConsole.Instance.Output(String.Format("Content-type: {0}", asset.Metadata.ContentType)); for (i = 0 ; i < 5 ; i++) { int off = i * 16; if (asset.Data.Length <= off) break; int len = 16; if (asset.Data.Length < off + len) len = asset.Data.Length - off; byte[] line = new byte[len]; Array.Copy(asset.Data, off, line, 0, len); string text = BitConverter.ToString(line); MainConsole.Instance.Output(String.Format("{0:x4}: {1}", off, text)); } } void HandleDeleteAsset(string module, string[] args) { if (args.Length < 3) { MainConsole.Instance.Output("Syntax: delete asset <ID>"); return; } AssetBase asset = Get(args[2]); if (asset == null || asset.Data.Length == 0) { MainConsole.Instance.Output("Asset not found"); return; } Delete(args[2]); //MainConsole.Instance.Output("Asset deleted"); // TODO: Implement this MainConsole.Instance.Output("Asset deletion not supported by database"); } #region remote asset server /// <summary> /// This is the common remote asset search method. It is called /// for both client and region requests. It tries all of the /// remote servers it knows about and declares victory on the /// first positive response. If it cannot be found, then a null /// reference is returned. /// </summary> private AssetBase lookElseWhere(string assetId) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Searching for <{0}>", assetId); AssetBase asset; RemoteAssetServer[] servers = RemoteServerList.ToArray(); foreach (RemoteAssetServer server in servers) { if (server.GetAsset(assetId, out asset)) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Asset resolved {0} by server {1}", assetId, server.ID); return asset; } } m_log.DebugFormat("[SCATTERED ASSET SERVICE] {0} not found", assetId); return null; } /// <summary> /// This method hides the mechanics of maintaining the list /// of known servers. /// [AMW] A more sophisticated mechanism is needed. /// </summary> private void AddRemoteServer(string ipa, string port, string prefix) { RemoteServerList.Add(new RemoteAssetServer(this, ipa, port, prefix)); } private bool FindRemoteServer(string ipa, string port) { foreach (RemoteAssetServer server in RemoteServerList) if (server.ipa == ipa && server.port == port) return true; return false; } /// <summary> /// This class represents a remote server. All communication /// is via this class. /// </summary> public class RemoteAssetServer { private ScatteredAssetService g_service = null; private bool g_rrs; private string g_ipa; private string g_port; private string g_prefix; public string ipa { get { return g_ipa; } } public string port { get { return g_port; } } public string prefix { get { return g_prefix; } } public string ID { get { return g_ipa+":"+g_port+":"+g_prefix; }} public RemoteAssetServer(ScatteredAssetService service, string ipa, string port, string prefix) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] {0} {1} {2} added to known server table", ipa, port, prefix); g_service = service; g_ipa = ipa; g_port = port; g_prefix = prefix; g_rrs = (port == RRS_PORT); } private static readonly string GAP1 = "http://{0}:{1}{2}?asset={3}"; private static readonly string GAP2 = "http://{0}:{1}{2}{3}"; public bool GetAsset(string assetid, out AssetBase asset) { if (g_rrs) { string requrl = String.Format(GAP1, g_ipa, g_port, g_prefix, assetid); XmlElement resp; m_log.DebugFormat("[SCATTERED ASSET SERVICE] RSS request sent to <{0}>", requrl); if (webCall(requrl, out resp)) { string text; if (XmlFind(resp, "body.asset", out text)) { int version = 0; if (XmlFind(resp, "body.asset.version", out text)) version = Convert.ToInt32(text); // For now we will assume backward compatability if(version >= AC_VERSION) { asset = new AssetBase(); if (XmlFind(resp, "body.asset.data", out text)) asset.Data = Convert.FromBase64String(text); if (XmlFind(resp, "body.asset.id", out text)) asset.Metadata.ID = text; if (XmlFind(resp, "body.asset.fullid", out text)) asset.Metadata.FullID = new UUID(text); if (XmlFind(resp, "body.asset.name", out text)) asset.Metadata.Name = text; if (XmlFind(resp, "body.asset.desc", out text)) asset.Metadata.Description = text; if (XmlFind(resp, "body.asset.type", out text)) asset.Metadata.Type = SByte.Parse(text); if (XmlFind(resp, "body.asset.ctype", out text)) asset.Metadata.ContentType = text; asset.Metadata.Temporary = true; asset.Metadata.Local = true; return true; } } } } else { string requrl = String.Format(GAP2, g_ipa, g_port, "/assets/", assetid); m_log.DebugFormat("[SCATTERED ASSET SERVICE] OSS request sent to <{0}>", requrl); asset = SynchronousRestObjectRequester. MakeRequest<int, AssetBase>("GET", requrl, 0); if ( asset != null) return true; } m_log.DebugFormat("[SCATTERED ASSET SERVICE] Could not resolve <{0}>", assetid); asset = null; return false; } private bool webCall(string requrl, out XmlElement resp) { // Otherwise prepare the request resp = null; HttpWebRequest req = null; HttpWebResponse rsp = null; try { req = (HttpWebRequest)WebRequest.Create(requrl); req.ContentLength = 0; // We are sending just parameters, no content // Send request and retrieve the response rsp = (HttpWebResponse) req.GetResponse(); XmlTextReader rdr = new XmlTextReader(rsp.GetResponseStream()); XmlDocument doc = new XmlDocument(); doc.Load(rdr); rdr.Close(); // If we're debugging server responses, dump the whole // load now if (g_service.DUMP) XmlScanl(doc.DocumentElement,0); resp = doc.DocumentElement; return true; } catch (WebException w) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Web exception: {0}", w.Message); } return false; } /// <summary> /// The XmlScan routine is provided to aid in the /// debugging of exchanged packets. It works if the /// DUMP switch is set. /// </summary> private void XmlScanl(XmlElement e, int index) { if (e.HasChildNodes) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] <{0}>".PadLeft(index+14), e.Name); XmlNodeList children = e.ChildNodes; foreach (XmlNode node in children) switch (node.NodeType) { case XmlNodeType.Element : XmlScanl((XmlElement)node, index+1); break; case XmlNodeType.Text : m_log.DebugFormat("[SCATTERED ASSET SERVICE] \"{0}\"".PadLeft(index+14), node.Value); break; default : break; } m_log.DebugFormat("[SCATTERED ASSET SERVICE] </{0}>".PadLeft(index+15), e.Name); } else { m_log.DebugFormat("[SCATTERED ASSET SERVICE] <{0}/>".PadLeft(index+15), e.Name); } } /// <summary> /// The Find method is passed an element whose /// inner text is scanned in an attempt to match /// the name hierarchy passed in the 'tag' parameter. /// If the whole hierarchy is resolved, the InnerText /// value at that point is returned. Note that this /// may itself be a subhierarchy of the entire /// document. The function returns a boolean indicator /// of the search's success. The search is performed /// by the recursive Search method. /// </summary> private static readonly char[] C_POINT = {'.'}; private bool XmlFind(XmlElement root, string tag, out string result) { int nth = 0; if (root == null || tag == null || tag == String.Empty) { result = String.Empty; return false; } return XmlSearch(root,tag.Split(C_POINT),0, ref nth, out result); } /// <summary> /// XmlSearch is initially called by XmlFind, and then /// recursively called by itself until the document /// supplied to XmlFind is either exhausted or the name hierarchy /// is matched. /// /// If the hierarchy is matched, the value is returned in /// result, and true returned as the function's /// value. Otherwise the result is set to the empty string and /// false is returned. /// </summary> private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result) { if (index == tags.Length || e.Name != tags[index]) { result = String.Empty; return false; } if (tags.Length-index == 1) { if (nth == 0) { result = e.InnerText; return true; } else { nth--; result = String.Empty; return false; } } if (e.HasChildNodes) { XmlNodeList children = e.ChildNodes; foreach (XmlNode node in children) { switch (node.NodeType) { case XmlNodeType.Element : if (XmlSearch((XmlElement)node, tags, index+1, ref nth, out result)) return true; break; default : break; } } } result = String.Empty; return false; } } #endregion #region Agent Asset Server private void ScatteredAssetServerInit(IConfig config) { // Agent parameters DUMP = config.GetBoolean("RASXML", DUMP); m_port = config.GetString("RASPort", RRS_PORT); m_prefix = config.GetString("RASRequestPath", m_prefix); m_register = config.GetString("RASRegisterPath", m_register); m_rafile = config.GetString("RASConfig", m_rafile); m_server = config.GetString("AssetServerURI", String.Empty); if(m_server != String.Empty) { m_uri = String.Format("{0}/assets/", m_server); AddServer(m_server); } if(File.Exists(m_rafile)) { // Load the starting set of known asset servers string local = Util.GetLocalHost().ToString(); try { string[] slist = File.ReadAllLines(m_rafile); foreach (string s in slist) { if (s != local) { string line = s.Trim(); if (!line.StartsWith("#")) { string[] parts = line.Split('='); switch (parts[0].Trim().ToLower()) { case "localport" : m_log.InfoFormat("[SCATTERED ASSET SERVICE] Setting server listener port to {0}", s); m_port = parts[1].Trim(); break; case "prefix" : m_log.InfoFormat("[SCATTERED ASSET SERVICE] Setting asset server prefix to {0}", s); m_prefix = parts[1].Trim(); break; case "register" : m_log.InfoFormat("[SCATTERED ASSET SERVICE] Setting registration prefix to {0}", s); m_register = parts[1].Trim(); break; case "server" : AddServer(parts[1]); break; default : m_log.DebugFormat("[SCATTERED ASSET SERVICE] Unrecognized command {0}:{1}", parts[0], parts[1]); break; } } else { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Ignoring line {0}", s); } } else m_log.DebugFormat("[SCATTERED ASSET SERVICE] Ignoring local host {0}", s); } } catch(Exception e) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Failed to read configuration file. {0}", e.Message); } } m_httpServer = new BaseHttpServer((uint) Convert.ToInt32(m_port)); m_httpServer.Start(); m_httpServer.AddStreamHandler(new RestStreamHandler("GET", m_prefix, RemoteRequest)); m_httpServer.AddStreamHandler(new RestStreamHandler("GET", m_register, RegisterServer)); } private void AddServer(string addr) { string port = String.Empty; string path = String.Empty; int ci; m_log.InfoFormat("[SCATTERED ASSET SERVICE] Registering host {0}", addr); if (addr == String.Empty) return; if (addr.StartsWith("http://")) addr = addr.Substring(7); ci = addr.IndexOf('/'); if (ci != -1) { path = addr.Substring(ci, addr.Length-ci).Trim(); addr = addr.Substring(0,ci).Trim(); } ci = addr.IndexOf(':'); if (ci != -1) { port = addr.Substring(ci+1, addr.Length-ci-1).Trim(); addr = addr.Substring(0,ci).Trim(); } addr = addr.Trim(); // If our special port is used, it MUST be our special path if (port == m_port) path = m_prefix; if (port == String.Empty) port = "80"; if (addr != String.Empty) AddRemoteServer(addr, port, path); } #endregion #region Remote web interface // This is WAY too promiscuous, but will suffice for initial testing private string RegisterServer(string body, string path, string parms, OSHttpRequest req, OSHttpResponse rsp) { NameValueCollection qstr = req.QueryString; m_log.DebugFormat("[SCATTERED ASSET SERVICE] Register http://{0}:{1}{2}({3})", req.Headers["remote_addr"], req.Headers["remote_port"], path, parms); string ipa = getValue(qstr, "ip", String.Empty); string port = getValue(qstr, "port", String.Empty); AddRemoteServer(ipa, port, m_prefix); return String.Empty; } private string RemoteRequest(string body, string path, string parms, OSHttpRequest req, OSHttpResponse rsp) { AssetBase asset = null; string response = String.Empty; NameValueCollection qstr = req.QueryString; NameValueCollection hdrs = req.Headers; if (DUMP) m_log.DebugFormat("[SCATTERED ASSET SERVICE] Remote request for received: http://{0}:{1}{2}({3})", req.Headers["remote_addr"], req.Headers["remote_port"], path, parms); // Remember all who try to talk to us ... if (!FindRemoteServer(req.Headers["remote_addr"], RRS_PORT)) AddRemoteServer(req.Headers["remote_addr"], RRS_PORT, m_prefix); if (DUMP) { foreach (string key in qstr.AllKeys) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Query: {0:-10}:{1}", key, qstr.Get(key)); } foreach (string key in hdrs.AllKeys) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] Header: {0:-10}:{1}", key, hdrs.Get(key)); } } string assetid = getValue(qstr, "asset", String.Empty); m_log.DebugFormat("[SCATTERED ASSET SERVICE] Remote request for asset base {0}", assetid); if(m_Database != null) { asset = m_Database.GetAsset(new UUID(assetid)); } if (asset == null) { m_log.DebugFormat("[SCATTERED ASSET SERVICE] {0} was not found locally", assetid); rsp.StatusCode = 404; rsp.StatusDescription = "Asset not found"; } else { m_log.DebugFormat("[SCATTERED ASSET SERVICE] {0} was resolved successfully", assetid); // Explicit serialization protects us from server // differences response = String.Format("<body><asset>{0}</asset></body>", String.Format("<version>{0}</version>", AC_VERSION) + String.Format("<data>{0}</data>", Convert.ToBase64String(asset.Data)) + String.Format("<id>{0}</id>", asset.Metadata.ID) + String.Format("<fullid>{0}</fullid>", asset.Metadata.FullID.ToString()) + String.Format("<name>{0}</name>", asset.Metadata.Name) + String.Format("<desc>{0}</desc>", asset.Metadata.Description) + String.Format("<type>{0}</type>", asset.Metadata.Type) + String.Format("<ctype>{0}</ctype>", asset.Metadata.ContentType) + String.Format("<local>{0}</local>", asset.Metadata.Local) + String.Format("<temp>{0}</temp>", asset.Metadata.Temporary) ); } return response; } private string getValue(NameValueCollection coll, string key, string dft) { try { return coll[key]; } catch (Exception) { return dft; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests { internal abstract class EditAndContinueTestHelpers { public abstract AbstractEditAndContinueAnalyzer Analyzer { get; } public abstract SyntaxNode FindNode(SyntaxNode root, TextSpan span); public abstract SyntaxTree ParseText(string source); public abstract Compilation CreateLibraryCompilation(string name, IEnumerable<SyntaxTree> trees); public abstract ImmutableArray<SyntaxNode> GetDeclarators(ISymbol method); internal void VerifyUnchangedDocument( string source, ActiveStatementSpan[] oldActiveStatements, TextSpan?[] trackingSpansOpt, TextSpan[] expectedNewActiveStatements, ImmutableArray<TextSpan>[] expectedOldExceptionRegions, ImmutableArray<TextSpan>[] expectedNewExceptionRegions) { var text = SourceText.From(source); var tree = ParseText(source); var root = tree.GetRoot(); tree.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument"); TestActiveStatementTrackingService trackingService; if (trackingSpansOpt != null) { trackingService = new TestActiveStatementTrackingService(documentId, trackingSpansOpt); } else { trackingService = null; } var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length]; var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length]; Analyzer.AnalyzeUnchangedDocument( oldActiveStatements.AsImmutable(), text, root, documentId, trackingService, actualNewActiveStatements, actualNewExceptionRegions); // check active statements: AssertSpansEqual(expectedNewActiveStatements, actualNewActiveStatements, source, text); // check new exception regions: Assert.Equal(expectedNewExceptionRegions.Length, actualNewExceptionRegions.Length); for (int i = 0; i < expectedNewExceptionRegions.Length; i++) { AssertSpansEqual(expectedNewExceptionRegions[i], actualNewExceptionRegions[i], source, text); } } internal void VerifyRudeDiagnostics( EditScript<SyntaxNode> editScript, ActiveStatementsDescription description, RudeEditDiagnosticDescription[] expectedDiagnostics) { var oldActiveStatements = description.OldSpans; if (description.TrackingSpans != null) { Assert.Equal(oldActiveStatements.Length, description.TrackingSpans.Length); } string newSource = editScript.Match.NewRoot.SyntaxTree.ToString(); string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString(); var oldText = SourceText.From(oldSource); var newText = SourceText.From(newSource); var diagnostics = new List<RudeEditDiagnostic>(); var actualNewActiveStatements = new LinePositionSpan[oldActiveStatements.Length]; var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[oldActiveStatements.Length]; var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMethodInfo>(); var editMap = Analyzer.BuildEditMap(editScript); DocumentId documentId = DocumentId.CreateNewId(ProjectId.CreateNewId("TestEnCProject"), "TestEnCDocument"); TestActiveStatementTrackingService trackingService; if (description.TrackingSpans != null) { trackingService = new TestActiveStatementTrackingService(documentId, description.TrackingSpans); } else { trackingService = null; } Analyzer.AnalyzeSyntax( editScript, editMap, oldText, newText, documentId, trackingService, oldActiveStatements.AsImmutable(), actualNewActiveStatements, actualNewExceptionRegions, updatedActiveMethodMatches, diagnostics); diagnostics.Verify(newSource, expectedDiagnostics); // check active statements: AssertSpansEqual(description.NewSpans, actualNewActiveStatements, newSource, newText); if (diagnostics.Count == 0) { // check old exception regions: for (int i = 0; i < oldActiveStatements.Length; i++) { var actualOldExceptionRegions = Analyzer.GetExceptionRegions( oldText, editScript.Match.OldRoot, oldActiveStatements[i].Span, isLeaf: (oldActiveStatements[i].Flags & ActiveStatementFlags.LeafFrame) != 0); AssertSpansEqual(description.OldRegions[i], actualOldExceptionRegions, oldSource, oldText); } // check new exception regions: Assert.Equal(description.NewRegions.Length, actualNewExceptionRegions.Length); for (int i = 0; i < description.NewRegions.Length; i++) { AssertSpansEqual(description.NewRegions[i], actualNewExceptionRegions[i], newSource, newText); } } else { for (int i = 0; i < oldActiveStatements.Length; i++) { Assert.Equal(0, description.NewRegions[i].Length); } } if (description.TrackingSpans != null) { AssertEx.Equal(trackingService.TrackingSpans, description.NewSpans.Select(s => (TextSpan?)s)); } } internal void VerifyLineEdits( EditScript<SyntaxNode> editScript, IEnumerable<LineChange> expectedLineEdits, IEnumerable<string> expectedNodeUpdates, RudeEditDiagnosticDescription[] expectedDiagnostics) { string newSource = editScript.Match.NewRoot.SyntaxTree.ToString(); string oldSource = editScript.Match.OldRoot.SyntaxTree.ToString(); var oldText = SourceText.From(oldSource); var newText = SourceText.From(newSource); var diagnostics = new List<RudeEditDiagnostic>(); var editMap = Analyzer.BuildEditMap(editScript); var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); var actualLineEdits = new List<LineChange>(); Analyzer.AnalyzeTrivia( oldText, newText, editScript.Match, editMap, triviaEdits, actualLineEdits, diagnostics, default(CancellationToken)); diagnostics.Verify(newSource, expectedDiagnostics); AssertEx.Equal(expectedLineEdits, actualLineEdits, itemSeparator: ",\r\n"); var actualNodeUpdates = triviaEdits.Select(e => e.Value.ToString().ToLines().First()); AssertEx.Equal(expectedNodeUpdates, actualNodeUpdates, itemSeparator: ",\r\n"); } internal void VerifySemantics( EditScript<SyntaxNode> editScript, ActiveStatementsDescription activeStatements, IEnumerable<string> additionalOldSources, IEnumerable<string> additionalNewSources, SemanticEditDescription[] expectedSemanticEdits, RudeEditDiagnosticDescription[] expectedDiagnostics) { var editMap = Analyzer.BuildEditMap(editScript); var oldRoot = editScript.Match.OldRoot; var newRoot = editScript.Match.NewRoot; var oldSource = oldRoot.SyntaxTree.ToString(); var newSource = newRoot.SyntaxTree.ToString(); var oldText = SourceText.From(oldSource); var newText = SourceText.From(newSource); IEnumerable<SyntaxTree> oldTrees = new[] { oldRoot.SyntaxTree }; IEnumerable<SyntaxTree> newTrees = new[] { newRoot.SyntaxTree }; if (additionalOldSources != null) { oldTrees = oldTrees.Concat(additionalOldSources.Select(s => ParseText(s))); } if (additionalOldSources != null) { newTrees = newTrees.Concat(additionalNewSources.Select(s => ParseText(s))); } var oldCompilation = CreateLibraryCompilation("Old", oldTrees); var newCompilation = CreateLibraryCompilation("New", newTrees); if (oldCompilation is CSharpCompilation) { oldCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); newCompilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); } else { // TODO: verify all compilation diagnostics like C# does (tests need to be updated) oldTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); newTrees.SelectMany(tree => tree.GetDiagnostics()).Where(d => d.Severity == DiagnosticSeverity.Error).Verify(); } var oldModel = oldCompilation.GetSemanticModel(oldRoot.SyntaxTree); var newModel = newCompilation.GetSemanticModel(newRoot.SyntaxTree); var oldActiveStatements = activeStatements.OldSpans.AsImmutable(); var updatedActiveMethodMatches = new List<AbstractEditAndContinueAnalyzer.UpdatedMethodInfo>(); var triviaEdits = new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); var actualLineEdits = new List<LineChange>(); var actualSemanticEdits = new List<SemanticEdit>(); var diagnostics = new List<RudeEditDiagnostic>(); var actualNewActiveStatements = new LinePositionSpan[activeStatements.OldSpans.Length]; var actualNewExceptionRegions = new ImmutableArray<LinePositionSpan>[activeStatements.OldSpans.Length]; Analyzer.AnalyzeSyntax( editScript, editMap, oldText, newText, null, null, oldActiveStatements, actualNewActiveStatements, actualNewExceptionRegions, updatedActiveMethodMatches, diagnostics); diagnostics.Verify(newSource); Analyzer.AnalyzeTrivia( oldText, newText, editScript.Match, editMap, triviaEdits, actualLineEdits, diagnostics, default(CancellationToken)); diagnostics.Verify(newSource); Analyzer.AnalyzeSemantics( editScript, editMap, oldText, oldActiveStatements, triviaEdits, updatedActiveMethodMatches, oldModel, newModel, actualSemanticEdits, diagnostics, default(CancellationToken)); diagnostics.Verify(newSource, expectedDiagnostics); if (expectedSemanticEdits == null) { return; } Assert.Equal(expectedSemanticEdits.Length, actualSemanticEdits.Count); for (int i = 0; i < actualSemanticEdits.Count; i++) { var editKind = expectedSemanticEdits[i].Kind; Assert.Equal(editKind, actualSemanticEdits[i].Kind); var expectedOldSymbol = (editKind == SemanticEditKind.Update) ? expectedSemanticEdits[i].SymbolProvider(oldCompilation) : null; var expectedNewSymbol = expectedSemanticEdits[i].SymbolProvider(newCompilation); var actualOldSymbol = actualSemanticEdits[i].OldSymbol; var actualNewSymbol = actualSemanticEdits[i].NewSymbol; Assert.Equal(expectedOldSymbol, actualOldSymbol); Assert.Equal(expectedNewSymbol, actualNewSymbol); var expectedSyntaxMap = expectedSemanticEdits[i].SyntaxMap; var actualSyntaxMap = actualSemanticEdits[i].SyntaxMap; Assert.Equal(expectedSemanticEdits[i].PreserveLocalVariables, actualSemanticEdits[i].PreserveLocalVariables); if (expectedSyntaxMap != null) { Assert.NotNull(actualSyntaxMap); Assert.True(expectedSemanticEdits[i].PreserveLocalVariables); var newNodes = new List<SyntaxNode>(); foreach (var expectedSpanMapping in expectedSyntaxMap) { var newNode = FindNode(newRoot, expectedSpanMapping.Value); var expectedOldNode = FindNode(oldRoot, expectedSpanMapping.Key); var actualOldNode = actualSyntaxMap(newNode); Assert.Equal(expectedOldNode, actualOldNode); newNodes.Add(newNode); } } else { Assert.Null(actualSyntaxMap); } } } private static void AssertSpansEqual(IList<TextSpan> expected, IList<LinePositionSpan> actual, string newSource, SourceText newText) { AssertEx.Equal( expected, actual.Select(span => newText.Lines.GetTextSpan(span)), itemSeparator: "\r\n", itemInspector: s => DisplaySpan(newSource, s)); } private static string DisplaySpan(string source, TextSpan span) { return span + ": [" + source.Substring(span.Start, span.Length).Replace("\r\n", " ") + "]"; } internal static IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> GetMethodMatches(AbstractEditAndContinueAnalyzer analyzer, Match<SyntaxNode> bodyMatch) { Dictionary<SyntaxNode, AbstractEditAndContinueAnalyzer.LambdaInfo> lazyActiveOrMatchedLambdas = null; var map = analyzer.ComputeMap(bodyMatch, Array.Empty<AbstractEditAndContinueAnalyzer.ActiveNode>(), ref lazyActiveOrMatchedLambdas, new List<RudeEditDiagnostic>()); var result = new Dictionary<SyntaxNode, SyntaxNode>(); foreach (var pair in map.Forward) { if (pair.Value == bodyMatch.NewRoot) { Assert.Same(pair.Key, bodyMatch.OldRoot); continue; } result.Add(pair.Key, pair.Value); } return result; } public static MatchingPairs ToMatchingPairs(Match<SyntaxNode> match) { return ToMatchingPairs(match.Matches.Where(partners => partners.Key != match.OldRoot)); } public static MatchingPairs ToMatchingPairs(IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>> matches) { return new MatchingPairs(matches .OrderBy(partners => partners.Key.GetLocation().SourceSpan.Start) .ThenByDescending(partners => partners.Key.Span.Length) .Select(partners => new MatchingPair { Old = partners.Key.ToString().Replace("\r\n", " ").Replace("\n", " "), New = partners.Value.ToString().Replace("\r\n", " ").Replace("\n", " ") })); } private static IEnumerable<KeyValuePair<K, V>> ReverseMapping<K, V>(IEnumerable<KeyValuePair<V, K>> mapping) { foreach (var pair in mapping) { yield return KeyValuePair.Create(pair.Value, pair.Key); } } } internal static class EditScriptTestUtils { public static void VerifyEdits<TNode>(this EditScript<TNode> actual, params string[] expected) { AssertEx.Equal(expected, actual.Edits.Select(e => e.GetDebuggerDisplay()), itemSeparator: ",\r\n"); } } }
/****************************** Module Header ******************************\ * Module Name: PropertyPage.cs * Project: CSVSXProjectSubType * Copyright (c) Microsoft Corporation. * * A PropertyPage object contains a PropertyStore object which stores the Properties, * and a PageView object which is a UserControl used to display the Properties. * * The IPropertyPage and IPropertyPage2 Interfaces provide the main features of * a property page object that manages a particular page within a property sheet. * * A property page implements at least IPropertyPage and can optionally implement * IPropertyPage2 if selection of a specific property is supported. See * http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.ole.interop.ipropertypage2.aspx * http://msdn.microsoft.com/en-us/library/ms683996(VS.85).aspx * * * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; namespace InsmaSoftware.MXA_Game_Studio.PropertyPageBase { abstract public class PropertyPage : IPropertyPage2, IPropertyPage, IPageViewSite { private IPropertyPageSite propertyPageSite; /// <summary> /// Use a site object with this interface to set up communications between the /// property frame and the property page object. /// http://msdn.microsoft.com/en-us/library/ms690583(VS.85).aspx /// </summary> public IPropertyPageSite PropertyPageSite { get { return propertyPageSite; } set { propertyPageSite = value; } } private IPropertyStore propertyStore; /// <summary> /// A PropertyStore object is used to store the Properties of a /// PropertyPage object. /// </summary> public IPropertyStore PropertyStore { get { return propertyStore; } set { propertyStore = value; } } protected IPageView myPageView; /// <summary> /// A PageView is a UserControl that is used to display the Properties of a /// PropertyPage object. /// </summary> public IPageView MyPageView { get { if (myPageView == null) { IPageView concretePageView = GetNewPageView( ); this.MyPageView = concretePageView; } return myPageView; } set { myPageView = value; } } // The changed Property Name / Value KeyValuePair. private KeyValuePair<string, string>? propertyToBePersisted; /// <summary> /// The Property Page Title that is displayed in Visual Studio. /// </summary> abstract public string Title { get; } /// <summary> /// The HelpKeyword if F1 is pressed. By default, it will return String.Empty. /// </summary> protected abstract string HelpKeyword { get; } abstract protected IPageView GetNewPageView( ); abstract protected IPropertyStore GetNewPropertyStore( ); protected PropertyPage( ) { } #region IPropertyPage2 Members /// <summary> /// Initialize a property page and provides the page with a pointer to the /// IPropertyPageSite interface through which the property page communicates /// with the property frame. /// </summary> public void SetPageSite(IPropertyPageSite pPageSite) { PropertyPageSite = pPageSite; } /// <summary> /// Create the dialog box window for the property page. /// The dialog box is created without a frame, caption, or system menu/controls. /// </summary> /// <param name="hWndParent"> /// The window handle of the parent of the dialog box that is being created. /// </param> /// <param name="pRect"> /// The RECT structure containing the positioning information for the dialog box. /// This method must create its dialog box with the placement and dimensions /// described by this structure. /// </param> /// <param name="bModal"> /// Indicates whether the dialog box frame is modal (TRUE) or modeless (FALSE). /// </param> public void Activate(IntPtr hWndParent, RECT[] pRect, int bModal) { if ((pRect == null) || (pRect.Length == 0)) { throw new ArgumentNullException("pRect"); } Control parentControl = Control.FromHandle(hWndParent); RECT rect = pRect[0]; this.MyPageView.Initialize(parentControl, Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom)); } /// <summary> /// Destroy the window created in IPropertyPage::Activate. /// </summary> public void Deactivate( ) { if (this.myPageView != null) { this.myPageView.Dispose( ); this.myPageView = null; } } /// <summary> /// Retrieve information about the property page. /// </summary> /// <param name="pPageInfo"></param> public void GetPageInfo(PROPPAGEINFO[] pPageInfo) { PROPPAGEINFO proppageinfo; if ((pPageInfo == null) || (pPageInfo.Length == 0)) { throw new ArgumentNullException("pPageInfo"); } proppageinfo.cb = (uint)Marshal.SizeOf(typeof(PROPPAGEINFO)); proppageinfo.dwHelpContext = 0; proppageinfo.pszDocString = null; proppageinfo.pszHelpFile = null; proppageinfo.pszTitle = this.Title; proppageinfo.SIZE.cx = this.MyPageView.ViewSize.Width; proppageinfo.SIZE.cy = this.MyPageView.ViewSize.Height; pPageInfo[0] = proppageinfo; } /// <summary> /// Provide the property page with an array of pointers to objects associated /// with this property page. /// When the property page receives a call to IPropertyPage::Apply, it must send /// value changes to these objects through whatever interfaces are appropriate. /// The property page must query for those interfaces. This method can fail if /// the objects do not support the interfaces expected by the property page. /// </summary> /// <param name="cObjects"> /// The number of pointers in the array pointed to by ppUnk. /// If this parameter is 0, the property page must release any pointers previously /// passed to this method. /// </param> /// <param name="ppunk"></param> public void SetObjects(uint cObjects, object[] ppunk) { // If cObjects ==0 or ppunk == null, release the PropertyStore. if ((ppunk == null) || (cObjects == 0)) { if (this.PropertyStore != null) { this.PropertyStore.Dispose( ); this.PropertyStore = null; } } else { // Initialize the PropertyStore using the provided objects. bool flag = false; if (this.PropertyStore != null) { flag = true; } this.PropertyStore = this.GetNewPropertyStore( ); this.PropertyStore.Initialize(ppunk); // If PropertyStore is not null, which means that the PageView UI has been // initialized, then it needs to be refreshed. if (flag) { this.MyPageView.RefreshPropertyValues( ); } } } /// <summary> /// Make the property page dialog box visible or invisible. /// If the page is made visible, the page should set the focus /// to itself, specifically to the first property on the page. /// </summary> /// <param name="nCmdShow"> /// A command describing whether to become visible (SW_SHOW or SW_SHOWNORMAL) or /// hidden (SW_HIDE). No other values are valid for this parameter. /// </param> public void Show(uint nCmdShow) { switch (nCmdShow) { case PropertyPageBase.Constants.SW_HIDE: this.MyPageView.HideView( ); return; case PropertyPageBase.Constants.SW_SHOW: case PropertyPageBase.Constants.SW_SHOWNORMAL: this.MyPageView.ShowView( ); return; } } /// <summary> /// Positions and resizes the property page dialog box within the frame. /// </summary> /// <param name="pRect"></param> public void Move(RECT[] pRect) { this.MyPageView.MoveView(Rectangle.FromLTRB( pRect[0].left, pRect[0].top, pRect[0].right, pRect[0].bottom)); } /// <summary> /// Indicate whether the property page has changed since it was activated /// or since the most recent call to Apply. /// </summary> /// <returns> /// This method returns S_OK to indicate that the property page has changed. /// Otherwise, it returns S_FALSE. /// </returns> public int IsPageDirty( ) { if (!this.propertyToBePersisted.HasValue) { return VSConstants.S_FALSE; } return VSConstants.S_OK; } /// <summary> /// Apply the current values to the underlying objects associated with the /// property page as previously passed to IPropertyPage::SetObjects. /// </summary> public void Apply( ) { // Save the changed value to PropertyStore. if (this.propertyToBePersisted.HasValue) { this.PropertyStore.Persist( this.propertyToBePersisted.Value.Key, this.propertyToBePersisted.Value.Value); this.propertyToBePersisted = null; } } /// <summary> /// Invoke the property page help in response to an end-user request. /// </summary> /// <param name="pszHelpDir"></param> public void Help(string pszHelpDir) { System.IServiceProvider iPropertyPageSite = this.PropertyPageSite as System.IServiceProvider; if (iPropertyPageSite != null) { Microsoft.VisualStudio.VSHelp.Help service = iPropertyPageSite.GetService( typeof(Microsoft.VisualStudio.VSHelp.Help)) as Microsoft.VisualStudio.VSHelp.Help; if (service != null) { service.DisplayTopicFromF1Keyword(this.HelpKeyword); } } } /// <summary> /// Pass a keystroke to the property page for processing. /// </summary> /// <param name="pMsg"> /// A pointer to the MSG structure describing the keystroke to be processed. /// </param> /// <returns></returns> public int TranslateAccelerator(MSG[] pMsg) { // Pass the message to the PageView object. Message message = Message.Create(pMsg[0].hwnd, (int)pMsg[0].message, pMsg[0].wParam, pMsg[0].lParam); int hr = this.MyPageView.ProcessAccelerator(ref message); pMsg[0].lParam = message.LParam; pMsg[0].wParam = message.WParam; return hr; } /// <summary> /// Specifies which field is to receive the focus when the property page is activated. /// </summary> /// <param name="DISPID"> /// The property that is to receive the focus. /// </param> public void EditProperty(int DISPID) { } #endregion #region IPropertyPage Members /// <summary> /// Applies the current values to the underlying objects associated with the /// property page as previously passed to IPropertyPage::SetObjects. /// </summary> int IPropertyPage.Apply( ) { this.Apply( ); return VSConstants.S_OK; } #endregion #region IPageViewSite Members /// <summary> /// Tis method is called if the value of a Control changed on a PageView object. /// </summary> /// <param name="propertyName"> /// The Property Name mapped to the Control. /// </param> /// <param name="propertyValue"> /// The new value. /// </param> public void PropertyChanged(string propertyName, string propertyValue) { if (this.PropertyStore != null) { this.propertyToBePersisted = new KeyValuePair<string, string>(propertyName, propertyValue); if (this.PropertyPageSite != null) { // Informs the frame that the property page managed by this site has // changed its state, that is, one or more property values have been // changed in the page. this.PropertyPageSite.OnStatusChange( PropertyPageBase.Constants.PROPPAGESTATUS_DIRTY | PropertyPageBase.Constants.PROPPAGESTATUS_VALIDATE); } } } /// <summary> /// Get the value of a Property which is stored in the PropertyStore, /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public string GetValueForProperty(string propertyName) { if (this.PropertyStore != null) { return this.PropertyStore.PropertyValue(propertyName); } return null; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="RangeBasedReader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; internal abstract class RangeBasedReader : TransferReaderWriterBase { /// <summary> /// Minimum size of empty range, the empty ranges which is smaller than this size will be merged to the adjacent range with data. /// </summary> const int MinimumNoDataRangeSize = 8 * 1024; private volatile State state; private TransferJob transferJob; private CountdownEvent getRangesCountDownEvent; private CountdownEvent toDownloadItemsCountdownEvent; private int getRangesSpanIndex = 0; private List<RangesSpan> rangesSpanList; private List<Range> rangeList; private int nextDownloadIndex = 0; private long lastTransferOffset; private TransferDownloadBuffer currentDownloadBuffer = null; private volatile bool hasWork; public RangeBasedReader( TransferScheduler scheduler, SyncTransferController controller, CancellationToken cancellationToken) : base(scheduler, controller, cancellationToken) { this.transferJob = this.SharedTransferData.TransferJob; this.Location = this.transferJob.Source; this.hasWork = true; } private enum State { FetchAttributes, GetRanges, Download, Error, Finished }; public override async Task DoWorkInternalAsync() { try { switch (this.state) { case State.FetchAttributes: await this.FetchAttributesAsync(); break; case State.GetRanges: await this.GetRangesAsync(); break; case State.Download: await this.DownloadRangeAsync(); break; default: break; } } catch { this.state = State.Error; throw; } } public override bool HasWork { get { return this.hasWork; } } public override bool IsFinished { get { return State.Error == this.state || State.Finished == this.state; } } protected TransferLocation Location { get; private set; } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { if (null != this.getRangesCountDownEvent) { this.getRangesCountDownEvent.Dispose(); this.getRangesCountDownEvent = null; } if (null != this.toDownloadItemsCountdownEvent) { this.toDownloadItemsCountdownEvent.Dispose(); this.toDownloadItemsCountdownEvent = null; } } } private async Task FetchAttributesAsync() { Debug.Assert( this.state == State.FetchAttributes, "FetchAttributesAsync called, but state isn't FetchAttributes"); this.hasWork = false; this.NotifyStarting(); try { await this.DoFetchAttributesAsync(); } catch (StorageException e) { // Getting a storage exception is expected if the blob doesn't // exist. For those cases that indicate the blob doesn't exist // we will set a specific error state. if (null != e.RequestInformation && e.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { throw new InvalidOperationException(Resources.SourceBlobDoesNotExistException); } else { throw; } } this.Location.CheckedAccessCondition = true; this.Controller.CheckCancellation(); this.state = State.GetRanges; this.PrepareToGetRanges(); if (!this.rangesSpanList.Any()) { // InitDownloadInfo will set hasWork. this.InitDownloadInfo(); this.PreProcessed = true; return; } this.PreProcessed = true; this.hasWork = true; } private async Task GetRangesAsync() { Debug.Assert( (this.state == State.GetRanges) || (this.state == State.Error), "GetRangesAsync called, but state isn't GetRanges or Error"); this.hasWork = false; this.lastTransferOffset = this.SharedTransferData.TransferJob.CheckPoint.EntryTransferOffset; int spanIndex = Interlocked.Increment(ref this.getRangesSpanIndex); this.hasWork = spanIndex < (this.rangesSpanList.Count - 1); RangesSpan rangesSpan = this.rangesSpanList[spanIndex]; rangesSpan.Ranges = await this.DoGetRangesAsync(rangesSpan); List<Range> ranges = new List<Range>(); Range currentRange = null; long currentStartOffset = rangesSpan.StartOffset; foreach (var range in rangesSpan.Ranges) { long emptySize = range.StartOffset - currentStartOffset; if (emptySize > 0 && emptySize < MinimumNoDataRangeSize) { // There is empty range which size is smaller than MinimumNoDataRangeSize // merge it to the adjacent data range. if (null == currentRange) { currentRange = new Range() { StartOffset = currentStartOffset, EndOffset = range.EndOffset, HasData = range.HasData }; } else { currentRange.EndOffset = range.EndOffset; } } else { // Empty range size is larger than MinimumNoDataRangeSize // put current data range in list and start to deal with the next data range. if (null != currentRange) { ranges.Add(currentRange); } currentRange = new Range { StartOffset = range.StartOffset, EndOffset = range.EndOffset, HasData = range.HasData }; } currentStartOffset = range.EndOffset + 1; } if (null != currentRange) { ranges.Add(currentRange); } rangesSpan.Ranges = ranges; if (this.getRangesCountDownEvent.Signal()) { this.ArrangeRanges(); // Don't call CallFinish here, InitDownloadInfo will call it. this.InitDownloadInfo(); } } private async Task DownloadRangeAsync() { Debug.Assert( this.state == State.Error || this.state == State.Download, "DownloadRangeAsync called, but state isn't Download or Error"); this.hasWork = false; if (State.Error == this.state) { // Some thread has set error message, just return here. return; } if (this.nextDownloadIndex < this.rangeList.Count) { Range rangeData = this.rangeList[this.nextDownloadIndex]; int blockSize = this.Scheduler.TransferOptions.BlockSize; long blockStartOffset = (rangeData.StartOffset / blockSize) * blockSize; long nextBlockStartOffset = Math.Min(blockStartOffset + blockSize, this.SharedTransferData.TotalLength); TransferDownloadStream downloadStream = null; if ((rangeData.StartOffset > blockStartOffset) && (rangeData.EndOffset < nextBlockStartOffset)) { Debug.Assert(null != this.currentDownloadBuffer, "Download buffer should have been allocated when range start offset is not block size aligned"); downloadStream = new TransferDownloadStream(this.Scheduler.MemoryManager, this.currentDownloadBuffer, (int)(rangeData.StartOffset - blockStartOffset), (int)(rangeData.EndOffset + 1 - rangeData.StartOffset)); } else { // Attempt to reserve memory. If none available we'll // retry some time later. byte[] memoryBuffer = this.Scheduler.MemoryManager.RequireBuffer(); if (null == memoryBuffer) { this.SetRangeDownloadHasWork(); return; } if (rangeData.EndOffset >= this.lastTransferOffset) { bool canRead = true; lock (this.transferJob.CheckPoint.TransferWindowLock) { if (this.transferJob.CheckPoint.TransferWindow.Count >= Constants.MaxCountInTransferWindow) { canRead = false; } else { if (this.transferJob.CheckPoint.EntryTransferOffset < this.SharedTransferData.TotalLength) { this.transferJob.CheckPoint.TransferWindow.Add(this.transferJob.CheckPoint.EntryTransferOffset); this.transferJob.CheckPoint.EntryTransferOffset = Math.Min(this.transferJob.CheckPoint.EntryTransferOffset + this.Scheduler.TransferOptions.BlockSize, this.SharedTransferData.TotalLength); } } } if (!canRead) { this.Scheduler.MemoryManager.ReleaseBuffer(memoryBuffer); this.SetRangeDownloadHasWork(); return; } } if (rangeData.StartOffset == blockStartOffset) { this.currentDownloadBuffer = new TransferDownloadBuffer(blockStartOffset, (int)Math.Min(blockSize, this.SharedTransferData.TotalLength - blockStartOffset), memoryBuffer); downloadStream = new TransferDownloadStream(this.Scheduler.MemoryManager, this.currentDownloadBuffer, 0, (int)(rangeData.EndOffset + 1 - rangeData.StartOffset)); } else { Debug.Assert(null != this.currentDownloadBuffer, "Download buffer should have been allocated when range start offset is not block size aligned"); TransferDownloadBuffer nextBuffer = new TransferDownloadBuffer(nextBlockStartOffset, (int)Math.Min(blockSize, this.SharedTransferData.TotalLength - nextBlockStartOffset), memoryBuffer); downloadStream = new TransferDownloadStream( this.Scheduler.MemoryManager, this.currentDownloadBuffer, (int)(rangeData.StartOffset - blockStartOffset), (int)(nextBlockStartOffset - rangeData.StartOffset), nextBuffer, 0, (int)(rangeData.EndOffset + 1 - nextBlockStartOffset)); this.currentDownloadBuffer = nextBuffer; } } using (downloadStream) { this.nextDownloadIndex++; this.SetRangeDownloadHasWork(); RangeBasedDownloadState rangeBasedDownloadState = new RangeBasedDownloadState { Range = rangeData, DownloadStream = downloadStream }; await this.DownloadRangeAsync(rangeBasedDownloadState); } this.SetChunkFinish(); return; } this.SetRangeDownloadHasWork(); } private void SetRangeDownloadHasWork() { if (this.HasWork) { return; } // Check if we have ranges available to download. if (this.nextDownloadIndex < this.rangeList.Count) { this.hasWork = true; return; } } private async Task DownloadRangeAsync(RangeBasedDownloadState asyncState) { Debug.Assert(null != asyncState, "asyncState object expected"); Debug.Assert( this.state == State.Download || this.state == State.Error, "DownloadRangeAsync called, but state isn't Download or Error"); // If a parallel operation caused the controller to be placed in // error state exit early to avoid unnecessary I/O. if (this.state == State.Error) { return; } if (asyncState.Range.HasData) { await this.DoDownloadRangeToStreamAsync(asyncState); } else { // Zero memory buffer. asyncState.DownloadStream.SetAllZero(); } asyncState.DownloadStream.FinishWrite(); asyncState.DownloadStream.ReserveBuffer = true; foreach (var buffer in asyncState.DownloadStream.GetBuffers()) { // Two download streams can refer to the same download buffer instance. It may cause the download // buffer be added into shared transfer data twice if only buffer.Finished is checked here: // Thread A: FinishedWrite() // Thread B: FinishedWrite(), buffer.Finished is true now // Thread A: Check buffer.Finished // Thread B: Check buffer.Finished // Thread A: Add buffer into sharedTransferData // Thread C: Writer remove buffer from sharedTransferData // Thread B: Add buffer into sharedTransferData again // So call MarkAsProcessed to make sure buffer is added exactly once. if (buffer.Finished && buffer.MarkAsProcessed()) { TransferData transferData = new TransferData(this.Scheduler.MemoryManager) { StartOffset = buffer.StartOffset, Length = buffer.Length, MemoryBuffer = buffer.MemoryBuffer }; this.SharedTransferData.AvailableData.TryAdd(buffer.StartOffset, transferData); } } } /// <summary> /// It might fail to get large ranges list from storage. This method is to split the whole file to spans of 148MB to get ranges. /// In restartable, we only need to get ranges for chunks in TransferWindow and after TransferEntryOffset in check point. /// In TransferWindow, there might be some chunks adjacent to TransferEntryOffset, so this method will first merge these chunks into TransferEntryOffset; /// Then in remained chunks in the TransferWindow, it's very possible that ranges of several chunks can be got in one 148MB span. /// To avoid sending too many get ranges requests, this method will merge the chunks to 148MB spans. /// </summary> private void PrepareToGetRanges() { this.getRangesSpanIndex = -1; this.rangesSpanList = new List<RangesSpan>(); this.rangeList = new List<Range>(); this.nextDownloadIndex = 0; SingleObjectCheckpoint checkpoint = this.transferJob.CheckPoint; int blockSize = this.Scheduler.TransferOptions.BlockSize; RangesSpan rangesSpan = null; if ((null != checkpoint.TransferWindow) && (checkpoint.TransferWindow.Any())) { checkpoint.TransferWindow.Sort(); long lastOffset = 0; if (checkpoint.EntryTransferOffset == this.SharedTransferData.TotalLength) { long lengthBeforeLastChunk = checkpoint.EntryTransferOffset % blockSize; lastOffset = 0 == lengthBeforeLastChunk ? checkpoint.EntryTransferOffset - blockSize : checkpoint.EntryTransferOffset - lengthBeforeLastChunk; } else { lastOffset = checkpoint.EntryTransferOffset - blockSize; } for (int i = checkpoint.TransferWindow.Count - 1; i >= 0; i--) { if (lastOffset == checkpoint.TransferWindow[i]) { checkpoint.TransferWindow.RemoveAt(i); checkpoint.EntryTransferOffset = lastOffset; } else if (lastOffset < checkpoint.TransferWindow[i]) { throw new FormatException(Resources.RestartableInfoCorruptedException); } else { break; } lastOffset = checkpoint.EntryTransferOffset - blockSize; } if (this.transferJob.CheckPoint.TransferWindow.Any()) { rangesSpan = new RangesSpan(); rangesSpan.StartOffset = checkpoint.TransferWindow[0]; rangesSpan.EndOffset = Math.Min(rangesSpan.StartOffset + Constants.PageRangesSpanSize, this.SharedTransferData.TotalLength) - 1; for (int i = 1; i < checkpoint.TransferWindow.Count; ++i ) { if (checkpoint.TransferWindow[i] + blockSize > rangesSpan.EndOffset) { long lastEndOffset = rangesSpan.EndOffset; this.rangesSpanList.Add(rangesSpan); rangesSpan = new RangesSpan(); rangesSpan.StartOffset = checkpoint.TransferWindow[i] > lastEndOffset ? checkpoint.TransferWindow[i] : lastEndOffset + 1; rangesSpan.EndOffset = Math.Min(rangesSpan.StartOffset + Constants.PageRangesSpanSize, this.SharedTransferData.TotalLength) - 1; } } this.rangesSpanList.Add(rangesSpan); } } long offset = null != rangesSpan ? rangesSpan.EndOffset > checkpoint.EntryTransferOffset ? rangesSpan.EndOffset + 1 : checkpoint.EntryTransferOffset : checkpoint.EntryTransferOffset; while (offset < this.SharedTransferData.TotalLength) { rangesSpan = new RangesSpan() { StartOffset = offset, EndOffset = Math.Min(offset + Constants.PageRangesSpanSize, this.SharedTransferData.TotalLength) - 1 }; this.rangesSpanList.Add(rangesSpan); offset = rangesSpan.EndOffset + 1; } if (this.rangesSpanList.Any()) { this.getRangesCountDownEvent = new CountdownEvent(this.rangesSpanList.Count); } } private void ClearForGetRanges() { this.rangesSpanList = null; if (null != this.getRangesCountDownEvent) { this.getRangesCountDownEvent.Dispose(); this.getRangesCountDownEvent = null; } } /// <summary> /// Turn raw ranges get from Azure Storage in rangesSpanList /// into list of Range. /// </summary> private void ArrangeRanges() { long currentEndOffset = -1; IEnumerator<RangesSpan> enumerator = this.rangesSpanList.GetEnumerator(); bool hasValue = enumerator.MoveNext(); bool reachLastTransferOffset = false; int lastTransferWindowIndex = 0; RangesSpan current; RangesSpan next; if (hasValue) { current = enumerator.Current; while (hasValue) { hasValue = enumerator.MoveNext(); if (!current.Ranges.Any()) { current = enumerator.Current; continue; } if (hasValue) { next = enumerator.Current; Debug.Assert( current.EndOffset < this.transferJob.CheckPoint.EntryTransferOffset || ((current.EndOffset + 1) == next.StartOffset), "Something wrong with ranges list."); if (next.Ranges.Any()) { if ((current.Ranges.Last().EndOffset + 1) == next.Ranges.First().StartOffset) { Range mergedRange = new Range() { StartOffset = current.Ranges.Last().StartOffset, EndOffset = next.Ranges.First().EndOffset, HasData = true }; current.Ranges.RemoveAt(current.Ranges.Count - 1); next.Ranges.RemoveAt(0); current.Ranges.Add(mergedRange); current.EndOffset = mergedRange.EndOffset; next.StartOffset = mergedRange.EndOffset + 1; if (next.EndOffset == mergedRange.EndOffset) { continue; } } } } foreach (Range range in current.Ranges) { // Check if we have a gap before the current range. // If so we'll generate a range with HasData = false. if (currentEndOffset != range.StartOffset - 1) { this.AddRangesByCheckPoint( currentEndOffset + 1, range.StartOffset - 1, false, ref reachLastTransferOffset, ref lastTransferWindowIndex); } this.AddRangesByCheckPoint( range.StartOffset, range.EndOffset, true, ref reachLastTransferOffset, ref lastTransferWindowIndex); currentEndOffset = range.EndOffset; } current = enumerator.Current; } } if (currentEndOffset < this.SharedTransferData.TotalLength - 1) { this.AddRangesByCheckPoint( currentEndOffset + 1, this.SharedTransferData.TotalLength - 1, false, ref reachLastTransferOffset, ref lastTransferWindowIndex); } } private void AddRangesByCheckPoint(long startOffset, long endOffset, bool hasData, ref bool reachLastTransferOffset, ref int lastTransferWindowIndex) { SingleObjectCheckpoint checkpoint = this.transferJob.CheckPoint; if (reachLastTransferOffset) { this.rangeList.AddRange( new Range { StartOffset = startOffset, EndOffset = endOffset, HasData = hasData, }.SplitRanges(this.Scheduler.TransferOptions.BlockSize)); } else { Range range = new Range() { StartOffset = -1, HasData = hasData }; while (lastTransferWindowIndex < checkpoint.TransferWindow.Count) { long lastTransferWindowStart = checkpoint.TransferWindow[lastTransferWindowIndex]; long lastTransferWindowEnd = Math.Min(checkpoint.TransferWindow[lastTransferWindowIndex] + this.Scheduler.TransferOptions.BlockSize - 1, this.SharedTransferData.TotalLength); if (lastTransferWindowStart <= endOffset) { if (-1 == range.StartOffset) { // New range range.StartOffset = Math.Max(lastTransferWindowStart, startOffset); range.EndOffset = Math.Min(lastTransferWindowEnd, endOffset); } else { if (range.EndOffset != lastTransferWindowStart - 1) { // Store the previous range and create a new one this.rangeList.AddRange(range.SplitRanges(this.Scheduler.TransferOptions.BlockSize)); range = new Range() { StartOffset = Math.Max(lastTransferWindowStart, startOffset), HasData = hasData }; } range.EndOffset = Math.Min(lastTransferWindowEnd, endOffset); } if (range.EndOffset == lastTransferWindowEnd) { // Reach the end of transfer window, move to next ++lastTransferWindowIndex; continue; } } break; } if (-1 != range.StartOffset) { this.rangeList.AddRange(range.SplitRanges(this.Scheduler.TransferOptions.BlockSize)); } if (checkpoint.EntryTransferOffset <= endOffset + 1) { reachLastTransferOffset = true; if (checkpoint.EntryTransferOffset <= endOffset) { this.rangeList.AddRange(new Range() { StartOffset = checkpoint.EntryTransferOffset, EndOffset = endOffset, HasData = hasData, }.SplitRanges(this.Scheduler.TransferOptions.BlockSize)); } } } } /// <summary> /// To initialize range based object download related information in the controller. /// This method will call CallFinish. /// </summary> private void InitDownloadInfo() { this.ClearForGetRanges(); this.state = State.Download; if (this.rangeList.Count == this.nextDownloadIndex) { this.toDownloadItemsCountdownEvent = new CountdownEvent(1); this.SetChunkFinish(); } else { this.toDownloadItemsCountdownEvent = new CountdownEvent(this.rangeList.Count); this.hasWork = true; } } private void SetChunkFinish() { if (this.toDownloadItemsCountdownEvent.Signal()) { this.state = State.Finished; this.hasWork = false; } } protected class RangesSpan { public long StartOffset { get; set; } public long EndOffset { get; set; } public List<Range> Ranges { get; set; } } protected class Range { public long StartOffset { get; set; } public long EndOffset { get; set; } public bool HasData { get; set; } /// <summary> /// Split a Range into multiple Range objects, each at most maxRangeSize long. /// </summary> /// <param name="maxRangeSize">Maximum length for each piece.</param> /// <returns>List of Range objects.</returns> public IEnumerable<Range> SplitRanges(long maxRangeSize) { long startOffset = this.StartOffset; long rangeSize = this.EndOffset - this.StartOffset + 1; do { long singleRangeSize = Math.Min(rangeSize, maxRangeSize); Range subRange = new Range { StartOffset = startOffset, EndOffset = startOffset + singleRangeSize - 1, HasData = this.HasData, }; startOffset += singleRangeSize; rangeSize -= singleRangeSize; yield return subRange; } while (rangeSize > 0); } } protected class RangeBasedDownloadState { private Range range; public Range Range { get { return this.range; } set { this.range = value; this.StartOffset = value.StartOffset; this.Length = (int)(value.EndOffset - value.StartOffset + 1); } } /// <summary> /// Gets or sets a handle to the memory buffer to ensure the /// memory buffer remains in memory during the entire operation. /// </summary> public TransferDownloadStream DownloadStream { get; set; } /// <summary> /// Gets or sets the starting offset of this part of data. /// </summary> public long StartOffset { get; set; } /// <summary> /// Gets or sets the length of this part of data. /// </summary> public int Length { get; set; } } protected abstract Task DoFetchAttributesAsync(); protected abstract Task DoDownloadRangeToStreamAsync(RangeBasedDownloadState asyncState); protected abstract Task<List<Range>> DoGetRangesAsync(RangesSpan rangesSpan); } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json; namespace Avro { internal delegate T Function<T>(); /// <summary> /// Class for record schemas /// </summary> public class RecordSchema : NamedSchema { /// <summary> /// List of fields in the record /// </summary> public List<Field> Fields { get; private set; } /// <summary> /// Number of fields in the record /// </summary> public int Count { get { return Fields.Count; } } /// <summary> /// Map of field name and Field object for faster field lookups /// </summary> private readonly IDictionary<string, Field> fieldLookup; private readonly IDictionary<string, Field> fieldAliasLookup; private bool request; /// <summary> /// Static function to return new instance of the record schema /// </summary> /// <param name="type">type of record schema, either record or error</param> /// <param name="jtok">JSON object for the record schema</param> /// <param name="names">list of named schema already read</param> /// <param name="encspace">enclosing namespace of the records schema</param> /// <returns>new RecordSchema object</returns> internal static RecordSchema NewInstance(Type type, JToken jtok, PropertyMap props, SchemaNames names, string encspace) { bool request = false; JToken jfields = jtok["fields"]; // normal record if (null == jfields) { jfields = jtok["request"]; // anonymous record from messages if (null != jfields) request = true; } if (null == jfields) throw new SchemaParseException("'fields' cannot be null for record"); if (jfields.Type != JTokenType.Array) throw new SchemaParseException("'fields' not an array for record"); var name = GetName(jtok, encspace); var aliases = NamedSchema.GetAliases(jtok, name.Space, name.EncSpace); var fields = new List<Field>(); var fieldMap = new Dictionary<string, Field>(); var fieldAliasMap = new Dictionary<string, Field>(); var result = new RecordSchema(type, name, aliases, props, fields, request, fieldMap, fieldAliasMap, names); int fieldPos = 0; foreach (JObject jfield in jfields) { string fieldName = JsonHelper.GetRequiredString(jfield, "name"); Field field = createField(jfield, fieldPos++, names, name.Namespace); // add record namespace for field look up fields.Add(field); addToFieldMap(fieldMap, fieldName, field); addToFieldMap(fieldAliasMap, fieldName, field); if (null != field.aliases) // add aliases to field lookup map so reader function will find it when writer field name appears only as an alias on the reader field foreach (string alias in field.aliases) addToFieldMap(fieldAliasMap, alias, field); } return result; } /// <summary> /// Constructor for the record schema /// </summary> /// <param name="type">type of record schema, either record or error</param> /// <param name="name">name of the record schema</param> /// <param name="aliases">list of aliases for the record name</param> /// <param name="fields">list of fields for the record</param> /// <param name="request">true if this is an anonymous record with 'request' instead of 'fields'</param> /// <param name="fieldMap">map of field names and field objects</param> /// <param name="names">list of named schema already read</param> private RecordSchema(Type type, SchemaName name, IList<SchemaName> aliases, PropertyMap props, List<Field> fields, bool request, IDictionary<string, Field> fieldMap, IDictionary<string, Field> fieldAliasMap, SchemaNames names) : base(type, name, aliases, props, names) { if (!request && null == name.Name) throw new SchemaParseException("name cannot be null for record schema."); this.Fields = fields; this.request = request; this.fieldLookup = fieldMap; this.fieldAliasLookup = fieldAliasMap; } /// <summary> /// Creates a new field for the record /// </summary> /// <param name="jfield">JSON object for the field</param> /// <param name="pos">position number of the field</param> /// <param name="names">list of named schemas already read</param> /// <param name="encspace">enclosing namespace of the records schema</param> /// <returns>new Field object</returns> private static Field createField(JToken jfield, int pos, SchemaNames names, string encspace) { var name = JsonHelper.GetRequiredString(jfield, "name"); var doc = JsonHelper.GetOptionalString(jfield, "doc"); var jorder = JsonHelper.GetOptionalString(jfield, "order"); Field.SortOrder sortorder = Field.SortOrder.ignore; if (null != jorder) sortorder = (Field.SortOrder) Enum.Parse(typeof(Field.SortOrder), jorder); var aliases = Field.GetAliases(jfield); var props = Schema.GetProperties(jfield); var defaultValue = jfield["default"]; JToken jtype = jfield["type"]; if (null == jtype) throw new SchemaParseException("'type' was not found for field: " + name); var schema = Schema.ParseJson(jtype, names, encspace); return new Field(schema, name, aliases, pos, doc, defaultValue, sortorder, props); } private static void addToFieldMap(Dictionary<string, Field> map, string name, Field field) { if (map.ContainsKey(name)) throw new SchemaParseException("field or alias " + name + " is a duplicate name"); map.Add(name, field); } /// <summary> /// Returns the field with the given name. /// </summary> /// <param name="name">field name</param> /// <returns>Field object</returns> public Field this[string name] { get { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); Field field; return (fieldLookup.TryGetValue(name, out field)) ? field : null; } } /// <summary> /// Returns true if and only if the record contains a field by the given name. /// </summary> /// <param name="fieldName">The name of the field</param> /// <returns>true if the field exists, false otherwise</returns> public bool Contains(string fieldName) { return fieldLookup.ContainsKey(fieldName); } public bool TryGetField(string fieldName, out Field field) { return fieldLookup.TryGetValue(fieldName, out field); } public bool TryGetFieldAlias(string fieldName, out Field field) { return fieldAliasLookup.TryGetValue(fieldName, out field); } /// <summary> /// Returns an enumerator which enumerates over the fields of this record schema /// </summary> /// <returns>Enumerator over the field in the order of their definition</returns> public IEnumerator<Field> GetEnumerator() { return Fields.GetEnumerator(); } /// <summary> /// Writes the records schema in JSON format /// </summary> /// <param name="writer">JSON writer</param> /// <param name="names">list of named schemas already written</param> /// <param name="encspace">enclosing namespace of the record schema</param> protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer, SchemaNames names, string encspace) { base.WriteJsonFields(writer, names, encspace); // we allow reading for empty fields, so writing of records with empty fields are allowed as well if (request) writer.WritePropertyName("request"); else writer.WritePropertyName("fields"); writer.WriteStartArray(); if (null != this.Fields && this.Fields.Count > 0) { foreach (Field field in this) field.writeJson(writer, names, this.Namespace); // use the namespace of the record for the fields } writer.WriteEndArray(); } /// <summary> /// Compares equality of two record schemas /// </summary> /// <param name="obj">record schema to compare against this schema</param> /// <returns>true if the two schemas are equal, false otherwise</returns> public override bool Equals(object obj) { if (obj == this) return true; if (obj != null && obj is RecordSchema) { RecordSchema that = obj as RecordSchema; return protect(() => true, () => { if (this.SchemaName.Equals(that.SchemaName) && this.Count == that.Count) { for (int i = 0; i < Fields.Count; i++) if (!Fields[i].Equals(that.Fields[i])) return false; return areEqual(that.Props, this.Props); } return false; }, that); } return false; } /// <summary> /// Hash code function /// </summary> /// <returns></returns> public override int GetHashCode() { return protect(() => 0, () => { int result = SchemaName.GetHashCode(); foreach (Field f in Fields) result += 29 * f.GetHashCode(); result += getHashCode(Props); return result; }, this); } /// <summary> /// Checks if this schema can read data written by the given schema. Used for decoding data. /// </summary> /// <param name="writerSchema">writer schema</param> /// <returns>true if this and writer schema are compatible based on the AVRO specification, false otherwise</returns> public override bool CanRead(Schema writerSchema) { if (writerSchema.Tag != Type.Record) return false; RecordSchema that = writerSchema as RecordSchema; return protect(() => true, () => { if (!that.SchemaName.Equals(SchemaName)) if (!InAliases(that.SchemaName)) return false; foreach (Field f in this) { Field f2 = that[f.Name]; if (null == f2) // reader field not in writer field, check aliases of reader field if any match with a writer field if (null != f.aliases) foreach (string alias in f.aliases) { f2 = that[alias]; if (null != f2) break; } if (f2 == null && f.DefaultValue != null) continue; // Writer field missing, reader has default. if (f2 != null && f.Schema.CanRead(f2.Schema)) continue; // Both fields exist and are compatible. return false; } return true; }, that); } private class RecordSchemaPair { public readonly RecordSchema first; public readonly RecordSchema second; public RecordSchemaPair(RecordSchema first, RecordSchema second) { this.first = first; this.second = second; } } [ThreadStatic] private static List<RecordSchemaPair> seen; /** * We want to protect against infinite recursion when the schema is recursive. We look into a thread local * to see if we have been into this if so, we execute the bypass function otherwise we execute the main function. * Before executing the main function, we ensure that we create a marker so that if we come back here recursively * we can detect it. * * The infinite loop happens in ToString(), Equals() and GetHashCode() methods. * Though it does not happen for CanRead() because of the current implemenation of UnionSchema's can read, * it could potenitally happen. * We do a linear seach for the marker as we don't expect the list to be very long. */ private T protect<T>(Function<T> bypass, Function<T> main, RecordSchema that) { if (seen == null) seen = new List<RecordSchemaPair>(); else if (seen.Find((RecordSchemaPair rs) => rs.first == this && rs.second == that) != null) return bypass(); RecordSchemaPair p = new RecordSchemaPair(this, that); seen.Add(p); try { return main(); } finally { seen.Remove(p); } } } }
//----------------------------------------------------------------------- // <copyright file="FlowGroupBySpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.Dsl.Internal; using Akka.Streams.Implementation; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Supervision; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod namespace Akka.Streams.Tests.Dsl { public class FlowGroupBySpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowGroupBySpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2); Materializer = ActorMaterializer.Create(Sys, settings); } private sealed class StreamPuppet { private readonly TestSubscriber.ManualProbe<int> _probe; private readonly ISubscription _subscription; public StreamPuppet(IPublisher<int> p, TestKitBase kit) { _probe = kit.CreateManualSubscriberProbe<int>(); p.Subscribe(_probe); _subscription = _probe.ExpectSubscription(); } public void Request(int demand) => _subscription.Request(demand); public void ExpectNext(int element) => _probe.ExpectNext(element); public void ExpectNoMsg(TimeSpan max) => _probe.ExpectNoMsg(max); public void ExpectComplete() => _probe.ExpectComplete(); public void ExpectError(Exception ex) => _probe.ExpectError().Should().Be(ex); public void Cancel() => _subscription.Cancel(); } private void WithSubstreamsSupport(int groupCount = 2, int elementCount = 6, int maxSubstream = -1, Action<TestSubscriber.ManualProbe<Tuple<int, Source<int, NotUsed>>>, ISubscription, Func<int, Source<int, NotUsed>>> run = null) { var source = Source.From(Enumerable.Range(1, elementCount)).RunWith(Sink.AsPublisher<int>(false), Materializer); var max = maxSubstream > 0 ? maxSubstream : groupCount; var groupStream = Source.FromPublisher(source) .GroupBy(max, x => x % groupCount) .Lift(x => x % groupCount) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var masterSubscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); groupStream.Subscribe(masterSubscriber); var masterSubscription = masterSubscriber.ExpectSubscription(); run?.Invoke(masterSubscriber, masterSubscription, expectedKey => { masterSubscription.Request(1); var tuple = masterSubscriber.ExpectNext(); tuple.Item1.Should().Be(expectedKey); return tuple.Item2; }); } private ByteString RandomByteString(int size) { var a = new byte[size]; ThreadLocalRandom.Current.NextBytes(a); return ByteString.Create(a); } [Fact] public void GroupBy_must_work_in_the_happy_case() { this.AssertAllStagesStopped(() => { WithSubstreamsSupport(2, run: (masterSubscriber, masterSubscription, getSubFlow) => { var s1 = new StreamPuppet(getSubFlow(1).RunWith(Sink.AsPublisher<int>(false), Materializer), this); masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); s1.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); s1.Request(1); s1.ExpectNext(1); s1.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); var s2 = new StreamPuppet(getSubFlow(0).RunWith(Sink.AsPublisher<int>(false), Materializer), this); s2.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); s2.Request(2); s2.ExpectNext(2); // Important to request here on the OTHER stream because the buffer space is exactly one without the fanout box s1.Request(1); s2.ExpectNext(4); s2.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); s1.ExpectNext(3); s2.Request(1); // Important to request here on the OTHER stream because the buffer space is exactly one without the fanout box s1.Request(1); s2.ExpectNext(6); s2.ExpectComplete(); s1.ExpectNext(5); s1.ExpectComplete(); masterSubscription.Request(1); masterSubscriber.ExpectComplete(); }); }, Materializer); } [Fact] public void GroupBy_must_work_in_normal_user_scenario() { var source = Source.From(new[] { "Aaa", "Abb", "Bcc", "Cdd", "Cee" }) .GroupBy(3, s => s.Substring(0, 1)) .Grouped(10) .MergeSubstreams() .Grouped(10); var task = ((Source<IEnumerable<IEnumerable<string>>, NotUsed>)source).RunWith( Sink.First<IEnumerable<IEnumerable<string>>>(), Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.OrderBy(e => e.First()) .ShouldBeEquivalentTo(new[] { new[] { "Aaa", "Abb" }, new[] { "Bcc" }, new[] { "Cdd", "Cee" } }); } [Fact] public void GroupBy_must_fail_when_key_function_returns_null() { var source = (Source<IEnumerable<string>, NotUsed>)Source.From(new[] { "Aaa", "Abb", "Bcc", "Cdd", "Cee" }) .GroupBy(3, s => s.StartsWith("A") ? null : s.Substring(0, 1)) .Grouped(10) .MergeSubstreams(); var down = source.RunWith(this.SinkProbe<IEnumerable<string>>(), Materializer); down.Request(1); var ex = down.ExpectError(); ex.Message.Should().Contain("Key cannot be null"); ex.Should().BeOfType<ArgumentNullException>(); } [Fact] public void GroupBy_must_support_cancelling_substreams() { this.AssertAllStagesStopped(() => { WithSubstreamsSupport(2, run: (masterSubscriber, masterSubscription, getSubFlow) => { new StreamPuppet(getSubFlow(1).RunWith(Sink.AsPublisher<int>(false), Materializer), this).Cancel(); var substream = new StreamPuppet(getSubFlow(0).RunWith(Sink.AsPublisher<int>(false), Materializer), this); substream.Request(2); substream.ExpectNext(2); substream.ExpectNext(4); substream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); substream.Request(2); substream.ExpectNext(6); substream.ExpectComplete(); masterSubscription.Request(1); masterSubscriber.ExpectComplete(); }); }, Materializer); } [Fact] public void GroupBy_must_accept_cancellation_of_master_stream_when_not_consume_anything() { this.AssertAllStagesStopped(() => { var publisherProbe = this.CreateManualPublisherProbe<int>(); var publisher = Source.FromPublisher(publisherProbe) .GroupBy(2, x => x % 2) .Lift(x => x % 2) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Cancel(); upstreamSubscription.ExpectCancellation(); }, Materializer); } [Fact] public void GroupBy_must_work_with_empty_input_stream() { this.AssertAllStagesStopped(() => { var publisher = Source.From(new List<int>()) .GroupBy(2, x => x % 2) .Lift(x => x % 2) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); publisher.Subscribe(subscriber); subscriber.ExpectSubscriptionAndComplete(); }, Materializer); } [Fact] public void GroupBy_must_abort_onError_from_upstream() { this.AssertAllStagesStopped(() => { var publisherProbe = this.CreateManualPublisherProbe<int>(); var publisher = Source.FromPublisher(publisherProbe) .GroupBy(2, x => x % 2) .Lift(x => x % 2) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Request(100); var ex = new TestException("test"); upstreamSubscription.SendError(ex); subscriber.ExpectError().Should().Be(ex); }, Materializer); } [Fact] public void GroupBy_must_abort_onError_from_upstream_when_substreams_are_running() { this.AssertAllStagesStopped(() => { var publisherProbe = this.CreateManualPublisherProbe<int>(); var publisher = Source.FromPublisher(publisherProbe) .GroupBy(2, x => x % 2) .Lift(x => x % 2) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Request(100); upstreamSubscription.SendNext(1); var substream = subscriber.ExpectNext().Item2; var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this); substreamPuppet.Request(1); substreamPuppet.ExpectNext(1); var ex = new TestException("test"); upstreamSubscription.SendError(ex); substreamPuppet.ExpectError(ex); subscriber.ExpectError().Should().Be(ex); }, Materializer); } [Fact] public void GroupBy_must_fail_stream_when_GroupBy_function_throws() { this.AssertAllStagesStopped(() => { var publisherProbe = this.CreateManualPublisherProbe<int>(); var ex = new TestException("test"); var publisher = Source.FromPublisher(publisherProbe).GroupBy(2, i => { if (i == 2) throw ex; return i % 2; }) .Lift(x => x % 2) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Request(100); upstreamSubscription.SendNext(1); var substream = subscriber.ExpectNext().Item2; var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this); substreamPuppet.Request(1); substreamPuppet.ExpectNext(1); upstreamSubscription.SendNext(2); subscriber.ExpectError().Should().Be(ex); substreamPuppet.ExpectError(ex); upstreamSubscription.ExpectCancellation(); }, Materializer); } [Fact] public void GroupBy_must_resume_stream_when_GroupBy_function_throws() { this.AssertAllStagesStopped(() => { var publisherProbe = this.CreateManualPublisherProbe<int>(); var ex = new TestException("test"); var publisher = Source.FromPublisher(publisherProbe).GroupBy(2, i => { if (i == 2) throw ex; return i % 2; }) .Lift(x => x % 2) .WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.ResumingDecider)) .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer); var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Request(100); upstreamSubscription.SendNext(1); var substream = subscriber.ExpectNext().Item2; var substreamPuppet1 = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this); substreamPuppet1.Request(10); substreamPuppet1.ExpectNext(1); upstreamSubscription.SendNext(2); upstreamSubscription.SendNext(4); var substream2 = subscriber.ExpectNext().Item2; var substreamPuppet2 = new StreamPuppet(substream2.RunWith(Sink.AsPublisher<int>(false), Materializer), this); substreamPuppet2.Request(10); substreamPuppet2.ExpectNext(4); upstreamSubscription.SendNext(3); substreamPuppet1.ExpectNext(3); upstreamSubscription.SendNext(6); substreamPuppet2.ExpectNext(6); upstreamSubscription.SendComplete(); subscriber.ExpectComplete(); substreamPuppet1.ExpectComplete(); substreamPuppet2.ExpectComplete(); }, Materializer); } [Fact] public void GroupBy_must_pass_along_early_cancellation() { this.AssertAllStagesStopped(() => { var up = this.CreateManualPublisherProbe<int>(); var down = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>(); var flowSubscriber = Source.AsSubscriber<int>() .GroupBy(2, x => x % 2) .Lift(x => x % 2) .To(Sink.FromSubscriber(down)).Run(Materializer); var downstream = down.ExpectSubscription(); downstream.Cancel(); up.Subscribe(flowSubscriber); var upSub = up.ExpectSubscription(); upSub.ExpectCancellation(); }, Materializer); } [Fact] public void GroupBy_must_fail_when_exceeding_maxSubstreams() { this.AssertAllStagesStopped(() => { var f = Flow.Create<int>().GroupBy(1, x => x % 2).PrefixAndTail(0).MergeSubstreams(); var t = ((Flow<int, Tuple<IImmutableList<int>, Source<int, NotUsed>>, NotUsed>)f) .RunWith(this.SourceProbe<int>(), this.SinkProbe<Tuple<IImmutableList<int>, Source<int, NotUsed>>>(), Materializer); var up = t.Item1; var down = t.Item2; down.Request(2); up.SendNext(1); var first = down.ExpectNext(); var s1 = new StreamPuppet(first.Item2.RunWith(Sink.AsPublisher<int>(false), Materializer), this); s1.Request(1); s1.ExpectNext(1); up.SendNext(2); var ex = down.ExpectError(); ex.Message.Should().Contain("too many substreams"); s1.ExpectError(ex); }, Materializer); } [Fact] public void GroupBy_must_emit_subscribe_before_completed() { this.AssertAllStagesStopped(() => { var source = (Source<Source<int, NotUsed>, NotUsed>)Source.Single(0).GroupBy(1, _ => "all") .PrefixAndTail(0) .Select(t => t.Item2) .ConcatSubstream(); var futureGroupSource = source.RunWith(Sink.First<Source<int, NotUsed>>(), Materializer); var publisher = futureGroupSource.AwaitResult().RunWith(Sink.AsPublisher<int>(false), Materializer); var probe = this.CreateSubscriberProbe<int>(); publisher.Subscribe(probe); var subscription = probe.ExpectSubscription(); subscription.Request(1); probe.ExpectNext(0); probe.ExpectComplete(); }, Materializer); } [Fact] public void GroupBy_must_work_under_fuzzing_stress_test() { this.AssertAllStagesStopped(() => { var publisherProbe = this.CreateManualPublisherProbe<ByteString>(); var subscriber = this.CreateManualSubscriberProbe<IEnumerable<byte>>(); var firstGroup = (Source<IEnumerable<byte>, NotUsed>)Source.FromPublisher(publisherProbe) .GroupBy(256, element => element.Head) .Select(b => b.Reverse()) .MergeSubstreams(); var secondGroup = (Source<IEnumerable<byte>, NotUsed>)firstGroup.GroupBy(256, bytes => bytes.First()) .Select(b => b.Reverse()) .MergeSubstreams(); var publisher = secondGroup.RunWith(Sink.AsPublisher<IEnumerable<byte>>(false), Materializer); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Request(300); for (var i = 1; i <= 300; i++) { var byteString = RandomByteString(10); upstreamSubscription.ExpectRequest(); upstreamSubscription.SendNext(byteString); subscriber.ExpectNext().ShouldBeEquivalentTo(byteString); } upstreamSubscription.SendComplete(); }, Materializer); } [Fact] public void GroupBy_must_Work_if_pull_is_exercised_from_both_substream_and_main() { this.AssertAllStagesStopped(() => { var upstream = this.CreatePublisherProbe<int>(); var downstreamMaster = this.CreateSubscriberProbe<Source<int, NotUsed>>(); Source.FromPublisher(upstream) .Via(new GroupBy<int, bool>(2, element => element == 0)) .RunWith(Sink.FromSubscriber(downstreamMaster), Materializer); var substream = this.CreateSubscriberProbe<int>(); downstreamMaster.Request(1); upstream.SendNext(1); downstreamMaster.ExpectNext().RunWith(Sink.FromSubscriber(substream), Materializer); // Read off first buffered element from subsource substream.Request(1); substream.ExpectNext(1); // Both will attempt to pull upstream substream.Request(1); substream.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); downstreamMaster.Request(1); downstreamMaster.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); // Cleanup, not part of the actual test substream.Cancel(); downstreamMaster.Cancel(); upstream.SendComplete(); }, Materializer); } [Fact] public void GroupBy_must_work_with_random_demand() { this.AssertAllStagesStopped(() => { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(1, 1); var materializer = Sys.Materializer(settings); var props = new RandomDemandProperties { Kit = this }; Enumerable.Range(0, 100) .ToList() .ForEach(_ => props.Probes.Add(new TaskCompletionSource<TestSubscriber.Probe<ByteString>>())); var map = new Dictionary<int, SubFlowState>(); var publisherProbe = this.CreateManualPublisherProbe<ByteString>(); var probeShape = new SinkShape<ByteString>(new Inlet<ByteString>("ProbeSink.in")); var probeSink = new ProbeSink(probeShape, props, Attributes.None); Source.FromPublisher(publisherProbe) .GroupBy(100, element => Math.Abs(element.Head % 100)) .To(new Sink<ByteString, TestSubscriber.Probe<ByteString>>(probeSink)) .Run(materializer); var upstreamSubscription = publisherProbe.ExpectSubscription(); for (var i = 1; i <= 400; i++) { var byteString = RandomByteString(10); var index = Math.Abs(byteString.Head % 100); upstreamSubscription.ExpectRequest(); upstreamSubscription.SendNext(byteString); if (!map.ContainsKey(index)) { var probe = props.Probes[props.PropesReaderTop].Task.AwaitResult(); props.PropesReaderTop++; map[index] = new SubFlowState(probe, false, byteString); //stream automatically requests next element } else { var state = map[index]; if (state.FirstElement != null) //first element in subFlow { if (!state.HasDemand) props.BlockingNextElement = byteString; RandomDemand(map, props); } else if (state.HasDemand) { if (props.BlockingNextElement == null) { state.Probe.ExpectNext().ShouldBeEquivalentTo(byteString); map[index] = new SubFlowState(state.Probe, false, null); RandomDemand(map, props); } else true.ShouldBeFalse("INVALID CASE"); } else { props.BlockingNextElement = byteString; RandomDemand(map, props); } } } upstreamSubscription.SendComplete(); }, Materializer); } private sealed class SubFlowState { public SubFlowState(TestSubscriber.Probe<ByteString> probe, bool hasDemand, ByteString firstElement) { Probe = probe; HasDemand = hasDemand; FirstElement = firstElement; } public TestSubscriber.Probe<ByteString> Probe { get; } public bool HasDemand { get; } public ByteString FirstElement { get; } } private sealed class ProbeSink : SinkModule<ByteString, TestSubscriber.Probe<ByteString>> { private readonly RandomDemandProperties _properties; public ProbeSink(SinkShape<ByteString> shape, RandomDemandProperties properties, Attributes attributes) : base(shape) { _properties = properties; Attributes = attributes; } public override Attributes Attributes { get; } public override IModule WithAttributes(Attributes attributes) { return new ProbeSink(AmendShape(attributes), _properties, attributes); } protected override SinkModule<ByteString, TestSubscriber.Probe<ByteString>> NewInstance(SinkShape<ByteString> shape) { return new ProbeSink(shape, _properties, Attributes); } public override object Create(MaterializationContext context, out TestSubscriber.Probe<ByteString> materializer) { var promise = _properties.Probes[_properties.ProbesWriterTop]; var probe = TestSubscriber.CreateSubscriberProbe<ByteString>(_properties.Kit); promise.SetResult(probe); _properties.ProbesWriterTop++; materializer = probe; return probe; } } private sealed class RandomDemandProperties { public TestKitBase Kit { get; set; } public int ProbesWriterTop { get; set; } public int PropesReaderTop { get; set; } public List<TaskCompletionSource<TestSubscriber.Probe<ByteString>>> Probes { get; } = new List<TaskCompletionSource<TestSubscriber.Probe<ByteString>>>(100); public ByteString BlockingNextElement { get; set; } } private void RandomDemand(Dictionary<int, SubFlowState> map, RandomDemandProperties props) { while (true) { var nextIndex = ThreadLocalRandom.Current.Next(0, map.Count); var key = map.Keys.ToArray()[nextIndex]; if (!map[key].HasDemand) { var state = map[key]; map[key] = new SubFlowState(state.Probe, true, state.FirstElement); state.Probe.Request(1); // need to verify elements that are first element in subFlow or is in nextElement buffer before // pushing next element from upstream if (state.FirstElement != null) { state.Probe.ExpectNext().ShouldBeEquivalentTo(state.FirstElement); map[key] = new SubFlowState(state.Probe, false, null); } else if (props.BlockingNextElement != null && Math.Abs(props.BlockingNextElement.Head % 100) == key) { state.Probe.ExpectNext().ShouldBeEquivalentTo(props.BlockingNextElement); props.BlockingNextElement = null; map[key] = new SubFlowState(state.Probe, false, null); } else if (props.BlockingNextElement == null) break; } } } } }