context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace ROOT_PROJECT_NAMESPACE.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using AspNet.Security.OpenIdConnect.Extensions; using AspNetApiMonolithSample.Api.EntityFramework; using AspNetApiMonolithSample.Api.EntityFramework.Stores; using AspNetApiMonolithSample.Api.Models; using AspNetApiMonolithSample.Api.Mvc; using AspNetApiMonolithSample.Api.Services; using AspNetApiMonolithSample.Api.Stores; using AspNetApiMonolithSample.Api.Swagger; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict; using Swashbuckle.Swagger.Model; using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace AspNetApiMonolithSample.Api { /// <summary> /// Cross origin settings /// /// Setting in the appsettings.json /// </summary> public class CorsConfiguration { public string[] Origins { get; set; } = new string[] { }; } /// <summary> /// Snippets of HTML to inject to the various pages, purpose is to provide branding /// through external snippets of HTML/CSS/JavaScript instead writing it in the API. /// /// Setting in the appsettings.json /// </summary> public class UiBrandingHtmlConfiguration { /// <summary> /// Login page /// </summary> public string Login { get; set; } = ""; /// <summary> /// OpenId authorize form (Accept or Deny) /// </summary> public string Authorize { get; set; } = ""; /// <summary> /// Generic error page, e.g. 404 /// </summary> public string Error { get; set; } = ""; /// <summary> /// Two Factor authentication form /// </summary> public string TwoFactor { get; set; } = ""; } /// <summary> /// Jwt appsettings.json configuration /// </summary> public class JwtConfiguration { /// <summary> /// Audience of jwt bearer authentication, this should match the resource /// </summary> public string Audience { get; set; } /// <summary> /// Authority of jwt bearer authentication /// </summary> public string Authority { get; set; } } /// <summary> /// Front end urls which user is redirected to deal with various parts of the /// application. /// /// Setting in the appsettings.json /// </summary> public class FrontendUrlsConfiguration { /// <summary> /// When user resets their password they will be emailed this link to reset the password /// </summary> public string ResetPassword { get; set; } = ""; /// <summary> /// When user registers they are emailed this confirmation link /// </summary> public string RegisterConfirmEmail { get; set; } = ""; } static public class AspNetApiMonolithSampleConstants { static public class Scopes { public const string ApiUser = "api_user"; } static public class Claims { public const string OwnsThingie = "ownsThingieId"; } } /// <summary> /// Startup class for Asp Net Core /// </summary> public class Startup { /// <summary> /// Development time Sqlite connection /// </summary> private SqliteConnection inMemorySqliteConnection; private readonly IConfigurationRoot Configuration; private readonly IHostingEnvironment env; /// <summary> /// Create a startup class, never created manually. This is initiated by UseStartup /// of the WebHostBuilder. /// </summary> /// <param name="env"></param> public Startup(IHostingEnvironment env) { this.env = env; var builder = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } /// <summary> /// Use redirection for OpenId controllers /// /// Includes the display property to inform login dialog /// about the display type (e.g. page or popup). /// </summary> private static Task redirectOnlyOpenId(CookieRedirectContext ctx) { if (ctx.Request.Path.StartsWithSegments("/OpenId")) { String display = ""; if (ctx.Request.Query.ContainsKey("display")) { display = ctx.Request.Query["display"].ToString(); } if (display != "") { ctx.Response.Redirect(QueryHelpers.AddQueryString(ctx.RedirectUri, new Dictionary<string, string> { { "display", display } })); } else { ctx.Response.Redirect(ctx.RedirectUri); } return Task.CompletedTask; } return Task.CompletedTask; } /// <summary> /// Groups actions in Swagger UI and in generated SDK e.g. /// /// "SomeApp.Controllers.HomeController" becomes "Home" /// "SomeApp.Controllers.Something.OtherController" becomes "Something.Other" /// </summary> public static string groupActions(ApiDescription s) { var r = new Regex(@"Controllers.(.*?)Controller"); var m = r.Match(s.ActionDescriptor.DisplayName); if (m.Success) { return m.Groups[1].Value; } return null; } /// <summary> /// Asp Net Core's dependency injection configuration /// </summary> public void ConfigureServices(IServiceCollection services) { services.AddCors(); // Add database in the application services.AddDbContext<AppDbContext>(options => { if (env.IsDevelopment()) { inMemorySqliteConnection = new SqliteConnection("Data Source=:memory:"); inMemorySqliteConnection.Open(); options.UseSqlite(inMemorySqliteConnection); } else { options.UseSqlServer(Configuration.GetConnectionString("Database")); } }); // Register MVC specific services, such as JSON, Authorization, ... services.AddMvcCore(opts => { opts.Filters.Add(new ModelStateValidationFilter()); opts.Filters.Add(new NullValidationFilter()); opts.Filters.Add(new ApiErrorFilter()); }) .AddApiExplorer() .AddAuthorization(opts => { opts.AddPolicy("COOKIES", opts.DefaultPolicy); opts.DefaultPolicy = new AuthorizationPolicyBuilder() .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme) .RequireClaim(OpenIdConnectConstants.Claims.Scope, AspNetApiMonolithSampleConstants.Scopes.ApiUser) .Build(); }) .AddDataAnnotations() .AddFormatterMappings() .AddJsonFormatters(); services.AddIdentity<User, Role>(opts => { opts.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = redirectOnlyOpenId, OnRedirectToAccessDenied = redirectOnlyOpenId, }; opts.Cookies.ApplicationCookie.AccessDeniedPath = "/OpenId/Login"; opts.Cookies.ApplicationCookie.LoginPath = "/OpenId/Login"; opts.Cookies.ApplicationCookie.LogoutPath = "/OpenId/Logout"; opts.Cookies.ApplicationCookie.CookiePath = "/OpenId/"; }) .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders(); var openIdDict = services.AddOpenIddict<AppDbContext>() .EnableAuthorizationEndpoint("/OpenId/Authorize") .EnableLogoutEndpoint("/OpenId/Logout") .AllowImplicitFlow() .UseJsonWebTokens(); if (env.IsDevelopment()) { openIdDict .AddSigningCertificate(File.Open("test.pfx", FileMode.Open), password: "test") // .AddEphemeralSigningKey() use ephemeral signin key if you // want to login each time as you restart .DisableHttpsRequirement(); } else { // On production, using a X.509 certificate stored in the machine store is recommended. // You can generate a self-signed certificate using Pluralsight's self-cert utility: // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip openIdDict .AddSigningCertificate(Configuration.GetOrFail("OpenId:SigningCertificateThumbprint")); } services.AddSwaggerGen(opts => { // Include .NET namespace in the Swagger UI sections opts.GroupActionsBy(groupActions); if (!Configuration.GetOrFail("Api:Url").EndsWith("/")) { throw new System.Exception("Configuration `Api.Url` must end with /"); } opts.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = Configuration.GetOrFail("Api:Url") + "OpenId/Authorize", TokenUrl = Configuration.GetOrFail("Api:Url") + "OpenId/token", Scopes = new Dictionary<string, string> { { AspNetApiMonolithSampleConstants.Scopes.ApiUser, "API user" } } }); }); // Stores and repositories services.AddScoped<IThingieStore, ThingieStore>(); services.AddTransient<EmailService, EmailService>(); services.Configure<EmailPlaceholders>(Configuration.GetSection("EmailPlaceholders")); services.AddSingleton<IEmailSender>((s) => { return new EmailSender(s) { FromName = Configuration.GetValue<string>("EmailSender:FromName"), FromEmail = Configuration.GetValue<string>("EmailSender:FromEmail"), SmtpHost = Configuration.GetValue<string>("EmailSender:SmtpHost"), SmtpPort = Configuration.GetValue<int>("EmailSender:SmtpPort"), SmtpSsl = Configuration.GetValue<bool>("EmailSender:SmtpSsl", true), SmtpUsername = Configuration.GetValue<string>("EmailSender:SmtpUsername"), SmtpPassword = Configuration.GetValue<string>("EmailSender:SmtpPassword"), }; }); services.Configure<JwtConfiguration>(Configuration.GetSection("Jwt")); services.Configure<Dictionary<string, OpenIddictApplication>>(Configuration.GetSection("Applications")); services.Configure<CorsConfiguration>(Configuration.GetSection("Cors")); services.Configure<UiBrandingHtmlConfiguration>(Configuration.GetSection("UiBrandingHtml")); services.Configure<FrontendUrlsConfiguration>(Configuration.GetSection("FrontendUrls")); if (env.IsDevelopment()) { services.AddTransient<IInitDatabase, AppDbInitDev>(); } else { services.AddTransient<IInitDatabase, AppDbInitProd>(); } } /// <summary> /// Asp Net Core's application configuration /// </summary> public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { // Logger if (env.IsDevelopment()) { loggerFactory.AddConsole(LogLevel.Debug); } else { loggerFactory.AddConsole(LogLevel.Warning); } // Uses static files, for now only Swagger need these app.UseStaticFiles(); // Cross origin request settings app.UseCors(builder => { // In development, allow all requests regardless of origin if (env.IsDevelopment()) { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader() .WithExposedHeaders("WwW-Authenticate"); // For JWT Bearer } else { var cors = app.ApplicationServices.GetService<IOptions<CorsConfiguration>>().Value; builder.WithOrigins(cors.Origins).AllowAnyMethod().AllowAnyHeader() .WithExposedHeaders("WwW-Authenticate"); // For JWT Bearer } }); // use JWT bearer authentication app.UseJwtBearerAuthentication(new JwtBearerOptions() { AutomaticAuthenticate = true, AutomaticChallenge = true, RequireHttpsMetadata = false, Audience = Configuration.GetOrFail("Jwt:Audience"), Authority = Configuration.GetOrFail("Jwt:Authority"), }); app.UseIdentity(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStatusCodePagesWithReExecute("/Error", "?status={0}"); app.UseOpenIddict(); app.UseMvc(); app.UseSwagger("docs/{apiVersion}/definition.json"); app.UseCustomSwaggerUi(new CustomSwaggerMiddlewareOpts() { definitionUrl = "/docs/v1/definition.json", baseRoute = "docs", oauth2_clientId = Configuration.GetOrFail("Applications:Docs:ClientId"), oauth2_appName = Configuration.GetOrFail("Applications:Docs:DisplayName"), oauth2_clientSecret = Configuration.GetValue<string>("Applications:Docs:Secret"), oauth2_additionalQueryStringParams = new Dictionary<string, string> { { "resource", Configuration.GetOrFail("Api:Url") } } }); app.ApplicationServices.GetService<IInitDatabase>().InitAsync().Wait(); } /// <summary> /// Experimental development interactive /// /// Maybe removed in the future /// </summary> private static async Task DevelopmentInteractive(IServiceProvider services) { while (true) { Console.Write("> "); string command = (Console.ReadLine() ?? "").Trim().ToLower(); switch (command) { case "mails": { Console.WriteLine("List of mails:"); var appDbContextOpts = services.GetService<DbContextOptions<AppDbContext>>(); using (var appDbContext = new AppDbContext(appDbContextOpts)) { var mails = await appDbContext.Emails.ToListAsync(); foreach (var m in mails) { Console.WriteLine($"* To: {m.ToEmail} ({m.ProcessGuid})"); Console.WriteLine($"Subject: {m.Subject} "); Console.WriteLine($"Message:\r\n\r\n{m.Body}\r\n\r\n"); } } Console.WriteLine("End of mails."); break; } default: { Console.WriteLine($"'{command}' is not recognized command."); break; } } } } /// <summary> /// Main entry point of the application /// </summary> /// <param name="args"> /// <list type="bullet"> /// <item> /// <term>gensdk</term> /// <description>Will output a API.ts SDK for TypeScript.</description> /// </item> /// <item> /// <term>dev</term> /// <description>When in Development environment will start additionally interactive console.</description> /// </item> /// </list> /// </param> public static void Main(string[] args) { var listArgs = new List<string>(args); var host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseKestrel() .UseStartup<Startup>() .Build(); var env = host.Services.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment; if (listArgs.Contains("gensdk")) { Console.WriteLine("Generating the SDK..."); var mvcOptions = host.Services.GetService<IOptions<MvcJsonOptions>>(); var apiProvider = host.Services.GetService<IApiDescriptionGroupCollectionProvider>(); var logger = host.Services.GetService<Logger<GenSdk>>(); var wrote = new GenSdk(apiProvider, mvcOptions, logger).Generate(new GenSdkOptions() { GroupActionsBy = groupActions, }); if (wrote) { Console.WriteLine("Generation done, file Api.ts was written."); } else { Console.WriteLine("Generation done, no changes."); } return; } if (env.IsDevelopment()) { if (listArgs.Contains("dev")) { Task.Run(() => { DevelopmentInteractive(host.Services).Wait(); }); } host.Run(); } else { host.Run(); } } } }
// 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 Microsoft.CodeAnalysis.CodeGeneration; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public partial class MetadataAsSourceTests : AbstractMetadataAsSourceTests { [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestClass() { var metadataSource = "public class C {}"; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|] Public Sub New() End Class"); } [WorkItem(546241)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestInterface() { var metadataSource = "public interface I {}"; var symbolName = "I"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public interface [|I|] {{ }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Interface [|I|] End Interface"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestConstructor() { var metadataSource = "public class C {}"; var symbolName = "C..ctor"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public [|C|](); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub [|New|]() End Class"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestMethod() { var metadataSource = "public class C { public void Foo() {} }"; var symbolName = "C.Foo"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public void [|Foo|](); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Sub [|Foo|]() End Class"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestField() { var metadataSource = "public class C { public string S; }"; var symbolName = "C.S"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public string [|S|]; public C(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public [|S|] As String Public Sub New() End Class"); } [WorkItem(546240)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestProperty() { var metadataSource = "public class C { public string S { get; protected set; } }"; var symbolName = "C.S"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public string [|S|] {{ get; protected set; }} }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Property [|S|] As String End Class"); } [WorkItem(546194)] [WorkItem(546291)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEvent() { var metadataSource = "using System; public class C { public event Action E; }"; var symbolName = "C.E"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; public class C {{ public C(); public event Action [|E|]; }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Public Class C Public Sub New() Public Event [|E|] As Action End Class"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNestedType() { var metadataSource = "public class C { protected class D { } }"; var symbolName = "C+D"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); protected class [|D|] {{ public D(); }} }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Protected Class [|D|] Public Sub New() End Class End Class"); } [WorkItem(546195), WorkItem(546269)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEnum() { var metadataSource = "public enum E { A, B, C }"; var symbolName = "E.C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E {{ A, B, [|C|] }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E A B [|C|] End Enum"); } [WorkItem(546273)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEnumWithUnderlyingType() { var metadataSource = "public enum E : short { A = 0, B = 1, C = 2 }"; var symbolName = "E.C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : short {{ A, B, [|C|] }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As Short A B [|C|] End Enum"); } [WorkItem(650741)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEnumWithOverflowingUnderlyingType() { var metadataSource = "public enum E : ulong { A = 9223372036854775808 }"; var symbolName = "E.A"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : ulong {{ [|A|] = 9223372036854775808 }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As ULong [|A|] = 9223372036854775808UL End Enum"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEnumWithDifferentValues() { var metadataSource = "public enum E : short { A = 1, B = 2, C = 3 }"; var symbolName = "E.C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public enum E : short {{ A = 1, B = 2, [|C|] = 3 }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Enum E As Short A = 1 B = 2 [|C|] = 3 End Enum"); } [WorkItem(546198)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestTypeInNamespace() { var metadataSource = "namespace N { public class C {} }"; var symbolName = "N.C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion namespace N {{ public class [|C|] {{ public C(); }} }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Namespace N Public Class [|C|] Public Sub New() End Class End Namespace"); } [WorkItem(546223)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestInlineConstant() { var metadataSource = @"public class C { public const string S = ""Hello mas""; }"; var symbolName = "C.S"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public const string [|S|] = ""Hello mas""; public C(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Const [|S|] As String = ""Hello mas"" Public Sub New() End Class"); } [WorkItem(546221)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestInlineTypeOf() { var metadataSource = @" using System; public class MyTypeAttribute : Attribute { public MyTypeAttribute(Type type) {} } [MyType(typeof(string))] public class C {}"; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion [MyType(typeof(string))] public class [|C|] {{ public C(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region <MyType(GetType(String))> Public Class [|C|] Public Sub New() End Class"); } [WorkItem(546231)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNoDefaultConstructorInStructs() { var metadataSource = "public struct S {}"; var symbolName = "S"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public struct [|S|] {{ }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Structure [|S|] End Structure"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestReferenceDefinedType() { var metadataSource = "public class C { public static C Create() { return new C(); } }"; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|C|] {{ public C(); public static C Create(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|C|] Public Sub New() Public Shared Function Create() As C End Class"); } [WorkItem(546227)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestGenericType() { var metadataSource = "public class G<SomeType> { public SomeType S; }"; var symbolName = "G`1"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class [|G|]<SomeType> {{ public SomeType S; public G(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class [|G|](Of SomeType) Public S As SomeType Public Sub New() End Class"); } [WorkItem(546227)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestGenericDelegate() { var metadataSource = "public class C { public delegate void D<SomeType>(SomeType s); }"; var symbolName = "C+D`1"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public delegate void [|D|]<SomeType>(SomeType s); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Public Class C Public Sub New() Public Delegate Sub [|D|](Of SomeType)(s As SomeType) End Class"); } [WorkItem(546200)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestAttribute() { var metadataSource = @" using System; namespace N { public class WorkingAttribute : Attribute { public WorkingAttribute(bool working) {} } } [N.Working(true)] public class C {}"; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using N; [Working(true)] public class [|C|] {{ public C(); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports N <Working(True)> Public Class [|C|] Public Sub New() End Class"); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestSymbolIdMatchesMetadata() { TestSymbolIdMatchesMetadata(LanguageNames.CSharp); TestSymbolIdMatchesMetadata(LanguageNames.VisualBasic); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNotReusedOnAssemblyDiffers() { TestNotReusedOnAssemblyDiffers(LanguageNames.CSharp); TestNotReusedOnAssemblyDiffers(LanguageNames.VisualBasic); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestThrowsOnGenerateNamespace() { var namespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol("Outerspace"); using (var context = new TestContext()) { Assert.Throws<ArgumentException>(() => { try { context.GenerateSource(namespaceSymbol); } catch (AggregateException ae) { throw ae.InnerException; } }); } } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestReuseGenerateMemberOfGeneratedType() { var metadataSource = "public class C { public bool Is; }"; using (var context = new TestContext(LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadataSource))) { var a = context.GenerateSource("C"); var b = context.GenerateSource("C.Is"); context.VerifyDocumentReused(a, b); } } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestReuseRepeatGeneration() { using (var context = new TestContext()) { var a = context.GenerateSource(); var b = context.GenerateSource(); context.VerifyDocumentReused(a, b); } } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestReuseGenerateFromDifferentProject() { using (var context = new TestContext()) { var projectId = ProjectId.CreateNewId(); var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.CSharp).GetProject(projectId) .WithMetadataReferences(context.DefaultProject.MetadataReferences) .WithCompilationOptions(new CS.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var a = context.GenerateSource(project: context.DefaultProject); var b = context.GenerateSource(project: project); context.VerifyDocumentReused(a, b); } } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNotReusedGeneratingForDifferentLanguage() { using (var context = new TestContext(LanguageNames.CSharp)) { var projectId = ProjectId.CreateNewId(); var project = context.CurrentSolution.AddProject(projectId, "ProjectB", "ProjectB", LanguageNames.VisualBasic).GetProject(projectId) .WithMetadataReferences(context.DefaultProject.MetadataReferences) .WithCompilationOptions(new VB.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var a = context.GenerateSource(project: context.DefaultProject); var b = context.GenerateSource(project: project); context.VerifyDocumentNotReused(a, b); } } [WorkItem(546311)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatMetadataAsSource() { using (var context = new TestContext(LanguageNames.CSharp)) { var file = context.GenerateSource("System.Console", project: context.DefaultProject); var document = context.GetDocument(file); Microsoft.CodeAnalysis.Formatting.Formatter.FormatAsync(document).Wait(); } } [WorkItem(530829)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void IndexedProperty() { var metadataSource = @" Public Class C Public Property IndexProp(ByVal p1 As Integer) As String Get Return Nothing End Get Set(ByVal value As String) End Set End Property End Class"; var expected = $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public class C {{ public C(); public string [|get_IndexProp|](int p1); public void set_IndexProp(int p1, string value); }}"; var symbolName = "C.get_IndexProp"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expected); } [WorkItem(566688)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void AttributeReferencingInternalNestedType() { var metadataSource = @"using System; [My(typeof(D))] public class C { public C() { } internal class D { } } public class MyAttribute : Attribute { public MyAttribute(Type t) { } }"; var expected = $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion [My(typeof(D))] public class [|C|] {{ public C(); }}"; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expected); } [WorkItem(530978)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestAttributesOnMembers() { var metadataSource = @"using System; [Obsolete] public class C { [Obsolete] [ThreadStatic] public int field1; [Obsolete] public int prop1 { get; set; } [Obsolete] public int prop2 { get { return 10; } set {} } [Obsolete] public void method1() {} [Obsolete] public C() {} [Obsolete] ~C() {} [Obsolete] public int this[int x] { get { return 10; } set {} } [Obsolete] public event Action event1; [Obsolete] public event Action event2 { add {} remove {}} public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {} [Obsolete] public static C operator + (C c1, C c2) { return new C(); } } "; var expectedCS = $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [DefaultMember(""Item"")] [Obsolete] public class [|C|] {{ [Obsolete] [ThreadStatic] public int field1; [Obsolete] public C(); [Obsolete] ~C(); [Obsolete] public int this[int x] {{ get; set; }} [Obsolete] public int prop1 {{ get; set; }} [Obsolete] public int prop2 {{ get; set; }} [Obsolete] public event Action event1; [Obsolete] public event Action event2; [Obsolete] public void method1(); public void method2([CallerMemberName] string name = """"); [Obsolete] public static C operator +(C c1, C c2); }} "; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expectedCS); var expectedVB = $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <DefaultMember(""Item"")> <Obsolete> Public Class [|C|] <Obsolete> <ThreadStatic> Public field1 As Integer <Obsolete> Public Sub New() <Obsolete> Default Public Property Item(x As Integer) As Integer <Obsolete> Public Property prop1 As Integer <Obsolete> Public Property prop2 As Integer <Obsolete> Public Event event1 As Action <Obsolete> Public Event event2 As Action <Obsolete> Public Sub method1() Public Sub method2(<CallerMemberName> Optional name As String = """") <Obsolete> Protected Overrides Sub Finalize() <Obsolete> Public Shared Operator +(c1 As C, c2 As C) As C End Class "; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB); } [WorkItem(530923)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEmptyLineBetweenMembers() { var metadataSource = @"using System; public class C { public int field1; public int prop1 { get; set; } public int field2; public int prop2 { get { return 10; } set {} } public void method1() {} public C() {} public void method2([System.Runtime.CompilerServices.CallerMemberName] string name = """") {} ~C() {} public int this[int x] { get { return 10; } set {} } public event Action event1; public static C operator + (C c1, C c2) { return new C(); } public event Action event2 { add {} remove {}} public static C operator - (C c1, C c2) { return new C(); } } "; var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; using System.Reflection; using System.Runtime.CompilerServices; [DefaultMember(""Item"")] public class [|C|] {{ public int field1; public int field2; public C(); ~C(); public int this[int x] {{ get; set; }} public int prop1 {{ get; set; }} public int prop2 {{ get; set; }} public event Action event1; public event Action event2; public void method1(); public void method2([CallerMemberName] string name = """"); public static C operator +(C c1, C c2); public static C operator -(C c1, C c2); }} "; var symbolName = "C"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, expectedCS, compareTokens: false); var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System Imports System.Reflection Imports System.Runtime.CompilerServices <DefaultMember(""Item"")> Public Class [|C|] Public field1 As Integer Public field2 As Integer Public Sub New() Default Public Property Item(x As Integer) As Integer Public Property prop1 As Integer Public Property prop2 As Integer Public Event event1 As Action Public Event event2 As Action Public Sub method1() Public Sub method2(<CallerMemberName> Optional name As String = """") Protected Overrides Sub Finalize() Public Shared Operator +(c1 As C, c2 As C) As C Public Shared Operator -(c1 As C, c2 As C) As C End Class"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, expectedVB, compareTokens: false); } [WorkItem(728644)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestEmptyLineBetweenMembers2() { var source = @" using System; /// <summary>T:IFoo</summary> public interface IFoo { /// <summary>P:IFoo.Prop1</summary> Uri Prop1 { get; set; } /// <summary>M:IFoo.Method1</summary> Uri Method1(); } "; var symbolName = "IFoo"; var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; // // {FeaturesResources.Summary} // T:IFoo public interface [|IFoo|] {{ // // {FeaturesResources.Summary} // P:IFoo.Prop1 Uri Prop1 {{ get; set; }} // // {FeaturesResources.Summary} // M:IFoo.Method1 Uri Method1(); }} "; GenerateAndVerifySource(source, symbolName, LanguageNames.CSharp, expectedCS, compareTokens: false, includeXmlDocComments: true); var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System ' ' {FeaturesResources.Summary} ' T:IFoo Public Interface [|IFoo|] ' ' {FeaturesResources.Summary} ' P:IFoo.Prop1 Property Prop1 As Uri ' ' {FeaturesResources.Summary} ' M:IFoo.Method1 Function Method1() As Uri End Interface "; GenerateAndVerifySource(source, symbolName, LanguageNames.VisualBasic, expectedVB, compareTokens: false, includeXmlDocComments: true); } [WorkItem(679114), WorkItem(715013)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestDefaultValueEnum() { var source = @" using System.IO; public class Test { public void foo(FileOptions options = 0) {} } "; var symbolName = "Test"; var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.IO; public class [|Test|] {{ public Test(); public void foo(FileOptions options = FileOptions.None); }} "; GenerateAndVerifySource(source, symbolName, LanguageNames.CSharp, expectedCS); var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.IO Public Class [|Test|] Public Sub New() Public Sub foo(Optional options As FileOptions = FileOptions.None) End Class"; GenerateAndVerifySource(source, symbolName, LanguageNames.VisualBasic, expectedVB); } [WorkItem(651261)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNullAttribute() { var source = @" using System; [Test(null)] public class TestAttribute : Attribute { public TestAttribute(int[] i) { } }"; var symbolName = "TestAttribute"; var expectedCS = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System; [Test(null)] public class [|TestAttribute|] : Attribute {{ public TestAttribute(int[] i); }} "; GenerateAndVerifySource(source, symbolName, LanguageNames.CSharp, expectedCS); var expectedVB = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System <Test(Nothing)> Public Class [|TestAttribute|] Inherits Attribute Public Sub New(i() As Integer) End Class"; GenerateAndVerifySource(source, symbolName, LanguageNames.VisualBasic, expectedVB); } [WorkItem(897006)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNavigationViaReducedExtensionMethodCS() { var metadata = @"using System; public static class ObjectExtensions { public static void M(this object o, int x) { } }"; var sourceWithSymbolReference = @" class C { void M() { new object().[|M|](5); } }"; var expected = $@"#region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion public static class ObjectExtensions {{ public static void [|M|](this object o, int x); }} "; using (var context = new TestContext( LanguageNames.CSharp, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, sourceWithSymbolReference: sourceWithSymbolReference)) { var navigationSymbol = context.GetNavigationSymbol(); var metadataAsSourceFile = context.GenerateSource(navigationSymbol); context.VerifyResult(metadataAsSourceFile, expected); } } [WorkItem(897006)] [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestNavigationViaReducedExtensionMethodVB() { var metadata = @"Imports System.Runtime.CompilerServices Namespace NS Public Module StringExtensions <Extension()> Public Sub M(ByVal o As String, x As Integer) End Sub End Module End Namespace"; var sourceWithSymbolReference = @" Imports NS.StringExtensions Public Module C Sub M() Dim s = ""Yay"" s.[|M|](1) End Sub End Module"; var expected = $@"#Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Runtime.CompilerServices Namespace NS <Extension> Public Module StringExtensions <Extension> Public Sub [|M|](o As String, x As Integer) End Module End Namespace"; using (var context = new TestContext( LanguageNames.VisualBasic, SpecializedCollections.SingletonEnumerable(metadata), includeXmlDocComments: false, sourceWithSymbolReference: sourceWithSymbolReference)) { var navigationSymbol = context.GetNavigationSymbol(); var metadataAsSourceFile = context.GenerateSource(navigationSymbol); context.VerifyResult(metadataAsSourceFile, expected); } } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TestIndexersAndOperators() { var metadataSource = @"public class Program { public int this[int x] { get { return 0; } set { } } public static Program operator + (Program p1, Program p2) { return new Program(); } }"; var symbolName = "Program"; GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.CSharp, $@" #region {FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null // {CodeAnalysisResources.InMemoryAssembly} #endregion using System.Reflection; [DefaultMember(""Item"")] public class [|Program|] {{ public Program(); public int this[int x] {{ get; set; }} public static Program operator +(Program p1, Program p2); }}"); GenerateAndVerifySource(metadataSource, symbolName, LanguageNames.VisualBasic, $@" #Region ""{FeaturesResources.Assembly} ReferencedAssembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"" ' {CodeAnalysisResources.InMemoryAssembly} #End Region Imports System.Reflection <DefaultMember(""Item"")> Public Class [|Program|] Public Sub New() Default Public Property Item(x As Integer) As Integer Public Shared Operator +(p1 As Program, p2 As Program) As Program End Class"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Graph.RBAC { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// ApplicationsOperations operations. /// </summary> public partial interface IApplicationsOperations { /// <summary> /// Create a new application. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='parameters'> /// Parameters to create an application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// 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> Task<AzureOperationResponse<Application>> CreateWithHttpMessagesAsync(ApplicationCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists applications by filter parameters. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// 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> Task<AzureOperationResponse<IEnumerable<Application>>> ListWithHttpMessagesAsync(ODataQuery<Application> odataQuery = default(ODataQuery<Application>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Delete an application. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an application by object Id. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// 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> Task<AzureOperationResponse<Application>> GetWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update existing application. Reference: /// http://msdn.microsoft.com/en-us/library/azure/hh974476.aspx /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='parameters'> /// Parameters to update an existing application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PatchWithHttpMessagesAsync(string applicationObjectId, ApplicationUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get keyCredentials associated with the application by object Id. /// Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// 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> Task<AzureOperationResponse<IEnumerable<KeyCredential>>> ListKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Update keyCredentials associated with an existing application. /// Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#keycredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='parameters'> /// Parameters to update keyCredentials of an existing application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdateKeyCredentialsWithHttpMessagesAsync(string applicationObjectId, KeyCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets passwordCredentials associated with an existing application. /// Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// 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> Task<AzureOperationResponse<IEnumerable<PasswordCredential>>> ListPasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Updates passwordCredentials associated with an existing /// application. Reference: /// https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#passwordcredential-type /// </summary> /// <param name='applicationObjectId'> /// Application object id /// </param> /// <param name='parameters'> /// Parameters to update passwordCredentials of an existing /// application. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="GraphErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> UpdatePasswordCredentialsWithHttpMessagesAsync(string applicationObjectId, PasswordCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// ===================================================================== // Copyright 2012-2013 FluffyUnderware // All rights reserved // ===================================================================== #if UNITY_3_3 || UNITY_3_4 || UNITY_3_5 #define UNITY_3 #endif using UnityEngine; using System.Collections.Generic; /// <summary> /// Class to manage a pool of prefabs /// </summary> public class SmartPool : MonoBehaviour { public const string Version = "1.02"; static Dictionary<string, SmartPool> _Pools = new Dictionary<string, SmartPool>(); /// <summary> /// Name of the Pool /// </summary> public string PoolName; /// <summary> /// The Prefab being managed by this pool /// </summary> public GameObject Prefab; /// <summary> /// Keep persistent between scene changes /// </summary> public bool DontDestroy=false; /// <summary> /// Automatically prepare when the game starts. If false, you'll need to call Prepare() by yourself /// </summary> public bool PrepareAtStart = true; /// <summary> /// Blocksize when the pool needs to grow or shrink /// </summary> public int AllocationBlockSize=1; /// <summary> /// Minimum pool size /// </summary> public int MinPoolSize=1; /// <summary> /// Maximum pool size /// </summary> public int MaxPoolSize=1; /// <summary> /// Behaviour when the maximum pool size is exceeded /// </summary> public PoolExceededMode OnMaxPoolSize = PoolExceededMode.Ignore; /// <summary> /// Automatically cull items until the pool reaches MaxPoolSize /// </summary> public bool AutoCull = true; /// <summary> /// Time in seconds between automatic culling occurs /// </summary> public float CullingSpeed = 1.0f; /// <summary> /// Whether all actions should be logged /// </summary> public bool DebugLog = false; Stack<GameObject> mStock=new Stack<GameObject>(); List<GameObject> mSpawned=new List<GameObject>(); float mLastCullingTime; public int InStock { get { return mStock.Count; } } public int Spawned { get { return mSpawned.Count; } } #region ### Unity Callbacks ### void Awake() { if (PoolName.Length == 0) Debug.LogWarning("SmartPool: Missing PoolName for pool belonging to '" + gameObject.name + "'!"); if (DontDestroy) DontDestroyOnLoad(gameObject); } void OnEnable() { if (Prefab != null) { if (GetPoolByName(PoolName) == null) { _Pools.Add(PoolName, this); if (DebugLog) Debug.Log("SmartPool: Adding '" + PoolName + "' to the pool dictionary!"); } } else { Debug.LogError("SmartPool: Pool '" + PoolName + "' is missing it's prefab!"); } } void Start() { if (PrepareAtStart) Prepare(); } void LateUpdate() { if (AutoCull && Time.time - mLastCullingTime > CullingSpeed) { mLastCullingTime = Time.time; Cull(true); } } void OnDisable() { if (!DontDestroy) { Clear(); if (_Pools.Remove(PoolName) && DebugLog) Debug.Log("SmartPool: Removing " + PoolName + " from the pool dictionary!"); } } void Reset() { PoolName = ""; Prefab = null; DontDestroy = false; AllocationBlockSize = 1; MinPoolSize = 1; MaxPoolSize = 1; OnMaxPoolSize = PoolExceededMode.Ignore; DebugLog = false; AutoCull = true; CullingSpeed = 1f; mLastCullingTime = 0; } #endregion #region ### Methods for the current pool ### /// <summary> /// Remove all instances held by this pool /// </summary> void Clear() { if (DebugLog) Debug.Log("SmartPool (" + PoolName + "): Clearing all instances of " + Prefab.name); foreach (GameObject go in mSpawned) Destroy(go); mSpawned.Clear(); foreach (GameObject go in mStock) Destroy(go); mStock.Clear(); } /// <summary> /// Shrink the stock to match MaxPoolSize /// </summary> public void Cull() { Cull(false); } /// <summary> /// Shrink the stock to match MaxPoolSize /// </summary> /// <param name="smartCull">if true a maximum of AllocationBlockSize items are culled</param> public void Cull(bool smartCull) { int toCull=(smartCull) ? Mathf.Min(AllocationBlockSize,mStock.Count-MaxPoolSize) : mStock.Count-MaxPoolSize; if (DebugLog && toCull>0) Debug.Log("SmartPool (" + PoolName + "): Culling "+(toCull)+" items"); while (toCull-->0) { GameObject item = mStock.Pop(); Destroy(item); } } /// <summary> /// Despawn a gameobject and add it to the stock /// </summary> /// <param name="item"></param> public void DespawnItem(GameObject item) { if (!item) { if (DebugLog) Debug.LogWarning("SmartPool (" + PoolName + ").DespawnItem: item is null!"); return; } if (IsSpawned(item)) { #if UNITY_3 item.active = false; #else item.SetActive(false); #endif item.name = Prefab.name + "_stock"; mSpawned.Remove(item); mStock.Push(item); if (DebugLog) Debug.Log("SmartPool (" + PoolName + "): Despawning '" + item.name); } else { GameObject.Destroy(item); if (DebugLog) Debug.LogWarning("SmartPool (" + PoolName + "): Cant Despawn" + item.name + "' because it's not managed by this pool! However, SmartPool destroyed it!"); } } /// <summary> /// Despawn all items of this pool /// </summary> public void DespawnAllItems() { while (mSpawned.Count > 0) DespawnItem(mSpawned[0]); } /// <summary> /// Destroys a spawned item instead of despawning it /// </summary> /// <param name="item">the spawned item to destroy</param> public void KillItem(GameObject item) { if (!item) { if (DebugLog) Debug.LogWarning("SmartPool (" + PoolName + ").KillItem: item is null!"); return; } mSpawned.Remove(item); Destroy(item); } /// <summary> /// Whether a gameobject is managed by this pool /// </summary> /// <param name="item">an item</param> /// <returns>true if item is managed by this pool</returns> public bool IsManagedObject(GameObject item) { if (!item) { if (DebugLog) Debug.LogWarning("SmartPool (" + PoolName + ").IsManagedObject: item is null!"); return false; } if (mSpawned.Contains(item) || mStock.Contains(item)) return true; else return false; } /// <summary> /// Whether a gameobject is spawned by this pool /// </summary> /// <param name="item">an item</param> /// <returns>true if the item is spawned by this pool</returns> public bool IsSpawned(GameObject item) { if (!item) { if (DebugLog) Debug.LogWarning("SmartPool (" + PoolName + ").IsSpawned: item is null!"); return false; } return (mSpawned.Contains(item)); } /// <summary> /// Create instances and add them to the stock /// </summary> /// <param name="no"></param> void Populate(int no) { while (no > 0) { GameObject go = (GameObject)Instantiate(Prefab); #if UNITY_3 go.active=false; #else go.SetActive(false); #endif go.transform.parent = transform; go.name = Prefab.name + "_stock"; mStock.Push(go); no--; } if (DebugLog) Debug.Log("SmartPool (" + PoolName + "): Instantiated " + mStock.Count + " instances of " + Prefab.name); } /// <summary> /// Clear all instances and repopulate the pool to match MinPoolSize /// </summary> public void Prepare() { Clear(); mStock = new Stack<GameObject>(MinPoolSize); Populate(MinPoolSize); } /// <summary> /// Spawn an instance, make it active and add it to the Spawned list /// </summary> /// <returns>the instance spawned</returns> public GameObject SpawnItem() { GameObject item=null; // if we ran out of objects, create some if (InStock == 0) { if (Spawned < MaxPoolSize || OnMaxPoolSize==PoolExceededMode.Ignore) Populate(AllocationBlockSize); } // maybe we've got objects ready now if (InStock > 0) { item = mStock.Pop(); if (DebugLog) Debug.Log("SmartPool (" + PoolName + "): Spawning item, taking it from the stock!"); // or maybe we want to reuse the oldest spawned item } else if (OnMaxPoolSize == PoolExceededMode.ReUse) { item = mSpawned[0]; mSpawned.RemoveAt(0); if (DebugLog) Debug.Log("SmartPool (" + PoolName + "): Spawning item, reusing an existing item!"); } else if (DebugLog) Debug.Log("SmartPool (" + PoolName + "): MaxPoolSize exceeded, nothing was spawned!"); if (item != null) { mSpawned.Add(item); #if UNITY_3 item.active = true; #else item.SetActive(true); #endif item.name = Prefab.name + "_clone"; item.transform.localPosition = Vector3.zero; } return item; } #endregion #region ### Methods to access pools (static) ### /// <summary> /// Shrink a stock to match MaxPoolSize /// </summary> /// <param name="poolName"></param> public static void Cull(string poolName) { Cull(poolName, false); } /// <summary> /// Shrink a stock to match MaxPoolSize /// </summary> /// <param name="smartCull">if true a maximum of AllocationBlockSize items are culled</param> public static void Cull(string poolName, bool smartCull) { SmartPool P = GetPoolByName(poolName); if (P) P.Cull(); } /// <summary> /// Despawn a managed item, returning it to the pool /// </summary> /// <param name="item">an item</param> /// <remarks>If the object is unmanaged, it will be destroyed</remarks> public static void Despawn(GameObject item) { if (item) { SmartPool P = GetPoolByItem(item); if (P != null) P.DespawnItem(item); else GameObject.Destroy(item); } } /// <summary> /// Despawn all items of a certain pool /// </summary> /// <param name="poolName">name of the pool</param> public static void DespawnAllItems(string poolName) { SmartPool P = GetPoolByName(poolName); if (P!=null) P.DespawnAllItems(); } /// <summary> /// Find the pool an item belongs to /// </summary> /// <param name="item">an item</param> /// <returns>the corresponding pool or null if the item is unmanaged</returns> public static SmartPool GetPoolByItem(GameObject item) { foreach (SmartPool P in _Pools.Values) if (P.IsManagedObject(item)) return P; return null; } /// <summary> /// Gets a pool by it's name /// </summary> /// <param name="poolName">name of the pool</param> /// <returns>a pool or null</returns> public static SmartPool GetPoolByName(string poolName) { SmartPool P; _Pools.TryGetValue(poolName, out P); return P; } /// <summary> /// Kill a spawned item instead of despawning it /// </summary> /// <param name="item">the spawned item to kill</param> /// <remarks>If the item is unmanaged, it will be destroyed anyway</remarks> public static void Kill(GameObject item) { if (item) { SmartPool P = GetPoolByItem(item); if (P != null) P.KillItem(item); else GameObject.Destroy(item); } } /// <summary> /// Clear all instances and repopulate a pool to match MinPoolSize /// </summary> public static void Prepare(string poolName) { SmartPool P = GetPoolByName(poolName); if (P != null) P.Prepare(); } /// <summary> /// Spawn an item from a specific pool /// </summary> /// <param name="poolName">the pool's name</param> /// <returns>a gameobject or null if spawning failed</returns> public static GameObject Spawn(string poolName) { SmartPool P; if (_Pools.TryGetValue(poolName, out P)) return P.SpawnItem(); else { Debug.LogWarning("SmartPool: No pool with name '" + poolName + "' found!"); return null; } } #endregion } /// <summary> /// Determining reaction when MaxPoolSize is exceeded /// </summary> [System.Serializable] public enum PoolExceededMode:int { /// <summary> /// MaxPoolSize will be ignored /// </summary> Ignore = 0, /// <summary> /// Spawning will fail when MaxPoolSize is exceeded /// </summary> StopSpawning = 1, /// <summary> /// Already spawned items will be returned when MaxPoolSize is exceeded /// </summary> ReUse = 2 }
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 LinkRelationsIntro.Areas.HelpPage.ModelDescriptions; using LinkRelationsIntro.Areas.HelpPage.Models; namespace LinkRelationsIntro.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); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>OperatingSystemVersionConstant</c> resource.</summary> public sealed partial class OperatingSystemVersionConstantName : gax::IResourceName, sys::IEquatable<OperatingSystemVersionConstantName> { /// <summary>The possible contents of <see cref="OperatingSystemVersionConstantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>operatingSystemVersionConstants/{criterion_id}</c>.</summary> Criterion = 1, } private static gax::PathTemplate s_criterion = new gax::PathTemplate("operatingSystemVersionConstants/{criterion_id}"); /// <summary> /// Creates a <see cref="OperatingSystemVersionConstantName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="OperatingSystemVersionConstantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static OperatingSystemVersionConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new OperatingSystemVersionConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="OperatingSystemVersionConstantName"/> with the pattern /// <c>operatingSystemVersionConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="OperatingSystemVersionConstantName"/> constructed from the provided ids. /// </returns> public static OperatingSystemVersionConstantName FromCriterion(string criterionId) => new OperatingSystemVersionConstantName(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="OperatingSystemVersionConstantName"/> with /// pattern <c>operatingSystemVersionConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="OperatingSystemVersionConstantName"/> with pattern /// <c>operatingSystemVersionConstants/{criterion_id}</c>. /// </returns> public static string Format(string criterionId) => FormatCriterion(criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="OperatingSystemVersionConstantName"/> with /// pattern <c>operatingSystemVersionConstants/{criterion_id}</c>. /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="OperatingSystemVersionConstantName"/> with pattern /// <c>operatingSystemVersionConstants/{criterion_id}</c>. /// </returns> public static string FormatCriterion(string criterionId) => s_criterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Parses the given resource name string into a new <see cref="OperatingSystemVersionConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>operatingSystemVersionConstants/{criterion_id}</c></description></item> /// </list> /// </remarks> /// <param name="operatingSystemVersionConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="OperatingSystemVersionConstantName"/> if successful.</returns> public static OperatingSystemVersionConstantName Parse(string operatingSystemVersionConstantName) => Parse(operatingSystemVersionConstantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="OperatingSystemVersionConstantName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>operatingSystemVersionConstants/{criterion_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="operatingSystemVersionConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="OperatingSystemVersionConstantName"/> if successful.</returns> public static OperatingSystemVersionConstantName Parse(string operatingSystemVersionConstantName, bool allowUnparsed) => TryParse(operatingSystemVersionConstantName, allowUnparsed, out OperatingSystemVersionConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="OperatingSystemVersionConstantName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>operatingSystemVersionConstants/{criterion_id}</c></description></item> /// </list> /// </remarks> /// <param name="operatingSystemVersionConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="OperatingSystemVersionConstantName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string operatingSystemVersionConstantName, out OperatingSystemVersionConstantName result) => TryParse(operatingSystemVersionConstantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="OperatingSystemVersionConstantName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>operatingSystemVersionConstants/{criterion_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="operatingSystemVersionConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="OperatingSystemVersionConstantName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string operatingSystemVersionConstantName, bool allowUnparsed, out OperatingSystemVersionConstantName result) { gax::GaxPreconditions.CheckNotNull(operatingSystemVersionConstantName, nameof(operatingSystemVersionConstantName)); gax::TemplatedResourceName resourceName; if (s_criterion.TryParseName(operatingSystemVersionConstantName, out resourceName)) { result = FromCriterion(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(operatingSystemVersionConstantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private OperatingSystemVersionConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string criterionId = null) { Type = type; UnparsedResource = unparsedResourceName; CriterionId = criterionId; } /// <summary> /// Constructs a new instance of a <see cref="OperatingSystemVersionConstantName"/> class from the component /// parts of pattern <c>operatingSystemVersionConstants/{criterion_id}</c> /// </summary> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public OperatingSystemVersionConstantName(string criterionId) : this(ResourceNameType.Criterion, criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.Criterion: return s_criterion.Expand(CriterionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as OperatingSystemVersionConstantName); /// <inheritdoc/> public bool Equals(OperatingSystemVersionConstantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(OperatingSystemVersionConstantName a, OperatingSystemVersionConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(OperatingSystemVersionConstantName a, OperatingSystemVersionConstantName b) => !(a == b); } public partial class OperatingSystemVersionConstant { /// <summary> /// <see cref="gagvr::OperatingSystemVersionConstantName"/>-typed view over the <see cref="ResourceName"/> /// resource name property. /// </summary> internal OperatingSystemVersionConstantName ResourceNameAsOperatingSystemVersionConstantName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::OperatingSystemVersionConstantName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::OperatingSystemVersionConstantName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> internal OperatingSystemVersionConstantName OperatingSystemVersionConstantName { get => string.IsNullOrEmpty(Name) ? null : gagvr::OperatingSystemVersionConstantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EventInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class EventInfo : MemberInfo, _EventInfo { #region Constructor protected EventInfo() { } #endregion public static bool operator ==(EventInfo left, EventInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeEventInfo || right is RuntimeEventInfo) { return false; } return left.Equals(right); } public static bool operator !=(EventInfo left, EventInfo right) { return !(left == right); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } #endregion #region Public Abstract\Virtual Members public virtual MethodInfo[] GetOtherMethods(bool nonPublic) { throw new NotImplementedException(); } public abstract MethodInfo GetAddMethod(bool nonPublic); public abstract MethodInfo GetRemoveMethod(bool nonPublic); public abstract MethodInfo GetRaiseMethod(bool nonPublic); public abstract EventAttributes Attributes { get; } #endregion #region Public Members public virtual MethodInfo AddMethod { get { return GetAddMethod(true); } } public virtual MethodInfo RemoveMethod { get { return GetRemoveMethod(true); } } public virtual MethodInfo RaiseMethod { get { return GetRaiseMethod(true); } } public MethodInfo[] GetOtherMethods() { return GetOtherMethods(false); } public MethodInfo GetAddMethod() { return GetAddMethod(false); } public MethodInfo GetRemoveMethod() { return GetRemoveMethod(false); } public MethodInfo GetRaiseMethod() { return GetRaiseMethod(false); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void AddEventHandler(Object target, Delegate handler) { MethodInfo addMethod = GetAddMethod(); if (addMethod == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); #if FEATURE_COMINTEROP if (addMethod.ReturnType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event Contract.Assert(addMethod.ReturnType == typeof(void)); #endif // FEATURE_COMINTEROP addMethod.Invoke(target, new object[] { handler }); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void RemoveEventHandler(Object target, Delegate handler) { MethodInfo removeMethod = GetRemoveMethod(); if (removeMethod == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicRemoveMethod")); #if FEATURE_COMINTEROP ParameterInfo[] parameters = removeMethod.GetParametersNoCopy(); Contract.Assert(parameters != null && parameters.Length == 1); if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); #endif // FEATURE_COMINTEROP removeMethod.Invoke(target, new object[] { handler }); } public virtual Type EventHandlerType { get { MethodInfo m = GetAddMethod(true); ParameterInfo[] p = m.GetParametersNoCopy(); Type del = typeof(Delegate); for (int i = 0; i < p.Length; i++) { Type c = p[i].ParameterType; if (c.IsSubclassOf(del)) return c; } return null; } } public bool IsSpecialName { get { return(Attributes & EventAttributes.SpecialName) != 0; } } public virtual bool IsMulticast { get { Type cl = EventHandlerType; Type mc = typeof(MulticastDelegate); return mc.IsAssignableFrom(cl); } } #endregion #if !FEATURE_CORECLR Type _EventInfo.GetType() { return base.GetType(); } void _EventInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and // include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable { #region Private Data Members private int m_token; private EventAttributes m_flags; private string m_name; [System.Security.SecurityCritical] private void* m_utf8name; private RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_addMethod; private RuntimeMethodInfo m_removeMethod; private RuntimeMethodInfo m_raiseMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; #endregion #region Constructor internal RuntimeEventInfo() { // Used for dummy head node during population } [System.Security.SecurityCritical] // auto-generated internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); Contract.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; m_token = tkEvent; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType(); scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); RuntimeMethodInfo dummy; Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, out m_addMethod, out m_removeMethod, out m_raiseMethod, out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeEventInfo m = o as RuntimeEventInfo; if ((object)m == null) return false; return m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } #endregion #region Object Overrides public override String ToString() { if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = new Utf8String(m_utf8name).ToString(); return m_name; } } public override Type DeclaringType { get { return m_declaringType; } } public override Type ReflectedType { get { return ReflectedTypeInternal; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } public override int MetadataToken { get { return m_token; } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region ISerializable [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, null, MemberTypes.Event); } #endregion #region EventInfo Overrides public override MethodInfo[] GetOtherMethods(bool nonPublic) { List<MethodInfo> ret = new List<MethodInfo>(); if ((object)m_otherMethod == null) return new MethodInfo[0]; for(int i = 0; i < m_otherMethod.Length; i ++) { if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic)) ret.Add(m_otherMethod[i]); } return ret.ToArray(); } public override MethodInfo GetAddMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) return null; return m_addMethod; } public override MethodInfo GetRemoveMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) return null; return m_removeMethod; } public override MethodInfo GetRaiseMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) return null; return m_raiseMethod; } public override EventAttributes Attributes { get { return m_flags; } } #endregion } }
using System; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using System.Windows.Input; using Prism.Properties; namespace Prism.Commands { /// <summary> /// An <see cref="ICommand"/> whose delegates can be attached for <see cref="Execute"/> and <see cref="CanExecute"/>. /// </summary> /// <typeparam name="T">Parameter type.</typeparam> /// <remarks> /// The constructor deliberately prevents the use of value types. /// Because ICommand takes an object, having a value type for T would cause unexpected behavior when CanExecute(null) is called during XAML initialization for command bindings. /// Using default(T) was considered and rejected as a solution because the implementor would not be able to distinguish between a valid and defaulted values. /// <para/> /// Instead, callers should support a value type by using a nullable value type and checking the HasValue property before using the Value property. /// <example> /// <code> /// public MyClass() /// { /// this.submitCommand = new DelegateCommand&lt;int?&gt;(this.Submit, this.CanSubmit); /// } /// /// private bool CanSubmit(int? customerId) /// { /// return (customerId.HasValue &amp;&amp; customers.Contains(customerId.Value)); /// } /// </code> /// </example> /// </remarks> public class DelegateCommand<T> : DelegateCommandBase { /// <summary> /// Initializes a new instance of <see cref="DelegateCommand{T}"/>. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <remarks><see cref="CanExecute"/> will always return true.</remarks> public DelegateCommand(Action<T> executeMethod) : this(executeMethod, (o) => true) { } /// <summary> /// Initializes a new instance of <see cref="DelegateCommand{T}"/>. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <exception cref="ArgumentNullException">When both <paramref name="executeMethod"/> and <paramref name="canExecuteMethod"/> ar <see langword="null" />.</exception> public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod) : base((o) => executeMethod((T)o), (o) => canExecuteMethod((T)o)) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull); TypeInfo genericTypeInfo = typeof(T).GetTypeInfo(); // DelegateCommand allows object or Nullable<>. // note: Nullable<> is a struct so we cannot use a class constraint. if (genericTypeInfo.IsValueType) { if ((!genericTypeInfo.IsGenericType) || (!typeof(Nullable<>).GetTypeInfo().IsAssignableFrom(genericTypeInfo.GetGenericTypeDefinition().GetTypeInfo()))) { throw new InvalidCastException(Resources.DelegateCommandInvalidGenericPayloadType); } } } /// <summary> /// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications. /// </summary> /// <typeparam name="TP">The object type containing the property specified in the expression.</typeparam> /// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param> /// <returns>The current instance of DelegateCommand</returns> public DelegateCommand<T> ObservesProperty<TP>(Expression<Func<TP>> propertyExpression) { ObservesPropertyInternal(propertyExpression); return this; } /// <summary> /// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications. /// </summary> /// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute((o) => PropertyName).</param> /// <returns>The current instance of DelegateCommand</returns> public DelegateCommand<T> ObservesCanExecute(Expression<Func<object, bool>> canExecuteExpression) { ObservesCanExecuteInternal(canExecuteExpression); return this; } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand{T}"/> from an awaitable handler method. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command.</param> /// <returns>Constructed instance of <see cref="DelegateCommand{T}"/></returns> public static DelegateCommand<T> FromAsyncHandler(Func<T, Task> executeMethod) { return new DelegateCommand<T>(executeMethod); } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand{T}"/> from an awaitable handler method. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <returns>Constructed instance of <see cref="DelegateCommand{T}"/></returns> public static DelegateCommand<T> FromAsyncHandler(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod) { return new DelegateCommand<T>(executeMethod, canExecuteMethod); } ///<summary> ///Determines if the command can execute by invoked the <see cref="Func{T,Bool}"/> provided during construction. ///</summary> ///<param name="parameter">Data used by the command to determine if it can execute.</param> ///<returns> ///<see langword="true" /> if this command can be executed; otherwise, <see langword="false" />. ///</returns> public virtual bool CanExecute(T parameter) { return base.CanExecute(parameter); } ///<summary> ///Executes the command and invokes the <see cref="Action{T}"/> provided during construction. ///</summary> ///<param name="parameter">Data used by the command.</param> public virtual Task Execute(T parameter) { return base.Execute(parameter); } private DelegateCommand(Func<T, Task> executeMethod) : this(executeMethod, (o) => true) { } private DelegateCommand(Func<T, Task> executeMethod, Func<T, bool> canExecuteMethod) : base((o) => executeMethod((T)o), (o) => canExecuteMethod((T)o)) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull); } } /// <summary> /// An <see cref="ICommand"/> whose delegates do not take any parameters for <see cref="Execute"/> and <see cref="CanExecute"/>. /// </summary> /// <see cref="DelegateCommandBase"/> /// <see cref="DelegateCommand{T}"/> public class DelegateCommand : DelegateCommandBase { /// <summary> /// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Action"/> to invoke on execution. /// </summary> /// <param name="executeMethod">The <see cref="Action"/> to invoke when <see cref="ICommand.Execute"/> is called.</param> public DelegateCommand(Action executeMethod) : this(executeMethod, () => true) { } /// <summary> /// Creates a new instance of <see cref="DelegateCommand"/> with the <see cref="Action"/> to invoke on execution /// and a <see langword="Func" /> to query for determining if the command can execute. /// </summary> /// <param name="executeMethod">The <see cref="Action"/> to invoke when <see cref="ICommand.Execute"/> is called.</param> /// <param name="canExecuteMethod">The <see cref="Func{TResult}"/> to invoke when <see cref="ICommand.CanExecute"/> is called</param> public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod) : base((o) => executeMethod(), (o) => canExecuteMethod()) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull); } /// <summary> /// Observes a property that implements INotifyPropertyChanged, and automatically calls DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications. /// </summary> /// <typeparam name="T">The object type containing the property specified in the expression.</typeparam> /// <param name="propertyExpression">The property expression. Example: ObservesProperty(() => PropertyName).</param> /// <returns>The current instance of DelegateCommand</returns> public DelegateCommand ObservesProperty<T>(Expression<Func<T>> propertyExpression) { ObservesPropertyInternal(propertyExpression); return this; } /// <summary> /// Observes a property that is used to determine if this command can execute, and if it implements INotifyPropertyChanged it will automatically call DelegateCommandBase.RaiseCanExecuteChanged on property changed notifications. /// </summary> /// <param name="canExecuteExpression">The property expression. Example: ObservesCanExecute((o) => PropertyName).</param> /// <returns>The current instance of DelegateCommand</returns> public DelegateCommand ObservesCanExecute(Expression<Func<object, bool>> canExecuteExpression) { ObservesCanExecuteInternal(canExecuteExpression); return this; } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand"/> from an awaitable handler method. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command.</param> /// <returns>Constructed instance of <see cref="DelegateCommand"/></returns> public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod) { return new DelegateCommand(executeMethod); } /// <summary> /// Factory method to create a new instance of <see cref="DelegateCommand"/> from an awaitable handler method. /// </summary> /// <param name="executeMethod">Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param> /// <param name="canExecuteMethod">Delegate to execute when CanExecute is called on the command. This can be null.</param> /// <returns>Constructed instance of <see cref="DelegateCommand"/></returns> public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod, Func<bool> canExecuteMethod) { return new DelegateCommand(executeMethod, canExecuteMethod); } ///<summary> /// Executes the command. ///</summary> public virtual Task Execute() { return Execute(null); } /// <summary> /// Determines if the command can be executed. /// </summary> /// <returns>Returns <see langword="true"/> if the command can execute, otherwise returns <see langword="false"/>.</returns> public virtual bool CanExecute() { return CanExecute(null); } private DelegateCommand(Func<Task> executeMethod) : this(executeMethod, () => true) { } private DelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod) : base((o) => executeMethod(), (o) => canExecuteMethod()) { if (executeMethod == null || canExecuteMethod == null) throw new ArgumentNullException("executeMethod", Resources.DelegateCommandDelegatesCannotBeNull); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.IO; using System.Collections; using System.Xml.Schema; using MS.Internal.Xml.XPath; /*--------------------------------------------------------------------------------------------- * * Dynamic Part Below... * * -------------------------------------------------------------------------------------------- */ // stack element class // this one needn't change, even the parameter in methods internal class AxisElement { internal DoubleLinkAxis curNode; // current under-checking node during navigating internal int rootDepth; // root depth -- contextDepth + 1 if ! isDss; context + {1...} if isDss internal int curDepth; // current depth internal bool isMatch; // current is already matching or waiting for matching internal DoubleLinkAxis CurNode { get { return this.curNode; } } // constructor internal AxisElement(DoubleLinkAxis node, int depth) { this.curNode = node; this.rootDepth = this.curDepth = depth; this.isMatch = false; } internal void SetDepth(int depth) { this.rootDepth = this.curDepth = depth; return; } // "a/b/c" pointer from b move to a // needn't change even tree structure changes internal void MoveToParent(int depth, ForwardAxis parent) { // "a/b/c", trying to match b (current node), but meet the end of a, so move pointer to a if (depth == this.curDepth - 1) { // really need to move the current node pointer to parent // what i did here is for seperating the case of IsDss or only IsChild // bcoz in the first case i need to expect "a" from random depth // -1 means it doesn't expect some specific depth (referecing the dealing to -1 in movetochild method // while in the second case i can't change the root depth which is 1. if ((this.curNode.Input == parent.RootNode) && (parent.IsDss)) { this.curNode = parent.RootNode; this.rootDepth = this.curDepth = -1; return; } else if (this.curNode.Input != null) { // else cur-depth --, cur-node change this.curNode = (DoubleLinkAxis)(this.curNode.Input); this.curDepth--; return; } else return; } // "a/b/c", trying to match b (current node), but meet the end of x (another child of a) // or maybe i matched, now move out the current node // or move out after failing to match attribute // the node i m next expecting is still the current node else if (depth == this.curDepth) { // after matched or [2] failed in matching attribute if (this.isMatch) { this.isMatch = false; } } return; // this node is still what i am expecting // ignore } // equal & ! attribute then move // "a/b/c" pointer from a move to b // return true if reach c and c is an element and c is the axis internal bool MoveToChild(string name, string URN, int depth, ForwardAxis parent) { // an attribute can never be the same as an element if (Asttree.IsAttribute(this.curNode)) { return false; } // either moveToParent or moveToChild status will have to be changed into unmatch... if (this.isMatch) { this.isMatch = false; } if (!AxisStack.Equal(this.curNode.Name, this.curNode.Urn, name, URN)) { return false; } if (this.curDepth == -1) { SetDepth(depth); } else if (depth > this.curDepth) { return false; } // matched ... if (this.curNode == parent.TopNode) { this.isMatch = true; return true; } // move down this.curNode DoubleLinkAxis nowNode = (DoubleLinkAxis)(this.curNode.Next); if (Asttree.IsAttribute(nowNode)) { this.isMatch = true; // for attribute return false; } this.curNode = nowNode; this.curDepth++; return false; } } internal class AxisStack { // property private ArrayList _stack; // of AxisElement private ForwardAxis _subtree; // reference to the corresponding subtree private ActiveAxis _parent; internal ForwardAxis Subtree { get { return _subtree; } } internal int Length { // stack length get { return _stack.Count; } } // instructor public AxisStack(ForwardAxis faxis, ActiveAxis parent) { _subtree = faxis; _stack = new ArrayList(); _parent = parent; // need to use its contextdepth each time.... // improvement: // if ! isDss, there has nothing to do with Push/Pop, only one copy each time will be kept // if isDss, push and pop each time.... if (!faxis.IsDss) { // keep an instance this.Push(1); // context depth + 1 } // else just keep stack empty } // method internal void Push(int depth) { AxisElement eaxis = new AxisElement(_subtree.RootNode, depth); _stack.Add(eaxis); } internal void Pop() { _stack.RemoveAt(Length - 1); } // used in the beginning of .// and MoveToChild // didn't consider Self, only consider name internal static bool Equal(string thisname, string thisURN, string name, string URN) { // which means "b" in xpath, no namespace should be specified if (thisURN == null) { if (!((URN == null) || (URN.Length == 0))) { return false; } } // != "*" else if ((thisURN.Length != 0) && (thisURN != URN)) { return false; } // != "a:*" || "*" if ((thisname.Length != 0) && (thisname != name)) { return false; } return true; } // "a/b/c" pointer from b move to a // needn't change even tree structure changes internal void MoveToParent(string name, string URN, int depth) { if (_subtree.IsSelfAxis) { return; } for (int i = 0; i < _stack.Count; ++i) { ((AxisElement)_stack[i]).MoveToParent(depth, _subtree); } // in ".//"'s case, since each time you push one new element while match, why not pop one too while match? if (_subtree.IsDss && Equal(_subtree.RootNode.Name, _subtree.RootNode.Urn, name, URN)) { Pop(); } // only the last one } // "a/b/c" pointer from a move to b // return true if reach c internal bool MoveToChild(string name, string URN, int depth) { bool result = false; // push first if (_subtree.IsDss && Equal(_subtree.RootNode.Name, _subtree.RootNode.Urn, name, URN)) { Push(-1); } for (int i = 0; i < _stack.Count; ++i) { if (((AxisElement)_stack[i]).MoveToChild(name, URN, depth, _subtree)) { result = true; } } return result; } // attribute can only at the topaxis part // dealing with attribute only here, didn't go into stack element at all // stack element only deal with moving the pointer around elements internal bool MoveToAttribute(string name, string URN, int depth) { if (!_subtree.IsAttribute) { return false; } if (!Equal(_subtree.TopNode.Name, _subtree.TopNode.Urn, name, URN)) { return false; } bool result = false; // no stack element for single attribute, so dealing with it separately if (_subtree.TopNode.Input == null) { return (_subtree.IsDss || (depth == 1)); } for (int i = 0; i < _stack.Count; ++i) { AxisElement eaxis = (AxisElement)_stack[i]; if ((eaxis.isMatch) && (eaxis.CurNode == _subtree.TopNode.Input)) { result = true; } } return result; } } // whenever an element is under identity-constraint, an instance of this class will be called // only care about property at this time internal class ActiveAxis { // consider about reactivating.... the stack should be clear right?? // just reset contextDepth & isActive.... private int _currentDepth; // current depth, trace the depth by myself... movetochild, movetoparent, movetoattribute private bool _isActive; // not active any more after moving out context node private Asttree _axisTree; // reference to the whole tree // for each subtree i need to keep a stack... private ArrayList _axisStack; // of AxisStack public int CurrentDepth { get { return _currentDepth; } } // if an instance is !IsActive, then it can be reactive and reuse // still need thinking..... internal void Reactivate() { _isActive = true; _currentDepth = -1; } internal ActiveAxis(Asttree axisTree) { _axisTree = axisTree; // only a pointer. do i need it? _currentDepth = -1; // context depth is 0 -- enforce moveToChild for the context node // otherwise can't deal with "." node _axisStack = new ArrayList(axisTree.SubtreeArray.Count); // defined length // new one stack element for each one for (int i = 0; i < axisTree.SubtreeArray.Count; ++i) { AxisStack stack = new AxisStack((ForwardAxis)axisTree.SubtreeArray[i], this); _axisStack.Add(stack); } _isActive = true; } public bool MoveToStartElement(string localname, string URN) { if (!_isActive) { return false; } // for each: _currentDepth++; bool result = false; for (int i = 0; i < _axisStack.Count; ++i) { AxisStack stack = (AxisStack)_axisStack[i]; // special case for self tree "." | ".//." if (stack.Subtree.IsSelfAxis) { if (stack.Subtree.IsDss || (this.CurrentDepth == 0)) result = true; continue; } // otherwise if it's context node then return false if (this.CurrentDepth == 0) continue; if (stack.MoveToChild(localname, URN, _currentDepth)) { result = true; // even already know the last result is true, still need to continue... // run everyone once } } return result; } // return result doesn't have any meaning until in SelectorActiveAxis public virtual bool EndElement(string localname, string URN) { // need to think if the early quitting will affect reactivating.... if (_currentDepth == 0) { // leave context node _isActive = false; _currentDepth--; } if (!_isActive) { return false; } for (int i = 0; i < _axisStack.Count; ++i) { ((AxisStack)_axisStack[i]).MoveToParent(localname, URN, _currentDepth); } _currentDepth--; return false; } // Secondly field interface public bool MoveToAttribute(string localname, string URN) { if (!_isActive) { return false; } bool result = false; for (int i = 0; i < _axisStack.Count; ++i) { if (((AxisStack)_axisStack[i]).MoveToAttribute(localname, URN, _currentDepth + 1)) { // don't change depth for attribute, but depth is add 1 result = true; } } return result; } } /* ---------------------------------------------------------------------------------------------- * * Static Part Below... * * ---------------------------------------------------------------------------------------------- */ // each node in the xpath tree internal class DoubleLinkAxis : Axis { internal Axis next; internal Axis Next { get { return this.next; } set { this.next = value; } } //constructor internal DoubleLinkAxis(Axis axis, DoubleLinkAxis inputaxis) : base(axis.TypeOfAxis, inputaxis, axis.Prefix, axis.Name, axis.NodeType) { this.next = null; this.Urn = axis.Urn; this.abbrAxis = axis.AbbrAxis; if (inputaxis != null) { inputaxis.Next = this; } } // recursive here internal static DoubleLinkAxis ConvertTree(Axis axis) { if (axis == null) { return null; } return (new DoubleLinkAxis(axis, ConvertTree((Axis)(axis.Input)))); } } // only keep axis, rootNode, isAttribute, isDss inside // act as an element tree for the Asttree internal class ForwardAxis { // Axis tree private DoubleLinkAxis _topNode; private DoubleLinkAxis _rootNode; // the root for reverse Axis // Axis tree property private bool _isAttribute; // element or attribute? "@"? private bool _isDss; // has ".//" in front of it? private bool _isSelfAxis; // only one node in the tree, and it's "." (self) node internal DoubleLinkAxis RootNode { get { return _rootNode; } } internal DoubleLinkAxis TopNode { get { return _topNode; } } internal bool IsAttribute { get { return _isAttribute; } } // has ".//" in front of it? internal bool IsDss { get { return _isDss; } } internal bool IsSelfAxis { get { return _isSelfAxis; } } public ForwardAxis(DoubleLinkAxis axis, bool isdesorself) { _isDss = isdesorself; _isAttribute = Asttree.IsAttribute(axis); _topNode = axis; _rootNode = axis; while (_rootNode.Input != null) { _rootNode = (DoubleLinkAxis)(_rootNode.Input); } // better to calculate it out, since it's used so often, and if the top is self then the whole tree is self _isSelfAxis = Asttree.IsSelf(_topNode); } } // static, including an array of ForwardAxis (this is the whole picture) internal class Asttree { // set private then give out only get access, to keep it intact all along private ArrayList _fAxisArray; private string _xpathexpr; private bool _isField; // field or selector private XmlNamespaceManager _nsmgr; internal ArrayList SubtreeArray { get { return _fAxisArray; } } // when making a new instance for Asttree, we do the compiling, and create the static tree instance public Asttree(string xPath, bool isField, XmlNamespaceManager nsmgr) { _xpathexpr = xPath; _isField = isField; _nsmgr = nsmgr; // checking grammar... and build fAxisArray this.CompileXPath(xPath, isField, nsmgr); // might throw exception in the middle } // only for debug #if DEBUG public void PrintTree (StreamWriter msw) { for (int i = 0; i < _fAxisArray.Count; ++i) { ForwardAxis axis = (ForwardAxis)_fAxisArray[i]; msw.WriteLine("<Tree IsDss=\"{0}\" IsAttribute=\"{1}\">", axis.IsDss, axis.IsAttribute); DoubleLinkAxis printaxis = axis.TopNode; while ( printaxis != null ) { msw.WriteLine (" <node>"); msw.WriteLine (" <URN> {0} </URN>", printaxis.Urn); msw.WriteLine (" <Prefix> {0} </Prefix>", printaxis.Prefix); msw.WriteLine (" <Name> {0} </Name>", printaxis.Name); msw.WriteLine (" <NodeType> {0} </NodeType>", printaxis.NodeType); msw.WriteLine (" <AxisType> {0} </AxisType>", printaxis.TypeOfAxis); msw.WriteLine (" </node>"); printaxis = (DoubleLinkAxis) (printaxis.Input); } msw.WriteLine ("</Tree>"); } } #endif // this part is for parsing restricted xpath from grammar private static bool IsNameTest(Axis ast) { // Type = Element, abbrAxis = false // all are the same, has child:: or not return ((ast.TypeOfAxis == Axis.AxisType.Child) && (ast.NodeType == XPathNodeType.Element)); } internal static bool IsAttribute(Axis ast) { return ((ast.TypeOfAxis == Axis.AxisType.Attribute) && (ast.NodeType == XPathNodeType.Attribute)); } private static bool IsDescendantOrSelf(Axis ast) { return ((ast.TypeOfAxis == Axis.AxisType.DescendantOrSelf) && (ast.NodeType == XPathNodeType.All) && (ast.AbbrAxis)); } internal static bool IsSelf(Axis ast) { return ((ast.TypeOfAxis == Axis.AxisType.Self) && (ast.NodeType == XPathNodeType.All) && (ast.AbbrAxis)); } // don't return true or false, if it's invalid path, just throw exception during the process // for whitespace thing, i will directly trim the tree built here... public void CompileXPath(string xPath, bool isField, XmlNamespaceManager nsmgr) { if ((xPath == null) || (xPath.Length == 0)) { throw new XmlSchemaException(SR.Sch_EmptyXPath, string.Empty); } // firstly i still need to have an ArrayList to store tree only... // can't new ForwardAxis right away string[] xpath = xPath.Split('|'); ArrayList AstArray = new ArrayList(xpath.Length); _fAxisArray = new ArrayList(xpath.Length); // throw compile exceptions // can i only new one builder here then run compile several times?? try { for (int i = 0; i < xpath.Length; ++i) { // default ! isdesorself (no .//) Axis ast = (Axis)(XPathParser.ParseXPathExpression(xpath[i])); AstArray.Add(ast); } } catch { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } Axis stepAst; for (int i = 0; i < AstArray.Count; ++i) { Axis ast = (Axis)AstArray[i]; // Restricted form // field can have an attribute: // throw exceptions during casting if ((stepAst = ast) == null) { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } Axis top = stepAst; // attribute will have namespace too // field can have top attribute if (IsAttribute(stepAst)) { if (!isField) { throw new XmlSchemaException(SR.Sch_SelectorAttr, xPath); } else { SetURN(stepAst, nsmgr); try { stepAst = (Axis)(stepAst.Input); } catch { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } } } // field or selector while ((stepAst != null) && (IsNameTest(stepAst) || IsSelf(stepAst))) { // trim tree "." node, if it's not the top one if (IsSelf(stepAst) && (ast != stepAst)) { top.Input = stepAst.Input; } else { top = stepAst; // set the URN if (IsNameTest(stepAst)) { SetURN(stepAst, nsmgr); } } try { stepAst = (Axis)(stepAst.Input); } catch { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } } // the rest part can only be .// or null // trim the rest part, but need compile the rest part first top.Input = null; if (stepAst == null) { // top "." and has other element beneath, trim this "." node too if (IsSelf(ast) && (ast.Input != null)) { _fAxisArray.Add(new ForwardAxis(DoubleLinkAxis.ConvertTree((Axis)(ast.Input)), false)); } else { _fAxisArray.Add(new ForwardAxis(DoubleLinkAxis.ConvertTree(ast), false)); } continue; } if (!IsDescendantOrSelf(stepAst)) { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } try { stepAst = (Axis)(stepAst.Input); } catch { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } if ((stepAst == null) || (!IsSelf(stepAst)) || (stepAst.Input != null)) { throw new XmlSchemaException(SR.Sch_ICXpathError, xPath); } // trim top "." if it's not the only node if (IsSelf(ast) && (ast.Input != null)) { _fAxisArray.Add(new ForwardAxis(DoubleLinkAxis.ConvertTree((Axis)(ast.Input)), true)); } else { _fAxisArray.Add(new ForwardAxis(DoubleLinkAxis.ConvertTree(ast), true)); } } } // depending on axis.Name & axis.Prefix, i will set the axis.URN; // also, record urn from prefix during this // 4 different types of element or attribute (with @ before it) combinations: // (1) a:b (2) b (3) * (4) a:* // i will check xpath to be strictly conformed from these forms // for (1) & (4) i will have URN set properly // for (2) the URN is null // for (3) the URN is empty private void SetURN(Axis axis, XmlNamespaceManager nsmgr) { if (axis.Prefix.Length != 0) { // (1) (4) axis.Urn = nsmgr.LookupNamespace(axis.Prefix); if (axis.Urn == null) { throw new XmlSchemaException(SR.Sch_UnresolvedPrefix, axis.Prefix); } } else if (axis.Name.Length != 0) { // (2) axis.Urn = null; } else { // (3) axis.Urn = ""; } } }// Asttree }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public class DockContent : Form, IDockContent { public DockContent() { m_dockHandler = new DockContentHandler(this, new GetPersistStringCallback(GetPersistString)); m_dockHandler.DockStateChanged += new EventHandler(DockHandler_DockStateChanged); //Suggested as a fix by bensty regarding form resize this.ParentChanged += new EventHandler(DockContent_ParentChanged); } //Suggested as a fix by bensty regarding form resize private void DockContent_ParentChanged(object Sender, EventArgs e) { if (this.Parent != null) this.Font = this.Parent.Font; } private DockContentHandler m_dockHandler = null; [Browsable(false)] public DockContentHandler DockHandler { get { return m_dockHandler; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_AllowEndUserDocking_Description")] [DefaultValue(true)] public bool AllowEndUserDocking { get { return DockHandler.AllowEndUserDocking; } set { DockHandler.AllowEndUserDocking = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_DockAreas_Description")] [DefaultValue(DockAreas.DockLeft|DockAreas.DockRight|DockAreas.DockTop|DockAreas.DockBottom|DockAreas.Document|DockAreas.Float)] public DockAreas DockAreas { get { return DockHandler.DockAreas; } set { DockHandler.DockAreas = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_AutoHidePortion_Description")] [DefaultValue(0.25)] public double AutoHidePortion { get { return DockHandler.AutoHidePortion; } set { DockHandler.AutoHidePortion = value; } } private string m_tabText = null; [Localizable(true)] [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabText_Description")] [DefaultValue(null)] public string TabText { get { return m_tabText; } set { DockHandler.TabText = m_tabText = value; } } private bool ShouldSerializeTabText() { return (m_tabText != null); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_CloseButton_Description")] [DefaultValue(true)] public bool CloseButton { get { return DockHandler.CloseButton; } set { DockHandler.CloseButton = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_CloseButtonVisible_Description")] [DefaultValue(true)] public bool CloseButtonVisible { get { return DockHandler.CloseButtonVisible; } set { DockHandler.CloseButtonVisible = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPanel DockPanel { get { return DockHandler.DockPanel; } set { DockHandler.DockPanel = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockState DockState { get { return DockHandler.DockState; } set { DockHandler.DockState = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPane Pane { get { return DockHandler.Pane; } set { DockHandler.Pane = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsHidden { get { return DockHandler.IsHidden; } set { DockHandler.IsHidden = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockState VisibleState { get { return DockHandler.VisibleState; } set { DockHandler.VisibleState = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsFloat { get { return DockHandler.IsFloat; } set { DockHandler.IsFloat = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPane PanelPane { get { return DockHandler.PanelPane; } set { DockHandler.PanelPane = value; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DockPane FloatPane { get { return DockHandler.FloatPane; } set { DockHandler.FloatPane = value; } } [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected virtual string GetPersistString() { return GetType().ToString(); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_HideOnClose_Description")] [DefaultValue(false)] public bool HideOnClose { get { return DockHandler.HideOnClose; } set { DockHandler.HideOnClose = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_ShowHint_Description")] [DefaultValue(DockState.Unknown)] public DockState ShowHint { get { return DockHandler.ShowHint; } set { DockHandler.ShowHint = value; } } [Browsable(false)] public bool IsActivated { get { return DockHandler.IsActivated; } } public bool IsDockStateValid(DockState dockState) { return DockHandler.IsDockStateValid(dockState); } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabPageContextMenu_Description")] [DefaultValue(null)] public ContextMenu TabPageContextMenu { get { return DockHandler.TabPageContextMenu; } set { DockHandler.TabPageContextMenu = value; } } [LocalizedCategory("Category_Docking")] [LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")] [DefaultValue(null)] public ContextMenuStrip TabPageContextMenuStrip { get { return DockHandler.TabPageContextMenuStrip; } set { DockHandler.TabPageContextMenuStrip = value; } } [Localizable(true)] [Category("Appearance")] [LocalizedDescription("DockContent_ToolTipText_Description")] [DefaultValue(null)] public string ToolTipText { get { return DockHandler.ToolTipText; } set { DockHandler.ToolTipText = value; } } public new void Activate() { DockHandler.Activate(); } public new void Hide() { DockHandler.Hide(); } public new void Show() { DockHandler.Show(); } public void Show(DockPanel dockPanel) { DockHandler.Show(dockPanel); } public void Show(DockPanel dockPanel, DockState dockState) { DockHandler.Show(dockPanel, dockState); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { DockHandler.Show(dockPanel, floatWindowBounds); } public void Show(DockPane pane, IDockContent beforeContent) { DockHandler.Show(pane, beforeContent); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { DockHandler.Show(previousPane, alignment, proportion); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void FloatAt(Rectangle floatWindowBounds) { DockHandler.FloatAt(floatWindowBounds); } public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex) { DockHandler.DockTo(paneTo, dockStyle, contentIndex); } public void DockTo(DockPanel panel, DockStyle dockStyle) { DockHandler.DockTo(panel, dockStyle); } #region IDockContent Members void IDockContent.OnActivated(EventArgs e) { this.OnActivated(e); } void IDockContent.OnDeactivate(EventArgs e) { this.OnDeactivate(e); } #endregion #region Events private void DockHandler_DockStateChanged(object sender, EventArgs e) { OnDockStateChanged(e); } private static readonly object DockStateChangedEvent = new object(); [LocalizedCategory("Category_PropertyChanged")] [LocalizedDescription("Pane_DockStateChanged_Description")] public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion /// <summary> /// Overridden to avoid resize issues with nested controls /// </summary> /// <remarks> /// http://blogs.msdn.com/b/alejacma/archive/2008/11/20/controls-won-t-get-resized-once-the-nesting-hierarchy-of-windows-exceeds-a-certain-depth-x64.aspx /// http://support.microsoft.com/kb/953934 /// </remarks> protected override void OnSizeChanged(EventArgs e) { if (DockPanel != null && DockPanel.SupportDeeplyNestedContent && IsHandleCreated) { BeginInvoke((MethodInvoker)delegate { base.OnSizeChanged(e); }); } else { base.OnSizeChanged(e); } } } }
/* Copyright (C) 2009 Volker Berlin ([email protected]) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters [email protected] */ using System; using System.Collections.Generic; using System.Text; using ikvm.debugger.requests; using ikvm.debugger.win; namespace ikvm.debugger { /// <summary> /// Implementation of the JDWP Protocol. The documentation is at: /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html /// </summary> class JdwpHandler { private readonly JdwpConnection conn; // TODO Create a real implementation private readonly TargetVM target; internal JdwpHandler(JdwpConnection conn, TargetVM target) { this.conn = conn; this.target = target; } internal void Run() { while (true) { Packet packet = conn.ReadPacket(); Console.Error.WriteLine("Packet:"+packet.CommandSet + " " + packet.Command); switch (packet.CommandSet) { case CommandSet.VirtualMachine: CommandSetVirtualMachine(packet); break; case CommandSet.ReferenceType: CommandSetReferenceType(packet); break; case CommandSet.EventRequest: CommandSetEventRequest(packet); break; default: NotImplementedPacket(packet); break; } conn.SendPacket(packet); } } /// <summary> /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_VirtualMachine /// </summary> /// <param name="packet"></param> private void CommandSetVirtualMachine(Packet packet) { switch (packet.Command) { case VirtualMachine.Version: packet.WriteString("IKVM Debugger"); packet.WriteInt(1); packet.WriteInt(6); packet.WriteString("1.6.0"); packet.WriteString("IKVM.NET"); break; case VirtualMachine.ClassesBySignature: String jniClassName = packet.ReadString(); IList<TargetType> types = target.FindTypes(jniClassName); packet.WriteInt(types.Count); // count foreach (TargetType type in types) { Console.Error.WriteLine("FindTypes:" + jniClassName + ":" + type.TypeId); packet.WriteByte(TypeTag.CLASS); //TODO can also a interface packet.WriteObjectID(type.TypeId); packet.WriteInt(ClassStatus.INITIALIZED); } break; case VirtualMachine.AllThreads: int[] ids = target.GetThreadIDs(); packet.WriteInt(ids.Length); for (int i = 0; i < ids.Length; i++) { packet.WriteObjectID(ids[i]); } break; case VirtualMachine.IDSizes: int size = 4; //we use a size of 4, a value of 8 is also possible packet.WriteInt(size); // fieldID size in bytes packet.WriteInt(size); // methodID size in bytes packet.WriteInt(size); // objectID size in bytes packet.WriteInt(size); // referenceTypeID size in bytes packet.WriteInt(size); // frameID size in bytes break; case VirtualMachine.Suspend: target.Suspend(); break; case VirtualMachine.Resume: target.Resume(); break; case VirtualMachine.Exit: target.Exit(packet.ReadInt()); break; case VirtualMachine.Capabilities: packet.WriteBool(false); // Can the VM watch field modification, and therefore can it send the Modification Watchpoint Event? packet.WriteBool(false); // Can the VM watch field access, and therefore can it send the Access Watchpoint Event? packet.WriteBool(false); // Can the VM get the bytecodes of a given method? packet.WriteBool(false); // Can the VM determine whether a field or method is synthetic? (that is, can the VM determine if the method or the field was invented by the compiler?) packet.WriteBool(false); // Can the VM get the owned monitors infornation for a thread? packet.WriteBool(false); // Can the VM get the current contended monitor of a thread? packet.WriteBool(false); // Can the VM get the monitor information for a given object? break; case VirtualMachine.CapabilitiesNew: packet.WriteBool(false); // Can the VM watch field modification, and therefore can it send the Modification Watchpoint Event? packet.WriteBool(false); // Can the VM watch field access, and therefore can it send the Access Watchpoint Event? packet.WriteBool(false); // Can the VM get the bytecodes of a given method? packet.WriteBool(false); // Can the VM determine whether a field or method is synthetic? (that is, can the VM determine if the method or the field was invented by the compiler?) packet.WriteBool(false); // Can the VM get the owned monitors infornation for a thread? packet.WriteBool(false); // Can the VM get the current contended monitor of a thread? packet.WriteBool(false); // Can the VM get the monitor information for a given object? packet.WriteBool(false); // Can the VM redefine classes? packet.WriteBool(false); // Can the VM add methods when redefining classes? packet.WriteBool(false); // Can the VM redefine classesin arbitrary ways? packet.WriteBool(false); // Can the VM pop stack frames? packet.WriteBool(false); // Can the VM filter events by specific object? packet.WriteBool(false); // Can the VM get the source debug extension? packet.WriteBool(false); // Can the VM request VM death events? packet.WriteBool(false); // Can the VM set a default stratum? packet.WriteBool(false); // Can the VM return instances, counts of instances of classes and referring objects? packet.WriteBool(false); // Can the VM request monitor events? packet.WriteBool(false); // Can the VM get monitors with frame depth info? packet.WriteBool(false); // Can the VM filter class prepare events by source name? packet.WriteBool(false); // Can the VM return the constant pool information? packet.WriteBool(false); // Can the VM force early return from a method? packet.WriteBool(false); // reserved22 packet.WriteBool(false); // reserved23 packet.WriteBool(false); // reserved24 packet.WriteBool(false); // reserved25 packet.WriteBool(false); // reserved26 packet.WriteBool(false); // reserved27 packet.WriteBool(false); // reserved28 packet.WriteBool(false); // reserved29 packet.WriteBool(false); // reserved30 packet.WriteBool(false); // reserved31 packet.WriteBool(false); // reserved32 break; default: NotImplementedPacket(packet); // include a SendPacket break; } } /// <summary> /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_ReferenceType /// </summary> /// <param name="packet"></param> private void CommandSetReferenceType(Packet packet) { switch (packet.Command) { case ReferenceType.Signature: int typeID = packet.ReadObjectID(); TargetType type = target.FindType(typeID); Console.Error.WriteLine(typeID + ":" + type.GetJniSignature()); packet.WriteString(type.GetJniSignature()); break; case ReferenceType.ClassLoader: int classLoaderID = packet.ReadObjectID(); packet.WriteObjectID(0); //TODO 0 - System Classloader, we can use module ID instead break; case ReferenceType.MethodsWithGeneric: typeID = packet.ReadObjectID(); Console.Error.WriteLine(typeID); type = target.FindType(typeID); IList<TargetMethod> methods = type.GetMethods(); packet.WriteInt(methods.Count); foreach (TargetMethod method in methods) { Console.Error.WriteLine(method.MethodId + ":" + method.Name + ":" + method.JniSignature + ":" + method.GenericSignature+":"+method.AccessFlags); packet.WriteObjectID(method.MethodId); packet.WriteString(method.Name); packet.WriteString(method.JniSignature); packet.WriteString(method.GenericSignature); packet.WriteInt(method.AccessFlags); } break; default: NotImplementedPacket(packet); break; } } /// <summary> /// http://java.sun.com/javase/6/docs/platform/jpda/jdwp/jdwp-protocol.html#JDWP_EventRequest /// </summary> /// <param name="packet"></param> private void CommandSetEventRequest(Packet packet) { switch (packet.Command) { case EventRequest.CmdSet: EventRequest eventRequest = EventRequest.create(packet); Console.Error.WriteLine(eventRequest); if (eventRequest == null) { NotImplementedPacket(packet); } else { target.AddEventRequest(eventRequest); packet.WriteInt(eventRequest.RequestId); } break; default: NotImplementedPacket(packet); break; } } private void NotImplementedPacket(Packet packet) { Console.Error.WriteLine("================================"); Console.Error.WriteLine("Not Implemented Packet:" + packet.CommandSet + "-" + packet.Command); Console.Error.WriteLine("================================"); packet.Error = Error.NOT_IMPLEMENTED; } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Compiler.Common; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.PlatformAbstractions; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resources; using Microsoft.Extensions.DependencyModel; using NuGet.Frameworks; namespace Orchard.Environment.Extensions.Compilers { public class CSharpExtensionCompiler { private static readonly Object _syncLock = new Object(); private static readonly ConcurrentDictionary<string, object> _compilationlocks = new ConcurrentDictionary<string, object>(); private static RuntimeLibrary CscLibrary => _cscLibrary.Value; private static RuntimeLibrary NativePDBWriter => _nativePDBWriter.Value; private static HashSet<string> AmbientLibraries => _ambientLibraries.Value; private static readonly Lazy<RuntimeLibrary> _cscLibrary = new Lazy<RuntimeLibrary>(GetCscLibrary); private static readonly Lazy<RuntimeLibrary> _nativePDBWriter = new Lazy<RuntimeLibrary>(GetNativePDBWriter); private static readonly Lazy<HashSet<string>> _ambientLibraries = new Lazy<HashSet<string>>(GetAmbientLibraries); private static readonly ConcurrentDictionary<string, bool> _compiledLibraries = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private readonly string _applicationName; public CSharpExtensionCompiler(string applicationName) { _applicationName = applicationName; Diagnostics = new List<string>(); } public IList<string> Diagnostics { get; private set; } private static RuntimeLibrary GetCscLibrary() { return DependencyContext.Default?.RuntimeLibraries.FirstOrDefault(l => l.NativeLibraryGroups.Any( g => g.Runtime.Equals("any", StringComparison.OrdinalIgnoreCase) && g.AssetPaths.Any( p => p.IndexOf("csc.exe", StringComparison.OrdinalIgnoreCase) >= 0))); } private static RuntimeLibrary GetNativePDBWriter() { return DependencyContext.Default?.RuntimeLibraries.FirstOrDefault(l => l.Name.Equals( "Microsoft.DiaSymReader.Native", StringComparison.OrdinalIgnoreCase)); } private static HashSet<string> GetAmbientLibraries() { return new HashSet<string>(DependencyContext.Default.CompileLibraries .Where(x => x.Type.Equals(LibraryType.Project.ToString(), StringComparison.OrdinalIgnoreCase)) .Select(x => x.Name), StringComparer.OrdinalIgnoreCase); } public bool Compile(ProjectContext context, string config, string probingFolderPath) { var compilationlock = _compilationlocks.GetOrAdd(context.ProjectName(), id => new object()); lock (compilationlock) { return CompileInternal(context, config, probingFolderPath); } } internal bool CompileInternal(ProjectContext context, string config, string probingFolderPath) { // Check if ambient library if (AmbientLibraries.Contains(context.ProjectName())) { return true; } bool compilationResult; // Check if already compiled if (_compiledLibraries.TryGetValue(context.ProjectName(), out compilationResult)) { return compilationResult; } // Get compilation options and source files var compilationOptions = context.ResolveCompilationOptions(config); var projectSourceFiles = CompilerUtility.GetCompilationSources(context, compilationOptions); // Check if precompiled if (!projectSourceFiles.Any()) { return _compiledLibraries[context.ProjectName()] = true; } // Set up Output Paths var outputPaths = context.GetOutputPaths(config); var outputPath = outputPaths.CompilationOutputPath; var intermediateOutputPath = outputPaths.IntermediateOutputDirectoryPath; Directory.CreateDirectory(outputPath); Directory.CreateDirectory(intermediateOutputPath); // Create the library exporter var exporter = context.CreateExporter(config); // Gather exports for the project var dependencies = exporter.GetDependencies().ToList(); // Get compilation options var outputName = outputPaths.CompilationFiles.Assembly; // Set default platform if it isn't already set and we're on desktop if (compilationOptions.EmitEntryPoint == true && String.IsNullOrEmpty(compilationOptions.Platform) && context.TargetFramework.IsDesktop()) { // See https://github.com/dotnet/cli/issues/2428 for more details. compilationOptions.Platform = RuntimeInformation.ProcessArchitecture == Architecture.X64 ? "x64" : "anycpu32bitpreferred"; } var references = new List<string>(); var sourceFiles = new List<string>(); var resources = new List<string>(); // Get the runtime directory var runtimeDirectory = ApplicationEnvironment.ApplicationBasePath; foreach (var dependency in dependencies) { sourceFiles.AddRange(dependency.SourceReferences.Select(s => s.GetTransformedFile(intermediateOutputPath))); foreach (var resourceFile in dependency.EmbeddedResources) { var transformedResource = resourceFile.GetTransformedFile(intermediateOutputPath); var resourceName = ResourceManifestName.CreateManifestName( Path.GetFileName(resourceFile.ResolvedPath), compilationOptions.OutputName); resources.Add($"\"{transformedResource}\",{resourceName}"); } var library = dependency.Library as ProjectDescription; var package = dependency.Library as PackageDescription; // Compile other referenced libraries if (library != null && !AmbientLibraries.Contains(library.Identity.Name) && dependency.CompilationAssemblies.Any()) { if (!_compiledLibraries.ContainsKey(library.Identity.Name)) { var projectContext = GetProjectContextFromPath(library.Project.ProjectDirectory); if (projectContext != null) { // Right now, if !success we try to use the last build var success = Compile(projectContext, config, probingFolderPath); } } } // Check for an unresolved library if (library != null && !library.Resolved) { var assetFileName = CompilerUtility.GetAssemblyFileName(library.Identity.Name); // Search in the runtime directory var assetResolvedPath = Path.Combine(runtimeDirectory, assetFileName); if (!File.Exists(assetResolvedPath)) { // Fallback to the project output path or probing folder assetResolvedPath = ResolveAssetPath(outputPath, probingFolderPath, assetFileName); if (String.IsNullOrEmpty(assetResolvedPath)) { // Fallback to this (possible) precompiled module bin folder var path = Path.Combine(Paths.GetParentFolderPath(library.Path), Constants.BinDirectoryName, assetFileName); assetResolvedPath = File.Exists(path) ? path : null; } } if (!String.IsNullOrEmpty(assetResolvedPath)) { references.Add(assetResolvedPath); } } // Check for an unresolved package else if (package != null && !package.Resolved) { var runtimeAssets = new HashSet<string>(package.RuntimeAssemblies.Select(x => x.Path), StringComparer.OrdinalIgnoreCase); string fallbackBinPath = null; foreach (var asset in package.CompileTimeAssemblies) { var assetFileName = Path.GetFileName(asset.Path); var isRuntimeAsset = runtimeAssets.Contains(asset.Path); // Search in the runtime directory var relativeFolderPath = isRuntimeAsset ? String.Empty : CompilerUtility.RefsDirectoryName; var assetResolvedPath = Path.Combine(runtimeDirectory, relativeFolderPath, assetFileName); if (!File.Exists(assetResolvedPath)) { // Fallback to the project output path or probing folder assetResolvedPath = ResolveAssetPath(outputPath, probingFolderPath, assetFileName, relativeFolderPath); } if (String.IsNullOrEmpty(assetResolvedPath)) { if (fallbackBinPath == null) { fallbackBinPath = String.Empty; // Fallback to a (possible) parent precompiled module bin folder var parentBinPaths = CompilerUtility.GetOtherParentProjectsLocations(context, package) .Select(x => Path.Combine(x, Constants.BinDirectoryName)); foreach (var binaryPath in parentBinPaths) { var path = Path.Combine(binaryPath, relativeFolderPath, assetFileName); if (File.Exists(path)) { assetResolvedPath = path; fallbackBinPath = binaryPath; break; } } } else if (!String.IsNullOrEmpty(fallbackBinPath)) { var path = Path.Combine(fallbackBinPath, relativeFolderPath, assetFileName); assetResolvedPath = File.Exists(path) ? path : null; } } if (!String.IsNullOrEmpty(assetResolvedPath)) { references.Add(assetResolvedPath); } } } // Check for a precompiled library else if (library != null && !dependency.CompilationAssemblies.Any()) { // Search in the project output path or probing folder var assetFileName = CompilerUtility.GetAssemblyFileName(library.Identity.Name); var assetResolvedPath = ResolveAssetPath(outputPath, probingFolderPath, assetFileName); if (String.IsNullOrEmpty(assetResolvedPath)) { // Fallback to this precompiled project output path var path = Path.Combine(CompilerUtility.GetAssemblyFolderPath(library.Project.ProjectDirectory, config, context.TargetFramework.DotNetFrameworkName), assetFileName); assetResolvedPath = File.Exists(path) ? path : null; } if (!String.IsNullOrEmpty(assetResolvedPath)) { references.Add(assetResolvedPath); } } // Check for a resolved but ambient library (compiled e.g by VS) else if (library != null && AmbientLibraries.Contains(library.Identity.Name)) { // Search in the regular project output path, fallback to the runtime directory references.AddRange(dependency.CompilationAssemblies.Select(r => File.Exists(r.ResolvedPath) ? r.ResolvedPath : Path.Combine(runtimeDirectory, r.FileName))); } else { references.AddRange(dependency.CompilationAssemblies.Select(r => r.ResolvedPath)); } } // Check again if already compiled, here through the dependency graph if (_compiledLibraries.TryGetValue(context.ProjectName(), out compilationResult)) { return compilationResult; } var sw = Stopwatch.StartNew(); string depsJsonFile = null; DependencyContext dependencyContext = null; // Add dependency context as a resource if (compilationOptions.PreserveCompilationContext == true) { var allExports = exporter.GetAllExports().ToList(); var exportsLookup = allExports.ToDictionary(e => e.Library.Identity.Name); var buildExclusionList = context.GetTypeBuildExclusionList(exportsLookup); var filteredExports = allExports .Where(e => e.Library.Identity.Type.Equals(LibraryType.ReferenceAssembly) || !buildExclusionList.Contains(e.Library.Identity.Name)); dependencyContext = new DependencyContextBuilder().Build(compilationOptions, filteredExports, filteredExports, false, // For now, just assume non-portable mode in the legacy deps file (this is going away soon anyway) context.TargetFramework, context.RuntimeIdentifier ?? string.Empty); depsJsonFile = Path.Combine(intermediateOutputPath, compilationOptions.OutputName + "dotnet-compile.deps.json"); resources.Add($"\"{depsJsonFile}\",{compilationOptions.OutputName}.deps.json"); } // Add project source files sourceFiles.AddRange(projectSourceFiles); // Add non culture resources var resgenFiles = CompilerUtility.GetNonCultureResources(context.ProjectFile, intermediateOutputPath, compilationOptions); AddNonCultureResources(resources, resgenFiles); var translated = TranslateCommonOptions(compilationOptions, outputName); var allArgs = new List<string>(translated); allArgs.AddRange(GetDefaultOptions()); // Add assembly info var assemblyInfo = Path.Combine(intermediateOutputPath, $"dotnet-compile.assemblyinfo.cs"); allArgs.Add($"\"{assemblyInfo}\""); if (!String.IsNullOrEmpty(outputName)) { allArgs.Add($"-out:\"{outputName}\""); } allArgs.AddRange(references.Select(r => $"-r:\"{r}\"")); allArgs.AddRange(resources.Select(resource => $"-resource:{resource}")); allArgs.AddRange(sourceFiles.Select(s => $"\"{s}\"")); // Gather all compile IO var inputs = new List<string>(); var outputs = new List<string>(); inputs.Add(context.ProjectFile.ProjectFilePath); if (context.LockFile != null) { inputs.Add(context.LockFile.LockFilePath); } if (context.LockFile.ExportFile != null) { inputs.Add(context.LockFile.ExportFile.ExportFilePath); } inputs.AddRange(sourceFiles); inputs.AddRange(references); inputs.AddRange(resgenFiles.Select(x => x.InputFile)); var cultureResgenFiles = CompilerUtility.GetCultureResources(context.ProjectFile, outputPath, compilationOptions); inputs.AddRange(cultureResgenFiles.SelectMany(x => x.InputFileToMetadata.Keys)); outputs.AddRange(outputPaths.CompilationFiles.All()); outputs.AddRange(resgenFiles.Where(x => x.OutputFile != null).Select(x => x.OutputFile)); //outputs.AddRange(cultureResgenFiles.Where(x => x.OutputFile != null).Select(x => x.OutputFile)); // Locate RSP file var rsp = Path.Combine(intermediateOutputPath, $"dotnet-compile-csc.rsp"); // Check if there is no need to compile if (!CheckMissingIO(inputs, outputs) && !TimestampsChanged(inputs, outputs)) { if (File.Exists(rsp)) { // Check if the compilation context has been changed var prevInputs = new HashSet<string>(File.ReadAllLines(rsp)); var newInputs = new HashSet<string>(allArgs); if (!prevInputs.Except(newInputs).Any() && !newInputs.Except(prevInputs).Any()) { PrintMessage($"{context.ProjectName()}: Previously compiled, skipping dynamic compilation."); return _compiledLibraries[context.ProjectName()] = true; } } else { // Write RSP file for the next time File.WriteAllLines(rsp, allArgs); PrintMessage($"{context.ProjectName()}: Previously compiled, skipping dynamic compilation."); return _compiledLibraries[context.ProjectName()] = true; } } if (!CompilerUtility.GenerateNonCultureResources(context.ProjectFile, resgenFiles, Diagnostics)) { return _compiledLibraries[context.ProjectName()] = false; } PrintMessage(String.Format($"{context.ProjectName()}: Dynamic compiling for {context.TargetFramework.DotNetFrameworkName}")); // Write the dependencies file if (dependencyContext != null) { var writer = new DependencyContextWriter(); using (var fileStream = File.Create(depsJsonFile)) { writer.Write(dependencyContext, fileStream); } } // Write assembly info and RSP files var assemblyInfoOptions = AssemblyInfoOptions.CreateForProject(context); File.WriteAllText(assemblyInfo, AssemblyInfoFileGenerator.GenerateCSharp(assemblyInfoOptions, sourceFiles)); File.WriteAllLines(rsp, allArgs); // Locate runtime config files var runtimeConfigPath = Path.Combine(runtimeDirectory, _applicationName + FileNameSuffixes.RuntimeConfigJson); var cscRuntimeConfigPath = Path.Combine(runtimeDirectory, "csc" + FileNameSuffixes.RuntimeConfigJson); // Automatically create the csc runtime config file if (Files.IsNewer(runtimeConfigPath, cscRuntimeConfigPath)) { lock (_syncLock) { if (Files.IsNewer(runtimeConfigPath, cscRuntimeConfigPath)) { File.Copy(runtimeConfigPath, cscRuntimeConfigPath, true); } } } // Locate csc.dll and the csc.exe asset var cscDllPath = Path.Combine(runtimeDirectory, CompilerUtility.GetAssemblyFileName("csc")); // Search in the runtime directory var cscRelativePath = Path.Combine("runtimes", "any", "native", "csc.exe"); var cscExePath = Path.Combine(runtimeDirectory, cscRelativePath); // Fallback to the packages storage if (!File.Exists(cscExePath) && !String.IsNullOrEmpty(context.PackagesDirectory)) { cscExePath = Path.Combine(context.PackagesDirectory, CscLibrary?.Name ?? String.Empty, CscLibrary?.Version ?? String.Empty, cscRelativePath); } // Automatically create csc.dll if (Files.IsNewer(cscExePath, cscDllPath)) { lock (_syncLock) { if (Files.IsNewer(cscExePath, cscDllPath)) { File.Copy(cscExePath, cscDllPath, true); } } } // Locate the csc dependencies file var cscDepsPath = Path.Combine(runtimeDirectory, "csc.deps.json"); // Automatically create csc.deps.json if (NativePDBWriter != null && Files.IsNewer(cscDllPath, cscDepsPath)) { lock (_syncLock) { if (Files.IsNewer(cscDllPath, cscDepsPath)) { // Only reference windows native pdb writers var runtimeLibraries = new List<RuntimeLibrary>(); runtimeLibraries.Add(NativePDBWriter); DependencyContext cscDependencyContext = new DependencyContext( DependencyContext.Default.Target, CompilationOptions.Default, new List<CompilationLibrary>(), runtimeLibraries, new List<RuntimeFallbacks>()); // Write the csc.deps.json file if (cscDependencyContext != null) { var writer = new DependencyContextWriter(); using (var fileStream = File.Create(cscDepsPath)) { writer.Write(cscDependencyContext, fileStream); } } // Windows native pdb writers are outputed on dotnet publish. // But not on dotnet build during development, we do it here. // Check if there is a packages storage if (!String.IsNullOrEmpty(context.PackagesDirectory)) { var assetPaths = NativePDBWriter.NativeLibraryGroups.SelectMany(l => l.AssetPaths); foreach (var assetPath in assetPaths) { // Resolve the pdb writer from the packages storage var pdbResolvedPath = Path.Combine(context.PackagesDirectory, NativePDBWriter.Name, NativePDBWriter.Version, assetPath); var pdbOutputPath = Path.Combine(runtimeDirectory, assetPath); // Store the pdb writer in the runtime directory if (Files.IsNewer(pdbResolvedPath, pdbOutputPath)) { Directory.CreateDirectory(Paths.GetParentFolderPath(pdbOutputPath)); File.Copy(pdbResolvedPath, pdbOutputPath, true); } } } } } } // Execute CSC! var result = Command.Create("csc.dll", new string[] { $"-noconfig", "@" + $"{rsp}" }) .WorkingDirectory(runtimeDirectory) .OnErrorLine(line => Diagnostics.Add(line)) .OnOutputLine(line => Diagnostics.Add(line)) .Execute(); compilationResult = result.ExitCode == 0; if (compilationResult) { compilationResult &= CompilerUtility.GenerateCultureResourceAssemblies(context.ProjectFile, cultureResgenFiles, references, Diagnostics); } PrintMessage(String.Empty); if (compilationResult && Diagnostics.Count == 0) { PrintMessage($"{context.ProjectName()}: Dynamic compilation succeeded."); PrintMessage($"0 Warning(s)"); PrintMessage($"0 Error(s)"); } else if (compilationResult && Diagnostics.Count > 0) { PrintMessage($"{context.ProjectName()}: Dynamic compilation succeeded but has warnings."); PrintMessage($"0 Error(s)"); } else { PrintMessage($"{context.ProjectName()}: Dynamic compilation failed."); } foreach (var diagnostic in Diagnostics) { PrintMessage(diagnostic); } PrintMessage($"Time elapsed {sw.Elapsed}"); PrintMessage(String.Empty); return _compiledLibraries[context.ProjectName()] = compilationResult; } private static void PrintMessage(string message) { if (Debugger.IsAttached) { Debug.WriteLine(message); } else { Reporter.Output.WriteLine(message); } } private ProjectContext GetProjectContextFromPath(string projectPath) { return ProjectContext.CreateContextForEachFramework(projectPath).FirstOrDefault(); } private string ResolveAssetPath(string binaryFolderPath, string probingFolderPath, string assetFileName, string relativeFolderPath = null) { return CompilerUtility.ResolveAssetPath(binaryFolderPath, probingFolderPath, assetFileName, relativeFolderPath); } private static void AddNonCultureResources(List<string> resources, List<CompilerUtility.NonCultureResgenIO> resgenFiles) { foreach (var resgenFile in resgenFiles) { if (ResourceUtility.IsResxFile(resgenFile.InputFile)) { resources.Add($"\"{resgenFile.OutputFile}\",{Path.GetFileName(resgenFile.MetadataName)}"); } else { resources.Add($"\"{resgenFile.InputFile}\",{Path.GetFileName(resgenFile.MetadataName)}"); } } } private static IEnumerable<string> GetDefaultOptions() { var args = new List<string>() { "-nostdlib", "-nologo", }; return args; } private static IEnumerable<string> TranslateCommonOptions(CommonCompilerOptions options, string outputName) { List<string> commonArgs = new List<string>(); if (options.Defines != null) { commonArgs.AddRange(options.Defines.Select(def => $"-d:{def}")); } if (options.SuppressWarnings != null) { commonArgs.AddRange(options.SuppressWarnings.Select(w => $"-nowarn:{w}")); } // Additional arguments are added verbatim if (options.AdditionalArguments != null) { commonArgs.AddRange(options.AdditionalArguments); } if (options.LanguageVersion != null) { commonArgs.Add($"-langversion:{GetLanguageVersion(options.LanguageVersion)}"); } if (options.Platform != null) { commonArgs.Add($"-platform:{options.Platform}"); } if (options.AllowUnsafe == true) { commonArgs.Add("-unsafe"); } if (options.WarningsAsErrors == true) { commonArgs.Add("-warnaserror"); } if (options.Optimize == true) { commonArgs.Add("-optimize"); } if (options.KeyFile != null) { commonArgs.Add($"-keyfile:\"{options.KeyFile}\""); // If we're not on Windows, full signing isn't supported, so we'll // public sign, unless the public sign switch has been set to false if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && options.PublicSign == null) { commonArgs.Add("-publicsign"); } } if (options.DelaySign == true) { commonArgs.Add("-delaysign"); } if (options.PublicSign == true) { commonArgs.Add("-publicsign"); } if (options.GenerateXmlDocumentation == true) { commonArgs.Add($"-doc:\"{Path.ChangeExtension(outputName, "xml")}\""); } if (options.EmitEntryPoint != true) { commonArgs.Add("-t:library"); } if (string.IsNullOrEmpty(options.DebugType)) { commonArgs.Add(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "-debug:full" : "-debug:portable"); } else { commonArgs.Add("-debug:" + options.DebugType); } return commonArgs; } private static string GetLanguageVersion(string languageVersion) { // project.json supports the enum that the roslyn APIs expose if (languageVersion?.StartsWith("csharp", StringComparison.OrdinalIgnoreCase) == true) { // We'll be left with the number csharp6 = 6 return languageVersion.Substring("csharp".Length); } return languageVersion; } private bool CheckMissingIO(IEnumerable<string> inputs, IEnumerable<string> outputs) { if (!inputs.Any() || !outputs.Any()) { return false; } return CheckMissingIO(inputs) || CheckMissingIO(outputs); } private bool CheckMissingIO(IEnumerable<string> items) { return items.Where(i => !File.Exists(i)).Any(); } private bool TimestampsChanged(IEnumerable<string> inputs, IEnumerable<string> outputs) { // Find the output with the earliest write time var minDateUtc = outputs.Min(output => File.GetLastWriteTimeUtc(output)); // Find inputs that are newer than the earliest output return inputs.Any(p => File.GetLastWriteTimeUtc(p) >= minDateUtc); } } }
/** * 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. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; namespace Thrift.Protocol { /** * TProtocolDecorator forwards all requests to an enclosed TProtocol instance, * providing a way to author concise concrete decorator subclasses. While it has * no abstract methods, it is marked abstract as a reminder that by itself, * it does not modify the behaviour of the enclosed TProtocol. * * See p.175 of Design Patterns (by Gamma et al.) * See TMultiplexedProtocol */ public abstract class TProtocolDecorator : TProtocol { private TProtocol WrappedProtocol; /** * Encloses the specified protocol. * @param protocol All operations will be forward to this protocol. Must be non-null. */ public TProtocolDecorator(TProtocol protocol) : base( protocol.Transport) { WrappedProtocol = protocol; } public override void WriteMessageBegin(TMessage tMessage) { WrappedProtocol.WriteMessageBegin(tMessage); } public override void WriteMessageEnd() { WrappedProtocol.WriteMessageEnd(); } public override void WriteStructBegin(TStruct tStruct) { WrappedProtocol.WriteStructBegin(tStruct); } public override void WriteStructEnd() { WrappedProtocol.WriteStructEnd(); } public override void WriteFieldBegin(TField tField) { WrappedProtocol.WriteFieldBegin(tField); } public override void WriteFieldEnd() { WrappedProtocol.WriteFieldEnd(); } public override void WriteFieldStop() { WrappedProtocol.WriteFieldStop(); } public override void WriteMapBegin(TMap tMap) { WrappedProtocol.WriteMapBegin(tMap); } public override void WriteMapEnd() { WrappedProtocol.WriteMapEnd(); } public override void WriteListBegin(TList tList) { WrappedProtocol.WriteListBegin(tList); } public override void WriteListEnd() { WrappedProtocol.WriteListEnd(); } public override void WriteSetBegin(TSet tSet) { WrappedProtocol.WriteSetBegin(tSet); } public override void WriteSetEnd() { WrappedProtocol.WriteSetEnd(); } public override void WriteBool(bool b) { WrappedProtocol.WriteBool(b); } public override void WriteByte(sbyte b) { WrappedProtocol.WriteByte(b); } public override void WriteI16(short i) { WrappedProtocol.WriteI16(i); } public override void WriteI32(int i) { WrappedProtocol.WriteI32(i); } public override void WriteI64(long l) { WrappedProtocol.WriteI64(l); } public override void WriteDouble(double v) { WrappedProtocol.WriteDouble(v); } public override void WriteString(String s) { WrappedProtocol.WriteString(s); } public override void WriteBinary(byte[] bytes) { WrappedProtocol.WriteBinary(bytes); } public override TMessage ReadMessageBegin() { return WrappedProtocol.ReadMessageBegin(); } public override void ReadMessageEnd() { WrappedProtocol.ReadMessageEnd(); } public override TStruct ReadStructBegin() { return WrappedProtocol.ReadStructBegin(); } public override void ReadStructEnd() { WrappedProtocol.ReadStructEnd(); } public override TField ReadFieldBegin() { return WrappedProtocol.ReadFieldBegin(); } public override void ReadFieldEnd() { WrappedProtocol.ReadFieldEnd(); } public override TMap ReadMapBegin() { return WrappedProtocol.ReadMapBegin(); } public override void ReadMapEnd() { WrappedProtocol.ReadMapEnd(); } public override TList ReadListBegin() { return WrappedProtocol.ReadListBegin(); } public override void ReadListEnd() { WrappedProtocol.ReadListEnd(); } public override TSet ReadSetBegin() { return WrappedProtocol.ReadSetBegin(); } public override void ReadSetEnd() { WrappedProtocol.ReadSetEnd(); } public override bool ReadBool() { return WrappedProtocol.ReadBool(); } public override sbyte ReadByte() { return WrappedProtocol.ReadByte(); } public override short ReadI16() { return WrappedProtocol.ReadI16(); } public override int ReadI32() { return WrappedProtocol.ReadI32(); } public override long ReadI64() { return WrappedProtocol.ReadI64(); } public override double ReadDouble() { return WrappedProtocol.ReadDouble(); } public override String ReadString() { return WrappedProtocol.ReadString(); } public override byte[] ReadBinary() { return WrappedProtocol.ReadBinary(); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf.WellKnownTypes { /// <summary>Holder for reflection information generated from google/protobuf/type.proto</summary> public static partial class TypeReflection { #region Descriptor /// <summary>File descriptor for google/protobuf/type.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static TypeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxIPZ29vZ2xlLnByb3RvYnVm", "Ghlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvGiRnb29nbGUvcHJvdG9idWYv", "c291cmNlX2NvbnRleHQucHJvdG8i1wEKBFR5cGUSDAoEbmFtZRgBIAEoCRIm", "CgZmaWVsZHMYAiADKAsyFi5nb29nbGUucHJvdG9idWYuRmllbGQSDgoGb25l", "b2ZzGAMgAygJEigKB29wdGlvbnMYBCADKAsyFy5nb29nbGUucHJvdG9idWYu", "T3B0aW9uEjYKDnNvdXJjZV9jb250ZXh0GAUgASgLMh4uZ29vZ2xlLnByb3Rv", "YnVmLlNvdXJjZUNvbnRleHQSJwoGc3ludGF4GAYgASgOMhcuZ29vZ2xlLnBy", "b3RvYnVmLlN5bnRheCLVBQoFRmllbGQSKQoEa2luZBgBIAEoDjIbLmdvb2ds", "ZS5wcm90b2J1Zi5GaWVsZC5LaW5kEjcKC2NhcmRpbmFsaXR5GAIgASgOMiIu", "Z29vZ2xlLnByb3RvYnVmLkZpZWxkLkNhcmRpbmFsaXR5Eg4KBm51bWJlchgD", "IAEoBRIMCgRuYW1lGAQgASgJEhAKCHR5cGVfdXJsGAYgASgJEhMKC29uZW9m", "X2luZGV4GAcgASgFEg4KBnBhY2tlZBgIIAEoCBIoCgdvcHRpb25zGAkgAygL", "MhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhIRCglqc29uX25hbWUYCiABKAkS", "FQoNZGVmYXVsdF92YWx1ZRgLIAEoCSLIAgoES2luZBIQCgxUWVBFX1VOS05P", "V04QABIPCgtUWVBFX0RPVUJMRRABEg4KClRZUEVfRkxPQVQQAhIOCgpUWVBF", "X0lOVDY0EAMSDwoLVFlQRV9VSU5UNjQQBBIOCgpUWVBFX0lOVDMyEAUSEAoM", "VFlQRV9GSVhFRDY0EAYSEAoMVFlQRV9GSVhFRDMyEAcSDQoJVFlQRV9CT09M", "EAgSDwoLVFlQRV9TVFJJTkcQCRIOCgpUWVBFX0dST1VQEAoSEAoMVFlQRV9N", "RVNTQUdFEAsSDgoKVFlQRV9CWVRFUxAMEg8KC1RZUEVfVUlOVDMyEA0SDQoJ", "VFlQRV9FTlVNEA4SEQoNVFlQRV9TRklYRUQzMhAPEhEKDVRZUEVfU0ZJWEVE", "NjQQEBIPCgtUWVBFX1NJTlQzMhAREg8KC1RZUEVfU0lOVDY0EBIidAoLQ2Fy", "ZGluYWxpdHkSFwoTQ0FSRElOQUxJVFlfVU5LTk9XThAAEhgKFENBUkRJTkFM", "SVRZX09QVElPTkFMEAESGAoUQ0FSRElOQUxJVFlfUkVRVUlSRUQQAhIYChRD", "QVJESU5BTElUWV9SRVBFQVRFRBADIs4BCgRFbnVtEgwKBG5hbWUYASABKAkS", "LQoJZW51bXZhbHVlGAIgAygLMhouZ29vZ2xlLnByb3RvYnVmLkVudW1WYWx1", "ZRIoCgdvcHRpb25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2", "Cg5zb3VyY2VfY29udGV4dBgEIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3Vy", "Y2VDb250ZXh0EicKBnN5bnRheBgFIAEoDjIXLmdvb2dsZS5wcm90b2J1Zi5T", "eW50YXgiUwoJRW51bVZhbHVlEgwKBG5hbWUYASABKAkSDgoGbnVtYmVyGAIg", "ASgFEigKB29wdGlvbnMYAyADKAsyFy5nb29nbGUucHJvdG9idWYuT3B0aW9u", "IjsKBk9wdGlvbhIMCgRuYW1lGAEgASgJEiMKBXZhbHVlGAIgASgLMhQuZ29v", "Z2xlLnByb3RvYnVmLkFueSouCgZTeW50YXgSEQoNU1lOVEFYX1BST1RPMhAA", "EhEKDVNZTlRBWF9QUk9UTzMQAUJ9ChNjb20uZ29vZ2xlLnByb3RvYnVmQglU", "eXBlUHJvdG9QAVovZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vcHJvdG9i", "dWYvcHR5cGU7cHR5cGX4AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2Vs", "bEtub3duVHlwZXNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.AnyReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.SourceContextReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Google.Protobuf.WellKnownTypes.Syntax), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Type), global::Google.Protobuf.WellKnownTypes.Type.Parser, new[]{ "Name", "Fields", "Oneofs", "Options", "SourceContext", "Syntax" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Field), global::Google.Protobuf.WellKnownTypes.Field.Parser, new[]{ "Kind", "Cardinality", "Number", "Name", "TypeUrl", "OneofIndex", "Packed", "Options", "JsonName", "DefaultValue" }, null, new[]{ typeof(global::Google.Protobuf.WellKnownTypes.Field.Types.Kind), typeof(global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality) }, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Enum), global::Google.Protobuf.WellKnownTypes.Enum.Parser, new[]{ "Name", "Enumvalue", "Options", "SourceContext", "Syntax" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.EnumValue), global::Google.Protobuf.WellKnownTypes.EnumValue.Parser, new[]{ "Name", "Number", "Options" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Option), global::Google.Protobuf.WellKnownTypes.Option.Parser, new[]{ "Name", "Value" }, null, null, null) })); } #endregion } #region Enums /// <summary> /// The syntax in which a protocol buffer element is defined. /// </summary> public enum Syntax { /// <summary> /// Syntax `proto2`. /// </summary> [pbr::OriginalName("SYNTAX_PROTO2")] Proto2 = 0, /// <summary> /// Syntax `proto3`. /// </summary> [pbr::OriginalName("SYNTAX_PROTO3")] Proto3 = 1, } #endregion #region Messages /// <summary> /// A protocol buffer message type. /// </summary> public sealed partial class Type : pb::IMessage<Type> { private static readonly pb::MessageParser<Type> _parser = new pb::MessageParser<Type>(() => new Type()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Type> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Type() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Type(Type other) : this() { name_ = other.name_; fields_ = other.fields_.Clone(); oneofs_ = other.oneofs_.Clone(); options_ = other.options_.Clone(); SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; syntax_ = other.syntax_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Type Clone() { return new Type(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The fully qualified message name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "fields" field.</summary> public const int FieldsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Field> _repeated_fields_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Field.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Field> fields_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Field>(); /// <summary> /// The list of fields. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Field> Fields { get { return fields_; } } /// <summary>Field number for the "oneofs" field.</summary> public const int OneofsFieldNumber = 3; private static readonly pb::FieldCodec<string> _repeated_oneofs_codec = pb::FieldCodec.ForString(26); private readonly pbc::RepeatedField<string> oneofs_ = new pbc::RepeatedField<string>(); /// <summary> /// The list of types appearing in `oneof` definitions in this type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Oneofs { get { return oneofs_; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// The protocol buffer options. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "source_context" field.</summary> public const int SourceContextFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; /// <summary> /// The source context. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } /// <summary>Field number for the "syntax" field.</summary> public const int SyntaxFieldNumber = 6; private global::Google.Protobuf.WellKnownTypes.Syntax syntax_ = 0; /// <summary> /// The source syntax. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Syntax Syntax { get { return syntax_; } set { syntax_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Type); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Type other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!fields_.Equals(other.fields_)) return false; if(!oneofs_.Equals(other.oneofs_)) return false; if(!options_.Equals(other.options_)) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; if (Syntax != other.Syntax) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= fields_.GetHashCode(); hash ^= oneofs_.GetHashCode(); hash ^= options_.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); if (Syntax != 0) hash ^= Syntax.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } fields_.WriteTo(output, _repeated_fields_codec); oneofs_.WriteTo(output, _repeated_oneofs_codec); options_.WriteTo(output, _repeated_options_codec); if (sourceContext_ != null) { output.WriteRawTag(42); output.WriteMessage(SourceContext); } if (Syntax != 0) { output.WriteRawTag(48); output.WriteEnum((int) Syntax); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += fields_.CalculateSize(_repeated_fields_codec); size += oneofs_.CalculateSize(_repeated_oneofs_codec); size += options_.CalculateSize(_repeated_options_codec); if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } if (Syntax != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Syntax); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Type other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } fields_.Add(other.fields_); oneofs_.Add(other.oneofs_); options_.Add(other.options_); if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } if (other.Syntax != 0) { Syntax = other.Syntax; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { fields_.AddEntriesFrom(input, _repeated_fields_codec); break; } case 26: { oneofs_.AddEntriesFrom(input, _repeated_oneofs_codec); break; } case 34: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 42: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } input.ReadMessage(sourceContext_); break; } case 48: { syntax_ = (global::Google.Protobuf.WellKnownTypes.Syntax) input.ReadEnum(); break; } } } } } /// <summary> /// A single field of a message type. /// </summary> public sealed partial class Field : pb::IMessage<Field> { private static readonly pb::MessageParser<Field> _parser = new pb::MessageParser<Field>(() => new Field()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Field> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Field() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Field(Field other) : this() { kind_ = other.kind_; cardinality_ = other.cardinality_; number_ = other.number_; name_ = other.name_; typeUrl_ = other.typeUrl_; oneofIndex_ = other.oneofIndex_; packed_ = other.packed_; options_ = other.options_.Clone(); jsonName_ = other.jsonName_; defaultValue_ = other.defaultValue_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Field Clone() { return new Field(this); } /// <summary>Field number for the "kind" field.</summary> public const int KindFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Field.Types.Kind kind_ = 0; /// <summary> /// The field type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Field.Types.Kind Kind { get { return kind_; } set { kind_ = value; } } /// <summary>Field number for the "cardinality" field.</summary> public const int CardinalityFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality cardinality_ = 0; /// <summary> /// The field cardinality. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality Cardinality { get { return cardinality_; } set { cardinality_ = value; } } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 3; private int number_; /// <summary> /// The field number. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Number { get { return number_; } set { number_ = value; } } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 4; private string name_ = ""; /// <summary> /// The field name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "type_url" field.</summary> public const int TypeUrlFieldNumber = 6; private string typeUrl_ = ""; /// <summary> /// The field type URL, without the scheme, for message or enumeration /// types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string TypeUrl { get { return typeUrl_; } set { typeUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "oneof_index" field.</summary> public const int OneofIndexFieldNumber = 7; private int oneofIndex_; /// <summary> /// The index of the field type in `Type.oneofs`, for message or enumeration /// types. The first type has index 1; zero means the type is not in the list. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int OneofIndex { get { return oneofIndex_; } set { oneofIndex_ = value; } } /// <summary>Field number for the "packed" field.</summary> public const int PackedFieldNumber = 8; private bool packed_; /// <summary> /// Whether to use alternative packed wire representation. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Packed { get { return packed_; } set { packed_ = value; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 9; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(74, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// The protocol buffer options. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "json_name" field.</summary> public const int JsonNameFieldNumber = 10; private string jsonName_ = ""; /// <summary> /// The field JSON name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JsonName { get { return jsonName_; } set { jsonName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "default_value" field.</summary> public const int DefaultValueFieldNumber = 11; private string defaultValue_ = ""; /// <summary> /// The string value of the default value of this field. Proto2 syntax only. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string DefaultValue { get { return defaultValue_; } set { defaultValue_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Field); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Field other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Kind != other.Kind) return false; if (Cardinality != other.Cardinality) return false; if (Number != other.Number) return false; if (Name != other.Name) return false; if (TypeUrl != other.TypeUrl) return false; if (OneofIndex != other.OneofIndex) return false; if (Packed != other.Packed) return false; if(!options_.Equals(other.options_)) return false; if (JsonName != other.JsonName) return false; if (DefaultValue != other.DefaultValue) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Kind != 0) hash ^= Kind.GetHashCode(); if (Cardinality != 0) hash ^= Cardinality.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); if (OneofIndex != 0) hash ^= OneofIndex.GetHashCode(); if (Packed != false) hash ^= Packed.GetHashCode(); hash ^= options_.GetHashCode(); if (JsonName.Length != 0) hash ^= JsonName.GetHashCode(); if (DefaultValue.Length != 0) hash ^= DefaultValue.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Kind != 0) { output.WriteRawTag(8); output.WriteEnum((int) Kind); } if (Cardinality != 0) { output.WriteRawTag(16); output.WriteEnum((int) Cardinality); } if (Number != 0) { output.WriteRawTag(24); output.WriteInt32(Number); } if (Name.Length != 0) { output.WriteRawTag(34); output.WriteString(Name); } if (TypeUrl.Length != 0) { output.WriteRawTag(50); output.WriteString(TypeUrl); } if (OneofIndex != 0) { output.WriteRawTag(56); output.WriteInt32(OneofIndex); } if (Packed != false) { output.WriteRawTag(64); output.WriteBool(Packed); } options_.WriteTo(output, _repeated_options_codec); if (JsonName.Length != 0) { output.WriteRawTag(82); output.WriteString(JsonName); } if (DefaultValue.Length != 0) { output.WriteRawTag(90); output.WriteString(DefaultValue); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Kind != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind); } if (Cardinality != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Cardinality); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (TypeUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); } if (OneofIndex != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); } if (Packed != false) { size += 1 + 1; } size += options_.CalculateSize(_repeated_options_codec); if (JsonName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonName); } if (DefaultValue.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(DefaultValue); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Field other) { if (other == null) { return; } if (other.Kind != 0) { Kind = other.Kind; } if (other.Cardinality != 0) { Cardinality = other.Cardinality; } if (other.Number != 0) { Number = other.Number; } if (other.Name.Length != 0) { Name = other.Name; } if (other.TypeUrl.Length != 0) { TypeUrl = other.TypeUrl; } if (other.OneofIndex != 0) { OneofIndex = other.OneofIndex; } if (other.Packed != false) { Packed = other.Packed; } options_.Add(other.options_); if (other.JsonName.Length != 0) { JsonName = other.JsonName; } if (other.DefaultValue.Length != 0) { DefaultValue = other.DefaultValue; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { kind_ = (global::Google.Protobuf.WellKnownTypes.Field.Types.Kind) input.ReadEnum(); break; } case 16: { cardinality_ = (global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality) input.ReadEnum(); break; } case 24: { Number = input.ReadInt32(); break; } case 34: { Name = input.ReadString(); break; } case 50: { TypeUrl = input.ReadString(); break; } case 56: { OneofIndex = input.ReadInt32(); break; } case 64: { Packed = input.ReadBool(); break; } case 74: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 82: { JsonName = input.ReadString(); break; } case 90: { DefaultValue = input.ReadString(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Field message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Basic field types. /// </summary> public enum Kind { /// <summary> /// Field type unknown. /// </summary> [pbr::OriginalName("TYPE_UNKNOWN")] TypeUnknown = 0, /// <summary> /// Field type double. /// </summary> [pbr::OriginalName("TYPE_DOUBLE")] TypeDouble = 1, /// <summary> /// Field type float. /// </summary> [pbr::OriginalName("TYPE_FLOAT")] TypeFloat = 2, /// <summary> /// Field type int64. /// </summary> [pbr::OriginalName("TYPE_INT64")] TypeInt64 = 3, /// <summary> /// Field type uint64. /// </summary> [pbr::OriginalName("TYPE_UINT64")] TypeUint64 = 4, /// <summary> /// Field type int32. /// </summary> [pbr::OriginalName("TYPE_INT32")] TypeInt32 = 5, /// <summary> /// Field type fixed64. /// </summary> [pbr::OriginalName("TYPE_FIXED64")] TypeFixed64 = 6, /// <summary> /// Field type fixed32. /// </summary> [pbr::OriginalName("TYPE_FIXED32")] TypeFixed32 = 7, /// <summary> /// Field type bool. /// </summary> [pbr::OriginalName("TYPE_BOOL")] TypeBool = 8, /// <summary> /// Field type string. /// </summary> [pbr::OriginalName("TYPE_STRING")] TypeString = 9, /// <summary> /// Field type group. Proto2 syntax only, and deprecated. /// </summary> [pbr::OriginalName("TYPE_GROUP")] TypeGroup = 10, /// <summary> /// Field type message. /// </summary> [pbr::OriginalName("TYPE_MESSAGE")] TypeMessage = 11, /// <summary> /// Field type bytes. /// </summary> [pbr::OriginalName("TYPE_BYTES")] TypeBytes = 12, /// <summary> /// Field type uint32. /// </summary> [pbr::OriginalName("TYPE_UINT32")] TypeUint32 = 13, /// <summary> /// Field type enum. /// </summary> [pbr::OriginalName("TYPE_ENUM")] TypeEnum = 14, /// <summary> /// Field type sfixed32. /// </summary> [pbr::OriginalName("TYPE_SFIXED32")] TypeSfixed32 = 15, /// <summary> /// Field type sfixed64. /// </summary> [pbr::OriginalName("TYPE_SFIXED64")] TypeSfixed64 = 16, /// <summary> /// Field type sint32. /// </summary> [pbr::OriginalName("TYPE_SINT32")] TypeSint32 = 17, /// <summary> /// Field type sint64. /// </summary> [pbr::OriginalName("TYPE_SINT64")] TypeSint64 = 18, } /// <summary> /// Whether a field is optional, required, or repeated. /// </summary> public enum Cardinality { /// <summary> /// For fields with unknown cardinality. /// </summary> [pbr::OriginalName("CARDINALITY_UNKNOWN")] Unknown = 0, /// <summary> /// For optional fields. /// </summary> [pbr::OriginalName("CARDINALITY_OPTIONAL")] Optional = 1, /// <summary> /// For required fields. Proto2 syntax only. /// </summary> [pbr::OriginalName("CARDINALITY_REQUIRED")] Required = 2, /// <summary> /// For repeated fields. /// </summary> [pbr::OriginalName("CARDINALITY_REPEATED")] Repeated = 3, } } #endregion } /// <summary> /// Enum type definition. /// </summary> public sealed partial class Enum : pb::IMessage<Enum> { private static readonly pb::MessageParser<Enum> _parser = new pb::MessageParser<Enum>(() => new Enum()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Enum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Enum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Enum(Enum other) : this() { name_ = other.name_; enumvalue_ = other.enumvalue_.Clone(); options_ = other.options_.Clone(); SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; syntax_ = other.syntax_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Enum Clone() { return new Enum(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Enum type name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "enumvalue" field.</summary> public const int EnumvalueFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.EnumValue> _repeated_enumvalue_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.EnumValue.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.EnumValue> enumvalue_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.EnumValue>(); /// <summary> /// Enum value definitions. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.EnumValue> Enumvalue { get { return enumvalue_; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// Protocol buffer options. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } /// <summary>Field number for the "source_context" field.</summary> public const int SourceContextFieldNumber = 4; private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; /// <summary> /// The source context. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } /// <summary>Field number for the "syntax" field.</summary> public const int SyntaxFieldNumber = 5; private global::Google.Protobuf.WellKnownTypes.Syntax syntax_ = 0; /// <summary> /// The source syntax. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Syntax Syntax { get { return syntax_; } set { syntax_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Enum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Enum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!enumvalue_.Equals(other.enumvalue_)) return false; if(!options_.Equals(other.options_)) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; if (Syntax != other.Syntax) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= enumvalue_.GetHashCode(); hash ^= options_.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); if (Syntax != 0) hash ^= Syntax.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } enumvalue_.WriteTo(output, _repeated_enumvalue_codec); options_.WriteTo(output, _repeated_options_codec); if (sourceContext_ != null) { output.WriteRawTag(34); output.WriteMessage(SourceContext); } if (Syntax != 0) { output.WriteRawTag(40); output.WriteEnum((int) Syntax); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += enumvalue_.CalculateSize(_repeated_enumvalue_codec); size += options_.CalculateSize(_repeated_options_codec); if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } if (Syntax != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Syntax); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Enum other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } enumvalue_.Add(other.enumvalue_); options_.Add(other.options_); if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } if (other.Syntax != 0) { Syntax = other.Syntax; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { enumvalue_.AddEntriesFrom(input, _repeated_enumvalue_codec); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 34: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); } input.ReadMessage(sourceContext_); break; } case 40: { syntax_ = (global::Google.Protobuf.WellKnownTypes.Syntax) input.ReadEnum(); break; } } } } } /// <summary> /// Enum value definition. /// </summary> public sealed partial class EnumValue : pb::IMessage<EnumValue> { private static readonly pb::MessageParser<EnumValue> _parser = new pb::MessageParser<EnumValue>(() => new EnumValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<EnumValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EnumValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EnumValue(EnumValue other) : this() { name_ = other.name_; number_ = other.number_; options_ = other.options_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public EnumValue Clone() { return new EnumValue(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Enum value name. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "number" field.</summary> public const int NumberFieldNumber = 2; private int number_; /// <summary> /// Enum value number. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Number { get { return number_; } set { number_ = value; } } /// <summary>Field number for the "options" field.</summary> public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.WellKnownTypes.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option>(); /// <summary> /// Protocol buffer options. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Protobuf.WellKnownTypes.Option> Options { get { return options_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as EnumValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(EnumValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Number != other.Number) return false; if(!options_.Equals(other.options_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); hash ^= options_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Number != 0) { output.WriteRawTag(16); output.WriteInt32(Number); } options_.WriteTo(output, _repeated_options_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } size += options_.CalculateSize(_repeated_options_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(EnumValue other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Number != 0) { Number = other.Number; } options_.Add(other.options_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 16: { Number = input.ReadInt32(); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } } } } } /// <summary> /// A protocol buffer option, which can be attached to a message, field, /// enumeration, etc. /// </summary> public sealed partial class Option : pb::IMessage<Option> { private static readonly pb::MessageParser<Option> _parser = new pb::MessageParser<Option>(() => new Option()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Option> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.WellKnownTypes.TypeReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Option() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Option(Option other) : this() { name_ = other.name_; Value = other.value_ != null ? other.Value.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Option Clone() { return new Option(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// The option's name. For protobuf built-in options (options defined in /// descriptor.proto), this is the short name. For example, `"map_entry"`. /// For custom options, it should be the fully-qualified name. For example, /// `"google.api.http"`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "value" field.</summary> public const int ValueFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Any value_; /// <summary> /// The option's value packed in an Any message. If the value is a primitive, /// the corresponding wrapper type defined in google/protobuf/wrappers.proto /// should be used. If the value is an enum, it should be stored as an int32 /// value using the google.protobuf.Int32Value type. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Any Value { get { return value_; } set { value_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Option); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Option other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Value, other.Value)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (value_ != null) hash ^= Value.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (value_ != null) { output.WriteRawTag(18); output.WriteMessage(Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (value_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Value); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Option other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.value_ != null) { if (value_ == null) { value_ = new global::Google.Protobuf.WellKnownTypes.Any(); } Value.MergeFrom(other.Value); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (value_ == null) { value_ = new global::Google.Protobuf.WellKnownTypes.Any(); } input.ReadMessage(value_); break; } } } } } #endregion } #endregion Designer generated code
using System.Collections.Generic; using Microsoft.Xna.Framework; using System.Text; using System.Threading; using FlatRedBall.IO; using System; using System.Threading.Tasks; namespace FlatRedBall { #region Enums /// <summary> /// Represents the unit of time measurement. This can be used in files that store timing information. /// </summary> public enum TimeMeasurementUnit { Undefined, Millisecond, Second } #endregion #region Struct public struct TimedSection { public string Name; public double Time; public override string ToString() { return Name + ": " + Time; } } #endregion /// <summary> /// Class providing timing information for the current frame, absolute time since the game has started running, and for the current screen. /// </summary> public static class TimeManager { #region Classes struct VoidTaskResult { } #endregion #region Fields static float mSecondDifference; static float mLastSecondDifference; static float mSecondDifferenceSquaredDividedByTwo; /// <summary> /// The amount of time in seconds since the game started running. /// This value is updated once-per-frame so it will /// always be the same value until the next frame is called. /// This value does not consider pausing. To consider pausing, see CurrentScreenTime. /// </summary> /// <remarks> /// This value can be used to uniquely identify a frame. /// </remarks> public static double CurrentTime; static double mLastCurrentTime; static double mTimeFactor = 1.0f; static double mCurrentTimeForTimedSections; static System.Diagnostics.Stopwatch stopWatch; static List<double> sections = new List<double>(); static List<string> sectionLabels = new List<string>(); static List<double> lastSections = new List<double>(); static List<string> lastSectionLabels = new List<string>(); static Dictionary<string, double> mPersistentSections = new Dictionary<string, double>(); static double mLastPersistentTime; static Dictionary<string, double> mSumSections = new Dictionary<string, double>(); static Dictionary<string, int> mSumSectionHitCount = new Dictionary<string, int>(); static double mLastSumTime; static StringBuilder stringBuilder; static bool mTimeSectionsEnabled = true; static bool mIsPersistentTiming = false; static GameTime mLastUpdateGameTime; static TimeMeasurementUnit mTimedSectionReportngUnit = TimeMeasurementUnit.Millisecond; static float mMaxFrameTime = 0.5f; #endregion #region Properties public static double LastCurrentTime { get { return mLastCurrentTime; } } /// <summary> /// The number of seconds (usually a fraction of a second) since /// the last frame. This value can be used for time-based movement. /// This value is changed once per frame, and will remain constant within each frame. /// </summary> public static float SecondDifference { get { return mSecondDifference; } } public static float LastSecondDifference { get { return mLastSecondDifference; } } public static float SecondDifferenceSquaredDividedByTwo { get { return mSecondDifferenceSquaredDividedByTwo; } } public static bool TimeSectionsEnabled { get { return mTimeSectionsEnabled; } set { mTimeSectionsEnabled = value; } } /// <summary> /// A multiplier for how fast time runs. This is 1 by default. Setting /// this value to 2 will make everything run twice as fast. /// </summary> public static double TimeFactor { get { return mTimeFactor; } set { mTimeFactor = value; } } public static GameTime LastUpdateGameTime { get { return mLastUpdateGameTime; } } public static TimeMeasurementUnit TimedSectionReportingUnit { get { return mTimedSectionReportngUnit; } set { mTimedSectionReportngUnit = value; } } public static float MaxFrameTime { get { return mMaxFrameTime; } set { mMaxFrameTime = value; } } /// <summary> /// Returns the amount of time since the current screen started. This value does not /// advance when the screen is paused. /// </summary> /// <remarks> /// This value is the same as /// Screens.ScreenManager.CurrentScreen.PauseAdjustedCurrentTime /// </remarks> public static double CurrentScreenTime { get { return Screens.ScreenManager.CurrentScreen.PauseAdjustedCurrentTime; } } public static Dictionary<string, double> SumSectionDictionary { get { return mSumSections; } } [Obsolete("Use CurrentSystemTime as that name is more consistent and this will eventually be removed.")] public static double SystemCurrentTime { get { return stopWatch.Elapsed.TotalSeconds; } } public static double CurrentSystemTime => stopWatch.Elapsed.TotalSeconds; public static int TimedSectionCount { get { return sections.Count; } } public static bool SetNextFrameTimeTo0 { get; set; } #endregion #region Methods public static void CreateXmlSumTimeSectionReport(string fileName) { List<TimedSection> tempList = GetTimedSectionList(); FileManager.XmlSerialize<List<TimedSection>>(tempList, fileName); } public static List<TimedSection> GetTimedSectionList() { List<TimedSection> tempList = new List<TimedSection>( mSumSections.Count); foreach (KeyValuePair<string, double> kvp in mSumSections) { TimedSection timedSection = new TimedSection() { Name = kvp.Key, Time = kvp.Value }; tempList.Add(timedSection); } return tempList; } /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public static void Initialize() { stringBuilder = new StringBuilder(200); InitializeStopwatch(); } public static void InitializeStopwatch() { if(stopWatch == null) { // This may be initialized outside of FRB if the user is trying to time pre-FRB calls stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); } } #region TimeSection code public static string GetPersistentTimedSections() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (KeyValuePair<string, double> kvp in mPersistentSections) { sb.Append(kvp.Key).Append(": ").AppendLine(kvp.Value.ToString()); } mIsPersistentTiming = false; return sb.ToString(); } public static string GetSumTimedSections() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (KeyValuePair<string, double> kvp in mSumSections) { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { sb.Append(kvp.Key).Append(": ").AppendLine((kvp.Value * 1000.0f).ToString("f2")); } else { sb.Append(kvp.Key).Append(": ").AppendLine(kvp.Value.ToString()); } } return sb.ToString(); } public static string GetTimedSections(bool showTotal) { stringBuilder.Remove(0, stringBuilder.Length); int largestIndex = -1; double longestTime = -1; for (int i = 0; i < lastSections.Count; i++) { if (lastSections[i] > longestTime) { longestTime = lastSections[i]; largestIndex = i; } } for (int i = 0; i < lastSections.Count; i++) { if (i == largestIndex) { if (lastSectionLabels[i] != "") { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { stringBuilder.Append("-!-" + lastSectionLabels[i]).Append(": ").Append(lastSections[i].ToString("f2")).Append("\n"); } else { stringBuilder.Append("-!-" + lastSectionLabels[i]).Append(": ").Append(lastSections[i].ToString()).Append("\n"); } } else { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { stringBuilder.Append("-!-" + lastSections[i].ToString("f2")).Append("\n"); } else { stringBuilder.Append("-!-" + lastSections[i].ToString()).Append("\n"); } } } else { if (lastSectionLabels[i] != "") { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { stringBuilder.Append(lastSectionLabels[i]).Append(": ").Append(lastSections[i].ToString("f2")).Append("\n"); } else { stringBuilder.Append(lastSectionLabels[i]).Append(": ").Append(lastSections[i].ToString()).Append("\n"); } } else { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { stringBuilder.Append(lastSections[i].ToString("f2")).Append("\n"); } else { stringBuilder.Append(lastSections[i].ToString()).Append("\n"); } } } } if (showTotal) { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { stringBuilder.Append("Total Timed: " + ((TimeManager.CurrentSystemTime - TimeManager.mCurrentTimeForTimedSections) * 1000.0f).ToString("f2")); } else { stringBuilder.Append("Total Timed: " + (TimeManager.CurrentSystemTime - TimeManager.mCurrentTimeForTimedSections)); } } return stringBuilder.ToString(); } public static void PersistentTimeSection(string label) { if (mIsPersistentTiming) { double currentTime = CurrentSystemTime; if (mPersistentSections.ContainsKey(label)) { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { mPersistentSections[label] = ((currentTime - mLastPersistentTime) * 1000.0f); } else { mPersistentSections[label] = currentTime - mLastPersistentTime; } } else { if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { mPersistentSections.Add(label, (currentTime - mLastPersistentTime) * 1000.0f); } else { mPersistentSections.Add(label, currentTime - mLastPersistentTime); } } mLastPersistentTime = currentTime; } } public static void StartPersistentTiming() { mPersistentSections.Clear(); mIsPersistentTiming = true; mLastPersistentTime = CurrentSystemTime; } /// <summary> /// Begins Sum Timing /// </summary> /// <remarks> /// <code> /// /// StartSumTiming(); /// /// foreach(Sprite sprite in someSpriteArray) /// { /// SumTimeRefresh(); /// PerformSomeFunction(sprite); /// SumTimeSection("PerformSomeFunction time:"); /// /// /// SumTimeRefresh(); /// PerformSomeOtherFunction(sprite); /// SumTimeSection("PerformSomeOtherFunction time:); /// /// } /// </code> /// /// </remarks> public static void StartSumTiming() { mSumSections.Clear(); mSumSectionHitCount.Clear(); mLastSumTime = CurrentSystemTime; } public static void SumTimeSection(string label) { double currentTime = CurrentSystemTime; if (mSumSections.ContainsKey(label)) { mSumSections[label] += currentTime - mLastSumTime; //mSumSectionHitCount[label]++; } else { mSumSections.Add(label, currentTime - mLastSumTime); //mSumSectionHitCount.Add(label, 1); } mLastSumTime = currentTime; } public static void SumTimeRefresh() { mLastSumTime = CurrentSystemTime; } #region XML Docs /// <summary> /// Stores an unnamed timed section. /// </summary> /// <remarks> /// A timed section is the amount of time (in seconds) since the last time either Update /// or TimeSection has been called. The sections are reset every time Update is called. /// The sections can be retrieved through the GetTimedSections method. /// <seealso cref="FRB.TimeManager.GetTimedSection"/> /// </remarks> #endregion public static void TimeSection() { TimeSection(""); } #region XML Docs /// <summary> /// Stores an named timed section. /// </summary> /// <remarks> /// A timed section is the amount of time (in seconds) since the last time either Update /// or TimeSection has been called. The sections are reset every time Update is called. /// The sections can be retrieved through the GetTimedSections method. /// <seealso cref="FRB.TimeManager.GetTimedSection"/> /// </remarks> /// <param name="label">The label for the timed section.</param> #endregion public static void TimeSection(string label) { if (mTimeSectionsEnabled) { #if !SILVERLIGHT && !WINDOWS_PHONE Monitor.Enter(sections); #endif double f = (CurrentSystemTime - mCurrentTimeForTimedSections); if (TimedSectionReportingUnit == TimeMeasurementUnit.Millisecond) { f *= 1000.0f; } for (int i = sections.Count - 1; i > -1; i--) f -= sections[i]; sections.Add(f); sectionLabels.Add(label); #if !SILVERLIGHT && !WINDOWS_PHONE Monitor.Exit(sections); #endif } } #endregion public static double SecondsSince(double absoluteTime) { return CurrentTime - absoluteTime; } /// <summary> /// Returns the number of seconds that have passed since the arugment value. The /// return value will not increase when the screen is paused, so it can be used to /// determine how much game time has passed for event swhich should occur on a timer. /// </summary> /// <param name="time">The time value, probably obtained earlier by calling CurrentScreenTime</param> /// <returns>The number of unpaused seconds that have passed since the argument time.</returns> public static double CurrentScreenSecondsSince(double time) { return Screens.ScreenManager.CurrentScreen.PauseAdjustedSecondsSince(time); } public static Task Delay(TimeSpan timeSpan) { return DelaySeconds(timeSpan.TotalSeconds); } public static async Task DelaySeconds(double seconds) { var time = CurrentScreenTime + seconds; while(CurrentScreenTime < time) { //await Task.Delay(1); await Task.Yield(); } } /// <summary> /// Performs every-frame logic to update timing values such as CurrentTime and SecondDifference. If this method is not called, CurrentTime will not advance. /// </summary> /// <param name="time">The GameTime value provided by the MonoGame Game class.</param> public static void Update(GameTime time) { mLastUpdateGameTime = time; lastSections.Clear(); lastSectionLabels.Clear(); for (int i = sections.Count - 1; i > -1; i--) { lastSections.Insert(0, sections[i]); lastSectionLabels.Insert(0, sectionLabels[i]); } sections.Clear(); sectionLabels.Clear(); mLastSecondDifference = mSecondDifference; mLastCurrentTime = CurrentTime; const bool useSystemCurrentTime = false; double elapsedTime; if (useSystemCurrentTime) { double systemCurrentTime = CurrentSystemTime; elapsedTime = systemCurrentTime - mLastCurrentTime; mLastCurrentTime = systemCurrentTime; //stop big frame times if (elapsedTime > MaxFrameTime) { elapsedTime = MaxFrameTime; } } else { /* mSecondDifference = (float)(currentSystemTime - mCurrentTime); mCurrentTime = currentSystemTime; */ if(SetNextFrameTimeTo0) { elapsedTime = 0; SetNextFrameTimeTo0 = false; } else { elapsedTime = time.ElapsedGameTime.TotalSeconds * mTimeFactor; } //stop big frame times if (elapsedTime > MaxFrameTime) { elapsedTime = MaxFrameTime; } } mSecondDifference = (float)(elapsedTime); CurrentTime += elapsedTime; double currentSystemTime = CurrentSystemTime + mSecondDifference; mSecondDifferenceSquaredDividedByTwo = (mSecondDifference * mSecondDifference) / 2.0f; mCurrentTimeForTimedSections = currentSystemTime; } #endregion } }
namespace Oculus.Platform.Samples.VrHoops { using UnityEngine; using System.Collections.Generic; using Oculus.Platform; using Oculus.Platform.Models; using System; using UnityEngine.Assertions; // This helper class coordinates establishing Peer-to-Peer connections between the // players in the match. It tries to sychronize time between the devices and // handles position update messages for the backboard and moving balls. public class P2PManager { #region Member variables // helper class to hold data we need for remote players private class RemotePlayerData { // the last received Net connection state public PeerConnectionState state; // the Unity Monobehaviour public RemotePlayer player; // offset from my local time to the time of the remote host public float remoteTimeOffset; // the last ball update remote time, used to disgard out of order packets public float lastReceivedBallsTime; // remote Instance ID -> local MonoBahaviours for balls we're receiving updates on public readonly Dictionary<int, P2PNetworkBall> activeBalls = new Dictionary<int, P2PNetworkBall>(); } // authorized users to connect to and associated data private readonly Dictionary<ulong, RemotePlayerData> m_remotePlayers = new Dictionary<ulong, RemotePlayerData>(); // when to send the next update to remotes on the state on my local balls private float m_timeForNextBallUpdate; private const byte TIME_SYNC_MESSAGE = 1; private const uint TIME_SYNC_MESSAGE_SIZE = 1+4; private const int TIME_SYNC_MESSAGE_COUNT = 7; private const byte START_TIME_MESSAGE = 2; private const uint START_TIME_MESSAGE_SIZE = 1+4; private const byte BACKBOARD_UPDATE_MESSAGE = 3; private const uint BACKBOARD_UPDATE_MESSAGE_SIZE = 1+4+12+12+12; private const byte LOCAL_BALLS_UPDATE_MESSAGE = 4; private const uint LOCAL_BALLS_UPDATE_MESSATE_SIZE_MAX = 1+4+(2*Player.MAX_BALLS*(1+4+12+12)); private const float LOCAL_BALLS_UPDATE_DELAY = 0.1f; private const byte SCORE_UPDATE_MESSAGE = 5; private const uint SCORE_UPDATE_MESSAGE_SIZE = 1 + 4; // cache of local balls that we are sending updates for private readonly Dictionary<int, P2PNetworkBall> m_localBalls = new Dictionary<int, P2PNetworkBall>(); // reusable buffer to read network data into private readonly byte[] readBuffer = new byte[LOCAL_BALLS_UPDATE_MESSATE_SIZE_MAX]; // temporary time-sync cache of the calculated time offsets private readonly Dictionary<ulong, List<float>> m_remoteSyncTimeCache = new Dictionary<ulong, List<float>>(); // temporary time-sync cache of the last sent message private readonly Dictionary<ulong, float> m_remoteSentTimeCache = new Dictionary<ulong, float>(); // the delegate to handle start-time coordination private StartTimeOffer m_startTimeOfferCallback; #endregion public P2PManager() { Net.SetPeerConnectRequestCallback(PeerConnectRequestCallback); Net.SetConnectionStateChangedCallback(ConnectionStateChangedCallback); } public void UpdateNetwork() { if (m_remotePlayers.Count == 0) return; // check for new messages Packet packet; while ((packet = Net.ReadPacket()) != null) { if (!m_remotePlayers.ContainsKey(packet.SenderID)) continue; packet.ReadBytes(readBuffer); switch (readBuffer[0]) { case TIME_SYNC_MESSAGE: Assert.AreEqual(TIME_SYNC_MESSAGE_SIZE, packet.Size); ReadTimeSyncMessage(packet.SenderID, readBuffer); break; case START_TIME_MESSAGE: Assert.AreEqual(START_TIME_MESSAGE_SIZE, packet.Size); ReceiveMatchStartTimeOffer(packet.SenderID, readBuffer); break; case BACKBOARD_UPDATE_MESSAGE: Assert.AreEqual(BACKBOARD_UPDATE_MESSAGE_SIZE, packet.Size); ReceiveBackboardUpdate(packet.SenderID, readBuffer); break; case LOCAL_BALLS_UPDATE_MESSAGE: ReceiveBallTransforms(packet.SenderID, readBuffer, packet.Size); break; case SCORE_UPDATE_MESSAGE: Assert.AreEqual(SCORE_UPDATE_MESSAGE_SIZE, packet.Size); ReceiveScoredUpdate(packet.SenderID, readBuffer); break; } } if (Time.time >= m_timeForNextBallUpdate && m_localBalls.Count > 0) { SendLocalBallTransforms(); } } #region Connection Management // adds a remote player to establish a connection to, or accept a connection from public void AddRemotePlayer(RemotePlayer player) { if (!m_remotePlayers.ContainsKey (player.ID)) { m_remotePlayers[player.ID] = new RemotePlayerData(); m_remotePlayers[player.ID].state = PeerConnectionState.Unknown; m_remotePlayers [player.ID].player = player; // ID comparison is used to decide who Connects and who Accepts if (PlatformManager.MyID < player.ID) { Debug.Log ("P2P Try Connect to: " + player.ID); Net.Connect (player.ID); } } } public void DisconnectAll() { foreach (var id in m_remotePlayers.Keys) { Net.Close(id); } m_remotePlayers.Clear(); } void PeerConnectRequestCallback(Message<NetworkingPeer> msg) { if (m_remotePlayers.ContainsKey(msg.Data.ID)) { Debug.LogFormat("P2P Accepting Connection request from {0}", msg.Data.ID); Net.Accept(msg.Data.ID); } else { Debug.LogFormat("P2P Ignoring unauthorized Connection request from {0}", msg.Data.ID); } } void ConnectionStateChangedCallback(Message<NetworkingPeer> msg) { Debug.LogFormat("P2P {0} Connection state changed to {1}", msg.Data.ID, msg.Data.State); if (m_remotePlayers.ContainsKey(msg.Data.ID)) { m_remotePlayers[msg.Data.ID].state = msg.Data.State; switch (msg.Data.State) { case PeerConnectionState.Connected: if (PlatformManager.MyID < msg.Data.ID) { SendTimeSyncMessage(msg.Data.ID); } break; case PeerConnectionState.Timeout: if (PlatformManager.MyID < msg.Data.ID) { Net.Connect(msg.Data.ID); } break; case PeerConnectionState.Closed: m_remotePlayers.Remove(msg.Data.ID); break; } } } #endregion #region Time Synchronizaiton // This section implements some basic time synchronization between the players. // The algorithm is: // -Send a time-sync message and receive a time-sync message response // -Estimate time offset // -Repeat several times // -Average values discarding any statistical anomalies // Normally delays would be added in case there is intermittent network congestion // however the match times are so short we don't do that here. Also, if one client // pauses their game and Unity stops their simulation, all bets are off for time // synchronization. Depending on the goals of your app, you could either reinitiate // time synchronization, or just disconnect that player. void SendTimeSyncMessage(ulong remoteID) { if (!m_remoteSyncTimeCache.ContainsKey(remoteID)) { m_remoteSyncTimeCache[remoteID] = new List<float>(); } float time = Time.realtimeSinceStartup; m_remoteSentTimeCache[remoteID] = time; byte[] buf = new byte[TIME_SYNC_MESSAGE_SIZE]; buf[0] = TIME_SYNC_MESSAGE; int offset = 1; PackFloat(time, buf, ref offset); Net.SendPacket(remoteID, buf, SendPolicy.Reliable); } void ReadTimeSyncMessage(ulong remoteID, byte[] msg) { if (!m_remoteSentTimeCache.ContainsKey(remoteID)) { SendTimeSyncMessage(remoteID); return; } int offset = 1; float remoteTime = UnpackFloat(msg, ref offset); float now = Time.realtimeSinceStartup; float latency = (now - m_remoteSentTimeCache[remoteID]) / 2; float remoteTimeOffset = now - (remoteTime + latency); m_remoteSyncTimeCache[remoteID].Add(remoteTimeOffset); if (m_remoteSyncTimeCache[remoteID].Count < TIME_SYNC_MESSAGE_COUNT) { SendTimeSyncMessage(remoteID); } else { if (PlatformManager.MyID < remoteID) { // this client started the sync, need to send one last message to // the remote so they can finish their sync calculation SendTimeSyncMessage(remoteID); } // sort the times and remember the median m_remoteSyncTimeCache[remoteID].Sort(); float median = m_remoteSyncTimeCache[remoteID][TIME_SYNC_MESSAGE_COUNT/2]; // calucate the mean and standard deviation double mean = 0; foreach (var time in m_remoteSyncTimeCache[remoteID]) { mean += time; } mean /= TIME_SYNC_MESSAGE_COUNT; double std_dev = 0; foreach (var time in m_remoteSyncTimeCache[remoteID]) { std_dev += (mean-time)*(mean-time); } std_dev = Math.Sqrt(std_dev)/TIME_SYNC_MESSAGE_COUNT; // time delta is the mean of the values less than 1 standard deviation from the median mean = 0; int meanCount = 0; foreach (var time in m_remoteSyncTimeCache[remoteID]) { if (Math.Abs(time-median) < std_dev) { mean += time; meanCount++; } } mean /= meanCount; Debug.LogFormat("Time offset to {0} is {1}", remoteID, mean); m_remoteSyncTimeCache.Remove(remoteID); m_remoteSentTimeCache.Remove(remoteID); m_remotePlayers[remoteID].remoteTimeOffset = (float)mean; // now that times are synchronized, lets try to coordinate the // start time for the match OfferMatchStartTime(); } } float ShiftRemoteTime(ulong remoteID, float remoteTime) { if (m_remotePlayers.ContainsKey(remoteID)) { return remoteTime + m_remotePlayers[remoteID].remoteTimeOffset; } else { return remoteTime; } } #endregion #region Match Start Coordination // Since all the clients will calculate a slightly different start time, this // message tries to coordinate the match start time to be the lastest of all // the clients in the match. // Delegate to coordiate match start times - the return value is our start time // and the argument is the remote start time, or 0 if that hasn't been given yet. public delegate float StartTimeOffer(float remoteTime); public StartTimeOffer StartTimeOfferCallback { private get { return m_startTimeOfferCallback; } set { m_startTimeOfferCallback = value; } } void OfferMatchStartTime() { byte[] buf = new byte[START_TIME_MESSAGE_SIZE]; buf[0] = START_TIME_MESSAGE; int offset = 1; PackFloat(StartTimeOfferCallback(0), buf, ref offset); foreach (var remoteID in m_remotePlayers.Keys) { if (m_remotePlayers [remoteID].state == PeerConnectionState.Connected) { Net.SendPacket (remoteID, buf, SendPolicy.Reliable); } } } void ReceiveMatchStartTimeOffer(ulong remoteID, byte[] msg) { int offset = 1; float remoteTime = UnpackTime(remoteID, msg, ref offset); StartTimeOfferCallback(remoteTime); } #endregion #region Backboard Transforms public void SendBackboardUpdate(float time, Vector3 pos, Vector3 moveDir, Vector3 nextMoveDir) { byte[] buf = new byte[BACKBOARD_UPDATE_MESSAGE_SIZE]; buf[0] = BACKBOARD_UPDATE_MESSAGE; int offset = 1; PackFloat(time, buf, ref offset); PackVector3(pos, buf, ref offset); PackVector3(moveDir, buf, ref offset); PackVector3(nextMoveDir, buf, ref offset); foreach (KeyValuePair<ulong,RemotePlayerData> player in m_remotePlayers) { if (player.Value.state == PeerConnectionState.Connected) { Net.SendPacket(player.Key, buf, SendPolicy.Reliable); } } } void ReceiveBackboardUpdate(ulong remoteID, byte[] msg) { int offset = 1; float remoteTime = UnpackTime(remoteID, msg, ref offset); Vector3 pos = UnpackVector3(msg, ref offset); Vector3 moveDir = UnpackVector3(msg, ref offset); Vector3 nextMoveDir = UnpackVector3(msg, ref offset); var goal = m_remotePlayers [remoteID].player.Goal; goal.RemoteBackboardUpdate(remoteTime, pos, moveDir, nextMoveDir); } #endregion #region Ball Tansforms public void AddNetworkBall(GameObject ball) { m_localBalls[ball.GetInstanceID()] = ball.AddComponent<P2PNetworkBall>(); } public void RemoveNetworkBall(GameObject ball) { m_localBalls.Remove(ball.GetInstanceID()); } void SendLocalBallTransforms() { m_timeForNextBallUpdate = Time.time + LOCAL_BALLS_UPDATE_DELAY; int msgSize = 1 + 4 + (m_localBalls.Count * (1 + 4 + 12 + 12)); byte[] sendBuffer = new byte[msgSize]; sendBuffer[0] = LOCAL_BALLS_UPDATE_MESSAGE; int offset = 1; PackFloat(Time.realtimeSinceStartup, sendBuffer, ref offset); foreach (var ball in m_localBalls.Values) { PackBool(ball.IsHeld(), sendBuffer, ref offset); PackInt32(ball.gameObject.GetInstanceID(), sendBuffer, ref offset); PackVector3(ball.transform.localPosition, sendBuffer, ref offset); PackVector3(ball.velocity, sendBuffer, ref offset); } foreach (KeyValuePair<ulong, RemotePlayerData> player in m_remotePlayers) { if (player.Value.state == PeerConnectionState.Connected) { Net.SendPacket(player.Key, sendBuffer, SendPolicy.Unreliable); } } } void ReceiveBallTransforms(ulong remoteID, byte[] msg, ulong msgLength) { int offset = 1; float remoteTime = UnpackTime(remoteID, msg, ref offset); // because we're using unreliable networking the packets could come out of order // and the best thing to do is just ignore old packets because the data isn't // very useful anyway if (remoteTime < m_remotePlayers[remoteID].lastReceivedBallsTime) return; m_remotePlayers[remoteID].lastReceivedBallsTime = remoteTime; // loop over all ball updates in the message while (offset != (int)msgLength) { bool isHeld = UnpackBool(msg, ref offset); int instanceID = UnpackInt32(msg, ref offset); Vector3 pos = UnpackVector3(msg, ref offset); Vector3 vel = UnpackVector3(msg, ref offset); if (!m_remotePlayers[remoteID].activeBalls.ContainsKey(instanceID)) { var newball = m_remotePlayers[remoteID].player.CreateBall().AddComponent<P2PNetworkBall>(); newball.transform.SetParent(m_remotePlayers[remoteID].player.transform.parent); m_remotePlayers[remoteID].activeBalls[instanceID] = newball; } var ball = m_remotePlayers[remoteID].activeBalls[instanceID]; if (ball) { ball.ProcessRemoteUpdate(remoteTime, isHeld, pos, vel); } } } #endregion #region Score Updates public void SendScoreUpdate(uint score) { byte[] buf = new byte[SCORE_UPDATE_MESSAGE_SIZE]; buf[0] = SCORE_UPDATE_MESSAGE; int offset = 1; PackUint32(score, buf, ref offset); foreach (KeyValuePair<ulong, RemotePlayerData> player in m_remotePlayers) { if (player.Value.state == PeerConnectionState.Connected) { Net.SendPacket(player.Key, buf, SendPolicy.Reliable); } } } void ReceiveScoredUpdate(ulong remoteID, byte[] msg) { int offset = 1; uint score = UnpackUint32(msg, ref offset); m_remotePlayers[remoteID].player.ReceiveRemoteScore(score); } #endregion #region Serialization // This region contains basic data serialization logic. This sample doesn't warrant // much optimization, but the opportunites are ripe those interested in the topic. void PackVector3(Vector3 vec, byte[] buf, ref int offset) { PackFloat(vec.x, buf, ref offset); PackFloat(vec.y, buf, ref offset); PackFloat(vec.z, buf, ref offset); } Vector3 UnpackVector3(byte[] buf, ref int offset) { Vector3 vec; vec.x = UnpackFloat(buf, ref offset); vec.y = UnpackFloat(buf, ref offset); vec.z = UnpackFloat(buf, ref offset); return vec; } void PackQuaternion(Quaternion quat, byte[] buf, ref int offset) { PackFloat(quat.x, buf, ref offset); PackFloat(quat.y, buf, ref offset); PackFloat(quat.z, buf, ref offset); PackFloat(quat.w, buf, ref offset); } void PackFloat(float value, byte[] buf, ref int offset) { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4); offset = offset + 4; } float UnpackFloat(byte[] buf, ref int offset) { float value = BitConverter.ToSingle(buf, offset); offset += 4; return value; } float UnpackTime(ulong remoteID, byte[] buf, ref int offset) { return ShiftRemoteTime(remoteID, UnpackFloat(buf, ref offset)); } void PackInt32(int value, byte[] buf, ref int offset) { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4); offset = offset + 4; } int UnpackInt32(byte[] buf, ref int offset) { int value = BitConverter.ToInt32(buf, offset); offset += 4; return value; } void PackUint32(uint value, byte[] buf, ref int offset) { Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4); offset = offset + 4; } uint UnpackUint32(byte[] buf, ref int offset) { uint value = BitConverter.ToUInt32(buf, offset); offset += 4; return value; } void PackBool(bool value, byte[] buf, ref int offset) { buf[offset++] = (byte)(value ? 1 : 0); } bool UnpackBool(byte[] buf, ref int offset) { return buf[offset++] != 0;; } #endregion } }
//----------------------------------------------------------------------- // <copyright file="CslaDataSource.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>A Web Forms data binding control designed to support</summary> //----------------------------------------------------------------------- using System; using System.Web.UI; using System.ComponentModel; using System.Reflection; using Csla.Properties; namespace Csla.Web { /// <summary> /// A Web Forms data binding control designed to support /// CSLA .NET business objects as data sources. /// </summary> [Designer(typeof(Csla.Web.Design.CslaDataSourceDesigner))] [DisplayName("CslaDataSource")] [Description("CSLA .NET Data Source Control")] [ToolboxData("<{0}:CslaDataSource runat=\"server\"></{0}:CslaDataSource>")] public class CslaDataSource : DataSourceControl { private CslaDataSourceView _defaultView; /// <summary> /// Event raised when an object is to be created and /// populated with data. /// </summary> /// <remarks>Handle this event in a page and set /// e.BusinessObject to the populated business object. /// </remarks> public event EventHandler<SelectObjectArgs> SelectObject; /// <summary> /// Event raised when an object is to be populated with data /// and inserted. /// </summary> /// <remarks>Handle this event in a page to create an /// instance of the object, load the object with data and /// insert the object into the database.</remarks> public event EventHandler<InsertObjectArgs> InsertObject; /// <summary> /// Event raised when an object is to be updated. /// </summary> /// <remarks>Handle this event in a page to update an /// existing instance of an object with new data and then /// save the object into the database.</remarks> public event EventHandler<UpdateObjectArgs> UpdateObject; /// <summary> /// Event raised when an object is to be deleted. /// </summary> /// <remarks>Handle this event in a page to delete /// an object from the database.</remarks> public event EventHandler<DeleteObjectArgs> DeleteObject; /// <summary> /// Returns the default view for this data control. /// </summary> /// <param name="viewName">Ignored.</param> /// <returns></returns> /// <remarks>This control only contains a "Default" view.</remarks> protected override DataSourceView GetView(string viewName) { if (_defaultView == null) _defaultView = new CslaDataSourceView(this, "Default"); return _defaultView; } /// <summary> /// Get or set the name of the assembly (no longer used). /// </summary> /// <value>Obsolete - do not use.</value> public string TypeAssemblyName { get { return ((CslaDataSourceView)this.GetView("Default")).TypeAssemblyName; } set { ((CslaDataSourceView)this.GetView("Default")).TypeAssemblyName = value; } } /// <summary> /// Get or set the full type name of the business object /// class to be used as a data source. /// </summary> /// <value>Full type name of the business class, /// including assembly name.</value> public string TypeName { get { return ((CslaDataSourceView)this.GetView("Default")).TypeName; } set { ((CslaDataSourceView)this.GetView("Default")).TypeName = value; } } /// <summary> /// Get or set a value indicating whether the /// business object data source supports paging. /// </summary> /// <remarks> /// To support paging, the business object /// (collection) must implement /// <see cref="Csla.Core.IReportTotalRowCount"/>. /// </remarks> public bool TypeSupportsPaging { get { return ((CslaDataSourceView)this.GetView("Default")).TypeSupportsPaging; } set { ((CslaDataSourceView)this.GetView("Default")).TypeSupportsPaging = value; } } /// <summary> /// Get or set a value indicating whether the /// business object data source supports sorting. /// </summary> public bool TypeSupportsSorting { get { return ((CslaDataSourceView)this.GetView("Default")).TypeSupportsSorting; } set { ((CslaDataSourceView)this.GetView("Default")).TypeSupportsSorting = value; } } private static System.Collections.Generic.Dictionary<string,Type> _typeCache = new System.Collections.Generic.Dictionary<string,Type>(); /// <summary> /// Returns a <see cref="Type">Type</see> object based on the /// assembly and type information provided. /// </summary> /// <param name="typeAssemblyName">Optional assembly name.</param> /// <param name="typeName">Full type name of the class, /// including assembly name.</param> /// <remarks></remarks> internal static Type GetType( string typeAssemblyName, string typeName) { Type result = null; if (!string.IsNullOrEmpty(typeAssemblyName)) { // explicit assembly name provided result = Type.GetType(string.Format( "{0}, {1}", typeName, typeAssemblyName), true, true); } else if (typeName.IndexOf(",") > 0) { // assembly qualified type name provided result = Type.GetType(typeName, true, true); } else { // no assembly name provided result = _typeCache[typeName]; if (result == null) foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { result = asm.GetType(typeName, false, true); if (result != null) { _typeCache.Add(typeName, result); break; } } } if (result == null) throw new TypeLoadException(String.Format(Resources.TypeLoadException, typeName)); return result; } /// <summary> /// Returns a list of views available for this control. /// </summary> /// <remarks>This control only provides the "Default" view.</remarks> protected override System.Collections.ICollection GetViewNames() { return new string[] { "Default" }; } /// <summary> /// Raises the SelectObject event. /// </summary> internal void OnSelectObject(SelectObjectArgs e) { if (SelectObject != null) SelectObject(this, e); } /// <summary> /// Raises the InsertObject event. /// </summary> internal void OnInsertObject(InsertObjectArgs e) { if (InsertObject != null) InsertObject(this, e); } /// <summary> /// Raises the UpdateObject event. /// </summary> internal void OnUpdateObject(UpdateObjectArgs e) { if (UpdateObject != null) UpdateObject(this, e); } /// <summary> /// Raises the DeleteObject event. /// </summary> internal void OnDeleteObject(DeleteObjectArgs e) { if (DeleteObject != null) DeleteObject(this, e); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Responses/RecycleInventoryItemResponse.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Networking.Responses { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Responses/RecycleInventoryItemResponse.proto</summary> public static partial class RecycleInventoryItemResponseReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Responses/RecycleInventoryItemResponse.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RecycleInventoryItemResponseReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CkJQT0dPUHJvdG9zL05ldHdvcmtpbmcvUmVzcG9uc2VzL1JlY3ljbGVJbnZl", "bnRvcnlJdGVtUmVzcG9uc2UucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2lu", "Zy5SZXNwb25zZXMi6wEKHFJlY3ljbGVJbnZlbnRvcnlJdGVtUmVzcG9uc2US", "VAoGcmVzdWx0GAEgASgOMkQuUE9HT1Byb3Rvcy5OZXR3b3JraW5nLlJlc3Bv", "bnNlcy5SZWN5Y2xlSW52ZW50b3J5SXRlbVJlc3BvbnNlLlJlc3VsdBIRCglu", "ZXdfY291bnQYAiABKAUiYgoGUmVzdWx0EgkKBVVOU0VUEAASCwoHU1VDQ0VT", "UxABEhsKF0VSUk9SX05PVF9FTk9VR0hfQ09QSUVTEAISIwofRVJST1JfQ0FO", "Tk9UX1JFQ1lDTEVfSU5DVUJBVE9SUxADYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Responses.RecycleInventoryItemResponse), global::POGOProtos.Networking.Responses.RecycleInventoryItemResponse.Parser, new[]{ "Result", "NewCount" }, null, new[]{ typeof(global::POGOProtos.Networking.Responses.RecycleInventoryItemResponse.Types.Result) }, null) })); } #endregion } #region Messages public sealed partial class RecycleInventoryItemResponse : pb::IMessage<RecycleInventoryItemResponse> { private static readonly pb::MessageParser<RecycleInventoryItemResponse> _parser = new pb::MessageParser<RecycleInventoryItemResponse>(() => new RecycleInventoryItemResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RecycleInventoryItemResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Responses.RecycleInventoryItemResponseReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RecycleInventoryItemResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RecycleInventoryItemResponse(RecycleInventoryItemResponse other) : this() { result_ = other.result_; newCount_ = other.newCount_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RecycleInventoryItemResponse Clone() { return new RecycleInventoryItemResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::POGOProtos.Networking.Responses.RecycleInventoryItemResponse.Types.Result result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Responses.RecycleInventoryItemResponse.Types.Result Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "new_count" field.</summary> public const int NewCountFieldNumber = 2; private int newCount_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int NewCount { get { return newCount_; } set { newCount_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RecycleInventoryItemResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RecycleInventoryItemResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (NewCount != other.NewCount) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (NewCount != 0) hash ^= NewCount.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (NewCount != 0) { output.WriteRawTag(16); output.WriteInt32(NewCount); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (NewCount != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(NewCount); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RecycleInventoryItemResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.NewCount != 0) { NewCount = other.NewCount; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::POGOProtos.Networking.Responses.RecycleInventoryItemResponse.Types.Result) input.ReadEnum(); break; } case 16: { NewCount = input.ReadInt32(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the RecycleInventoryItemResponse message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum Result { [pbr::OriginalName("UNSET")] Unset = 0, [pbr::OriginalName("SUCCESS")] Success = 1, [pbr::OriginalName("ERROR_NOT_ENOUGH_COPIES")] ErrorNotEnoughCopies = 2, [pbr::OriginalName("ERROR_CANNOT_RECYCLE_INCUBATORS")] ErrorCannotRecycleIncubators = 3, } } #endregion } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers; using System.Threading.Tasks; namespace Microsoft.DotNet.Cli.Build { public class AzurePublisher { private static readonly string s_dotnetBlobRootUrl = "https://dotnetcli.blob.core.windows.net/dotnet/"; private static readonly string s_dotnetBlobContainerName = "dotnet"; private string _connectionString { get; set; } private CloudBlobContainer _blobContainer { get; set; } public AzurePublisher() { _connectionString = EnvVars.EnsureVariable("CONNECTION_STRING").Trim('"'); _blobContainer = GetDotnetBlobContainer(_connectionString); } private CloudBlobContainer GetDotnetBlobContainer(string connectionString) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); return blobClient.GetContainerReference(s_dotnetBlobContainerName); } public void PublishInstallerFile(string installerFile, string channel, string version) { var installerFileBlob = CalculateInstallerBlob(installerFile, channel, version); PublishFile(installerFileBlob, installerFile); } public void PublishArchive(string archiveFile, string channel, string version) { var archiveFileBlob = CalculateArchiveBlob(archiveFile, channel, version); PublishFile(archiveFileBlob, archiveFile); } public void PublishFile(string blob, string file) { CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob); blockBlob.UploadFromFileAsync(file, FileMode.Open).Wait(); SetBlobPropertiesBasedOnFileType(blockBlob); } public void PublishStringToBlob(string blob, string content) { CloudBlockBlob blockBlob = _blobContainer.GetBlockBlobReference(blob); blockBlob.UploadTextAsync(content).Wait(); blockBlob.Properties.ContentType = "text/plain"; blockBlob.SetPropertiesAsync().Wait(); } public void CopyBlob(string sourceBlob, string targetBlob) { CloudBlockBlob source = _blobContainer.GetBlockBlobReference(sourceBlob); CloudBlockBlob target = _blobContainer.GetBlockBlobReference(targetBlob); // Create the empty blob using (MemoryStream ms = new MemoryStream()) { target.UploadFromStreamAsync(ms).Wait(); } // Copy actual blob data target.StartCopyAsync(source).Wait(); } private void SetBlobPropertiesBasedOnFileType(CloudBlockBlob blockBlob) { if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".svg") { blockBlob.Properties.ContentType = "image/svg+xml"; blockBlob.Properties.CacheControl = "no-cache"; blockBlob.SetPropertiesAsync().Wait(); } else if (Path.GetExtension(blockBlob.Uri.AbsolutePath.ToLower()) == ".version") { blockBlob.Properties.ContentType = "text/plain"; blockBlob.SetPropertiesAsync().Wait(); } } public IEnumerable<string> ListBlobs(string virtualDirectory) { CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(virtualDirectory); BlobContinuationToken continuationToken = new BlobContinuationToken(); var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result; return blobFiles.Results.Select(bf => bf.Uri.PathAndQuery); } public string AcquireLeaseOnBlob(string blob) { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); System.Threading.Tasks.Task<string> task = cloudBlob.AcquireLeaseAsync(TimeSpan.FromMinutes(1), null); task.Wait(); return task.Result; } public void ReleaseLeaseOnBlob(string blob, string leaseId) { CloudBlockBlob cloudBlob = _blobContainer.GetBlockBlobReference(blob); AccessCondition ac = new AccessCondition() { LeaseId = leaseId }; cloudBlob.ReleaseLeaseAsync(ac).Wait(); } public bool IsLatestSpecifiedVersion(string version) { System.Threading.Tasks.Task<bool> task = _blobContainer.GetBlockBlobReference(version).ExistsAsync(); task.Wait(); return task.Result; } public void DropLatestSpecifiedVersion(string version) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(version); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } public void CreateBlobIfNotExists(string path) { System.Threading.Tasks.Task<bool> task = _blobContainer.GetBlockBlobReference(path).ExistsAsync(); task.Wait(); if (!task.Result) { CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(path); using (MemoryStream ms = new MemoryStream()) { blob.UploadFromStreamAsync(ms).Wait(); } } } public bool TryDeleteBlob(string path) { try { DeleteBlob(path); return true; } catch (Exception e) { Console.WriteLine($"Deleting blob {path} failed with \r\n{e.Message}"); return false; } } public void DeleteBlob(string path) { _blobContainer.GetBlockBlobReference(path).DeleteAsync().Wait(); } public string CalculateInstallerUploadUrl(string installerFile, string channel, string version) { return $"{s_dotnetBlobRootUrl}{CalculateInstallerBlob(installerFile, channel, version)}"; } public static string CalculateInstallerBlob(string installerFile, string channel, string version) { return $"{channel}/Installers/{version}/{Path.GetFileName(installerFile)}"; } public static string CalculateArchiveBlob(string archiveFile, string channel, string version) { return $"{channel}/Binaries/{version}/{Path.GetFileName(archiveFile)}"; } public static async Task DownloadFile(string blobFilePath, string localDownloadPath) { var blobUrl = $"{s_dotnetBlobRootUrl}{blobFilePath}"; using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, blobUrl); var sendTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); var response = sendTask.Result.EnsureSuccessStatusCode(); var httpStream = await response.Content.ReadAsStreamAsync(); using (var fileStream = File.Create(localDownloadPath)) using (var reader = new StreamReader(httpStream)) { httpStream.CopyTo(fileStream); fileStream.Flush(); } } } public void DownloadFilesWithExtension(string blobVirtualDirectory, string fileExtension, string localDownloadPath) { CloudBlobDirectory blobDir = _blobContainer.GetDirectoryReference(blobVirtualDirectory); BlobContinuationToken continuationToken = new BlobContinuationToken(); var blobFiles = blobDir.ListBlobsSegmentedAsync(continuationToken).Result; foreach (var blobFile in blobFiles.Results.OfType<CloudBlockBlob>()) { if (Path.GetExtension(blobFile.Uri.AbsoluteUri) == fileExtension) { string localBlobFile = Path.Combine(localDownloadPath, Path.GetFileName(blobFile.Uri.AbsoluteUri)); Console.WriteLine($"Downloading {blobFile.Uri.AbsoluteUri} to {localBlobFile}..."); blobFile.DownloadToFileAsync(localBlobFile, FileMode.Create).Wait(); } } } } }
using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Serialization.Objects; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.AtomicOperations.Creating { public sealed class AtomicCreateResourceWithClientGeneratedIdTests : IClassFixture<IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext>> { private readonly IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> _testContext; private readonly OperationsFakers _fakers = new(); public AtomicCreateResourceWithClientGeneratedIdTests(IntegrationTestContext<TestableStartup<OperationsDbContext>, OperationsDbContext> testContext) { _testContext = testContext; testContext.UseController<OperationsController>(); // These routes need to be registered in ASP.NET for rendering links to resource/relationship endpoints. testContext.UseController<TextLanguagesController>(); testContext.ConfigureServicesAfterStartup(services => { services.AddResourceDefinition<ImplicitlyChangingTextLanguageDefinition>(); }); var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>(); options.AllowClientGeneratedIds = true; } [Fact] public async Task Can_create_resource_with_client_generated_guid_ID_having_side_effects() { // Arrange TextLanguage newLanguage = _fakers.TextLanguage.Generate(); newLanguage.Id = Guid.NewGuid(); var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "textLanguages", id = newLanguage.StringId, attributes = new { isoCode = newLanguage.IsoCode } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.OK); string isoCode = $"{newLanguage.IsoCode}{ImplicitlyChangingTextLanguageDefinition.Suffix}"; responseDocument.Results.Should().HaveCount(1); responseDocument.Results[0].Data.SingleValue.Should().NotBeNull(); responseDocument.Results[0].Data.SingleValue.Type.Should().Be("textLanguages"); responseDocument.Results[0].Data.SingleValue.Attributes["isoCode"].Should().Be(isoCode); responseDocument.Results[0].Data.SingleValue.Attributes.Should().NotContainKey("isRightToLeft"); responseDocument.Results[0].Data.SingleValue.Relationships.Should().NotBeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { TextLanguage languageInDatabase = await dbContext.TextLanguages.FirstWithIdAsync(newLanguage.Id); languageInDatabase.IsoCode.Should().Be(isoCode); }); } [Fact] public async Task Can_create_resource_with_client_generated_string_ID_having_no_side_effects() { // Arrange MusicTrack newTrack = _fakers.MusicTrack.Generate(); newTrack.Id = Guid.NewGuid(); var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "musicTracks", id = newTrack.StringId, attributes = new { title = newTrack.Title, lengthInSeconds = newTrack.LengthInSeconds, releasedAt = newTrack.ReleasedAt } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { MusicTrack trackInDatabase = await dbContext.MusicTracks.FirstWithIdAsync(newTrack.Id); trackInDatabase.Title.Should().Be(newTrack.Title); trackInDatabase.LengthInSeconds.Should().BeApproximately(newTrack.LengthInSeconds); }); } [Fact] public async Task Cannot_create_resource_for_existing_client_generated_ID() { // Arrange TextLanguage existingLanguage = _fakers.TextLanguage.Generate(); existingLanguage.Id = Guid.NewGuid(); TextLanguage languageToCreate = _fakers.TextLanguage.Generate(); languageToCreate.Id = existingLanguage.Id; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.TextLanguages.Add(languageToCreate); await dbContext.SaveChangesAsync(); }); var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "textLanguages", id = languageToCreate.StringId, attributes = new { isoCode = languageToCreate.IsoCode } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Conflict); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.Conflict); error.Title.Should().Be("Another resource with the specified ID already exists."); error.Detail.Should().Be($"Another resource of type 'textLanguages' with ID '{languageToCreate.StringId}' already exists."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_create_resource_for_incompatible_ID() { // Arrange string guid = Unknown.StringId.Guid; var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "performers", id = guid, attributes = new { } } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body."); error.Detail.Should().Be($"Failed to convert '{guid}' of type 'String' to type 'Int32'."); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } [Fact] public async Task Cannot_create_resource_for_ID_and_local_ID() { // Arrange var requestBody = new { atomic__operations = new[] { new { op = "add", data = new { type = "lyrics", id = Unknown.StringId.For<Lyric, long>(), lid = "local-1" } } } }; const string route = "/operations"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAtomicAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.UnprocessableEntity); responseDocument.Errors.Should().HaveCount(1); ErrorObject error = responseDocument.Errors[0]; error.StatusCode.Should().Be(HttpStatusCode.UnprocessableEntity); error.Title.Should().Be("Failed to deserialize request body: The 'data.id' or 'data.lid' element is required."); error.Detail.Should().BeNull(); error.Source.Pointer.Should().Be("/atomic:operations[0]"); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapAttribute.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using ArrayEnumeration = Novell.Directory.Ldap.Utilclass.ArrayEnumeration; using Base64 = Novell.Directory.Ldap.Utilclass.Base64; namespace Novell.Directory.Ldap { /// <summary> The name and values of one attribute of a directory entry. /// /// LdapAttribute objects are used when searching for, adding, /// modifying, and deleting attributes from the directory. /// LdapAttributes are often used in conjunction with an /// {@link LdapAttributeSet} when retrieving or adding multiple /// attributes to an entry. /// /// /// /// </summary> /// <seealso cref="LdapEntry"> /// </seealso> /// <seealso cref="LdapAttributeSet"> /// </seealso> /// <seealso cref="LdapModification"> /// </seealso> public class LdapAttribute : System.ICloneable, System.IComparable { class URLData { private void InitBlock(LdapAttribute enclosingInstance) { this.enclosingInstance = enclosingInstance; } private LdapAttribute enclosingInstance; public LdapAttribute Enclosing_Instance { get { return enclosingInstance; } } private int length; private sbyte[] data; public URLData(LdapAttribute enclosingInstance, sbyte[] data, int length) { InitBlock(enclosingInstance); this.length = length; this.data = data; return ; } public int getLength() { return length; } public sbyte[] getData() { return data; } } /// <summary> Returns an enumerator for the values of the attribute in byte format. /// /// </summary> /// <returns> The values of the attribute in byte format. /// Note: All string values will be UTF-8 encoded. To decode use the /// String constructor. Example: new String( byteArray, "UTF-8" ); /// </returns> virtual public System.Collections.IEnumerator ByteValues { get { return new ArrayEnumeration(ByteValueArray); } } /// <summary> Returns an enumerator for the string values of an attribute. /// /// </summary> /// <returns> The string values of an attribute. /// </returns> virtual public System.Collections.IEnumerator StringValues { get { return new ArrayEnumeration(StringValueArray); } } /// <summary> Returns the values of the attribute as an array of bytes. /// /// </summary> /// <returns> The values as an array of bytes or an empty array if there are /// no values. /// </returns> [CLSCompliantAttribute(false)] virtual public sbyte[][] ByteValueArray { get { if (null == this.values) return new sbyte[0][]; int size = this.values.Length; sbyte[][] bva = new sbyte[size][]; // Deep copy so application cannot change values for (int i = 0, u = size; i < u; i++) { bva[i] = new sbyte[((sbyte[]) values[i]).Length]; Array.Copy((System.Array) this.values[i], 0, (System.Array) bva[i], 0, bva[i].Length); } return bva; } } /// <summary> Returns the values of the attribute as an array of strings. /// /// </summary> /// <returns> The values as an array of strings or an empty array if there are /// no values /// </returns> virtual public System.String[] StringValueArray { get { if (null == this.values) return new System.String[0]; int size = values.Length; System.String[] sva = new System.String[size]; for (int j = 0; j < size; j++) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[j])); // char[] dchar = encoder.GetChars((byte[])values[j]); sva[j] = new String(dchar); // sva[j] = new String((sbyte[]) values[j], "UTF-8"); } catch (System.IO.IOException uee) { // Exception should NEVER get thrown but just in case it does ... throw new System.SystemException(uee.ToString()); } } return sva; } } /// <summary> Returns the the first value of the attribute as a <code>String</code>. /// /// </summary> /// <returns> The UTF-8 encoded<code>String</code> value of the attribute's /// value. If the value wasn't a UTF-8 encoded <code>String</code> /// to begin with the value of the returned <code>String</code> is /// non deterministic. /// /// If <code>this</code> attribute has more than one value the /// first value is converted to a UTF-8 encoded <code>String</code> /// and returned. It should be noted, that the directory may /// return attribute values in any order, so that the first /// value may vary from one call to another. /// /// If the attribute has no values <code>null</code> is returned /// </returns> virtual public System.String StringValue { get { System.String rval = null; if (this.values != null) { try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])this.values[0])); // char[] dchar = encoder.GetChars((byte[]) this.values[0]); rval = new String(dchar); } catch (System.IO.IOException use) { throw new System.SystemException(use.ToString()); } } return rval; } } /// <summary> Returns the the first value of the attribute as a byte array. /// /// </summary> /// <returns> The binary value of <code>this</code> attribute or /// <code>null</code> if <code>this</code> attribute doesn't have a value. /// /// If the attribute has no values <code>null</code> is returned /// </returns> [CLSCompliantAttribute(false)] virtual public sbyte[] ByteValue { get { sbyte[] bva = null; if (this.values != null) { // Deep copy so app can't change the value bva = new sbyte[((sbyte[]) values[0]).Length]; Array.Copy((System.Array) this.values[0], 0, (System.Array) bva, 0, bva.Length); } return bva; } } /// <summary> Returns the language subtype of the attribute, if any. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns the string, lang-ja. /// /// </summary> /// <returns> The language subtype of the attribute or null if the attribute /// has none. /// </returns> virtual public System.String LangSubtype { get { if (subTypes != null) { for (int i = 0; i < subTypes.Length; i++) { if (subTypes[i].StartsWith("lang-")) { return subTypes[i]; } } } return null; } } /// <summary> Returns the name of the attribute. /// /// </summary> /// <returns> The name of the attribute. /// </returns> virtual public System.String Name { get { return name; } } /// <summary> Replaces all values with the specified value. This protected method is /// used by sub-classes of LdapSchemaElement because the value cannot be set /// with a contructor. /// </summary> virtual protected internal System.String Value { set { values = null; try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(value); sbyte[] sbytes=SupportClass.ToSByteArray(ibytes); this.add(sbytes); } catch (System.IO.IOException ue) { throw new System.SystemException(ue.ToString()); } return ; } } private System.String name; // full attribute name private System.String baseName; // cn of cn;lang-ja;phonetic private System.String[] subTypes = null; // lang-ja of cn;lang-ja private System.Object[] values = null; // Array of byte[] attribute values /// <summary> Constructs an attribute with copies of all values of the input /// attribute. /// /// </summary> /// <param name="attr"> An LdapAttribute to use as a template. /// /// @throws IllegalArgumentException if attr is null /// </param> public LdapAttribute(LdapAttribute attr) { if (attr == null) { throw new System.ArgumentException("LdapAttribute class cannot be null"); } // Do a deep copy of the LdapAttribute template this.name = attr.name; this.baseName = attr.baseName; if (null != attr.subTypes) { this.subTypes = new System.String[attr.subTypes.Length]; Array.Copy((System.Array) attr.subTypes, 0, (System.Array) this.subTypes, 0, this.subTypes.Length); } // OK to just copy attributes, as the app only sees a deep copy of them if (null != attr.values) { this.values = new System.Object[attr.values.Length]; Array.Copy((System.Array) attr.values, 0, (System.Array) this.values, 0, this.values.Length); } return ; } /// <summary> Constructs an attribute with no values. /// /// </summary> /// <param name="attrName">Name of the attribute. /// /// @throws IllegalArgumentException if attrName is null /// </param> public LdapAttribute(System.String attrName) { if ((System.Object) attrName == null) { throw new System.ArgumentException("Attribute name cannot be null"); } this.name = attrName; this.baseName = LdapAttribute.getBaseName(attrName); this.subTypes = LdapAttribute.getSubtypes(attrName); return ; } /// <summary> Constructs an attribute with a byte-formatted value. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrBytes">Value of the attribute as raw bytes. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// /// @throws IllegalArgumentException if attrName or attrBytes is null /// </param> [CLSCompliantAttribute(false)] public LdapAttribute(System.String attrName, sbyte[] attrBytes):this(attrName) { if (attrBytes == null) { throw new System.ArgumentException("Attribute value cannot be null"); } // Make our own copy of the byte array to prevent app from changing it sbyte[] tmp = new sbyte[attrBytes.Length]; Array.Copy((System.Array) attrBytes, 0, (System.Array)tmp, 0, attrBytes.Length); this.add(tmp); return ; } /// <summary> Constructs an attribute with a single string value. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrString">Value of the attribute as a string. /// /// @throws IllegalArgumentException if attrName or attrString is null /// </param> public LdapAttribute(System.String attrName, System.String attrString):this(attrName) { if ((System.Object) attrString == null) { throw new System.ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes=SupportClass.ToSByteArray(ibytes); this.add(sbytes); } catch (System.IO.IOException e) { throw new System.SystemException(e.ToString()); } return ; } /// <summary> Constructs an attribute with an array of string values. /// /// </summary> /// <param name="attrName">Name of the attribute. /// </param> /// <param name="attrStrings">Array of values as strings. /// /// @throws IllegalArgumentException if attrName, attrStrings, or a member /// of attrStrings is null /// </param> public LdapAttribute(System.String attrName, System.String[] attrStrings):this(attrName) { if (attrStrings == null) { throw new System.ArgumentException("Attribute values array cannot be null"); } for (int i = 0, u = attrStrings.Length; i < u; i++) { try { if ((System.Object) attrStrings[i] == null) { throw new System.ArgumentException("Attribute value " + "at array index " + i + " cannot be null"); } System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrStrings[i]); sbyte[] sbytes=SupportClass.ToSByteArray(ibytes); this.add(sbytes); // this.add(attrStrings[i].getBytes("UTF-8")); } catch (System.IO.IOException e) { throw new System.SystemException(e.ToString()); } } return ; } /// <summary> Returns a clone of this LdapAttribute. /// /// </summary> /// <returns> clone of this LdapAttribute. /// </returns> public System.Object Clone() { try { System.Object newObj = base.MemberwiseClone(); if (values != null) { Array.Copy((System.Array) this.values, 0, (System.Array) ((LdapAttribute) newObj).values, 0, this.values.Length); } return newObj; } catch (System.Exception ce) { throw new System.SystemException("Internal error, cannot create clone"); } } /// <summary> Adds a string value to the attribute. /// /// </summary> /// <param name="attrString">Value of the attribute as a String. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addValue(System.String attrString) { if ((System.Object) attrString == null) { throw new System.ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes=SupportClass.ToSByteArray(ibytes); this.add(sbytes); // this.add(attrString.getBytes("UTF-8")); } catch (System.IO.IOException ue) { throw new System.SystemException(ue.ToString()); } return ; } /// <summary> Adds a byte-formatted value to the attribute. /// /// </summary> /// <param name="attrBytes">Value of the attribute as raw bytes. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// /// @throws IllegalArgumentException if attrBytes is null /// </param> [CLSCompliantAttribute(false)] public virtual void addValue(sbyte[] attrBytes) { if (attrBytes == null) { throw new System.ArgumentException("Attribute value cannot be null"); } this.add(attrBytes); return ; } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. String /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrString">The base64 value of the attribute as a String. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(System.String attrString) { if ((System.Object) attrString == null) { throw new System.ArgumentException("Attribute value cannot be null"); } this.add(Base64.decode(attrString)); return ; } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. Character /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrString">The base64 value of the attribute as a StringBuffer. /// </param> /// <param name="start"> The start index of base64 encoded part, inclusive. /// </param> /// <param name="end"> The end index of base encoded part, exclusive. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(System.Text.StringBuilder attrString, int start, int end) { if (attrString == null) { throw new System.ArgumentException("Attribute value cannot be null"); } this.add(Base64.decode(attrString, start, end)); return ; } /// <summary> Adds a base64 encoded value to the attribute. /// The value will be decoded and stored as bytes. Character /// data encoded as a base64 value must be UTF-8 characters. /// /// </summary> /// <param name="attrChars">The base64 value of the attribute as an array of /// characters. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void addBase64Value(char[] attrChars) { if (attrChars == null) { throw new System.ArgumentException("Attribute value cannot be null"); } this.add(Base64.decode(attrChars)); return ; } /// <summary> Adds a URL, indicating a file or other resource that contains /// the value of the attribute. /// /// </summary> /// <param name="url">String value of a URL pointing to the resource containing /// the value of the attribute. /// /// @throws IllegalArgumentException if url is null /// </param> public virtual void addURLValue(System.String url) { if ((System.Object) url == null) { throw new System.ArgumentException("Attribute URL cannot be null"); } addURLValue(new System.Uri(url)); return ; } /// <summary> Adds a URL, indicating a file or other resource that contains /// the value of the attribute. /// /// </summary> /// <param name="url">A URL class pointing to the resource containing the value /// of the attribute. /// /// @throws IllegalArgumentException if url is null /// </param> public virtual void addURLValue(System.Uri url) { // Class to encapsulate the data bytes and the length if (url == null) { throw new System.ArgumentException("Attribute URL cannot be null"); } try { // Get InputStream from the URL System.IO.Stream in_Renamed = System.Net.WebRequest.Create(url).GetResponse().GetResponseStream(); // Read the bytes into buffers and store the them in an arraylist System.Collections.ArrayList bufs = new System.Collections.ArrayList(); sbyte[] buf = new sbyte[4096]; int len, totalLength = 0; while ((len = SupportClass.ReadInput(in_Renamed, ref buf, 0, 4096)) != - 1) { bufs.Add(new URLData(this, buf, len)); buf = new sbyte[4096]; totalLength += len; } /* * Now that the length is known, allocate an array to hold all * the bytes of data and copy the data to that array, store * it in this LdapAttribute */ sbyte[] data = new sbyte[totalLength]; int offset = 0; // for (int i = 0; i < bufs.Count; i++) { URLData b = (URLData) bufs[i]; len = b.getLength(); Array.Copy((System.Array) b.getData(), 0, (System.Array) data, offset, len); offset += len; } this.add(data); } catch (System.IO.IOException ue) { throw new System.SystemException(ue.ToString()); } return ; } /// <summary> Returns the base name of the attribute. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns cn. /// /// </summary> /// <returns> The base name of the attribute. /// </returns> public virtual System.String getBaseName() { return baseName; } /// <summary> Returns the base name of the specified attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns cn. /// /// </summary> /// <param name="attrName">Name of the attribute from which to extract the /// base name. /// /// </param> /// <returns> The base name of the attribute. /// /// @throws IllegalArgumentException if attrName is null /// </returns> public static System.String getBaseName(System.String attrName) { if ((System.Object) attrName == null) { throw new System.ArgumentException("Attribute name cannot be null"); } int idx = attrName.IndexOf((System.Char) ';'); if (- 1 == idx) { return attrName; } return attrName.Substring(0, (idx) - (0)); } /// <summary> Extracts the subtypes from the attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns an array containing lang-ja and phonetic. /// /// </summary> /// <returns> An array subtypes or null if the attribute has none. /// </returns> public virtual System.String[] getSubtypes() { return subTypes; } /// <summary> Extracts the subtypes from the specified attribute name. /// /// For example, if the attribute name is cn;lang-ja;phonetic, /// this method returns an array containing lang-ja and phonetic. /// /// </summary> /// <param name="attrName"> Name of the attribute from which to extract /// the subtypes. /// /// </param> /// <returns> An array subtypes or null if the attribute has none. /// /// @throws IllegalArgumentException if attrName is null /// </returns> public static System.String[] getSubtypes(System.String attrName) { if ((System.Object) attrName == null) { throw new System.ArgumentException("Attribute name cannot be null"); } SupportClass.Tokenizer st = new SupportClass.Tokenizer(attrName, ";"); System.String[] subTypes = null; int cnt = st.Count; if (cnt > 0) { st.NextToken(); // skip over basename subTypes = new System.String[cnt - 1]; int i = 0; while (st.HasMoreTokens()) { subTypes[i++] = st.NextToken(); } } return subTypes; } /// <summary> Reports if the attribute name contains the specified subtype. /// /// For example, if you check for the subtype lang-en and the /// attribute name is cn;lang-en, this method returns true. /// /// </summary> /// <param name="subtype"> The single subtype to check for. /// /// </param> /// <returns> True, if the attribute has the specified subtype; /// false, if it doesn't. /// /// @throws IllegalArgumentException if subtype is null /// </returns> public virtual bool hasSubtype(System.String subtype) { if ((System.Object) subtype == null) { throw new System.ArgumentException("subtype cannot be null"); } if (null != this.subTypes) { for (int i = 0; i < subTypes.Length; i++) { if (subTypes[i].ToUpper().Equals(subtype.ToUpper())) return true; } } return false; } /// <summary> Reports if the attribute name contains all the specified subtypes. /// /// For example, if you check for the subtypes lang-en and phonetic /// and if the attribute name is cn;lang-en;phonetic, this method /// returns true. If the attribute name is cn;phonetic or cn;lang-en, /// this method returns false. /// /// </summary> /// <param name="subtypes"> An array of subtypes to check for. /// /// </param> /// <returns> True, if the attribute has all the specified subtypes; /// false, if it doesn't have all the subtypes. /// /// @throws IllegalArgumentException if subtypes is null or if array member /// is null. /// </returns> public virtual bool hasSubtypes(System.String[] subtypes) { if (subtypes == null) { throw new System.ArgumentException("subtypes cannot be null"); } for (int i = 0; i < subtypes.Length; i++) { for (int j = 0; j < subTypes.Length; j++) { if ((System.Object) subTypes[j] == null) { throw new System.ArgumentException("subtype " + "at array index " + i + " cannot be null"); } if (subTypes[j].ToUpper().Equals(subtypes[i].ToUpper())) { goto gotSubType; } } return false; gotSubType: ; } return true; } /// <summary> Removes a string value from the attribute. /// /// </summary> /// <param name="attrString"> Value of the attribute as a string. /// /// Note: Removing a value which is not present in the attribute has /// no effect. /// /// @throws IllegalArgumentException if attrString is null /// </param> public virtual void removeValue(System.String attrString) { if (null == (System.Object) attrString) { throw new System.ArgumentException("Attribute value cannot be null"); } try { System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); byte[] ibytes = encoder.GetBytes(attrString); sbyte[] sbytes=SupportClass.ToSByteArray(ibytes); this.removeValue(sbytes); // this.removeValue(attrString.getBytes("UTF-8")); } catch (System.IO.IOException uee) { // This should NEVER happen but just in case ... throw new System.SystemException(uee.ToString()); } return ; } /// <summary> Removes a byte-formatted value from the attribute. /// /// </summary> /// <param name="attrBytes"> Value of the attribute as raw bytes. /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// Example: <code>String.getBytes("UTF-8");</code> /// /// Note: Removing a value which is not present in the attribute has /// no effect. /// /// @throws IllegalArgumentException if attrBytes is null /// </param> [CLSCompliantAttribute(false)] public virtual void removeValue(sbyte[] attrBytes) { if (null == attrBytes) { throw new System.ArgumentException("Attribute value cannot be null"); } for (int i = 0; i < this.values.Length; i++) { if (equals(attrBytes, (sbyte[]) this.values[i])) { if (0 == i && 1 == this.values.Length) { // Optimize if first element of a single valued attr this.values = null; return ; } if (this.values.Length == 1) { this.values = null; } else { int moved = this.values.Length - i - 1; System.Object[] tmp = new System.Object[this.values.Length - 1]; if (i != 0) { Array.Copy((System.Array) values, 0, (System.Array) tmp, 0, i); } if (moved != 0) { Array.Copy((System.Array) values, i + 1, (System.Array) tmp, i, moved); } this.values = tmp; tmp = null; } break; } } return ; } /// <summary> Returns the number of values in the attribute. /// /// </summary> /// <returns> The number of values in the attribute. /// </returns> public virtual int size() { return null == this.values?0:this.values.Length; } /// <summary> Compares this object with the specified object for order. /// /// Ordering is determined by comparing attribute names (see /// {@link #getName() }) using the method compareTo() of the String class. /// /// /// </summary> /// <param name="attribute"> The LdapAttribute to be compared to this object. /// /// </param> /// <returns> Returns a negative integer, zero, or a positive /// integer as this object is less than, equal to, or greater than the /// specified object. /// </returns> public virtual int CompareTo(System.Object attribute) { return name.CompareTo(((LdapAttribute) attribute).name); } /// <summary> Adds an object to <code>this</code> object's list of attribute values /// /// </summary> /// <param name="bytes"> Ultimately all of this attribute's values are treated /// as binary data so we simplify the process by requiring /// that all data added to our list is in binary form. /// /// Note: If attrBytes represents a string it should be UTF-8 encoded. /// </param> private void add(sbyte[] bytes) { if (null == this.values) { this.values = new System.Object[]{bytes}; } else { // Duplicate attribute values not allowed for (int i = 0; i < this.values.Length; i++) { if (equals(bytes, (sbyte[]) this.values[i])) { return ; // Duplicate, don't add } } System.Object[] tmp = new System.Object[this.values.Length + 1]; Array.Copy((System.Array) this.values, 0, (System.Array) tmp, 0, this.values.Length); tmp[this.values.Length] = bytes; this.values = tmp; tmp = null; } return ; } /// <summary> Returns true if the two specified arrays of bytes are equal to each /// another. Matches the logic of Arrays.equals which is not available /// in jdk 1.1.x. /// /// </summary> /// <param name="e1">the first array to be tested /// </param> /// <param name="e2">the second array to be tested /// </param> /// <returns> true if the two arrays are equal /// </returns> private bool equals(sbyte[] e1, sbyte[] e2) { // If same object, they compare true if (e1 == e2) return true; // If either but not both are null, they compare false if (e1 == null || e2 == null) return false; // If arrays have different length, they compare false int length = e1.Length; if (e2.Length != length) return false; // If any of the bytes are different, they compare false for (int i = 0; i < length; i++) { if (e1[i] != e2[i]) return false; } return true; } /// <summary> Returns a string representation of this LdapAttribute /// /// </summary> /// <returns> a string representation of this LdapAttribute /// </returns> public override System.String ToString() { System.Text.StringBuilder result = new System.Text.StringBuilder("LdapAttribute: "); try { result.Append("{type='" + name + "'"); if (values != null) { result.Append(", "); if (values.Length == 1) { result.Append("value='"); } else { result.Append("values='"); } for (int i = 0; i < values.Length; i++) { if (i != 0) { result.Append("','"); } if (((sbyte[]) values[i]).Length == 0) { continue; } System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("utf-8"); // char[] dchar = encoder.GetChars((byte[]) values[i]); char[] dchar = encoder.GetChars(SupportClass.ToByteArray((sbyte[])values[i])); System.String sval = new String(dchar); // System.String sval = new String((sbyte[]) values[i], "UTF-8"); if (sval.Length == 0) { // didn't decode well, must be binary result.Append("<binary value, length:" + sval.Length); continue; } result.Append(sval); } result.Append("'"); } result.Append("}"); } catch (System.Exception e) { throw new System.SystemException(e.ToString()); } return result.ToString(); } } }
namespace JustGestures.OptionItems { partial class UC_visualisation { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.cB_gestureColor = new System.Windows.Forms.ComboBox(); this.cB_gestureWidth = new System.Windows.Forms.ComboBox(); this.lbl_color = new System.Windows.Forms.Label(); this.lbl_width = new System.Windows.Forms.Label(); this.checkB_showGesture = new System.Windows.Forms.CheckBox(); this.checkB_showToolTip = new System.Windows.Forms.CheckBox(); this.lbl_toolTipDelay = new System.Windows.Forms.Label(); this.gB_toolTipForGestures = new System.Windows.Forms.GroupBox(); this.nUD_toolTipDelay = new System.Windows.Forms.NumericUpDown(); this.gB_graphics = new System.Windows.Forms.GroupBox(); this.gB_toolTipForGestures.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nUD_toolTipDelay)).BeginInit(); this.gB_graphics.SuspendLayout(); this.SuspendLayout(); // // cB_gestureColor // this.cB_gestureColor.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.cB_gestureColor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cB_gestureColor.FormattingEnabled = true; this.cB_gestureColor.Location = new System.Drawing.Point(234, 42); this.cB_gestureColor.Name = "cB_gestureColor"; this.cB_gestureColor.Size = new System.Drawing.Size(160, 21); this.cB_gestureColor.TabIndex = 3; this.cB_gestureColor.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.cB_gestureColor_DrawItem); this.cB_gestureColor.SelectedIndexChanged += new System.EventHandler(this.comboBox_selectedIndexChanged); // // cB_gestureWidth // this.cB_gestureWidth.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.cB_gestureWidth.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cB_gestureWidth.FormattingEnabled = true; this.cB_gestureWidth.Location = new System.Drawing.Point(234, 69); this.cB_gestureWidth.Name = "cB_gestureWidth"; this.cB_gestureWidth.Size = new System.Drawing.Size(160, 21); this.cB_gestureWidth.TabIndex = 4; this.cB_gestureWidth.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.cB_gestureWidth_DrawItem); this.cB_gestureWidth.SelectedIndexChanged += new System.EventHandler(this.comboBox_selectedIndexChanged); // // lbl_color // this.lbl_color.AutoSize = true; this.lbl_color.Location = new System.Drawing.Point(6, 45); this.lbl_color.Name = "lbl_color"; this.lbl_color.Size = new System.Drawing.Size(31, 13); this.lbl_color.TabIndex = 2; this.lbl_color.Text = "Color"; // // lbl_width // this.lbl_width.AutoSize = true; this.lbl_width.Location = new System.Drawing.Point(6, 72); this.lbl_width.Name = "lbl_width"; this.lbl_width.Size = new System.Drawing.Size(35, 13); this.lbl_width.TabIndex = 3; this.lbl_width.Text = "Width"; // // checkB_showGesture // this.checkB_showGesture.AutoSize = true; this.checkB_showGesture.Checked = true; this.checkB_showGesture.CheckState = System.Windows.Forms.CheckState.Checked; this.checkB_showGesture.Location = new System.Drawing.Point(9, 19); this.checkB_showGesture.Name = "checkB_showGesture"; this.checkB_showGesture.Size = new System.Drawing.Size(257, 17); this.checkB_showGesture.TabIndex = 2; this.checkB_showGesture.Text = "Display graphic representation for Curve gestures"; this.checkB_showGesture.UseVisualStyleBackColor = true; this.checkB_showGesture.CheckedChanged += new System.EventHandler(this.checkB_showGesture_CheckedChanged); // // checkB_showToolTip // this.checkB_showToolTip.AutoSize = true; this.checkB_showToolTip.Checked = true; this.checkB_showToolTip.CheckState = System.Windows.Forms.CheckState.Checked; this.checkB_showToolTip.Location = new System.Drawing.Point(9, 19); this.checkB_showToolTip.Name = "checkB_showToolTip"; this.checkB_showToolTip.Size = new System.Drawing.Size(211, 17); this.checkB_showToolTip.TabIndex = 0; this.checkB_showToolTip.Text = "Show tool tip while creating the gesture"; this.checkB_showToolTip.UseVisualStyleBackColor = true; this.checkB_showToolTip.CheckedChanged += new System.EventHandler(this.checkB_showToolTip_CheckedChanged); // // lbl_toolTipDelay // this.lbl_toolTipDelay.AutoSize = true; this.lbl_toolTipDelay.Location = new System.Drawing.Point(6, 43); this.lbl_toolTipDelay.Name = "lbl_toolTipDelay"; this.lbl_toolTipDelay.Size = new System.Drawing.Size(103, 13); this.lbl_toolTipDelay.TabIndex = 8; this.lbl_toolTipDelay.Text = "Tool Tip Delay in ms"; // // gB_toolTipForGestures // this.gB_toolTipForGestures.Controls.Add(this.nUD_toolTipDelay); this.gB_toolTipForGestures.Controls.Add(this.checkB_showToolTip); this.gB_toolTipForGestures.Controls.Add(this.lbl_toolTipDelay); this.gB_toolTipForGestures.Location = new System.Drawing.Point(0, 0); this.gB_toolTipForGestures.Name = "gB_toolTipForGestures"; this.gB_toolTipForGestures.Size = new System.Drawing.Size(400, 70); this.gB_toolTipForGestures.TabIndex = 9; this.gB_toolTipForGestures.TabStop = false; this.gB_toolTipForGestures.Text = "Tool Tip of Recognized Gestures"; // // nUD_toolTipDelay // this.nUD_toolTipDelay.Increment = new decimal(new int[] { 50, 0, 0, 0}); this.nUD_toolTipDelay.Location = new System.Drawing.Point(234, 41); this.nUD_toolTipDelay.Maximum = new decimal(new int[] { 2000, 0, 0, 0}); this.nUD_toolTipDelay.Minimum = new decimal(new int[] { 50, 0, 0, 0}); this.nUD_toolTipDelay.Name = "nUD_toolTipDelay"; this.nUD_toolTipDelay.Size = new System.Drawing.Size(160, 20); this.nUD_toolTipDelay.TabIndex = 1; this.nUD_toolTipDelay.Value = new decimal(new int[] { 350, 0, 0, 0}); this.nUD_toolTipDelay.ValueChanged += new System.EventHandler(this.nUD_toolTipDelay_ValueChanged); // // gB_graphics // this.gB_graphics.Controls.Add(this.checkB_showGesture); this.gB_graphics.Controls.Add(this.cB_gestureColor); this.gB_graphics.Controls.Add(this.cB_gestureWidth); this.gB_graphics.Controls.Add(this.lbl_width); this.gB_graphics.Controls.Add(this.lbl_color); this.gB_graphics.Location = new System.Drawing.Point(0, 91); this.gB_graphics.Name = "gB_graphics"; this.gB_graphics.Size = new System.Drawing.Size(400, 103); this.gB_graphics.TabIndex = 10; this.gB_graphics.TabStop = false; this.gB_graphics.Text = "Graphics"; // // UC_visualisation // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.gB_graphics); this.Controls.Add(this.gB_toolTipForGestures); this.Name = "UC_visualisation"; this.Size = new System.Drawing.Size(486, 298); this.gB_toolTipForGestures.ResumeLayout(false); this.gB_toolTipForGestures.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nUD_toolTipDelay)).EndInit(); this.gB_graphics.ResumeLayout(false); this.gB_graphics.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ComboBox cB_gestureColor; private System.Windows.Forms.ComboBox cB_gestureWidth; private System.Windows.Forms.Label lbl_color; private System.Windows.Forms.Label lbl_width; private System.Windows.Forms.CheckBox checkB_showGesture; private System.Windows.Forms.CheckBox checkB_showToolTip; private System.Windows.Forms.Label lbl_toolTipDelay; private System.Windows.Forms.GroupBox gB_toolTipForGestures; private System.Windows.Forms.GroupBox gB_graphics; private System.Windows.Forms.NumericUpDown nUD_toolTipDelay; } }
using System.Text.RegularExpressions; using static Signum.Utilities.StringDistance; namespace Signum.Utilities; public class StringDistance { int[,]? _cachedNum; public int LevenshteinDistance(string strOld, string strNew, IEqualityComparer<char>? comparer = null, Func<Choice<char>, int>? weight = null, bool allowTransposition = false) { return LevenshteinDistance<char>(strOld.ToCharArray(), strNew.ToCharArray(), comparer, weight, allowTransposition); } public int LevenshteinDistance<T>(T[] strOld, T[] strNew, IEqualityComparer<T>? comparer = null, Func<Choice<T>, int>? weight = null, bool allowTransposition = false) { int M1 = strOld.Length + 1; int M2 = strNew.Length + 1; if (comparer == null) comparer = EqualityComparer<T>.Default; if (weight == null) weight = c => 1; var num = ResizeArray(M1, M2); num[0, 0] = 0; for (int i = 1; i < M1; i++) num[i, 0] = num[i - 1, 0] + weight(Choice<T>.Remove(strOld[i - 1])); for (int j = 1; j < M2; j++) num[0, j] = num[0, j - 1] + weight(Choice<T>.Add(strNew[j - 1])); for (int i = 1; i < M1; i++) { for (int j = 1; j < M2; j++) { if (comparer.Equals(strOld[i - 1], strNew[j - 1])) num[i, j] = num[i - 1, j - 1]; else { num[i, j] = Math.Min(Math.Min( num[i - 1, j] + weight(Choice<T>.Remove(strOld[i - 1])), num[i, j - 1] + weight(Choice<T>.Add(strNew[j - 1]))), num[i - 1, j - 1] + weight(Choice<T>.Substitute(strOld[i - 1], strNew[j - 1]))); if (allowTransposition && i > 1 && j > 1 && comparer.Equals(strOld[i - 1], strNew[j - 2]) && comparer.Equals(strOld[i - 2], strNew[j - 1])) num[i, j] = Math.Min(num[i, j], num[i - 2, j - 2] + weight(Choice<T>.Transpose(strOld[i - 1], strOld[i - 2]))); } } } return num[M1 - 1, M2 - 1]; } public enum ChoiceType { Equal, Substitute, Remove, Add, Transpose, } public struct Choice<T> { public readonly ChoiceType Type; public readonly T Removed; public readonly T Added; public bool HasRemoved { get { return Type != ChoiceType.Add; } } public bool HasAdded { get { return Type != ChoiceType.Remove; } } internal Choice( ChoiceType type, T removed, T added) { this.Type = type; this.Removed = removed; this.Added = added; } public static Choice<T> Add(T value) { return new Choice<T>(ChoiceType.Add, default!, value); } public static Choice<T> Remove(T value) { return new Choice<T>(ChoiceType.Remove, value, default!); } public static Choice<T> Equal(T value) { return new Choice<T>(ChoiceType.Equal, value, value); } public static Choice<T> Substitute(T remove, T add) { return new Choice<T>(ChoiceType.Substitute, remove, add); } internal static Choice<T> Transpose(T remove, T add) { return new Choice<T>(ChoiceType.Transpose, remove, add); } public override string? ToString() { switch (Type) { case ChoiceType.Equal: return "{0}".FormatWith(Added); case ChoiceType.Substitute: return "[-{0}+{1}]".FormatWith(Removed, Added); case ChoiceType.Remove: return "-{0}".FormatWith(Removed); case ChoiceType.Add: return "+{0}".FormatWith(Added); default: return null; } } } public List<Choice<char>> LevenshteinChoices(string strOld, string strNew, IEqualityComparer<char>? comparer = null, Func<Choice<char>, int>? weight = null) { return LevenshteinChoices<char>(strOld.ToCharArray(), strNew.ToCharArray(), comparer, weight); } public List<Choice<T>> LevenshteinChoices<T>(T[] strOld, T[] strNew, IEqualityComparer<T>? comparer = null, Func<Choice<T>, int>? weight = null) { if (comparer == null) comparer = EqualityComparer<T>.Default; if (weight == null) weight = (c) => 1; this.LevenshteinDistance<T>(strOld, strNew, comparer, weight); int i = strOld.Length; int j = strNew.Length; List<Choice<T>> result = new List<Choice<T>>(); while (i > 0 && j > 0) { if (comparer.Equals(strOld[i - 1], strNew[j - 1])) { result.Add(Choice<T>.Equal(strOld[i - 1])); i = i - 1; j = j - 1; } else { var cRemove = Choice<T>.Remove(strOld[i - 1]); var cAdd = Choice<T>.Add(strNew[j - 1]); var cSubstitute = Choice<T>.Substitute(strOld[i - 1], strNew[j - 1]); var num = _cachedNum!; var remove = num[i - 1, j] + weight(cRemove); var add = num[i, j - 1] + weight(cAdd); var substitute = num[i - 1, j - 1] + weight(cSubstitute); var min = Math.Min(remove, Math.Min(add, substitute)); if (substitute == min) { result.Add(cSubstitute); i = i - 1; j = j - 1; } else if (remove == min) { result.Add(cRemove); i = i - 1; } else if (add == min) { result.Add(cAdd); j = j - 1; } } } while (i > 0) { result.Add(Choice<T>.Remove(strOld[i - 1])); i = i - 1; } while (j > 0) { result.Add(Choice<T>.Add(strNew[j - 1])); j = j - 1; } result.Reverse(); return result; } public int LongestCommonSubstring(string str1, string str2) { if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) return 0; return LongestCommonSubstring<char>(str1.ToCharArray(), str2.ToCharArray(), out int pos1, out int pos2); } public int LongestCommonSubstring(string str1, string str2, out int startPos1, out int startPos2) { startPos1 = 0; startPos2 = 0; if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) return 0; return LongestCommonSubstring<char>(str1.ToCharArray(), str2.ToCharArray(), out startPos1, out startPos2); } public int LongestCommonSubstring<T>(T[] str1, T[] str2, out int startPos1, out int startPos2, IEqualityComparer<T>? comparer = null) { if (str1 == null) throw new ArgumentNullException("str1"); if (str2 == null) throw new ArgumentNullException("str2"); return LongestCommonSubstring(new Slice<T>(str1), new Slice<T>(str2), out startPos1, out startPos2, comparer); } //http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring public int LongestCommonSubstring<T>(Slice<T> str1, Slice<T> str2, out int startPos1, out int startPos2, IEqualityComparer<T>? comparer = null) { startPos1 = 0; startPos2 = 0; if (str1.Length == 0 || str2.Length == 0) return 0; if (comparer == null) comparer = EqualityComparer<T>.Default; var num = ResizeArray(str1.Length, str2.Length); int maxlen = 0; for (int i = 0; i < str1.Length; i++) { for (int j = 0; j < str2.Length; j++) { if (!comparer.Equals(str1[i], str2[j])) num[i, j] = 0; else { if ((i == 0) || (j == 0)) num[i, j] = 1; else num[i, j] = 1 + num[i - 1, j - 1]; if (num[i, j] > maxlen) { maxlen = num[i, j]; startPos1 = i - num[i, j] + 1; startPos2 = j - num[i, j] + 1; } } } } return maxlen; } string DebugTable() { if (_cachedNum == null) throw new InvalidOperationException("Not initialized"); return _cachedNum.SelectArray(a => a.ToString()).FormatTable(); } public int LongestCommonSubsequence(string str1, string str2) { if (string.IsNullOrEmpty(str1) || string.IsNullOrEmpty(str2)) return 0; return LongestCommonSubsequence<char>(str1.ToCharArray(), str2.ToCharArray()); } /// <summary> /// ACE is a subsequence of ABCDE /// </summary> public int LongestCommonSubsequence<T>(T[] str1, T[] str2, IEqualityComparer<T>? comparer = null) { if (str1 == null) throw new ArgumentNullException("str1"); if (str2 == null) throw new ArgumentNullException("str2"); if(str1.Length == 0 || str2.Length == 0) return 0; if (comparer == null) comparer = EqualityComparer<T>.Default; int M1 = str1.Length + 1; int M2 = str2.Length + 1; var num = ResizeArray(M1, M2); for (int i = 0; i < M1; i++) num[i, 0] = 0; for (int j = 0; j < M2; j++) num[0, j] = 0; for (int i = 1; i < M1; i++) { for (int j = 1; j < M2; j++) { if (comparer.Equals(str1[i - 1], str2[j - 1])) num[i, j] = num[i - 1, j - 1] + 1; else { if (num[i, j - 1] > num[i - 1, j]) num[i, j] = num[i, j - 1]; else num[i, j] = num[i - 1, j]; } } } return num[str1.Length, str2.Length]; } private int [,] ResizeArray(int M1, int M2) { if (_cachedNum == null || M1 > _cachedNum.GetLength(0) || M2 > _cachedNum.GetLength(1)) { _cachedNum = new int[M1, M2]; } return _cachedNum; } public enum DiffAction { Equal, Added, Removed } public struct DiffPair<T> { public DiffPair(DiffAction action, T value) { this.Action = action; this.Value = value; } public readonly DiffAction Action; public readonly T Value; public override string ToString() { var str = Action == DiffAction.Added ? "+" : Action == DiffAction.Removed ? "-" : ""; return str + Value; } } public List<DiffPair<List<DiffPair<string>>>> DiffText(string? textOld, string? textNew, bool lineEndingDifferences = true) { textOld = textOld ?? ""; textNew = textNew ?? ""; var linesOld = lineEndingDifferences ? textOld.Split('\n') : textOld.Lines(); var linesNew = lineEndingDifferences ? textNew.Split('\n') : textNew.Lines(); List<DiffPair<string>> diff = this.Diff(linesOld, linesNew); List<IGrouping<bool, DiffPair<string>>> groups = diff.GroupWhenChange(a => a.Action == DiffAction.Equal).ToList(); StringDistance sd = new StringDistance(); return groups.SelectMany(g=> { if (g.Key) return g.Select(dp => new DiffPair<List<DiffPair<string>>>(DiffAction.Equal, new List<DiffPair<string>> { dp })); var removed = g.Where(a=>a.Action == DiffAction.Removed).Select(a=>a.Value).ToArray(); var added = g.Where(a=>a.Action == DiffAction.Added).Select(a=>a.Value).ToArray(); var choices = this.LevenshteinChoices<string>(removed, added, weight: c => { if (c.Type == ChoiceType.Add) return c.Added.Length; if (c.Type == ChoiceType.Remove) return c.Removed.Length; var distance = sd.LevenshteinDistance(c.Added, c.Removed); return distance * 2; }); return choices.Select(c => { if (c.Type == ChoiceType.Add) return new DiffPair<List<DiffPair<string>>>(DiffAction.Added, new List<DiffPair<string>> { new DiffPair<string>(DiffAction.Added, c.Added) }); if (c.Type == ChoiceType.Remove) return new DiffPair<List<DiffPair<string>>>(DiffAction.Removed, new List<DiffPair<string>> { new DiffPair<string>(DiffAction.Removed, c.Removed) }); var diffWords = sd.DiffWords(c.Removed, c.Added); return new DiffPair<List<DiffPair<string>>>(DiffAction.Equal, diffWords); }); }).ToList(); } static readonly Regex WordsRegex = new Regex(@"([\w\d]+|\s+|.)"); public List<DiffPair<string>> DiffWords(string strOld, string strNew) { var wordsOld = WordsRegex.Matches(strOld).Cast<Match>().Select(m => m.Value).ToArray(); var wordsNew = WordsRegex.Matches(strNew).Cast<Match>().Select(m => m.Value).ToArray(); return Diff(wordsOld, wordsNew); } public List<DiffPair<T>> Diff<T>(T[] strOld, T[] strNew, IEqualityComparer<T>? comparer = null) { var result = new List<DiffPair<T>>(); DiffPrivate<T>(new Slice<T>(strOld), new Slice<T>(strNew), comparer, result); return result; } void DiffPrivate<T>(Slice<T> sliceOld, Slice<T> sliceNew, IEqualityComparer<T>? comparer, List<DiffPair<T>> result) { int length = LongestCommonSubstring<T>(sliceOld, sliceNew, out int posOld, out int posNew, comparer); if (length == 0) { AddResults(result, sliceOld, DiffAction.Removed); AddResults(result, sliceNew, DiffAction.Added); } else { TryDiff(sliceOld.SubSliceStart(posOld), sliceNew.SubSliceStart(posNew), comparer, result); AddResults(result, sliceOld.SubSlice(posOld, length), DiffAction.Equal); TryDiff(sliceOld.SubSliceEnd(posOld + length), sliceNew.SubSliceEnd(posNew + length), comparer, result); } } static void AddResults<T>(List<DiffPair<T>> list, Slice<T> slice, DiffAction action) { for (int i = 0; i < slice.Length; i++) list.Add(new DiffPair<T>(action, slice[i])); } void TryDiff<T>(Slice<T> sliceOld, Slice<T> sliceNew, IEqualityComparer<T>? comparer, List<DiffPair<T>> result) { if (sliceOld.Length > 0 && sliceOld.Length > 0) { DiffPrivate(sliceOld, sliceNew, comparer, result); } else if (sliceOld.Length > 0) { AddResults(result, sliceOld, DiffAction.Removed); } else if (sliceNew.Length > 0) { AddResults(result, sliceNew, DiffAction.Added); } } } public static class StringDistanceExtensions { public static string NiceToString(this List<DiffPair<List<DiffPair<string>>>> diff) { return diff.ToString(b => { if (b.Action == DiffAction.Equal) { if (b.Value.Count == 1) return " " + b.Value.Single().Value; return "-- " + b.Value.Where(a => a.Action == DiffAction.Removed || a.Action == DiffAction.Equal).ToString(a => a.Value, "") + "\n" + "++ " + b.Value.Where(a => a.Action == DiffAction.Added || a.Action == DiffAction.Equal).ToString(a => a.Value, ""); } else if (b.Action == DiffAction.Removed) return "-- " + b.Value.Single().Value; else if (b.Action == DiffAction.Added) return "++ " + b.Value.Single().Value; else throw new UnexpectedValueException(b.Action); }, "\n"); } } public struct Slice<T> :IEnumerable<T> { public Slice(T[] array) : this(array, 0, array.Length) { } public Slice(T[] array, int offset, int length) { if (offset + length > array.Length) throw new ArgumentException("Invalid slice"); this.Array = array; this.Offset = offset; this.Length = length; } public readonly T[] Array; public readonly int Offset; public readonly int Length; public T this[int index] { get { if (index > Length) throw new IndexOutOfRangeException(); return Array[Offset + index]; } set { if (index > Length) throw new IndexOutOfRangeException(); Array[Offset + index] = value; } } public Slice<T> SubSlice(int relativeIndex, int length) { return new Slice<T>(this.Array, this.Offset + relativeIndex, length); } public Slice<T> SubSliceStart(int relativeIndex) { return new Slice<T>(this.Array, this.Offset, relativeIndex); } public Slice<T> SubSliceEnd(int relativeIndex) { return new Slice<T>(this.Array, this.Offset + relativeIndex, this.Length - relativeIndex); } public override string ToString() { return this.Array.Skip(Offset).Take(Length).ToString(""); } public IEnumerator<T> GetEnumerator() { return this.Array.Skip(Offset).Take(Length).GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET * API Version: 2006-03-01 * */ using System; using System.Net; using System.Runtime.Serialization; using System.Security.Permissions; using Amazon.S3.Model; namespace Amazon.S3 { /// <summary> /// Amazon S3 Exception provides details of errors returned by Amazon S3 service. /// /// In particular, this class provides access to S3's extended request ID, the Date, /// and the host ID which are required debugging information in the odd case that /// you need to contact Amazon about an issue where Amazon S3 is incorrectly handling /// a request. /// /// The ResponseHeaders property of the AmazonS3Exception contains all the HTTP headers /// in the Error Response returned by the S3 service. /// </summary> [Serializable] public class AmazonS3Exception : Exception, ISerializable { private HttpStatusCode statusCode = default(HttpStatusCode); private string errorCode; private string message; private string hostId; private string requestId; private string xml; private string requestAddr; private WebHeaderCollection responseHeaders; /// <summary> /// Initializes a new AmazonS3Exception with default values. /// </summary> public AmazonS3Exception() : base() { } /// <summary> /// Initializes a new AmazonS3Exception with a specified error message /// </summary> /// <param name="message">A message that describes the error</param> public AmazonS3Exception(string message) { this.message = message; } /// <summary> /// Initializes a new AmazonS3Exception from the inner exception that is /// the cause of this exception. /// </summary> /// <param name="innerException">The nested exception that caused the AmazonS3Exception</param> public AmazonS3Exception(Exception innerException) : this(innerException.Message, innerException) { } /// <summary> /// Initializes a new AmazonS3Exception with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data. /// </param> /// <param name="context">The contextual information about the source or destination. /// </param> protected AmazonS3Exception(SerializationInfo info, StreamingContext context) : base(info, context) { this.statusCode = (HttpStatusCode)info.GetValue("statusCode", typeof(HttpStatusCode)); this.errorCode = info.GetString("errorCode"); this.message = info.GetString("message"); this.hostId = info.GetString("hostId"); this.requestId = info.GetString("requestId"); this.xml = info.GetString("xml"); this.requestAddr = info.GetString("requestAddr"); this.responseHeaders = (WebHeaderCollection)info.GetValue("responseHeaders", typeof(WebHeaderCollection)); } /// <summary> /// Serializes this instance of AmazonS3Exception. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination. /// </param> [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("statusCode", statusCode, typeof(HttpStatusCode)); info.AddValue("errorCode", errorCode, typeof(string)); info.AddValue("message", message, typeof(string)); info.AddValue("hostId", hostId, typeof(string)); info.AddValue("requestId", requestId, typeof(string)); info.AddValue("xml", xml, typeof(string)); info.AddValue("requestAddr", requestAddr, typeof(string)); info.AddValue("responseHeaders", responseHeaders, typeof(WebHeaderCollection)); base.GetObjectData(info, context); } /// <summary> /// Initializes a new AmazonS3Exception with a specific error message and the inner exception /// that is the cause of this exception. /// </summary> /// <param name="message">Overview of error</param> /// <param name="innerException">The exception that is the cause of the current exception. /// If the innerException parameter is not a null reference, the current exception is /// raised in a catch block that handles the inner exception.</param> public AmazonS3Exception(string message, Exception innerException) : base(message, innerException) { this.message = message; AmazonS3Exception ex = innerException as AmazonS3Exception; if (ex != null) { this.statusCode = ex.StatusCode; this.errorCode = ex.ErrorCode; this.requestId = ex.RequestId; this.message = ex.Message; this.hostId = ex.hostId; this.xml = ex.XML; } } /// <summary> /// Initializes an AmazonS3Exception with a specific message and /// HTTP status code /// </summary> /// <param name="message">Overview of error</param> /// <param name="statusCode">HTTP status code for error response</param> public AmazonS3Exception(string message, HttpStatusCode statusCode) : this(message) { this.statusCode = statusCode; } /// <summary> /// Initializes an AmazonS3Exception with error information provided in an /// AmazonS3 response. /// </summary> /// <param name="message">Overview of error</param> /// <param name="statusCode">HTTP status code for error response</param> /// <param name="errorCode">Error Code returned by the service</param> /// <param name="requestId">Request ID returned by the service</param> /// <param name="hostId">S3 Host ID returned by the service</param> /// <param name="xml">Compete xml found in response</param> /// <param name="requestAddr">The S3 request url</param> /// <param name="responseHeaders">The response headers containing S3 specific information /// </param> public AmazonS3Exception( string message, HttpStatusCode statusCode, string errorCode, string requestId, string hostId, string xml, string requestAddr, WebHeaderCollection responseHeaders) : this(message, statusCode) { this.errorCode = errorCode; this.hostId = hostId; this.requestId = requestId; this.xml = xml; this.requestAddr = requestAddr; this.responseHeaders = responseHeaders; } /// <summary> /// Initializes an AmazonS3Exception with error information provided in an /// AmazonS3 response and the inner exception that is the cause of the exception /// </summary> /// <param name="message">Overview of error</param> /// <param name="statusCode">HTTP status code for error response</param> /// <param name="requestAddr">The S3 request url</param> /// <param name="responseHeaders">The response headers containing S3 specific information /// <param name="innerException">The nested exception that caused the AmazonS3Exception</param> /// </param> public AmazonS3Exception( string message, HttpStatusCode statusCode, string requestAddr, WebHeaderCollection responseHeaders, Exception innerException) : this(message, innerException) { this.statusCode = statusCode; this.requestAddr = requestAddr; this.responseHeaders = responseHeaders; } /// <summary> /// Initializes an AmazonS3Exception with error information provided in an /// AmazonS3 response and the inner exception that is the cause of the exception /// </summary> /// <param name="statusCode">HTTP status code for error response</param> /// <param name="xml">Compete xml found in response</param> /// <param name="requestAddr">The S3 request url</param> /// <param name="responseHeaders">The response headers containing S3 specific information /// <param name="error">The nested exception that caused the AmazonS3Exception</param> /// </param> public AmazonS3Exception( HttpStatusCode statusCode, string xml, string requestAddr, WebHeaderCollection responseHeaders, S3Error error) { this.xml = xml; this.statusCode = statusCode; this.requestAddr = requestAddr; this.responseHeaders = responseHeaders; if (error != null) { this.errorCode = error.Code; this.hostId = error.HostId; this.requestId = error.RequestId; this.message = error.Message; } } /// <summary> /// Gets the HostId property. /// </summary> public string HostId { get { return this.hostId; } } /// <summary> /// Gets the ErrorCode property. /// </summary> public string ErrorCode { get { return this.errorCode; } } /// <summary> /// Gets error message /// </summary> public override string Message { get { return this.message; } } /// <summary> /// Gets status code returned by the service if available. If status /// code is set to -1, it means that status code was unavailable at the /// time exception was thrown /// </summary> public HttpStatusCode StatusCode { get { return this.statusCode; } } /// <summary> /// Gets XML returned by the service if available. /// </summary> public string XML { get { return this.xml; } } /// <summary> /// Gets Request ID returned by the service if available. /// </summary> public string RequestId { get { return this.requestId; } } /// <summary> /// Gets the S3 service address used to make this request. /// </summary> public string S3RequestAddress { get { return this.requestAddr; } } /// <summary> /// Gets the error response HTTP headers so that S3 specific information /// can be retrieved for debugging. Interesting fields are: /// a. x-amz-id-2 /// b. Date /// /// A value can be retrieved from this HeaderCollection via: /// ResponseHeaders.Get("key"); /// </summary> public WebHeaderCollection ResponseHeaders { get { return this.responseHeaders; } } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.AdWords.Lib; using Google.Api.Ads.AdWords.v201809; using System; using System.Threading; namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809 { /// <summary> /// This code example illustrates how to create a trial and wait for it to /// complete. See the Campaign Drafts and Experiments guide for more /// information: /// https://developers.google.com/adwords/api/docs/guides/campaign-drafts-experiments /// </summary> public class AddTrial : ExampleBase { /// <summary> /// The polling interval base to be used for exponential backoff. /// </summary> private const int POLL_INTERVAL_SECONDS_BASE = 30; /// <summary> /// The maximum number of retries. /// </summary> private const long MAX_RETRIES = 5; /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { AddTrial codeExample = new AddTrial(); Console.WriteLine(codeExample.Description); try { long draftId = long.Parse("INSERT_DRAFT_ID_HERE"); long baseCampaignId = long.Parse("INSERT_BASE_CAMPAIGN_ID_HERE"); codeExample.Run(new AdWordsUser(), draftId, baseCampaignId); } catch (Exception e) { Console.WriteLine("An exception occurred while running this code example. {0}", ExampleUtilities.FormatException(e)); } } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "This code example illustrates how to create a trial and wait for it to " + "complete. See the Campaign Drafts and Experiments guide for more " + "information: https://developers.google.com/adwords/api/docs/guides/campaign-" + "drafts-experiments"; } } /// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="baseCampaignId">Id of the campaign to use as base of the /// trial.</param> /// <param name="draftId">Id of the draft.</param> public void Run(AdWordsUser user, long draftId, long baseCampaignId) { using (TrialService trialService = (TrialService) user.GetService(AdWordsService.v201809.TrialService)) using (TrialAsyncErrorService trialAsyncErrorService = (TrialAsyncErrorService) user.GetService(AdWordsService.v201809 .TrialAsyncErrorService)) { Trial trial = new Trial() { draftId = draftId, baseCampaignId = baseCampaignId, name = "Test Trial #" + ExampleUtilities.GetRandomString(), trafficSplitPercent = 50, trafficSplitType = CampaignTrialTrafficSplitType.RANDOM_QUERY }; TrialOperation trialOperation = new TrialOperation() { @operator = Operator.ADD, operand = trial }; try { long trialId = trialService.mutate(new TrialOperation[] { trialOperation }).value[0].id; // Since creating a trial is asynchronous, we have to poll it to wait // for it to finish. Selector trialSelector = new Selector() { fields = new string[] { Trial.Fields.Id, Trial.Fields.Status, Trial.Fields.BaseCampaignId, Trial.Fields.TrialCampaignId }, predicates = new Predicate[] { Predicate.Equals(Trial.Fields.Id, trialId) } }; trial = null; bool isPending = true; int pollAttempts = 0; do { int sleepMillis = (int) Math.Pow(2, pollAttempts) * POLL_INTERVAL_SECONDS_BASE * 1000; Console.WriteLine("Sleeping {0} millis...", sleepMillis); Thread.Sleep(sleepMillis); trial = trialService.get(trialSelector).entries[0]; Console.WriteLine("Trial ID {0} has status '{1}'.", trial.id, trial.status); pollAttempts++; isPending = (trial.status == TrialStatus.CREATING); } while (isPending && pollAttempts <= MAX_RETRIES); if (trial.status == TrialStatus.ACTIVE) { // The trial creation was successful. Console.WriteLine( "Trial created with ID {0} and trial campaign ID {1}.", trial.id, trial.trialCampaignId); } else if (trial.status == TrialStatus.CREATION_FAILED) { // The trial creation failed, and errors can be fetched from the // TrialAsyncErrorService. Selector errorsSelector = new Selector() { fields = new string[] { TrialAsyncError.Fields.TrialId, TrialAsyncError.Fields.AsyncError }, predicates = new Predicate[] { Predicate.Equals(TrialAsyncError.Fields.TrialId, trial.id) } }; TrialAsyncErrorPage trialAsyncErrorPage = trialAsyncErrorService.get(errorsSelector); if (trialAsyncErrorPage.entries == null || trialAsyncErrorPage.entries.Length == 0) { Console.WriteLine("Could not retrieve errors for trial {0}.", trial.id); } else { Console.WriteLine( "Could not create trial ID {0} for draft ID {1} due to the " + "following errors:", trial.id, draftId); int i = 0; foreach (TrialAsyncError error in trialAsyncErrorPage.entries) { ApiError asyncError = error.asyncError; Console.WriteLine( "Error #{0}: errorType='{1}', errorString='{2}', " + "trigger='{3}', fieldPath='{4}'", i++, asyncError.ApiErrorType, asyncError.errorString, asyncError.trigger, asyncError.fieldPath); } } } else { // Most likely, the trial is still being created. You can continue // polling, but we have limited the number of attempts in the // example. Console.WriteLine( "Timed out waiting to create trial from draft ID {0} with " + "base campaign ID {1}.", draftId, baseCampaignId); } } catch (Exception e) { throw new System.ApplicationException("Failed to create trial from draft.", e); } } } } }
// Copyright 2005-2012 Moonfire Games // Released under the MIT license // http://mfgames.com/mfgames-cil/license using System; using MfGames; using NUnit.Framework; #pragma warning disable 1591 namespace UnitTests { /// <summary> /// Tests the ExtendedVersion class. /// </summary> [TestFixture] public class ExtendedVersionTests { #region Methods [Test] public void CompareDouble() { var v1 = new ExtendedVersion("1.1"); var v2 = new ExtendedVersion("1.1"); Assert.IsTrue(v1 == v2); } [Test] public void CompareDoubleGreater() { var v1 = new ExtendedVersion("1.2"); var v2 = new ExtendedVersion("1.1"); Assert.IsFalse(v1 == v2); } [Test] public void CompareDoubleLess() { var v1 = new ExtendedVersion("1.1"); var v2 = new ExtendedVersion("1.2"); Assert.IsFalse(v1 == v2); } [Test] public void CompareDoubleText() { var v1 = new ExtendedVersion("1.1"); var v2 = new ExtendedVersion("1.1a"); Assert.IsFalse(v1 == v2); } [Test] public void CompareDoubleTextEqual() { var v1 = new ExtendedVersion("1.1a"); var v2 = new ExtendedVersion("1.1a"); Assert.IsTrue(v1 == v2); } [Test] public void CompareDoubleTextGreater() { var v1 = new ExtendedVersion("1.2a"); var v2 = new ExtendedVersion("1.1a"); Assert.IsFalse(v1 == v2); } [Test] public void CompareDoubleTextLess() { var v1 = new ExtendedVersion("1.1a"); var v2 = new ExtendedVersion("1.2a"); Assert.IsFalse(v1 == v2); } [Test] public void CompareOpEqual() { var v1 = new ExtendedVersion("1.2.3"); Assert.IsTrue(v1.Compare("= 1.2.3"), "With space"); } [Test] public void CompareOpEqual2() { var v1 = new ExtendedVersion("1.2.3"); Assert.IsTrue(v1.Compare("=1.2.3"), "Without space"); } [Test] public void CompareOpEqual3() { var v1 = new ExtendedVersion("1.2.3"); Assert.IsTrue(v1.Compare("= 1.2.3"), "With too many spaces"); } [Test] public void CompareSingle() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("1"); Assert.IsTrue(v1 == v2); } [Test] public void CompareSingleGreater() { var v1 = new ExtendedVersion("2"); var v2 = new ExtendedVersion("1"); Assert.IsFalse(v1 == v2); } [Test] public void CompareSingleLess() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("2"); Assert.IsFalse(v1 == v2); } [Test] public void CompareSingleText() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 == v2); } [Test] public void CompareSingleTextEqual() { var v1 = new ExtendedVersion("1a"); var v2 = new ExtendedVersion("1a"); Assert.IsTrue(v1 == v2); } [Test] public void CompareSingleTextGreater() { var v1 = new ExtendedVersion("2a"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 == v2); } [Test] public void CompareSingleTextLess() { var v1 = new ExtendedVersion("1a"); var v2 = new ExtendedVersion("2a"); Assert.IsFalse(v1 == v2); } [Test] public void GreaterSingle() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("1"); Assert.IsFalse(v1 > v2); } [Test] public void GreaterSingleDouble() { var v1 = new ExtendedVersion("2.0"); var v2 = new ExtendedVersion("1"); Assert.IsTrue(v1 > v2); } [Test] public void GreaterSingleDoubleLess() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("2.0"); Assert.IsFalse(v1 > v2); } [Test] public void GreaterSingleGreater() { var v1 = new ExtendedVersion("2"); var v2 = new ExtendedVersion("1"); Assert.IsTrue(v1 > v2); } [Test] public void GreaterSingleLess() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("2"); Assert.IsFalse(v1 > v2); } [Test] public void GreaterSingleText() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 > v2); } [Test] public void GreaterSingleTextEqual() { var v1 = new ExtendedVersion("1a"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 > v2); } [Test] public void GreaterSingleTextGreater() { var v1 = new ExtendedVersion("2a"); var v2 = new ExtendedVersion("1a"); Assert.IsTrue(v1 > v2); } [Test] public void GreaterSingleTextLess() { var v1 = new ExtendedVersion("1a"); var v2 = new ExtendedVersion("2a"); Assert.IsFalse(v1 > v2); } [Test] public void HighVersesLowLessThan() { var v1 = new ExtendedVersion("20081.0"); var v2 = new ExtendedVersion("20071.2.0.0"); Assert.IsFalse(v1 <= v2); } [Test] public void LessSingle() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("1"); Assert.IsFalse(v1 < v2); } [Test] public void LessSingleDouble() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("2.0"); Assert.IsTrue(v1 < v2); } [Test] public void LessSingleDoubleGreater() { var v1 = new ExtendedVersion("2.0"); var v2 = new ExtendedVersion("1"); Assert.IsFalse(v1 < v2); } [Test] public void LessSingleGreater() { var v1 = new ExtendedVersion("2"); var v2 = new ExtendedVersion("1"); Assert.IsFalse(v1 < v2); } [Test] public void LessSingleLess() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("2"); Assert.IsTrue(v1 < v2); } [Test] public void LessSingleText() { var v1 = new ExtendedVersion("1"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 < v2); } [Test] public void LessSingleTextEqual() { var v1 = new ExtendedVersion("1a"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 < v2); } [Test] public void LessSingleTextGreater() { var v1 = new ExtendedVersion("2a"); var v2 = new ExtendedVersion("1a"); Assert.IsFalse(v1 < v2); } [Test] public void LessSingleTextLess() { var v1 = new ExtendedVersion("1a"); var v2 = new ExtendedVersion("2a"); Assert.IsTrue(v1 < v2); } [ExpectedException(typeof (Exception))] [Test] public void ParseBlank() { var v = new ExtendedVersion(""); Assert.IsTrue(v == null, "Never get here"); } [Test] public void ParseDebianVersion() { var v = new ExtendedVersion("1.2.3-4"); Assert.AreEqual("1.2.3-4", v.ToString()); } [Test] public void ParseDebianVersion2() { var v = new ExtendedVersion("1.2-3.4d"); Assert.AreEqual("1.2-3.4d", v.ToString()); } [ExpectedException(typeof (Exception))] [Test] public void ParseInnerSpace() { var v = new ExtendedVersion("1 2.3"); Assert.IsTrue(v == null, "Never get here"); } [ExpectedException(typeof (Exception))] [Test] public void ParseNull() { var v = new ExtendedVersion(null); Assert.IsTrue(v == null, "Never get here"); } [Test] public void ParseSingleNumber() { var v = new ExtendedVersion("1"); Assert.AreEqual("1", v.ToString()); } [ExpectedException(typeof (Exception))] [Test] public void ParseSpace() { var v = new ExtendedVersion(" "); Assert.IsTrue(v == null, "Never get here"); } [Test] public void ParseTextVersion() { var v = new ExtendedVersion("1.2b3"); Assert.AreEqual("1.2b3", v.ToString()); } [Test] public void ParseThreeNumbers() { var v = new ExtendedVersion("1.2.3"); Assert.AreEqual("1.2.3", v.ToString()); } [Test] public void ParseTwoNumbers() { var v = new ExtendedVersion("1.2"); Assert.AreEqual("1.2", v.ToString()); } [Test] public void ZeroVersesLotsLessThan() { var v1 = new ExtendedVersion("0.0"); var v2 = new ExtendedVersion("20071.2.0.0"); Assert.IsTrue(v1 <= v2); } #endregion } } #pragma warning restore 1591
// 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; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Buffers; namespace System.SpanTests { public static partial class MemoryMarshalTests { [Fact] public static void CreateFromPinnedArrayInt() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 2); pinnedMemory.Validate(93, 94); } [Fact] public static void CreateFromPinnedArrayLong() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<long> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 3); pinnedMemory.Validate(94, 95, 96); } [Fact] public static void CreateFromPinnedArrayString() { string[] a = { "90", "91", "92", "93", "94", "95", "96", "97", "98" }; Memory<string> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 3); pinnedMemory.Validate("94", "95", "96"); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "This unit test relies on internal implementation details of Memory<T> on netcoreapp.")] public static void CreateFromPinnedArrayIntSliceRemainsPinned() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 5); pinnedMemory.Validate(93, 94, 95, 96, 97); Memory<int> slice = pinnedMemory.Slice(0); TestMemory<int> testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(0, pinnedMemory.Length); testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(1); testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(4, testSlice._length); slice = pinnedMemory.Slice(1, 2); testSlice = Unsafe.As<Memory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(2, testSlice._length); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "This unit test relies on internal implementation details of Memory<T> on netcoreapp.")] public static void CreateFromPinnedArrayIntReadOnlyMemorySliceRemainsPinned() { int[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; ReadOnlyMemory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 5); pinnedMemory.Validate(93, 94, 95, 96, 97); ReadOnlyMemory<int> slice = pinnedMemory.Slice(0); TestMemory<int> testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(0, pinnedMemory.Length); testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(3 | (1 << 31), testSlice._index); Assert.Equal(5, testSlice._length); slice = pinnedMemory.Slice(1); testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(4, testSlice._length); slice = pinnedMemory.Slice(1, 2); testSlice = Unsafe.As<ReadOnlyMemory<int>, TestMemory<int>>(ref slice); Assert.Equal(4 | (1 << 31), testSlice._index); Assert.Equal(2, testSlice._length); } [Fact] public static void CreateFromPinnedArrayWithStartAndLengthRangeExtendsToEndOfArray() { long[] a = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; Memory<long> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 4, 5); pinnedMemory.Validate(94, 95, 96, 97, 98); } [Fact] public static void CreateFromPinnedArrayZeroLength() { int[] empty = Array.Empty<int>(); Memory<int> memory = MemoryMarshal.CreateFromPinnedArray(empty, 0, empty.Length); memory.Validate(); } [Fact] public static void CreateFromPinnedArrayNullArray() { Memory<int> memory = MemoryMarshal.CreateFromPinnedArray((int[])null, 0, 0); memory.Validate(); Assert.Equal(default, memory); } [Fact] public static void CreateFromPinnedArrayNullArrayNonZeroStartAndLength() { Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, 1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray((int[])null, -1, -1)); } [Fact] public static void CreateFromPinnedArrayWrongArrayType() { // Cannot pass variant array, if array type is not a valuetype. string[] a = { "Hello" }; Assert.Throws<ArrayTypeMismatchException>(() => MemoryMarshal.CreateFromPinnedArray<object>(a, 0, a.Length)); } [Fact] public static void CreateFromPinnedArrayWrongValueType() { // Can pass variant array, if array type is a valuetype. uint[] a = { 42u, 0xffffffffu }; int[] aAsIntArray = (int[])(object)a; Memory<int> memory = MemoryMarshal.CreateFromPinnedArray(aAsIntArray, 0, aAsIntArray.Length); memory.Validate(42, -1); } [Fact] public static void CreateFromPinnedArrayWithNegativeStartAndLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, -1, 0)); } [Fact] public static void CreateFromPinnedArrayWithStartTooLargeAndLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 4, 0)); } [Fact] public static void CreateFromPinnedArrayWithStartAndNegativeLength() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 0, -1)); } [Fact] public static void CreateFromPinnedArrayWithStartAndLengthTooLarge() { int[] a = new int[3]; Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 3, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 2, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 1, 3)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, 0, 4)); Assert.Throws<ArgumentOutOfRangeException>(() => MemoryMarshal.CreateFromPinnedArray(a, int.MaxValue, int.MaxValue)); } [Fact] public static void CreateFromPinnedArrayWithStartAndLengthBothEqual() { // Valid for start to equal the array length. This returns an empty memory that starts "just past the array." int[] a = { 91, 92, 93 }; Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(a, 3, 0); pinnedMemory.Validate(); } [Fact] public static unsafe void CreateFromPinnedArrayVerifyPinning() { int[] pinnedArray = { 90, 91, 92, 93, 94, 95, 96, 97, 98 }; GCHandle pinnedGCHandle = GCHandle.Alloc(pinnedArray, GCHandleType.Pinned); Memory<int> pinnedMemory = MemoryMarshal.CreateFromPinnedArray(pinnedArray, 0, 2); void* pinnedPtr = Unsafe.AsPointer(ref MemoryMarshal.GetReference(pinnedMemory.Span)); void* memoryHandlePinnedPtr = pinnedMemory.Pin().Pointer; GC.Collect(); GC.Collect(2); Assert.Equal((int)pinnedPtr, (int)Unsafe.AsPointer(ref MemoryMarshal.GetReference(pinnedMemory.Span))); Assert.Equal((int)memoryHandlePinnedPtr, (int)pinnedGCHandle.AddrOfPinnedObject().ToPointer()); pinnedGCHandle.Free(); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// CASES21 MESSAGES Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KMSGDataSet : EduHubDataSet<KMSG> { /// <inheritdoc /> public override string Name { get { return "KMSG"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KMSGDataSet(EduHubContext Context) : base(Context) { Index_KMSGKEY = new Lazy<Dictionary<int, KMSG>>(() => this.ToDictionary(i => i.KMSGKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KMSG" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KMSG" /> fields for each CSV column header</returns> internal override Action<KMSG, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KMSG, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KMSGKEY": mapper[i] = (e, v) => e.KMSGKEY = int.Parse(v); break; case "SEND_DATE": mapper[i] = (e, v) => e.SEND_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "SUBJECT": mapper[i] = (e, v) => e.SUBJECT = v; break; case "MESSAGE": mapper[i] = (e, v) => e.MESSAGE = v; break; case "EXPIRY": mapper[i] = (e, v) => e.EXPIRY = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "FREQUENCY": mapper[i] = (e, v) => e.FREQUENCY = v == null ? (short?)null : short.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KMSG" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KMSG" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KMSG" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KMSG}"/> of entities</returns> internal override IEnumerable<KMSG> ApplyDeltaEntities(IEnumerable<KMSG> Entities, List<KMSG> DeltaEntities) { HashSet<int> Index_KMSGKEY = new HashSet<int>(DeltaEntities.Select(i => i.KMSGKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KMSGKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KMSGKEY.Remove(entity.KMSGKEY); if (entity.KMSGKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, KMSG>> Index_KMSGKEY; #endregion #region Index Methods /// <summary> /// Find KMSG by KMSGKEY field /// </summary> /// <param name="KMSGKEY">KMSGKEY value used to find KMSG</param> /// <returns>Related KMSG entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KMSG FindByKMSGKEY(int KMSGKEY) { return Index_KMSGKEY.Value[KMSGKEY]; } /// <summary> /// Attempt to find KMSG by KMSGKEY field /// </summary> /// <param name="KMSGKEY">KMSGKEY value used to find KMSG</param> /// <param name="Value">Related KMSG entity</param> /// <returns>True if the related KMSG entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKMSGKEY(int KMSGKEY, out KMSG Value) { return Index_KMSGKEY.Value.TryGetValue(KMSGKEY, out Value); } /// <summary> /// Attempt to find KMSG by KMSGKEY field /// </summary> /// <param name="KMSGKEY">KMSGKEY value used to find KMSG</param> /// <returns>Related KMSG entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KMSG TryFindByKMSGKEY(int KMSGKEY) { KMSG value; if (Index_KMSGKEY.Value.TryGetValue(KMSGKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KMSG table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KMSG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KMSG]( [KMSGKEY] int IDENTITY NOT NULL, [SEND_DATE] datetime NULL, [SUBJECT] varchar(100) NULL, [MESSAGE] varchar(MAX) NULL, [EXPIRY] datetime NULL, [FREQUENCY] smallint NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KMSG_Index_KMSGKEY] PRIMARY KEY CLUSTERED ( [KMSGKEY] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="KMSGDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="KMSGDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KMSG"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KMSG"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KMSG> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_KMSGKEY = new List<int>(); foreach (var entity in Entities) { Index_KMSGKEY.Add(entity.KMSGKEY); } builder.AppendLine("DELETE [dbo].[KMSG] WHERE"); // Index_KMSGKEY builder.Append("[KMSGKEY] IN ("); for (int index = 0; index < Index_KMSGKEY.Count; index++) { if (index != 0) builder.Append(", "); // KMSGKEY var parameterKMSGKEY = $"@p{parameterIndex++}"; builder.Append(parameterKMSGKEY); command.Parameters.Add(parameterKMSGKEY, SqlDbType.Int).Value = Index_KMSGKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KMSG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KMSG data set</returns> public override EduHubDataSetDataReader<KMSG> GetDataSetDataReader() { return new KMSGDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KMSG data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KMSG data set</returns> public override EduHubDataSetDataReader<KMSG> GetDataSetDataReader(List<KMSG> Entities) { return new KMSGDataReader(new EduHubDataSetLoadedReader<KMSG>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KMSGDataReader : EduHubDataSetDataReader<KMSG> { public KMSGDataReader(IEduHubDataSetReader<KMSG> Reader) : base (Reader) { } public override int FieldCount { get { return 9; } } public override object GetValue(int i) { switch (i) { case 0: // KMSGKEY return Current.KMSGKEY; case 1: // SEND_DATE return Current.SEND_DATE; case 2: // SUBJECT return Current.SUBJECT; case 3: // MESSAGE return Current.MESSAGE; case 4: // EXPIRY return Current.EXPIRY; case 5: // FREQUENCY return Current.FREQUENCY; case 6: // LW_DATE return Current.LW_DATE; case 7: // LW_TIME return Current.LW_TIME; case 8: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // SEND_DATE return Current.SEND_DATE == null; case 2: // SUBJECT return Current.SUBJECT == null; case 3: // MESSAGE return Current.MESSAGE == null; case 4: // EXPIRY return Current.EXPIRY == null; case 5: // FREQUENCY return Current.FREQUENCY == null; case 6: // LW_DATE return Current.LW_DATE == null; case 7: // LW_TIME return Current.LW_TIME == null; case 8: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KMSGKEY return "KMSGKEY"; case 1: // SEND_DATE return "SEND_DATE"; case 2: // SUBJECT return "SUBJECT"; case 3: // MESSAGE return "MESSAGE"; case 4: // EXPIRY return "EXPIRY"; case 5: // FREQUENCY return "FREQUENCY"; case 6: // LW_DATE return "LW_DATE"; case 7: // LW_TIME return "LW_TIME"; case 8: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KMSGKEY": return 0; case "SEND_DATE": return 1; case "SUBJECT": return 2; case "MESSAGE": return 3; case "EXPIRY": return 4; case "FREQUENCY": return 5; case "LW_DATE": return 6; case "LW_TIME": return 7; case "LW_USER": return 8; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using Com.CodeGame.CodeHockey2014.DevKit.CSharpCgdk.Model; namespace Com.CodeGame.CodeHockey2014.DevKit.CSharpCgdk { public sealed class MyStrategy : IStrategy { private readonly double STRIKE_ANGLE = 1.0D * Math.PI / 180.0D; private readonly double MAXIMUM_DISTANCE = 500; private readonly double POSITION_MISMATCH = 50; double smallX = 100; double bigX = 500; public void Move(Hockeyist self, World world, Game game, Move move) { if (isYourTeamHasPuck(self, world)) { if (isThisHockeistHasPuck(self, world)) { if (self.State == HockeyistState.Swinging) { if (stopSwinging(self, game, move)) return; } attack(self, world, game, move); } else { defence(self, world, game, move); } } else { if (self.State == HockeyistState.Swinging) { move.Action = ActionType.CancelStrike; } else { takePuckOrDefence(self, world, game, move); } } } private static bool stopSwinging(Hockeyist self, Game game, Move move) { bool isStrike = false; if (self.SwingTicks > game.MaxEffectiveSwingTicks - 3) { move.Action = ActionType.Strike; isStrike = true; } return isStrike; } private static bool isYourTeamHasPuck(Hockeyist self, World world) { return world.Puck.OwnerPlayerId == self.PlayerId; } private static bool isThisHockeistHasPuck(Hockeyist self, World world) { return world.Puck.OwnerHockeyistId == self.Id; } private void takePuckOrDefence(Hockeyist self, World world, Game game, Move move) { Hockeyist closestToPuck = getTeammateClosestToPuck(world, game); if ((closestToPuck != null) && (closestToPuck.Id == self.Id)) { Hockeyist withPuck = getHockeyistWithPuck(world); if (withPuck != null && !withPuck.IsTeammate) { moveToUnit(self, game, move, withPuck, (m) => { m.Action = ActionType.Strike; }); } else { takePuck(self, world, game, move); } } else { defence(self, world, game, move); } } private Hockeyist getTeammateClosestToPuck(World world, Game game) { Hockeyist nearestTeammate = null; double nearestTeammateRange = 0.0D; foreach (Hockeyist hockeyist in world.Hockeyists) { if (hockeyist.IsTeammate && hockeyist.Type != HockeyistType.Goalie && hockeyist.State != HockeyistState.KnockedDown && hockeyist.State != HockeyistState.Resting) { double teammateRange = hockeyist.GetDistanceTo(world.Puck); if (nearestTeammate == null || teammateRange < nearestTeammateRange) { nearestTeammate = hockeyist; nearestTeammateRange = teammateRange; } } } return nearestTeammate; } private void defence(Hockeyist self, World world, Game game, Move move) { bool isLeft = self.X > world.GetMyPlayer().NetFront; double defencePositionX = world.GetMyPlayer().NetFront + (isLeft ? 1 : -1) * (getOpponentGoalieRadius(world) * 3 + 20); double defencePositionY = getCenterY(world); double distanceToDefence = self.GetDistanceTo(defencePositionX, defencePositionY); if (distanceToDefence < 20) { move.Turn = self.GetAngleTo(world.Puck); } else { move.Turn = self.GetAngleTo(defencePositionX, defencePositionY); move.SpeedUp = distanceToDefence * 4 / world.Width; } //obstructNearestOpponent(self, world, game, move); } private void attack(Hockeyist self, World world, Game game, Move move) { if (isOpponentTooClose(self, world, game)) { makePassToTeammate(self, world, game, move); } else { SideToAttck sideToMove = getSideToMove(self, world, game); double opponentNetX = getOpponentNetX(world); if (isInForthZone(self, world, game, sideToMove)) { move.SpeedUp = 1; move.Turn = self.GetAngleTo(opponentNetX + ((sideToMove == SideToAttck.BottomLeft || sideToMove == SideToAttck.TopLeft) ? 1 : -1) * bigX, self.Y); } else { if (isInThirdZone(self, world, game, sideToMove)) { move.SpeedUp = 1; double strikeX = opponentNetX + ((sideToMove == SideToAttck.BottomLeft || sideToMove == SideToAttck.TopLeft) ? 1 : -1) * bigX; double strikeY = getOptimalStrikePositionY(world, game, sideToMove); move.Turn = self.GetAngleTo(strikeX, strikeY); } else { if (isInSecondZone(self, world, game)) { double oppositeNetX; double oppositeNetY; getOppositeNetCorner(self, world, game, out oppositeNetX, out oppositeNetY); double angleToOppositeNetCorner = self.GetAngleTo(oppositeNetX, oppositeNetY); if (Math.Abs(angleToOppositeNetCorner) > STRIKE_ANGLE) { move.Turn = angleToOppositeNetCorner; } else { move.Action = ActionType.Swing; } move.SpeedUp = 1; } else { makePassToTeammate(self, world, game, move); } } } } } private double getOptimalStrikePositionY(World world, Game game, SideToAttck sideToMove) { double width = 150; bool isTop = (sideToMove == SideToAttck.TopLeft || sideToMove == SideToAttck.TopRight); double strikeY = isTop ? game.RinkTop + width : game.RinkBottom - width ;//(getOpponentNetYTop(world) + getOpponentGoalieRadius(world)) : (getOpponentNetYBottom(world) - getOpponentGoalieRadius(world)); return strikeY; } private double getOpponentNetYBottom(World world) { Player opponentPlayer = world.GetOpponentPlayer(); return opponentPlayer.NetBottom; } private double getOpponentNetYTop(World world) { Player opponentPlayer = world.GetOpponentPlayer(); return opponentPlayer.NetTop; } private double getOpponentNetX(World world) { Player opponentPlayer = world.GetOpponentPlayer(); return opponentPlayer.NetFront; } private bool isInSecondZone(Hockeyist self, World world, Game game) { double distance = Math.Abs(self.X - getOpponentNetX(world)); return distance < bigX && distance > smallX; } private bool isInThirdZone(Hockeyist self, World world, Game game, SideToAttck side) { double distance = Math.Abs(self.X - getOpponentNetX(world)); bool isTop = (side == SideToAttck.TopLeft || side == SideToAttck.TopRight); double strikeY = getOptimalStrikePositionY(world, game, side); return distance > smallX && (isTop ? self.Y > strikeY : self.Y < strikeY); } private bool isInForthZone(Hockeyist self, World world, Game game, SideToAttck side) { double distance = Math.Abs(self.X - getOpponentNetX(world)); bool isTop = (side == SideToAttck.TopLeft || side == SideToAttck.TopRight); double strikeY = getOptimalStrikePositionY(world, game, side); return distance > bigX && (isTop ? self.Y < strikeY : self.Y > strikeY); } private SideToAttck getSideToMove(Hockeyist self, World world, Game game) { double halfY = getCenterY(world); bool isOnTop = self.Y < halfY; if (getOpponentNetX(world) < self.X) { //Left return isOnTop ? SideToAttck.TopLeft : SideToAttck.BottomLeft; } else { //Right return isOnTop ? SideToAttck.TopRight : SideToAttck.BottomRight; } } private double getCenterY(World world) { return 0.5 * (getOpponentNetYTop(world) + getOpponentNetYBottom(world)); } private void takePuck(Hockeyist self, World world, Game game, Move move) { if (hypot(world.Puck.SpeedX, world.Puck.SpeedY) > 0.7) { moveToUnit(self, game, move, world.Puck, (m) => { m.Action = ActionType.Strike; }); } else { moveToUnit(self, game, move, world.Puck, (m) => { m.Action = ActionType.TakePuck; }); } } private static void moveToUnit(Hockeyist self, Game game, Move move, Unit unit, Action<Move> action) { bool isClose = self.GetDistanceTo(unit) < game.StickLength; bool isInSector = Math.Abs(self.GetAngleTo(unit)) < 0.5 * game.StickSector; if (isClose && isInSector) { action(move); } else { if (!isClose) { move.SpeedUp = 1.0D; } if (!isInSector) { move.Turn = self.GetAngleTo(unit); } } } private void makePassToTeammate(Hockeyist self, World world, Game game, Model.Move move) { Hockeyist teammate = getNearestAvailableTeammate(self, world); if (teammate != null) { double passAngle = self.GetAngleTo(teammate); if (Math.Abs(passAngle) < 0.5 * game.PassSector) { move.Action = ActionType.Pass; move.PassAngle = passAngle; move.PassPower = Math.Max(self.GetDistanceTo(teammate) / Math.Abs(game.RinkLeft - game.RinkRight), 0.25); } else { move.Turn = self.GetAngleTo(teammate); } } } private static void getOppositeNetCorner(Hockeyist self, World world, Game game, out double netX, out double netY) { getNetCenter(self, world, game, out netX, out netY); netY += (self.Y < netY ? 1 : -1) * (0.5 * game.GoalNetHeight - world.Puck.Radius); } private static void getNetCenter(Hockeyist self, World world, Game game, out double netX, out double netY) { Player opponentPlayer = world.GetOpponentPlayer(); netX = opponentPlayer.NetFront; netY = 0.5D * (opponentPlayer.NetBottom + opponentPlayer.NetTop); } private Hockeyist getNearestAvailableTeammate(Hockeyist self, World world) { Hockeyist nearestTeammate = null; double nearestTeammateRange = 0.0D; foreach (Hockeyist hockeyist in world.Hockeyists) { if (hockeyist.IsTeammate && hockeyist.Type != HockeyistType.Goalie && hockeyist.State != HockeyistState.KnockedDown && hockeyist.State != HockeyistState.Resting && hockeyist.Id != self.Id) { double teammateRange = self.GetDistanceTo(hockeyist); if (nearestTeammate == null || teammateRange < nearestTeammateRange) { nearestTeammate = hockeyist; nearestTeammateRange = teammateRange; } } } return nearestTeammate; } private Hockeyist getHockeyistWithPuck(World world) { foreach (Hockeyist hockeyist in world.Hockeyists) { if (hockeyist.Id == world.Puck.OwnerHockeyistId) { return hockeyist; } } return null; } private bool isOpponentTooClose(Hockeyist self, World world, Game game) { Hockeyist nearestOpponent = getNearestOpponent(self.X, self.Y, world); if (nearestOpponent != null) { return (self.GetDistanceTo(nearestOpponent) <= game.StickLength) && (Math.Abs(nearestOpponent.GetAngleTo(self)) < 0.5 * game.StickSector); } return false; } private Hockeyist getNearestOpponent(double x, double y, World world) { Hockeyist nearestOpponent = null; double nearestOpponentRange = 0.0D; foreach (Hockeyist hockeyist in world.Hockeyists) { if (hockeyist.IsTeammate || hockeyist.Type == HockeyistType.Goalie || hockeyist.State == HockeyistState.KnockedDown || hockeyist.State == HockeyistState.Resting) { continue; } double opponentRange = hypot(x - hockeyist.X, y - hockeyist.Y); if (nearestOpponent == null || opponentRange < nearestOpponentRange) { nearestOpponent = hockeyist; nearestOpponentRange = opponentRange; } } return nearestOpponent; } #region - trash - /* private void strikeToOppositeNetCorner(Hockeyist self, World world, Game game, Move move) { double netX; double netY; getOppositeNetCorner(self, world, game, out netX, out netY); double angleToNet = self.GetAngleTo(netX, netY); if (Math.Abs(angleToNet) < STRIKE_ANGLE) { move.Action = ActionType.Swing; } else { move.Turn = angleToNet; } } private void obstructNearestOpponent(Hockeyist self, World world, Game game, Move move) { Hockeyist nearestOpponent = getNearestOpponent(self.X, self.Y, world); if (nearestOpponent != null) { moveToUnit(self, game, move, nearestOpponent, (m) => { m.Action = ActionType.Strike; }); } } private void moveToStrikePosition(Hockeyist self, World world, Game game, Move move) { if (isOpponentTooClose(self, world, game)) { makePassToTeammate( self, world, game, move); } else { double nearestX, nearestY; getNearestStrikePosition(self, world, game, out nearestX, out nearestY); double angleToStrikePosition = self.GetAngleTo(nearestX, nearestY); if (Math.Abs(angleToStrikePosition) < STRIKE_ANGLE) { move.SpeedUp = 1.0D; } else { move.Turn = angleToStrikePosition; } } } private bool isOnStrikePosition(Hockeyist self, World world, Game game) { double netX; double netY; getOppositeNetCorner(self, world, game, out netX, out netY); double angle = world.Puck.GetAngleTo(netX, netY); double opponentGoalieRadius = getOpponentGoalieRadius(world); double h = (game.GoalNetHeight - world.Puck.Radius - opponentGoalieRadius) - (world.Puck.Radius + opponentGoalieRadius) / Math.Sin(angle) - opponentGoalieRadius / Math.Tan(angle); double S = world.Puck.GetDistanceTo(netX, netY); double puckVelocity = 25;//getPuckVelocityAfterStrike(self); return (h / game.GoalieMaxSpeed) > (S / puckVelocity); } private double getPuckVelocityAfterStrike(Hockeyist self) { return 20 * 0.75 + hypot(self.SpeedX, self.SpeedY); } private bool isOpponentTooClose(Hockeyist self, World world, Game game) { Hockeyist nearestOpponent = getNearestOpponent(self.X, self.Y, world); if (nearestOpponent != null) { return (self.GetDistanceTo(nearestOpponent) <= game.StickLength) && (Math.Abs(nearestOpponent.GetAngleTo(self)) < 0.5 * game.StickSector); } return false; } private Hockeyist getNearestOpponent(double x, double y, World world) { Hockeyist nearestOpponent = null; double nearestOpponentRange = 0.0D; foreach (Hockeyist hockeyist in world.Hockeyists) { if (hockeyist.IsTeammate || hockeyist.Type == HockeyistType.Goalie || hockeyist.State == HockeyistState.KnockedDown || hockeyist.State == HockeyistState.Resting) { continue; } double opponentRange = hypot(x - hockeyist.X, y - hockeyist.Y); if (nearestOpponent == null || opponentRange < nearestOpponentRange) { nearestOpponent = hockeyist; nearestOpponentRange = opponentRange; } } return nearestOpponent; } * */ private double getOpponentGoalieRadius(World world) { return 30; } private double hypot(double a, double b) { return System.Math.Sqrt(a * a + b * b); } #endregion } public enum SideToAttck { TopLeft, TopRight, BottomRight, BottomLeft } }
//--------------------------------------------------------------------- // <copyright file="ThreadSafeList.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Generic; using System.Threading; namespace System.Data.Common.Utils { internal sealed class ThreadSafeList<T> : IList<T> { private readonly ReaderWriterLockSlim _lock; private List<T> _list; internal ThreadSafeList() { _list = new List<T>(); _lock = new ReaderWriterLockSlim(); } public int Count { get { _lock.EnterReadLock(); int count; try { count = _list.Count; } finally { _lock.ExitReadLock(); } return count; } } public void Add(T item) { _lock.EnterWriteLock(); try { _list.Add(item); } finally { _lock.ExitWriteLock(); } } public T this[int index] { get { _lock.EnterReadLock(); T result; try { result = _list[index]; } finally { _lock.ExitReadLock(); } return result; } set { _lock.EnterWriteLock(); try { _list[index] = value; } finally { _lock.ExitWriteLock(); } } } public bool IsReadOnly { get { return false; } } public int IndexOf(T item) { _lock.EnterReadLock(); int result; try { result = _list.IndexOf(item); } finally { _lock.ExitReadLock(); } return result; } public void Insert(int index, T item) { _lock.EnterWriteLock(); try { _list.Insert(index, item); } finally { _lock.ExitWriteLock(); } } public void RemoveAt(int index) { _lock.EnterWriteLock(); try { _list.RemoveAt(index); } finally { _lock.ExitWriteLock(); } } public void Clear() { _lock.EnterWriteLock(); try { _list.Clear(); } finally { _lock.ExitWriteLock(); } } public bool Contains(T item) { _lock.EnterReadLock(); bool result; try { result = _list.Contains(item); } finally { _lock.ExitReadLock(); } return result; } public void CopyTo(T[] array, int arrayIndex) { _lock.EnterWriteLock(); try { _list.CopyTo(array, arrayIndex); } finally { _lock.ExitWriteLock(); } } public bool Remove(T item) { _lock.EnterWriteLock(); bool result; try { result = _list.Remove(item); } finally { _lock.ExitWriteLock(); } return result; } public IEnumerator<T> GetEnumerator() { _lock.EnterReadLock(); try { foreach (T value in _list) { yield return value; } } finally { _lock.ExitReadLock(); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
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 Mobet.Demo.ApiDocument.Areas.HelpPage.ModelDescriptions; using Mobet.Demo.ApiDocument.Areas.HelpPage.Models; namespace Mobet.Demo.ApiDocument.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); } } } }
// Copyright 2017 Google Inc. All rights reserved. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. using UnityEngine; using UnityEngine.EventSystems; using Gvr.Internal; using System; using System.Collections; using System.Collections.Generic; // Events to update the keyboard. // These values depend on C API keyboard values public enum GvrKeyboardEvent { /// Unknown error. GVR_KEYBOARD_ERROR_UNKNOWN = 0, /// The keyboard service could not be connected. This is usually due to the /// keyboard service not being installed. GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED = 1, /// No locale was found in the keyboard service. GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND = 2, /// The keyboard SDK tried to load dynamically but failed. This is usually due /// to the keyboard service not being installed or being out of date. GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED = 3, /// Keyboard becomes visible. GVR_KEYBOARD_SHOWN = 4, /// Keyboard becomes hidden. GVR_KEYBOARD_HIDDEN = 5, /// Text has been updated. GVR_KEYBOARD_TEXT_UPDATED = 6, /// Text has been committed. GVR_KEYBOARD_TEXT_COMMITTED = 7, }; // These values depend on C API keyboard values. public enum GvrKeyboardError { UNKNOWN = 0, SERVICE_NOT_CONNECTED = 1, NO_LOCALES_FOUND = 2, SDK_LOAD_FAILED = 3 }; // These values depend on C API keyboard values. public enum GvrKeyboardInputMode { DEFAULT = 0, NUMERIC = 1 }; // Handles keyboard state management such as hiding and displaying // the keyboard, directly modifying text and stereoscopic rendering. public class GvrKeyboard : MonoBehaviour { private static GvrKeyboard instance; private static IKeyboardProvider keyboardProvider; private KeyboardState keyboardState = new KeyboardState(); private IEnumerator keyboardUpdate; // Keyboard delegate types. public delegate void StandardCallback(); public delegate void EditTextCallback(string edit_text); public delegate void ErrorCallback(GvrKeyboardError err); public delegate void KeyboardCallback(IntPtr closure, GvrKeyboardEvent evt); // Private data and callbacks. private ErrorCallback errorCallback = null; private StandardCallback showCallback = null; private StandardCallback hideCallback = null; private EditTextCallback updateCallback = null; private EditTextCallback enterCallback = null; #if UNITY_HAS_GOOGLEVR // Which eye is currently being rendered. private bool isRight = false; #endif // UNITY_HAS_GOOGLEVR private bool isKeyboardHidden = false; private const float kExecuterWait = 0.01f; private static List<GvrKeyboardEvent> threadSafeCallbacks = new List<GvrKeyboardEvent>(); private static System.Object callbacksLock = new System.Object(); // Public parameters. public GvrKeyboardDelegateBase keyboardDelegate = null; public GvrKeyboardInputMode inputMode = GvrKeyboardInputMode.DEFAULT; public bool useRecommended = true; public float distance = 0; public string EditorText { get { return instance != null ? instance.keyboardState.editorText : string.Empty; } } public GvrKeyboardInputMode Mode { get { return instance != null ? instance.keyboardState.mode : GvrKeyboardInputMode.DEFAULT; } } public bool IsValid { get { return instance != null ? instance.keyboardState.isValid : false; } } public bool IsReady { get { return instance != null ? instance.keyboardState.isReady : false; } } public Matrix4x4 WorldMatrix { get { return instance != null ? instance.keyboardState.worldMatrix : Matrix4x4.zero; } } void Awake() { if (instance != null) { Debug.LogError("More than one GvrKeyboard instance was found in your scene. " + "Ensure that there is only one GvrKeyboard."); enabled = false; return; } instance = this; if (keyboardProvider == null) { keyboardProvider = KeyboardProviderFactory.CreateKeyboardProvider(this); } } void OnDestroy() { instance = null; } // Use this for initialization. void Start() { if (keyboardDelegate != null) { errorCallback = keyboardDelegate.OnKeyboardError; showCallback = keyboardDelegate.OnKeyboardShow; hideCallback = keyboardDelegate.OnKeyboardHide; updateCallback = keyboardDelegate.OnKeyboardUpdate; enterCallback = keyboardDelegate.OnKeyboardEnterPressed; keyboardDelegate.KeyboardHidden += KeyboardDelegate_KeyboardHidden; keyboardDelegate.KeyboardShown += KeyboardDelegate_KeyboardShown; } keyboardProvider.ReadState(keyboardState); if (IsValid) { if (keyboardProvider.Create(OnKeyboardCallback)) { keyboardProvider.SetInputMode(inputMode); } } else { Debug.LogError("Could not validate keyboard"); } } // Update per-frame data. void Update() { if (keyboardProvider == null) { return; } keyboardProvider.ReadState(keyboardState); if (IsReady) { // Reset position of keyboard. if (transform.hasChanged) { Show(); transform.hasChanged = false; } keyboardProvider.UpdateData(); } } // Use this function for procedural rendering // Gets called twice per frame, once for each eye. // On each frame, left eye renders before right eye so // we keep track of a boolean that toggles back and forth // between each eye. void OnRenderObject() { if (keyboardProvider == null || !IsReady) { return; } #if UNITY_HAS_GOOGLEVR Camera camera = Camera.current; if (camera && camera == Camera.main) { // Get current eye. Camera.StereoscopicEye camEye = isRight ? Camera.StereoscopicEye.Right : Camera.StereoscopicEye.Left; // Camera matrices. Matrix4x4 proj = camera.GetStereoProjectionMatrix(camEye); Matrix4x4 modelView = camera.GetStereoViewMatrix(camEye); // Camera viewport. Rect viewport = camera.pixelRect; // Render keyboard. keyboardProvider.Render((int) camEye, modelView, proj, viewport); // Swap. isRight = !isRight; } #else Debug.LogWarning("Keyboard is not supported in versions of Unity without the native integration"); #endif // !UNITY_HAS_GOOGLEVR } // Resets keyboard text. public void ClearText() { if (keyboardProvider != null) { keyboardProvider.EditorText = string.Empty; } } public void Show() { if (keyboardProvider == null) { return; } // Get user matrix. Quaternion fixRot = new Quaternion(transform.rotation.x * -1, transform.rotation.y * -1, transform.rotation.z, transform.rotation.w); Matrix4x4 modelMatrix = Matrix4x4.TRS(transform.position, fixRot, Vector3.one); Matrix4x4 mat = Matrix4x4.identity; Vector3 position = gameObject.transform.position; if (position.x == 0 && position.y == 0 && position.z == 0 && !useRecommended) { // Force use recommended to be true, otherwise keyboard won't show up. keyboardProvider.Show(mat, true, distance, modelMatrix); return; } // Matrix needs to be set only if we're not using the recommended one. // Uses the values of the keyboard gameobject transform as reported by Unity. If this is // the zero vector, parent it under another gameobject instead. if (!useRecommended) { mat = GetKeyboardObjectMatrix(position); } keyboardProvider.Show(mat, useRecommended, distance, modelMatrix); } public void Hide() { if (keyboardProvider != null) { keyboardProvider.Hide(); } } public void OnPointerClick(BaseEventData data) { if (isKeyboardHidden) { Show(); } } void OnEnable() { keyboardUpdate = Executer(); StartCoroutine(keyboardUpdate); } void OnDisable() { StopCoroutine(keyboardUpdate); } void OnApplicationPause(bool paused) { if (null == keyboardProvider) return; if (paused) { keyboardProvider.OnPause(); } else { keyboardProvider.OnResume(); } } IEnumerator Executer() { while (true) { yield return new WaitForSeconds(kExecuterWait); while (threadSafeCallbacks.Count > 0) { GvrKeyboardEvent keyboardEvent = threadSafeCallbacks[0]; PoolKeyboardCallbacks(keyboardEvent); lock (callbacksLock) { threadSafeCallbacks.RemoveAt(0); } } } } private void PoolKeyboardCallbacks(GvrKeyboardEvent keyboardEvent) { switch (keyboardEvent) { case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_UNKNOWN: errorCallback(GvrKeyboardError.UNKNOWN); break; case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED: errorCallback(GvrKeyboardError.SERVICE_NOT_CONNECTED); break; case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND: errorCallback(GvrKeyboardError.NO_LOCALES_FOUND); break; case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED: errorCallback(GvrKeyboardError.SDK_LOAD_FAILED); break; case GvrKeyboardEvent.GVR_KEYBOARD_SHOWN: showCallback(); break; case GvrKeyboardEvent.GVR_KEYBOARD_HIDDEN: hideCallback(); break; case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_UPDATED: updateCallback(keyboardProvider.EditorText); break; case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_COMMITTED: enterCallback(keyboardProvider.EditorText); break; } } private static void OnKeyboardCallback(IntPtr closure, GvrKeyboardEvent keyboardEvent) { lock (callbacksLock) { threadSafeCallbacks.Add(keyboardEvent); } } private void KeyboardDelegate_KeyboardShown(object sender, System.EventArgs e) { isKeyboardHidden = false; } private void KeyboardDelegate_KeyboardHidden(object sender, System.EventArgs e) { isKeyboardHidden = true; } // Returns a matrix populated by the keyboard's gameobject position. If the position is not // zero, but comes back as zero, parent this under another gameobject instead. private Matrix4x4 GetKeyboardObjectMatrix(Vector3 position) { // Set keyboard position based on this gameObject's position. float angleX = Mathf.Atan2(position.y, position.x); float kTanAngleX = Mathf.Tan(angleX); float newPosX = kTanAngleX * position.x; float angleY = Mathf.Atan2(position.x, position.y); float kTanAngleY = Mathf.Tan(angleY); float newPosY = kTanAngleY * position.y; float angleZ = Mathf.Atan2(position.y, position.z); float kTanAngleZ = Mathf.Tan(angleZ); float newPosZ = kTanAngleZ * position.z; Vector3 keyboardPosition = new Vector3(newPosX, newPosY, newPosZ); Vector3 lookPosition = Camera.main.transform.position; Quaternion rotation = Quaternion.LookRotation(lookPosition); Matrix4x4 mat = new Matrix4x4(); mat.SetTRS(keyboardPosition, rotation, position); // Set diagonal to identity if any of them are zero. if (mat[0, 0] == 0) { Vector4 row0 = mat.GetRow(0); mat.SetRow(0, new Vector4(1, row0.y, row0.z, row0.w)); } if (mat[1, 1] == 0) { Vector4 row1 = mat.GetRow(1); mat.SetRow(1, new Vector4(row1.x, 1, row1.z, row1.w)); } if (mat[2, 2] == 0) { Vector4 row2 = mat.GetRow(2); mat.SetRow(2, new Vector4(row2.x, row2.y, 1, row2.w)); } return mat; } }
// 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.Text; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.MethodInfos; using System.Reflection.Runtime.ParameterInfos; using System.Reflection.Runtime.CustomAttributes; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.PropertyInfos { // // The runtime's implementation of PropertyInfo's // [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimePropertyInfo : PropertyInfo, ISerializable, ITraceableTypeMember { // // propertyHandle - the "tkPropertyDef" that identifies the property. // definingType - the "tkTypeDef" that defined the field (this is where you get the metadata reader that created propertyHandle.) // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // protected RuntimePropertyInfo(RuntimeTypeInfo contextTypeInfo, RuntimeTypeInfo reflectedType) { ContextTypeInfo = contextTypeInfo; _reflectedType = reflectedType; } public sealed override bool CanRead { get { return Getter != null; } } public sealed override bool CanWrite { get { return Setter != null; } } public sealed override Type DeclaringType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_DeclaringType(this); #endif return ContextTypeInfo; } } public sealed override ParameterInfo[] GetIndexParameters() { ParameterInfo[] indexParameters = _lazyIndexParameters; if (indexParameters == null) { bool useGetter = CanRead; RuntimeMethodInfo accessor = (useGetter ? Getter : Setter); RuntimeParameterInfo[] runtimeMethodParameterInfos = accessor.RuntimeParameters; int count = runtimeMethodParameterInfos.Length; if (!useGetter) count--; // If we're taking the parameters off the setter, subtract one for the "value" parameter. if (count == 0) { _lazyIndexParameters = indexParameters = Array.Empty<ParameterInfo>(); } else { indexParameters = new ParameterInfo[count]; for (int i = 0; i < count; i++) { indexParameters[i] = RuntimePropertyIndexParameterInfo.GetRuntimePropertyIndexParameterInfo(this, runtimeMethodParameterInfos[i]); } _lazyIndexParameters = indexParameters; } } int numParameters = indexParameters.Length; if (numParameters == 0) return indexParameters; ParameterInfo[] result = new ParameterInfo[numParameters]; for (int i = 0; i < numParameters; i++) { result[i] = indexParameters[i]; } return result; } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); MemberInfoSerializationHolder.GetSerializationInfo(info, this); } public sealed override MethodInfo GetMethod { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_GetMethod(this); #endif return Getter; } } public sealed override Type[] GetOptionalCustomModifiers() => PropertyTypeHandle.GetCustomModifiers(ContextTypeInfo.TypeContext, optional: true); public sealed override Type[] GetRequiredCustomModifiers() => PropertyTypeHandle.GetCustomModifiers(ContextTypeInfo.TypeContext, optional: false); public sealed override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_GetValue(this, obj, index); #endif if (_lazyGetterInvoker == null) { if (!CanRead) throw new ArgumentException(); _lazyGetterInvoker = Getter.GetUncachedMethodInvoker(Array.Empty<RuntimeTypeInfo>(), this); } if (index == null) index = Array.Empty<Object>(); return _lazyGetterInvoker.Invoke(obj, index, binder, invokeAttr, culture); } public sealed override Module Module { get { return DefiningTypeInfo.Module; } } public sealed override String Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_Name(this); #endif return MetadataName; } } public sealed override Type PropertyType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_PropertyType(this); #endif TypeContext typeContext = ContextTypeInfo.TypeContext; return PropertyTypeHandle.Resolve(typeContext); } } public sealed override Type ReflectedType { get { return _reflectedType; } } public sealed override MethodInfo SetMethod { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_SetMethod(this); #endif return Setter; } } public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.PropertyInfo_SetValue(this, obj, value, index); #endif if (_lazySetterInvoker == null) { if (!CanWrite) throw new ArgumentException(); _lazySetterInvoker = Setter.GetUncachedMethodInvoker(Array.Empty<RuntimeTypeInfo>(), this); } Object[] arguments; if (index == null) { arguments = new Object[] { value }; } else { arguments = new Object[index.Length + 1]; for (int i = 0; i < index.Length; i++) { arguments[i] = index[i]; } arguments[index.Length] = value; } _lazySetterInvoker.Invoke(obj, arguments, binder, invokeAttr, culture); } public sealed override String ToString() { StringBuilder sb = new StringBuilder(30); TypeContext typeContext = ContextTypeInfo.TypeContext; sb.Append(PropertyTypeHandle.FormatTypeName(typeContext)); sb.Append(' '); sb.Append(this.Name); ParameterInfo[] indexParameters = this.GetIndexParameters(); if (indexParameters.Length != 0) { RuntimeParameterInfo[] indexRuntimeParameters = new RuntimeParameterInfo[indexParameters.Length]; for (int i = 0; i < indexParameters.Length; i++) indexRuntimeParameters[i] = (RuntimeParameterInfo)(indexParameters[i]); sb.Append(" ["); sb.Append(RuntimeMethodHelpers.ComputeParametersString(indexRuntimeParameters)); sb.Append(']'); } return sb.ToString(); } String ITraceableTypeMember.MemberName { get { return MetadataName; } } Type ITraceableTypeMember.ContainingType { get { return ContextTypeInfo; } } private RuntimeNamedMethodInfo Getter { get { RuntimeNamedMethodInfo getter = _lazyGetter; if (getter == null) { getter = GetPropertyMethod(PropertyMethodSemantics.Getter); if (getter == null) getter = RuntimeDummyMethodInfo.Instance; _lazyGetter = getter; } return object.ReferenceEquals(getter, RuntimeDummyMethodInfo.Instance) ? null : getter; } } private RuntimeNamedMethodInfo Setter { get { RuntimeNamedMethodInfo setter = _lazySetter; if (setter == null) { setter = GetPropertyMethod(PropertyMethodSemantics.Setter); if (setter == null) setter = RuntimeDummyMethodInfo.Instance; _lazySetter = setter; } return object.ReferenceEquals(setter, RuntimeDummyMethodInfo.Instance) ? null : setter; } } protected RuntimePropertyInfo WithDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return this; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. _debugName = MetadataName; } return this; } // Types that derive from RuntimePropertyInfo must implement the following public surface area members public abstract override PropertyAttributes Attributes { get; } public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; } public abstract override bool Equals(Object obj); public abstract override int GetHashCode(); public abstract override Object GetConstantValue(); public abstract override int MetadataToken { get; } /// <summary> /// Return a qualified handle that can be used to get the type of the property. /// </summary> protected abstract QSignatureTypeHandle PropertyTypeHandle { get; } protected enum PropertyMethodSemantics { Getter, Setter, } /// <summary> /// Override to return the Method that corresponds to the specified semantic. /// Return null if a method of the appropriate semantic does not exist /// </summary> protected abstract RuntimeNamedMethodInfo GetPropertyMethod(PropertyMethodSemantics whichMethod); /// <summary> /// Override to provide the metadata based name of a property. (Different from the Name /// property in that it does not go into the reflection trace logic.) /// </summary> protected abstract string MetadataName { get; } /// <summary> /// Return the DefiningTypeInfo as a RuntimeTypeInfo (instead of as a format specific type info) /// </summary> protected abstract RuntimeTypeInfo DefiningTypeInfo { get; } protected readonly RuntimeTypeInfo ContextTypeInfo; protected readonly RuntimeTypeInfo _reflectedType; private volatile MethodInvoker _lazyGetterInvoker = null; private volatile MethodInvoker _lazySetterInvoker = null; private volatile RuntimeNamedMethodInfo _lazyGetter; private volatile RuntimeNamedMethodInfo _lazySetter; private volatile ParameterInfo[] _lazyIndexParameters; private String _debugName; } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; using Hydra.Framework; using Hydra.Framework.Helpers; using Hydra.Framework.Java; using Hydra.Framework.Mapping.CoordinateSystems; using Hydra.Framework.Conversions; namespace Hydra.DomainModel { // //********************************************************************** /// <summary> /// Network Design (Antenas) Information Details /// </summary> //********************************************************************** // [Serializable] [DataContract(Namespace = CommonConstants.DATA_NAMESPACE)] [KnownType(typeof(InternalAPInterface))] [KnownType(typeof(InternalAntenna))] public class InternalAP : AbstractInternalData { #region Member Variables // //********************************************************************** /// <summary> /// Angle /// </summary> //********************************************************************** // [DataMember(Name = "Angle")] public float Angle { get; set; } // //********************************************************************** /// <summary> /// IP Address /// </summary> //********************************************************************** // [DataMember(Name = "IpAddress")] public string IpAddress { get; set; } // //********************************************************************** /// <summary> /// MAC Address /// </summary> //********************************************************************** // [DataMember(Name = "MacAddress")] public string MacAddress { get; set; } // //********************************************************************** /// <summary> /// Number Of Slots /// </summary> //********************************************************************** // [DataMember(Name = "NumOfSlots")] public int NumOfSlots { get; set; } // //********************************************************************** /// <summary> /// Switch StateName /// </summary> //********************************************************************** // [DataMember(Name = "SwitchName")] public string SwitchName { get; set; } // // ********************************************************************** /// <summary> /// Type of Access Point /// </summary> // ********************************************************************** // [DataMember(Name = "APType")] public int APType { get; set; } // //********************************************************************** /// <summary> /// List of Interfaces /// </summary> //********************************************************************** // [DataMember(Name = "InterfaceList")] public List<InternalAPInterface> InterfaceList { get; set; } // // ********************************************************************** /// <summary> /// Location Identifier /// </summary> // ********************************************************************** // [DataMember(Name = "LocationId")] public int LocationId { get; set; } #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="InternalAP"/> class. /// </summary> // ********************************************************************** // public InternalAP() : base(InternalLocationServiceType.Internal) { Log.Entry(); Log.Exit(); } // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:InternalAP"/> class. /// </summary> /// <param name="angle">The angle.</param> /// <param name="apType">Type of the ap.</param> /// <param name="changedOn">The changed on.</param> /// <param name="locationId">The location id.</param> /// <param name="ipAddress">The ip address.</param> /// <param name="macAddress">The mac address.</param> /// <param name="name">The name.</param> /// <param name="numOfSlots">The num of slots.</param> /// <param name="objectId">The object id.</param> /// <param name="parentId">The parent id.</param> /// <param name="switchName">StateName of the switch.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> //********************************************************************** // public InternalAP(float angle, int apType, DateTime changedOn, int locationId, string ipAddress, string macAddress, string name, int numOfSlots, int objectId, int parentId, string switchName, float x, float y, float z) : base(InternalLocationServiceType.Internal, objectId, parentId, changedOn, macAddress, string.Empty, x, y, z) { Log.Entry(angle, changedOn, ipAddress, macAddress, name); Angle = angle; APType = apType; IpAddress = IpAddress; MacAddress = macAddress; Name = name; NumOfSlots = numOfSlots; SwitchName = switchName; LocationId = locationId; InterfaceList = new List<InternalAPInterface>(); Log.Exit(); } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="InternalAP"/> class. /// </summary> /// <param name="angle">The angle.</param> /// <param name="apType">Type of the ap.</param> /// <param name="changedOn">The changed on.</param> /// <param name="locationId">The location id.</param> /// <param name="ipAddress">The ip address.</param> /// <param name="macAddress">The mac address.</param> /// <param name="name">The name.</param> /// <param name="numOfSlots">The num of slots.</param> /// <param name="objectId">The object id.</param> /// <param name="parentId">The parent id.</param> /// <param name="switchName">StateName of the switch.</param> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <param name="z">The z.</param> /// <param name="interfaceList">The interface list.</param> // ********************************************************************** // public InternalAP(float angle, int apType, DateTime changedOn, int locationId, string ipAddress, string macAddress, string name, int numOfSlots, int objectId, int parentId, string switchName, float x, float y, float z, List<InternalAPInterface> interfaceList) : base(InternalLocationServiceType.Internal, objectId, parentId, changedOn, macAddress, string.Empty, x, y, z) { Log.Entry(angle, changedOn, ipAddress, macAddress, name); Angle = angle; APType = apType; IpAddress = IpAddress; MacAddress = macAddress; Name = name; NumOfSlots = numOfSlots; SwitchName = switchName; LocationId = locationId; InterfaceList = interfaceList; Log.Exit(); } #endregion #region Properties #endregion #region Static Methods #endregion #region Private Methods #endregion } }
using TestUtils; using System.Collections.Generic; using NUnit.Framework; using GitHub.Unity; namespace UnitTests { [TestFixture] class StatusOutputProcessorTests : BaseOutputProcessorTests { [Test] public void ShouldParseDirtyWorkingTreeUntracked() { var output = new[] { "## master", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, "README.md", true), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, staged: true), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked), } }); } [Test] public void ShouldParseDirtyWorkingTreeTrackedAhead1Behind1() { var output = new[] { "## master...origin/master [ahead 1, behind 1]", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Behind = 1, Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, "README.md", true), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, staged: true), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked), } }); } [Test] public void ShouldParseDirtyWorkingTreeTrackedAhead1() { var output = new[] { "## master...origin/master [ahead 1]", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, "README.md", true), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, staged: true), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked), } }); } [Test] public void ShouldParseDirtyWorkingTreeTrackedBehind1() { var output = new[] { "## master...origin/master [behind 1]", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Behind = 1, Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, "README.md", true), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, staged: true), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked), } }); } [Test] public void ShouldParseDirtyWorkingTreeTracked() { var output = new[] { "## master...origin/master", " M GitHubVS.sln", "R README.md -> README2.md", " D deploy.cmd", @"A ""something added.txt""", "?? something.txt", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Entries = new List<GitStatusEntry> { new GitStatusEntry("GitHubVS.sln", TestRootPath + @"\GitHubVS.sln", null, GitFileStatus.Modified), new GitStatusEntry("README2.md", TestRootPath + @"\README2.md", null, GitFileStatus.Renamed, "README.md", true), new GitStatusEntry("deploy.cmd", TestRootPath + @"\deploy.cmd", null, GitFileStatus.Deleted), new GitStatusEntry("something added.txt", TestRootPath + @"\something added.txt", null, GitFileStatus.Added, staged: true), new GitStatusEntry("something.txt", TestRootPath + @"\something.txt", null, GitFileStatus.Untracked), } }); } [Test] public void ShouldParseCleanWorkingTreeUntracked() { var output = new[] { "## something", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "something", Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTrackedAhead1Behind1() { var output = new[] { "## master...origin/master [ahead 1, behind 1]", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Behind = 1, Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTrackedAhead1() { var output = new[] { "## master...origin/master [ahead 1]", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Ahead = 1, Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTrackedBehind1() { var output = new[] { "## master...origin/master [behind 1]", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Behind = 1, Entries = new List<GitStatusEntry>() }); } [Test] public void ShouldParseCleanWorkingTreeTracked() { var output = new[] { "## master...origin/master", null }; AssertProcessOutput(output, new GitStatus { LocalBranch = "master", RemoteBranch = "origin/master", Entries = new List<GitStatusEntry>() }); } private void AssertProcessOutput(IEnumerable<string> lines, GitStatus expected) { var gitObjectFactory = SubstituteFactory.CreateGitObjectFactory(TestRootPath); GitStatus? result = null; var outputProcessor = new StatusOutputProcessor(gitObjectFactory); outputProcessor.OnEntry += status => { result = status; }; foreach (var line in lines) { outputProcessor.LineReceived(line); } Assert.IsTrue(result.HasValue); result.Value.AssertEqual(expected); } } }
// 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.Hosting.Util; using System.Threading; using Microsoft.Internal; namespace System.Composition.Hosting.Core { /// <summary> /// Represents a node in the lifetime tree. A <see cref="LifetimeContext"/> is the unit of /// sharing for shared parts, controls the disposal of bound parts, and can be used to retrieve /// instances either as part of an existing <see cref="CompositionOperation"/> or as the basis of a new /// composition operation. An individual lifetime context can be marked to contain parts that are /// constrained by particular sharing boundaries. /// </summary> /// <remarks> /// Contains two pieces of _independently protected_ shared state. Shared part instances is /// lock-free-readable and does not result in issues if added to during disposal. It is protected /// by being locked itself. Activation logic is unavoidably called under this lock. /// Bound part instances is always protected, by locking [this], and should never be written to /// after disposal and so is set to null under a lock in Dispose(). If it were allowed it would result in /// disposable parts not being released. Dispose methods on parts are called outside the lock. /// </remarks> /// <seealso cref="Export{T}"/> public sealed class LifetimeContext : CompositionContext, IDisposable { private readonly LifetimeContext _root; private readonly LifetimeContext _parent; // Protects the two members holding shared instances private readonly object _sharingLock = new object(); private SmallSparseInitonlyArray _sharedPartInstances, _instancesUndergoingInitialization; // Protects the member holding bound instances. private readonly object _boundPartLock = new object(); private List<IDisposable> _boundPartInstances = new List<IDisposable>(0); private readonly string[] _sharingBoundaries; private readonly ExportDescriptorRegistry _partRegistry; private static int s_nextSharingId = -1; /// <summary> /// Generates an identifier that can be used to locate shared part instances. /// </summary> /// <returns>A new unique identifier.</returns> public static int AllocateSharingId() { return Interlocked.Increment(ref s_nextSharingId); } internal LifetimeContext(ExportDescriptorRegistry partRegistry, string[] sharingBoundaries) { _root = this; _sharingBoundaries = sharingBoundaries; _partRegistry = partRegistry; } internal LifetimeContext(LifetimeContext parent, string[] sharingBoundaries) { _parent = parent; _root = parent._root; _sharingBoundaries = sharingBoundaries; _partRegistry = parent._partRegistry; } /// <summary> /// Find the broadest lifetime context within all of the specified sharing boundaries. /// </summary> /// <param name="sharingBoundary">The sharing boundary to find a lifetime context within.</param> /// <returns>The broadest lifetime context within all of the specified sharing boundaries.</returns> /// <remarks>Currently, the root cannot be a boundary.</remarks> public LifetimeContext FindContextWithin(string sharingBoundary) { if (sharingBoundary == null) return _root; var toCheck = this; while (toCheck != null) { foreach (var implemented in toCheck._sharingBoundaries) { if (implemented == sharingBoundary) return toCheck; } toCheck = toCheck._parent; } // To generate acceptable error messages here we're going to need to pass in a description // of the component, or otherwise find a way to get one. throw ThrowHelper.CompositionException(SR.Format(SR.Component_NotCreatableOutsideSharingBoundary, sharingBoundary)); } /// <summary> /// Release the lifetime context and any disposable part instances /// that are bound to it. /// </summary> public void Dispose() { IEnumerable<IDisposable> toDispose = null; lock (_boundPartLock) { if (_boundPartInstances != null) { toDispose = _boundPartInstances; _boundPartInstances = null; } } if (toDispose != null) { foreach (var instance in toDispose) instance.Dispose(); } } /// <summary> /// Bind the lifetime of a disposable part to the current /// lifetime context. /// </summary> /// <param name="instance">The disposable part to bind.</param> public void AddBoundInstance(IDisposable instance) { lock (_boundPartLock) { if (_boundPartInstances == null) throw new ObjectDisposedException(ToString()); _boundPartInstances.Add(instance); } } /// <summary> /// Either retrieve an existing part instance with the specified sharing id, or /// create and share a new part instance using <paramref name="creator"/> within /// <paramref name="operation"/>. /// </summary> /// <param name="sharingId">Sharing id for the part in question.</param> /// <param name="operation">Operation in which to activate a new part instance if necessary.</param> /// <param name="creator">Activator that can activate a new part instance if necessary.</param> /// <returns>The part instance corresponding to <paramref name="sharingId"/> within this lifetime context.</returns> /// <remarks>This method is lock-free if the part instance already exists. If the part instance must be created, /// a lock will be taken that will serialize other writes via this method (concurrent reads will continue to /// be safe and lock-free). It is important that the composition, and thus lock acquisition, is strictly /// leaf-to-root in the lifetime tree.</remarks> public object GetOrCreate(int sharingId, CompositionOperation operation, CompositeActivator creator) { object result; if (_sharedPartInstances != null && _sharedPartInstances.TryGetValue(sharingId, out result)) return result; // Remains locked for the rest of the operation. operation.EnterSharingLock(_sharingLock); if (_sharedPartInstances == null) { _sharedPartInstances = new SmallSparseInitonlyArray(); _instancesUndergoingInitialization = new SmallSparseInitonlyArray(); } else if (_sharedPartInstances.TryGetValue(sharingId, out result)) { return result; } // Already being initialized _on the same thread_. if (_instancesUndergoingInitialization.TryGetValue(sharingId, out result)) return result; result = creator(this, operation); _instancesUndergoingInitialization.Add(sharingId, result); operation.AddPostCompositionAction(() => { _sharedPartInstances.Add(sharingId, result); }); return result; } /// <summary> /// Retrieve the single <paramref name="contract"/> instance from the /// <see cref="CompositionContext"/>. /// </summary> /// <param name="contract">The contract to retrieve.</param> /// <returns>An instance of the export.</returns> /// <param name="export">The export if available, otherwise, null.</param> /// <exception cref="CompositionFailedException" /> public override bool TryGetExport(CompositionContract contract, out object export) { ExportDescriptor defaultForExport; if (!_partRegistry.TryGetSingleForExport(contract, out defaultForExport)) { export = null; return false; } export = CompositionOperation.Run(this, defaultForExport.Activator); return true; } /// <summary> /// Describes this lifetime context. /// </summary> /// <returns>A string description.</returns> public override string ToString() { if (_parent == null) return "Root Lifetime Context"; if (_sharingBoundaries.Length == 0) return "Non-sharing Lifetime Context"; return "Boundary for " + string.Join(", ", _sharingBoundaries); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.AppService.Fluent { using HostNameBinding.UpdateDefinition; using Models; using ResourceManager.Fluent.Core; using ResourceManager.Fluent.Core.ResourceActions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using WebAppBase.Update; /// <summary> /// Implementation for HostNameBinding and its create and update interfaces. /// </summary> /// <typeparam name="Fluent">The fluent interface of the parent web app.</typeparam> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmFwcHNlcnZpY2UuaW1wbGVtZW50YXRpb24uSG9zdE5hbWVCaW5kaW5nSW1wbA== internal partial class HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> : IndexableWrapper<HostNameBindingInner>, ICreatable<IHostNameBinding>, IHostNameBinding, HostNameBinding.Definition.IDefinition<WebAppBase.Definition.IWithCreate<FluentT>>, IUpdateDefinition<IUpdate<FluentT>> where FluentImplT : WebAppBaseImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT>, FluentT where FluentT : class, IWebAppBase where DefAfterRegionT : class where DefAfterGroupT : class where UpdateT : class, IUpdate<FluentT> { private FluentImplT parent; private string domainName; private string name; string ICreatable<IHostNameBinding>.Name { get { return Name(); } } string IExternalChildResource<Microsoft.Azure.Management.AppService.Fluent.IHostNameBinding, Microsoft.Azure.Management.AppService.Fluent.IWebAppBase>.Id { get { return Id(); } } ///GENMHASH:6A2970A94B2DD4A859B00B9B9D9691AD:A96EEE048AFB7EAC724AC09421CBB824 public Region Region() { return parent.Region; } ///GENMHASH:4B19A5F1B35CA91D20F63FBB66E86252:783B8B84020BF7A1FA8A58B407A27A05 public IReadOnlyDictionary<string, string> Tags() { return Parent.Tags; } ///GENMHASH:4C616F44C9C4BFD93594B6D9092A394A:0AC8A05BCD3A6B7CBD7958C57BCC894F public string WebAppName() { return Inner.SiteName; } ///GENMHASH:6512D3749B75699084BD4F008D90C101:1006227322BF1ED668B3D3B04C2C1A00 public HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithSubDomain(string subDomain) { name = NormalizeHostNameBindingName(subDomain, domainName); return this; } ///GENMHASH:F340B9C68B7C557DDB54F615FEF67E89:0D9EEC636DF1E11A81923129881E6F92 public string RegionName() { return parent.RegionName; } ///GENMHASH:FD5D5A8D6904B467321E345BE1FA424E:8AB87020DE6C711CD971F3D80C33DD83 public IWebAppBase Parent { get { return parent; } } ///GENMHASH:F256BA36B49E86A329FE6E9053FAA2C2:30BCCB9C5D6F49D3148D3A9D412D6197 public HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithThirdPartyDomain(string domain) { Inner.HostNameType = Models.HostNameType.Verified; this.domainName = domain; return this; } ///GENMHASH:32A8B56FE180FA4429482D706189DEA2:9462BB1488F8B757A53382E31550B2EC public async Task<IHostNameBinding> CreateAsync(CancellationToken cancellationToken = default(CancellationToken)) { var hostNameBindingInner = parent is IDeploymentSlot ? await parent.Manager.Inner.WebApps.CreateOrUpdateHostNameBindingSlotAsync(parent.ResourceGroupName, ((IDeploymentSlot)parent).Parent.Name, name, Inner, parent.Name) : await parent.Manager.Inner.WebApps.CreateOrUpdateHostNameBindingAsync(parent.ResourceGroupName, parent.Name, name, Inner); SetInner(hostNameBindingInner); return this; } ///GENMHASH:8442F1C1132907DE46B62B277F4EE9B7:E3457FB289E9A7DFF460A938FF6FD7DA public string Type() { return Inner.Type; } ///GENMHASH:5E4C278C0FA45BB98AA6EAEE080D4953:FC16212D06A7CCEE646CE7693B370B6F public IHostNameBinding Create() { return Extensions.Synchronize(() => CreateAsync()); } ///GENMHASH:1AF7DCAA563064BE5F57020487ABA63B:9EB989BD7CA88C88EBCC64DAB83581CD private string NormalizeHostNameBindingName(string hostname, string domainName) { if (!hostname.EndsWith(domainName)) { hostname = hostname + "." + domainName; } if (hostname.StartsWith("@")) { hostname = hostname.Replace("@.", ""); } return hostname; } ///GENMHASH:027705B70337BE533ED77421800E496A:3479885A232C974264B5B36BDBB0BC94 public HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithDnsRecordType(CustomHostNameDnsRecordType hostNameDnsRecordType) { var regex = new Regex("([.\\w-]+)\\.([\\w-]+\\.\\w+)"); var matcher = regex.Match(name); if (hostNameDnsRecordType == CustomHostNameDnsRecordType.CName && !matcher.Success) { throw new ArgumentException("root hostname cannot be assigned with a CName record"); } Inner.CustomHostNameDnsRecordType = hostNameDnsRecordType; return this; } ///GENMHASH:391F429F2F6335F8A114F6E5D4A7CE4F:D5DE9C8F381EEA2FECB193111C19E3AD public string AzureResourceName() { return Inner.AzureResourceName; } ///GENMHASH:24340C987C56F99E226AF26D83E77627:7AF4C6011A58443A74EDBD12E2EA8E0D public AzureResourceType AzureResourceType() { return Inner.AzureResourceType.GetValueOrDefault(); } ///GENMHASH:405D133ADB31FC54FCFE6E63CC7CE6DF:528163E8A39CE260ED65B356ABCB872C internal HostNameBindingImpl(HostNameBindingInner innerObject, FluentImplT parent) : base(innerObject) { this.parent = parent; name = innerObject.Name; if (name != null && name.Contains("/")) { name = name.Replace(parent.Name + "/", ""); } } ///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:A3CF7B3DC953F353AAE8083D72F74056 public string Id() { return Inner.Id; } ///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:992852B5097545C1876518403FBE36D3 public FluentImplT Attach() { parent.WithHostNameBinding(this); return parent; } ///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:2436A145BB7A20817F8EDCB98EB71DCC public string Name() { return name; } ///GENMHASH:A701DC349A4F821FC206F08C4A471087:61F78AD55A4BB349399340E2341849F0 public HostNameType HostNameType() { return Inner.HostNameType.GetValueOrDefault(); } ///GENMHASH:3C4657168E780E36F1CE2B07D32C5B18:20A09597173832F7AFC3EB433FE6EE44 public string DomainId() { return Inner.DomainId; } ///GENMHASH:59BD08590AE4E08698EC46108AE16392:3DDC5ABFBDE5AEE9DE057925DDE8EFA7 public CustomHostNameDnsRecordType DnsRecordType() { return Inner.CustomHostNameDnsRecordType.GetValueOrDefault(); } ///GENMHASH:8F156E891E25FA23FCB8AE0E23601BEC:7FF0A8A46536F20F09EC2FE338F3B99E public HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> WithAzureManagedDomain(IAppServiceDomain domain) { Inner.DomainId = domain.Id; Inner.HostNameType = Models.HostNameType.Managed; domainName = domain.Name; return this; } ///GENMHASH:A50A011CA652E846C1780DCE98D171DE:3B4125CAAD58112F3DE1E3F8B2B754D5 public string HostName() { return Inner.Name; } ///GENMHASH:9E6C2387B371ABFFE71039FB9CDF745F:E5EF1EA4BA2D309DA43A37720754443C new public string ToString() { string suffix; if (AzureResourceType() == Models.AzureResourceType.TrafficManager) { suffix = ".Trafficmanager.Net"; } else { suffix = ".Azurewebsites.Net"; } return name + ": " + DnsRecordType() + " " + AzureResourceName() + suffix; } ///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:F1F7115B1E40CAAC3F18CBE220407AB0 public HostNameBindingImpl<FluentT, FluentImplT, DefAfterRegionT, DefAfterGroupT, UpdateT> Refresh() { if (parent is IDeploymentSlot) { SetInner(Extensions.Synchronize(() => parent.Manager.Inner.WebApps.GetHostNameBindingSlotAsync(Parent.ResourceGroupName, ((IDeploymentSlot)parent).Parent.Name, parent.Name, name))); } else { SetInner(Extensions.Synchronize(() => parent.Manager.Inner.WebApps.GetHostNameBindingAsync(parent.ResourceGroupName, parent.Name, name))); } return this; } IHostNameBinding IRefreshable<IHostNameBinding>.Refresh() { if (parent is IWebApp) { SetInner(Extensions.Synchronize(() => parent.Manager.Inner.WebApps.GetHostNameBindingAsync(parent.ResourceGroupName, parent.Name, Name()))); } else { SetInner(Extensions.Synchronize(() => parent.Manager.Inner.WebApps.GetHostNameBindingSlotAsync(parent.ResourceGroupName, ((IDeploymentSlot)parent).Parent.Name, parent.Name, Name()))); } return this; } public async Task<IHostNameBinding> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (parent is IWebApp) { SetInner(await parent.Manager.Inner.WebApps.GetHostNameBindingAsync(parent.ResourceGroupName, parent.Name, Name(), cancellationToken)); } else { SetInner(await parent.Manager.Inner.WebApps.GetHostNameBindingSlotAsync(parent.ResourceGroupName, ((IDeploymentSlot)parent).Parent.Name, parent.Name, Name(), cancellationToken)); } return this; } } }
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 PayStuffWeb.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; } } }
//------------------------------------------------------------------------------ // Microsoft Windows Presentation Foundation // Copyright (c) Microsoft Corporation, 2008 // // File: ShaderEffect.cs //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows; using System.Windows.Media; using System.IO; using System.Windows.Markup; using System.Windows.Media.Composition; using System.Windows.Media.Media3D; using System.Security; using System.Security.Permissions; using System.Runtime.InteropServices; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media.Effects { public abstract partial class ShaderEffect : Effect { /// <summary> /// Takes in content bounds, and returns the bounds of the rendered /// output of that content after the Effect is applied. /// </summary> internal override Rect GetRenderBounds(Rect contentBounds) { Point topLeft = new Point(); Point bottomRight = new Point(); topLeft.X = contentBounds.TopLeft.X - PaddingLeft; topLeft.Y = contentBounds.TopLeft.Y - PaddingTop; bottomRight.X = contentBounds.BottomRight.X + PaddingRight; bottomRight.Y = contentBounds.BottomRight.Y + PaddingBottom; return new Rect(topLeft, bottomRight); } /// <summary> /// Padding is used to specify that an effect's output texture is larger than its input /// texture in a specific direction, e.g. for a drop shadow effect. /// </summary> protected double PaddingTop { get { ReadPreamble(); return _topPadding; } set { WritePreamble(); if (value < 0.0) { throw new ArgumentOutOfRangeException("value", value, SR.Get(SRID.Effect_ShaderEffectPadding)); } else { _topPadding = value; RegisterForAsyncUpdateResource(); } WritePostscript(); } } /// <summary> /// Padding is used to specify that an effect's output texture is larger than its input /// texture in a specific direction, e.g. for a drop shadow effect. /// </summary> protected double PaddingBottom { get { ReadPreamble(); return _bottomPadding; } set { WritePreamble(); if (value < 0.0) { throw new ArgumentOutOfRangeException("value", value, SR.Get(SRID.Effect_ShaderEffectPadding)); } else { _bottomPadding = value; RegisterForAsyncUpdateResource(); } WritePostscript(); } } /// <summary> /// Padding is used to specify that an effect's output texture is larger than its input /// texture in a specific direction, e.g. for a drop shadow effect. /// </summary> protected double PaddingLeft { get { ReadPreamble(); return _leftPadding; } set { WritePreamble(); if (value < 0.0) { throw new ArgumentOutOfRangeException("value", value, SR.Get(SRID.Effect_ShaderEffectPadding)); } else { _leftPadding = value; RegisterForAsyncUpdateResource(); } WritePostscript(); } } /// <summary> /// Padding is used to specify that an effect's output texture is larger than its input /// texture in a specific direction, e.g. for a drop shadow effect. /// </summary> protected double PaddingRight { get { ReadPreamble(); return _rightPadding; } set { WritePreamble(); if (value < 0.0) { throw new ArgumentOutOfRangeException("value", value, SR.Get(SRID.Effect_ShaderEffectPadding)); } else { _rightPadding = value; RegisterForAsyncUpdateResource(); } WritePostscript(); } } /// <summary> /// To specify a shader constant register to set to the size of the /// destination. Default is -1, which means to not send any. Only /// intended to be set once, in the constructor, and will fail if set /// after the effect is initially processed. /// </summary> protected int DdxUvDdyUvRegisterIndex { get { ReadPreamble(); return _ddxUvDdyUvRegisterIndex; } set { WritePreamble(); _ddxUvDdyUvRegisterIndex = value; WritePostscript(); } } /// <summary> /// This method is invoked whenever the PixelShader property changes. /// </summary> private void PixelShaderPropertyChangedHook(DependencyPropertyChangedEventArgs e) { PixelShader oldShader = (PixelShader)e.OldValue; if (oldShader != null) { oldShader._shaderBytecodeChanged -= OnPixelShaderBytecodeChanged; } PixelShader newShader = (PixelShader)e.NewValue; if (newShader != null) { newShader._shaderBytecodeChanged += OnPixelShaderBytecodeChanged; } OnPixelShaderBytecodeChanged(PixelShader, null); } /// <summary> /// When the PixelShader's bytecode changes to a ps_2_0 shader, verify that registers only /// available in ps_3_0 are not being used. /// </summary> private void OnPixelShaderBytecodeChanged(object sender, EventArgs e) { PixelShader pixelShader = (PixelShader)sender; if (pixelShader != null && pixelShader.ShaderMajorVersion == 2 && pixelShader.ShaderMinorVersion == 0 && UsesPS30OnlyRegisters()) { throw new InvalidOperationException(SR.Get(SRID.Effect_20ShaderUsing30Registers)); } } private bool UsesPS30OnlyRegisters() { // int and bool registers are ps_3_0 only if (_intCount > 0 || _intRegisters != null || _boolCount > 0 || _boolRegisters != null) { return true; } // float registers 32 or above are ps_3_0 only if (_floatRegisters != null) { for (int i = PS_2_0_FLOAT_REGISTER_LIMIT; i < _floatRegisters.Count; i++) { if (_floatRegisters[i] != null) { return true; } } } // sampler registers 4 or above are ps_3_0 only // Note: it's really 16, but we use 4 because some cards have trouble with 16 samplers // being set. if (_samplerData != null) { for (int i = PS_2_0_SAMPLER_LIMIT; i < _samplerData.Count; i++) { if (_samplerData[i] != null) { return true; } } } return false; } /// <summary> /// Tells the Effect that the shader constant or sampler corresponding /// to the specified DependencyProperty needs to be updated. /// </summary> protected void UpdateShaderValue(DependencyProperty dp) { if (dp != null) { WritePreamble(); object val = this.GetValue(dp); var metadata = dp.GetMetadata(this); if (metadata != null) { var callback = metadata.PropertyChangedCallback; if (callback != null) { callback(this, new DependencyPropertyChangedEventArgs(dp, val, val)); } } WritePostscript(); } } /// <summary> /// Construct a PropertyChangedCallback which, when invoked, will result in the DP being /// associated with the specified shader constant register index. /// </summary> protected static PropertyChangedCallback PixelShaderConstantCallback(int floatRegisterIndex) { return (obj, args) => { ShaderEffect eff = obj as ShaderEffect; if (eff != null) { eff.UpdateShaderConstant(args.Property, args.NewValue, floatRegisterIndex); } }; } /// <summary> /// Construct a PropertyChangedCallback which, when invoked, will result /// in the DP being associated with the specified shader sampler /// register index. Expected to be called on a Brush-valued /// DependencyProperty. /// </summary> protected static PropertyChangedCallback PixelShaderSamplerCallback(int samplerRegisterIndex) { return PixelShaderSamplerCallback(samplerRegisterIndex, _defaultSamplingMode); } /// <summary> /// Construct a PropertyChangedCallback which, when invoked, will result /// in the DP being associated with the specified shader sampler /// register index. Expected to be called on a Brush-valued /// DependencyProperty. /// </summary> protected static PropertyChangedCallback PixelShaderSamplerCallback(int samplerRegisterIndex, SamplingMode samplingMode) { return (obj, args) => { ShaderEffect eff = obj as ShaderEffect; if (eff != null) { if (args.IsAValueChange) { eff.UpdateShaderSampler(args.Property, args.NewValue, samplerRegisterIndex, samplingMode); } } }; } /// <summary> /// Helper for defining Brush-valued DependencyProperties to associate with a /// sampler register in the PixelShader. /// </summary> protected static DependencyProperty RegisterPixelShaderSamplerProperty(string dpName, Type ownerType, int samplerRegisterIndex) { return RegisterPixelShaderSamplerProperty(dpName, ownerType, samplerRegisterIndex, _defaultSamplingMode); } /// <summary> /// Helper for defining Brush-valued DependencyProperties to associate with a /// sampler register in the PixelShader. /// </summary> protected static DependencyProperty RegisterPixelShaderSamplerProperty(string dpName, Type ownerType, int samplerRegisterIndex, SamplingMode samplingMode) { return DependencyProperty.Register(dpName, typeof(Brush), ownerType, new UIPropertyMetadata(Effect.ImplicitInput, PixelShaderSamplerCallback(samplerRegisterIndex, samplingMode))); } // Updates the shader constant referred to by the DP. Converts to the // form that the HLSL shaders want, and stores that value, since it will // be sent on every update. // We WritePreamble/Postscript here since this method is called by the user with the callback // created in PixelShaderConstantCallback. private void UpdateShaderConstant(DependencyProperty dp, object newValue, int registerIndex) { WritePreamble(); Type t = DetermineShaderConstantType(dp.PropertyType, PixelShader); if (t == null) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderConstantType, dp.PropertyType.Name)); } else { // // Treat as a float constant in ps_2_0 by default // int registerMax = PS_2_0_FLOAT_REGISTER_LIMIT; string srid = SRID.Effect_Shader20ConstantRegisterLimit; if (PixelShader != null && PixelShader.ShaderMajorVersion >= 3) { // // If there's a ps_3_0 shader, the limit depends on the type // if (t == typeof(float)) { registerMax = PS_3_0_FLOAT_REGISTER_LIMIT; srid = SRID.Effect_Shader30FloatConstantRegisterLimit; } else if (t == typeof(int)) { registerMax = PS_3_0_INT_REGISTER_LIMIT; srid = SRID.Effect_Shader30IntConstantRegisterLimit; } else if (t == typeof(bool)) { registerMax = PS_3_0_BOOL_REGISTER_LIMIT; srid = SRID.Effect_Shader30BoolConstantRegisterLimit; } } if (registerIndex >= registerMax || registerIndex < 0) { throw new ArgumentException(SR.Get(srid), "dp"); } if (t == typeof(float)) { MilColorF fourTuple; ConvertValueToMilColorF(newValue, out fourTuple); StashInPosition(ref _floatRegisters, registerIndex, fourTuple, registerMax, ref _floatCount); } else if (t == typeof(int)) { MilColorI fourTuple; ConvertValueToMilColorI(newValue, out fourTuple); StashInPosition(ref _intRegisters, registerIndex, fourTuple, registerMax, ref _intCount); } else if (t == typeof(bool)) { StashInPosition(ref _boolRegisters, registerIndex, (bool)newValue, registerMax, ref _boolCount); } else { // We should have converted all acceptable types. Debug.Assert(false); } } // Propagate dirty this.PropertyChanged(dp); WritePostscript(); } // Updates the shader sampler referred to by the DP. Converts to the // form that the HLSL shaders want, and stores that value, since it will // be sent on every update. // We WritePreamble/Postscript here since this method is called by the user with the callback // created in PixelShaderSamplerCallback. private void UpdateShaderSampler(DependencyProperty dp, object newValue, int registerIndex, SamplingMode samplingMode) { WritePreamble(); if (newValue != null) { if (!(typeof(VisualBrush).IsInstanceOfType(newValue) || typeof(BitmapCacheBrush).IsInstanceOfType(newValue) || typeof(ImplicitInputBrush).IsInstanceOfType(newValue) || typeof(ImageBrush).IsInstanceOfType(newValue)) ) { // Note that if the type of the brush is ImplicitInputBrush and the value is non null, the value is actually // Effect.ImplicitInput. This is because ImplicitInputBrush is internal and the user can only get to the singleton // Effect.ImplicitInput. throw new ArgumentException(SR.Get(SRID.Effect_ShaderSamplerType), "dp"); } } // // Treat as ps_2_0 by default // int registerMax = PS_2_0_SAMPLER_LIMIT; string srid = SRID.Effect_Shader20SamplerRegisterLimit; if (PixelShader != null && PixelShader.ShaderMajorVersion >= 3) { registerMax = PS_3_0_SAMPLER_LIMIT; srid = SRID.Effect_Shader30SamplerRegisterLimit; } if (registerIndex >= registerMax || registerIndex < 0) { throw new ArgumentException(SR.Get(srid)); } SamplerData sd = new SamplerData() { _brush = (Brush)newValue, _samplingMode = samplingMode }; StashSamplerDataInPosition(registerIndex, sd, registerMax); // Propagate dirty this.PropertyChanged(dp); WritePostscript(); } // Ensures that list is extended to 'position', and that // the specified value is inserted there. For lists of value types. private static void StashInPosition<T>(ref List<T?> list, int position, T value, int maxIndex, ref uint count) where T : struct { if (list == null) { list = new List<T?>(maxIndex); } if (list.Count <= position) { int numToAdd = position - list.Count + 1; for (int i = 0; i < numToAdd; i++) { list.Add((T?)null); } } if (!list[position].HasValue) { // Going from null to having a value, so increment count count++; } list[position] = value; } // Ensures that _samplerData is extended to 'position', and that // the specified value is inserted there. private void StashSamplerDataInPosition(int position, SamplerData newSampler, int maxIndex) { if (_samplerData == null) { _samplerData = new List<SamplerData?>(maxIndex); } if (_samplerData.Count <= position) { int numToAdd = position - _samplerData.Count + 1; for (int i = 0; i < numToAdd; i++) { _samplerData.Add((SamplerData?)null); } } if (!_samplerData[position].HasValue) { // Going from null to having a value, so increment count _samplerCount++; } System.Windows.Threading.Dispatcher dispatcher = this.Dispatcher; // Release the old value if it is a resource on channel. AddRef the // new value. if (dispatcher != null) { SamplerData? oldSampler = _samplerData[position]; Brush oldBrush = null; if (oldSampler.HasValue) { SamplerData ss = oldSampler.Value; oldBrush = ss._brush; } Brush newBrush = newSampler._brush; DUCE.IResource targetResource = (DUCE.IResource)this; using (CompositionEngineLock.Acquire()) { int channelCount = targetResource.GetChannelCount(); for (int channelIndex = 0; channelIndex < channelCount; channelIndex++) { DUCE.Channel channel = targetResource.GetChannel(channelIndex); Debug.Assert(!channel.IsOutOfBandChannel); Debug.Assert(!targetResource.GetHandle(channel).IsNull); ReleaseResource(oldBrush,channel); AddRefResource(newBrush,channel); } } } _samplerData[position] = newSampler; } /// <SecurityNote> /// Critical: This code accesses unsafe code blocks /// TreatAsSafe: This code does is safe to call and calling a channel with pointers is ok /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void ManualUpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { // If we're told we can skip the channel check, then we must be on channel Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel)); if (skipOnChannelCheck || _duceResource.IsOnChannel(channel)) { if (PixelShader == null) { throw new InvalidOperationException(SR.Get(SRID.Effect_ShaderPixelShaderSet)); } checked { DUCE.MILCMD_SHADEREFFECT data; data.Type = MILCMD.MilCmdShaderEffect; data.Handle = _duceResource.GetHandle(channel); data.TopPadding = _topPadding; data.BottomPadding = _bottomPadding; data.LeftPadding = _leftPadding; data.RightPadding = _rightPadding; data.DdxUvDdyUvRegisterIndex = this.DdxUvDdyUvRegisterIndex; data.hPixelShader = ((DUCE.IResource)PixelShader).GetHandle(channel); unsafe { data.ShaderConstantFloatRegistersSize = (uint)(sizeof(Int16) * _floatCount); data.DependencyPropertyFloatValuesSize = (uint)(4 * sizeof(Single) * _floatCount); data.ShaderConstantIntRegistersSize = (uint)(sizeof(Int16) * _intCount); data.DependencyPropertyIntValuesSize = (uint)(4 * sizeof(Int32) * _intCount); data.ShaderConstantBoolRegistersSize = (uint)(sizeof(Int16) * _boolCount); // // Note: the multiply by 4 is not because the boolean register holds 4 // values, but to compensate for the difference between sizeof(bool) // in managed code (1) and sizeof(BOOL) in native code (4). // data.DependencyPropertyBoolValuesSize = (uint)(4 * sizeof(bool) * _boolCount); data.ShaderSamplerRegistrationInfoSize = (uint)(2 * sizeof(uint) * _samplerCount); // 2 pieces of data per sampler. data.DependencyPropertySamplerValuesSize = (uint)(1 * sizeof(DUCE.ResourceHandle) * _samplerCount); channel.BeginCommand( (byte*)&data, sizeof(DUCE.MILCMD_SHADEREFFECT), (int)(data.ShaderConstantFloatRegistersSize + data.DependencyPropertyFloatValuesSize + data.ShaderConstantIntRegistersSize + data.DependencyPropertyIntValuesSize + data.ShaderConstantBoolRegistersSize + data.DependencyPropertyBoolValuesSize + data.ShaderSamplerRegistrationInfoSize + data.DependencyPropertySamplerValuesSize ) ); // Arrays appear in this order: // 1) float register indices // 2) float dp values // 3) int register indices // 4) int dp values // 5) bool register indices // 6) bool dp values // 7) sampler registration info // 8) sampler dp values // 1) float register indices AppendRegisters(channel, _floatRegisters); // 2) float dp values if (_floatRegisters != null) { for (int i = 0; i < _floatRegisters.Count; i++) { MilColorF? v = _floatRegisters[i]; if (v.HasValue) { MilColorF valueToPush = v.Value; channel.AppendCommandData((byte*)&valueToPush, sizeof(MilColorF)); } } } // 3) int register indices AppendRegisters(channel, _intRegisters); // 4) int dp values if (_intRegisters != null) { for (int i = 0; i < _intRegisters.Count; i++) { MilColorI? v = _intRegisters[i]; if (v.HasValue) { MilColorI valueToPush = v.Value; channel.AppendCommandData((byte*)&valueToPush, sizeof(MilColorI)); } } } // 5) bool register indices AppendRegisters(channel, _boolRegisters); // 6) bool dp values if (_boolRegisters != null) { for (int i = 0; i < _boolRegisters.Count; i++) { bool? v = _boolRegisters[i]; if (v.HasValue) { // // Note: need 4 bytes for the bool, because the render thread // unmarshals it into a 4-byte BOOL. See the comment above for // DependencyPropertyBoolValuesSize for more details. // Int32 valueToPush = v.Value ? 1 : 0; channel.AppendCommandData((byte*)&valueToPush, sizeof(Int32)); } } } // 7) sampler registration info if (_samplerCount > 0) { int count = _samplerData.Count; for (int i = 0; i < count; i++) { SamplerData? ssn = _samplerData[i]; if (ssn.HasValue) { SamplerData ss = ssn.Value; // add as a 2-tuple (SamplerRegisterIndex, // SamplingMode) channel.AppendCommandData((byte*)&i, sizeof(int)); int value = (int)(ss._samplingMode); channel.AppendCommandData((byte*)&value, sizeof(int)); } } } // 8) sampler dp values if (_samplerCount > 0) { for (int i = 0; i < _samplerData.Count; i++) { SamplerData? ssn = _samplerData[i]; if (ssn.HasValue) { SamplerData ss = ssn.Value; // Making this assumption by storing a collection of // handles as an Int32Collection Debug.Assert(sizeof(DUCE.ResourceHandle) == sizeof(Int32)); DUCE.ResourceHandle hBrush = ss._brush != null ? ((DUCE.IResource)ss._brush).GetHandle(channel) : DUCE.ResourceHandle.Null; Debug.Assert(!hBrush.IsNull || ss._brush == null, "If brush isn't null, hBrush better not be"); channel.AppendCommandData((byte*)&hBrush, sizeof(DUCE.ResourceHandle)); } } } // That's it... channel.EndCommand(); } } } } // write the non-null values of the list of nullables to the command data. /// <SecurityNote> /// Critical: This code accesses unsafe code blocks /// TreatAsSafe: This code does is safe to call and calling a channel with pointers is ok /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] private void AppendRegisters<T>(DUCE.Channel channel, List<T?> list) where T : struct { if (list != null) { unsafe { for (int i = 0; i < list.Count; i++) { T? v = list[i]; if (v.HasValue) { Int16 regIndex = (Int16)i; // put onto stack so next &-operator compiles channel.AppendCommandData((byte*)&regIndex, sizeof(Int16)); } } } } } // Written by hand to include management of input Brushes (which aren't DPs). internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_SHADEREFFECT)) { // Ensures brushes are property instantiated into Duce resources. if (_samplerCount > 0) { int numSamplers = _samplerData.Count; for (int i = 0; i < numSamplers; i++) { SamplerData? ssn = _samplerData[i]; if (ssn.HasValue) { SamplerData ss = ssn.Value; DUCE.IResource brush = ss._brush as DUCE.IResource; if (brush != null) { brush.AddRefOnChannel(channel); } } } } PixelShader vPixelShader = PixelShader; if (vPixelShader != null) ((DUCE.IResource)vPixelShader).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } // Written by hand to include management of input Brushes (which aren't DPs). internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { // Ensure that brushes are released. if (_samplerCount > 0) { int numSamplers = _samplerData.Count; for (int i = 0; i < numSamplers; i++) { SamplerData? ssn = _samplerData[i]; if (ssn.HasValue) { SamplerData ss = ssn.Value; DUCE.IResource brush = ss._brush as DUCE.IResource; if (brush != null) { brush.ReleaseOnChannel(channel); } } } } PixelShader vPixelShader = PixelShader; if (vPixelShader != null) ((DUCE.IResource)vPixelShader).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } // Shader constants can be coerced into 4-tuples of floats in ps_2_0. Ints and bools are // also supported in ps_3_0. internal static Type DetermineShaderConstantType(Type type, PixelShader pixelShader) { Type result = null; if (type == typeof(double) || type == typeof(float) || type == typeof(Color) || type == typeof(Point) || type == typeof(Size) || type == typeof(Vector) || type == typeof(Point3D) || type == typeof(Vector3D) || type == typeof(Point4D)) { result = typeof(float); } else if (pixelShader != null && pixelShader.ShaderMajorVersion >= 3) { // // int and bool are also supported by ps_3_0. // if (type == typeof(int) || type == typeof(uint) || type == typeof(byte) || type == typeof(sbyte) || type == typeof(long) || type == typeof(ulong) || type == typeof(short) || type == typeof(ushort) || type == typeof(char)) { result = typeof(int); } else if (type == typeof(bool)) { result = typeof(bool); } } return result; } // Convert to float four tuple internal static void ConvertValueToMilColorF(object value, out MilColorF newVal) { Type t = value.GetType(); // Fill in four-tuples. Always fill in 1.0's for where there are // empty slots, to avoid division by zero on vector operations that // these values are subjected to. // Should order these in terms of most likely to be hit first. if (t == typeof(double) || t == typeof(float)) { float fVal = (t == typeof(double)) ? (float)(double)value : (float)value; // Scalars extend out to fill entire vector. newVal.r = newVal.g = newVal.b = newVal.a = fVal; } else if (t == typeof(Color)) { Color col = (Color)value; newVal.r = (float)col.R / 255f; newVal.g = (float)col.G / 255f; newVal.b = (float)col.B / 255f; newVal.a = (float)col.A / 255f; } else if (t == typeof(Point)) { Point p = (Point)value; newVal.r = (float)p.X; newVal.g = (float)p.Y; newVal.b = 1f; newVal.a = 1f; } else if (t == typeof(Size)) { Size s = (Size)value; newVal.r = (float)s.Width; newVal.g = (float)s.Height; newVal.b = 1f; newVal.a = 1f; } else if (t == typeof(Vector)) { Vector v = (Vector)value; newVal.r = (float)v.X; newVal.g = (float)v.Y; newVal.b = 1f; newVal.a = 1f; } else if (t == typeof(Point3D)) { Point3D p = (Point3D)value; newVal.r = (float)p.X; newVal.g = (float)p.Y; newVal.b = (float)p.Z; newVal.a = 1f; } else if (t == typeof(Vector3D)) { Vector3D v = (Vector3D)value; newVal.r = (float)v.X; newVal.g = (float)v.Y; newVal.b = (float)v.Z; newVal.a = 1f; } else if (t == typeof(Point4D)) { Point4D p = (Point4D)value; newVal.r = (float)p.X; newVal.g = (float)p.Y; newVal.b = (float)p.Z; newVal.a = (float)p.W; } else { // We should never hit this case, since we check the type using DetermineShaderConstantType // before we call this method. Debug.Assert(false); newVal.r = newVal.b = newVal.g = newVal.a = 1f; } } // Convert to int four tuple internal static void ConvertValueToMilColorI(object value, out MilColorI newVal) { Type t = value.GetType(); // Fill in four-tuples. Always fill in 1's for where there are // empty slots, to avoid division by zero on vector operations that // these values are subjected to. int iVal = 1; // // Note: conversions from long/ulong/uint can change the sign of the number // if (t == typeof(long)) { iVal = (int)(long)value; } else if (t == typeof(ulong)) { iVal = (int)(ulong)value; } else if (t == typeof(uint)) { iVal = (int)(uint)value; } else if (t == typeof(short)) { iVal = (int)(short)value; } else if (t == typeof(ushort)) { iVal = (int)(ushort)value; } else if (t == typeof(byte)) { iVal = (int)(byte)value; } else if (t == typeof(sbyte)) { iVal = (int)(sbyte)value; } else if (t == typeof(char)) { iVal = (int)(char)value; } else { iVal = (int)value; } // Scalars extend out to fill entire vector. newVal.r = newVal.g = newVal.b = newVal.a = iVal; } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(Freezable)">Freezable.CloneCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void CloneCore(Freezable sourceFreezable) { ShaderEffect effect = (ShaderEffect)sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(effect); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { ShaderEffect effect = (ShaderEffect)sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(effect); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void GetAsFrozenCore(Freezable sourceFreezable) { ShaderEffect effect = (ShaderEffect)sourceFreezable; base.GetAsFrozenCore(sourceFreezable); CopyCommon(effect); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> /// <param name="sourceFreezable"></param> protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { ShaderEffect effect = (ShaderEffect)sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); CopyCommon(effect); } /// <summary> /// Clones values that do not have corresponding DPs. /// </summary> /// <param name="transform"></param> private void CopyCommon(ShaderEffect effect) { _topPadding = effect._topPadding; _bottomPadding = effect._bottomPadding; _leftPadding = effect._leftPadding; _rightPadding = effect._rightPadding; if (_floatRegisters != null) { _floatRegisters = new List<MilColorF?>(effect._floatRegisters); } if (_samplerData != null) { _samplerData = new List<SamplerData?>(effect._samplerData); } _floatCount = effect._floatCount; _samplerCount = effect._samplerCount; _ddxUvDdyUvRegisterIndex = effect._ddxUvDdyUvRegisterIndex; } private struct SamplerData { public Brush _brush; public SamplingMode _samplingMode; } private const SamplingMode _defaultSamplingMode = SamplingMode.Auto; // Instance data private double _topPadding = 0.0; private double _bottomPadding = 0.0; private double _leftPadding = 0.0; private double _rightPadding = 0.0; private List<MilColorF?> _floatRegisters = null; private List<MilColorI?> _intRegisters = null; private List<bool?> _boolRegisters = null; private List<SamplerData?> _samplerData = null; private uint _floatCount = 0; private uint _intCount = 0; private uint _boolCount = 0; private uint _samplerCount = 0; private int _ddxUvDdyUvRegisterIndex = -1; private const int PS_2_0_FLOAT_REGISTER_LIMIT = 32; private const int PS_3_0_FLOAT_REGISTER_LIMIT = 224; private const int PS_3_0_INT_REGISTER_LIMIT = 16; private const int PS_3_0_BOOL_REGISTER_LIMIT = 16; // ps_2_0 allows max 16, but some cards seem to have trouble with 16 samplers being set. // Restricting to 4 for now. private const int PS_2_0_SAMPLER_LIMIT = 4; private const int PS_3_0_SAMPLER_LIMIT = 8; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Globalization; using System.Runtime.ExceptionServices; using System.Threading.Tasks; namespace System.Net { internal class StreamFramer { private Stream _transport; private bool _eof; private FrameHeader _writeHeader = new FrameHeader(); private FrameHeader _curReadHeader = new FrameHeader(); private FrameHeader _readVerifier = new FrameHeader( FrameHeader.IgnoreValue, FrameHeader.IgnoreValue, FrameHeader.IgnoreValue); private byte[] _readHeaderBuffer; private byte[] _writeHeaderBuffer; private readonly AsyncCallback _readFrameCallback; private readonly AsyncCallback _beginWriteCallback; public StreamFramer(Stream Transport) { if (Transport == null || Transport == Stream.Null) { throw new ArgumentNullException(nameof(Transport)); } _transport = Transport; _readHeaderBuffer = new byte[_curReadHeader.Size]; _writeHeaderBuffer = new byte[_writeHeader.Size]; _readFrameCallback = new AsyncCallback(ReadFrameCallback); _beginWriteCallback = new AsyncCallback(BeginWriteCallback); } public FrameHeader ReadHeader { get { return _curReadHeader; } } public FrameHeader WriteHeader { get { return _writeHeader; } } public Stream Transport { get { return _transport; } } public byte[] ReadMessage() { if (_eof) { return null; } int offset = 0; byte[] buffer = _readHeaderBuffer; int bytesRead; while (offset < buffer.Length) { bytesRead = Transport.Read(buffer, offset, buffer.Length - offset); if (bytesRead == 0) { if (offset == 0) { // m_Eof, return null _eof = true; return null; } else { throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed))); } } offset += bytesRead; } _curReadHeader.CopyFrom(buffer, 0, _readVerifier); if (_curReadHeader.PayloadSize > _curReadHeader.MaxMessageSize) { throw new InvalidOperationException(SR.Format(SR.net_frame_size, _curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), _curReadHeader.PayloadSize.ToString(NumberFormatInfo.InvariantInfo))); } buffer = new byte[_curReadHeader.PayloadSize]; offset = 0; while (offset < buffer.Length) { bytesRead = Transport.Read(buffer, offset, buffer.Length - offset); if (bytesRead == 0) { throw new IOException(SR.Format(SR.net_io_readfailure, SR.Format(SR.net_io_connectionclosed))); } offset += bytesRead; } return buffer; } public IAsyncResult BeginReadMessage(AsyncCallback asyncCallback, object stateObject) { WorkerAsyncResult workerResult; if (_eof) { workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, null, 0, 0); workerResult.InvokeCallback(-1); return workerResult; } workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, _readHeaderBuffer, 0, _readHeaderBuffer.Length); IAsyncResult result = TaskToApm.Begin(_transport.ReadAsync(_readHeaderBuffer, 0, _readHeaderBuffer.Length), _readFrameCallback, workerResult); if (result.CompletedSynchronously) { ReadFrameComplete(result); } return workerResult; } private void ReadFrameCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is WorkerAsyncResult)) { NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } if (transportResult.CompletedSynchronously) { return; } WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; try { ReadFrameComplete(transportResult); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } if (!(e is IOException)) { e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e); } workerResult.InvokeCallback(e); } } // IO COMPLETION CALLBACK // // This callback is responsible for getting the complete protocol frame. // 1. it reads the header. // 2. it determines the frame size. // 3. loops while not all frame received or an error. // private void ReadFrameComplete(IAsyncResult transportResult) { do { if (!(transportResult.AsyncState is WorkerAsyncResult)) { NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; int bytesRead = TaskToApm.End<int>(transportResult); workerResult.Offset += bytesRead; if (!(workerResult.Offset <= workerResult.End)) { NetEventSource.Fail(this, $"WRONG: offset - end = {workerResult.Offset - workerResult.End}"); } if (bytesRead <= 0) { // (by design) This indicates the stream has receives EOF // If we are in the middle of a Frame - fail, otherwise - produce EOF object result = null; if (!workerResult.HeaderDone && workerResult.Offset == 0) { result = (object)-1; } else { result = new System.IO.IOException(SR.net_frame_read_io); } workerResult.InvokeCallback(result); return; } if (workerResult.Offset >= workerResult.End) { if (!workerResult.HeaderDone) { workerResult.HeaderDone = true; // This indicates the header has been read successfully _curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier); int payloadSize = _curReadHeader.PayloadSize; if (payloadSize < 0) { // Let's call user callback and he call us back and we will throw workerResult.InvokeCallback(new System.IO.IOException(SR.Format(SR.net_frame_read_size))); } if (payloadSize == 0) { // report empty frame (NOT eof!) to the caller, he might be interested in workerResult.InvokeCallback(0); return; } if (payloadSize > _curReadHeader.MaxMessageSize) { throw new InvalidOperationException(SR.Format(SR.net_frame_size, _curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), payloadSize.ToString(NumberFormatInfo.InvariantInfo))); } // Start reading the remaining frame data (note header does not count). byte[] frame = new byte[payloadSize]; // Save the ref of the data block workerResult.Buffer = frame; workerResult.End = frame.Length; workerResult.Offset = 0; // Transport.ReadAsync below will pickup those changes. } else { workerResult.HeaderDone = false; // Reset for optional object reuse. workerResult.InvokeCallback(workerResult.End); return; } } // This means we need more data to complete the data block. transportResult = TaskToApm.Begin(_transport.ReadAsync(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset), _readFrameCallback, workerResult); } while (transportResult.CompletedSynchronously); } // // User code will call this when workerResult gets signaled. // // On BeginRead, the user always gets back our WorkerAsyncResult. // The Result property represents either a number of bytes read or an // exception put by our async state machine. // public byte[] EndReadMessage(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; if (workerResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, typeof(WorkerAsyncResult).FullName), nameof(asyncResult)); } if (!workerResult.InternalPeekCompleted) { workerResult.InternalWaitForCompletion(); } if (workerResult.Result is Exception e) { ExceptionDispatchInfo.Capture(e).Throw(); } int size = (int)workerResult.Result; if (size == -1) { _eof = true; return null; } else if (size == 0) { // Empty frame. return Array.Empty<byte>(); } return workerResult.Buffer; } public void WriteMessage(byte[] message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } _writeHeader.PayloadSize = message.Length; _writeHeader.CopyTo(_writeHeaderBuffer, 0); Transport.Write(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length); if (message.Length == 0) { return; } Transport.Write(message, 0, message.Length); } public IAsyncResult BeginWriteMessage(byte[] message, AsyncCallback asyncCallback, object stateObject) { if (message == null) { throw new ArgumentNullException(nameof(message)); } _writeHeader.PayloadSize = message.Length; _writeHeader.CopyTo(_writeHeaderBuffer, 0); if (message.Length == 0) { return TaskToApm.Begin(_transport.WriteAsync(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length), asyncCallback, stateObject); } // Will need two async writes. Prepare the second: WorkerAsyncResult workerResult = new WorkerAsyncResult(this, stateObject, asyncCallback, message, 0, message.Length); // Charge the first: IAsyncResult result = TaskToApm.Begin(_transport.WriteAsync(_writeHeaderBuffer, 0, _writeHeaderBuffer.Length), _beginWriteCallback, workerResult); if (result.CompletedSynchronously) { BeginWriteComplete(result); } return workerResult; } private void BeginWriteCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is WorkerAsyncResult)) { NetEventSource.Fail(this, $"The state expected to be WorkerAsyncResult, received {transportResult}."); } if (transportResult.CompletedSynchronously) { return; } var workerResult = (WorkerAsyncResult)transportResult.AsyncState; try { BeginWriteComplete(transportResult); } catch (Exception e) { if (e is OutOfMemoryException) { throw; } workerResult.InvokeCallback(e); } } // IO COMPLETION CALLBACK // // Called when user IO request was wrapped to do several underlined IO. // private void BeginWriteComplete(IAsyncResult transportResult) { do { WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState; // First, complete the previous portion write. TaskToApm.End(transportResult); // Check on exit criterion. if (workerResult.Offset == workerResult.End) { workerResult.InvokeCallback(); return; } // Setup exit criterion. workerResult.Offset = workerResult.End; // Write next portion (frame body) using Async IO. transportResult = TaskToApm.Begin(_transport.WriteAsync(workerResult.Buffer, 0, workerResult.End), _beginWriteCallback, workerResult); } while (transportResult.CompletedSynchronously); } public void EndWriteMessage(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } WorkerAsyncResult workerResult = asyncResult as WorkerAsyncResult; if (workerResult != null) { if (!workerResult.InternalPeekCompleted) { workerResult.InternalWaitForCompletion(); } if (workerResult.Result is Exception e) { ExceptionDispatchInfo.Capture(e).Throw(); } } else { TaskToApm.End(asyncResult); } } } // // This class wraps an Async IO request. It is based on our internal LazyAsyncResult helper. // - If ParentResult is not null then the base class (LazyAsyncResult) methods must not be used. // - If ParentResult == null, then real user IO request is wrapped. // internal class WorkerAsyncResult : LazyAsyncResult { public byte[] Buffer; public int Offset; public int End; public bool HeaderDone; // This might be reworked so we read both header and frame in one chunk. public WorkerAsyncResult(object asyncObject, object asyncState, AsyncCallback savedAsyncCallback, byte[] buffer, int offset, int end) : base(asyncObject, asyncState, savedAsyncCallback) { Buffer = buffer; Offset = offset; End = end; } } // Describes the header used in framing of the stream data. internal class FrameHeader { public const int IgnoreValue = -1; public const int HandshakeDoneId = 20; public const int HandshakeErrId = 21; public const int HandshakeId = 22; public const int DefaultMajorV = 1; public const int DefaultMinorV = 0; private int _MessageId; private int _MajorV; private int _MinorV; private int _PayloadSize; public FrameHeader() { _MessageId = HandshakeId; _MajorV = DefaultMajorV; _MinorV = DefaultMinorV; _PayloadSize = -1; } public FrameHeader(int messageId, int majorV, int minorV) { _MessageId = messageId; _MajorV = majorV; _MinorV = minorV; _PayloadSize = -1; } public int Size { get { return 5; } } public int MaxMessageSize { get { return 0xFFFF; } } public int MessageId { get { return _MessageId; } set { _MessageId = value; } } public int MajorV { get { return _MajorV; } } public int MinorV { get { return _MinorV; } } public int PayloadSize { get { return _PayloadSize; } set { if (value > MaxMessageSize) { throw new ArgumentException(SR.Format(SR.net_frame_max_size, MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo), value.ToString(NumberFormatInfo.InvariantInfo)), "PayloadSize"); } _PayloadSize = value; } } public void CopyTo(byte[] dest, int start) { dest[start++] = (byte)_MessageId; dest[start++] = (byte)_MajorV; dest[start++] = (byte)_MinorV; dest[start++] = (byte)((_PayloadSize >> 8) & 0xFF); dest[start] = (byte)(_PayloadSize & 0xFF); } public void CopyFrom(byte[] bytes, int start, FrameHeader verifier) { _MessageId = bytes[start++]; _MajorV = bytes[start++]; _MinorV = bytes[start++]; _PayloadSize = (int)((bytes[start++] << 8) | bytes[start]); if (verifier.MessageId != FrameHeader.IgnoreValue && MessageId != verifier.MessageId) { throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MessageId", MessageId, verifier.MessageId)); } if (verifier.MajorV != FrameHeader.IgnoreValue && MajorV != verifier.MajorV) { throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MajorV", MajorV, verifier.MajorV)); } if (verifier.MinorV != FrameHeader.IgnoreValue && MinorV != verifier.MinorV) { throw new InvalidOperationException(SR.Format(SR.net_io_header_id, "MinorV", MinorV, verifier.MinorV)); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The Regex class represents a single compiled instance of a regular // expression. using System; using System.Threading; using System.Collections; using System.Reflection; using System.Globalization; using System.Runtime.CompilerServices; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace System.Text.RegularExpressions { /// <summary> /// Represents an immutable, compiled regular expression. Also /// contains static methods that allow use of regular expressions without instantiating /// a Regex explicitly. /// </summary> public class Regex { internal string _pattern; // The string pattern provided internal RegexOptions _roptions; // the top-level options from the options string // *********** Match timeout fields { *********** // We need this because time is queried using Environment.TickCount for performance reasons // (Environment.TickCount returns millisecs as an int and cycles): private static readonly TimeSpan MaximumMatchTimeout = TimeSpan.FromMilliseconds(Int32.MaxValue - 1); // InfiniteMatchTimeout specifies that match timeout is switched OFF. It allows for faster code paths // compared to simply having a very large timeout. // We do not want to ask users to use System.Threading.Timeout.InfiniteTimeSpan as a parameter because: // (1) We do not want to imply any relation between having using a RegEx timeout and using multi-threading. // (2) We do not want to require users to take ref to a contract assembly for threading just to use RegEx. // There may in theory be a SKU that has RegEx, but no multithreading. // We create a public Regex.InfiniteMatchTimeout constant, which for consistency uses the save underlying // value as Timeout.InfiniteTimeSpan creating an implementation detail dependency only. public static readonly TimeSpan InfiniteMatchTimeout = Timeout.InfiniteTimeSpan; internal TimeSpan _internalMatchTimeout; // timeout for the execution of this regex // DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified // by one means or another. Typically, it is set to InfiniteMatchTimeout. internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout; // *********** } match timeout fields *********** internal Dictionary<Int32, Int32> _caps; // if captures are sparse, this is the hashtable capnum->index internal Dictionary<String, Int32> _capnames; // if named captures are used, this maps names->index internal String[] _capslist; // if captures are sparse or named captures are used, this is the sorted list of names internal int _capsize; // the size of the capture array internal ExclusiveReference _runnerref; // cached runner internal SharedReference _replref; // cached parsed replacement pattern internal RegexCode _code; // if interpreted, this is the code for RegexIntepreter internal bool _refsInitialized = false; internal static LinkedList<CachedCodeEntry> s_livecode = new LinkedList<CachedCodeEntry>();// the cache of code and factories that are currently loaded internal static int s_cacheSize = 15; internal const int MaxOptionShift = 10; protected Regex() { _internalMatchTimeout = DefaultMatchTimeout; } /// <summary> /// Creates and compiles a regular expression object for the specified regular /// expression. /// </summary> public Regex(String pattern) : this(pattern, RegexOptions.None, DefaultMatchTimeout, false) { } /// <summary> /// Creates and compiles a regular expression object for the /// specified regular expression with options that modify the pattern. /// </summary> public Regex(String pattern, RegexOptions options) : this(pattern, options, DefaultMatchTimeout, false) { } public Regex(String pattern, RegexOptions options, TimeSpan matchTimeout) : this(pattern, options, matchTimeout, false) { } private Regex(String pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache) { RegexTree tree; CachedCodeEntry cached = null; string cultureKey = null; if (pattern == null) throw new ArgumentNullException("pattern"); if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0) throw new ArgumentOutOfRangeException("options"); if ((options & RegexOptions.ECMAScript) != 0 && (options & ~(RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant #if DEBUG | RegexOptions.Debug #endif )) != 0) throw new ArgumentOutOfRangeException("options"); ValidateMatchTimeout(matchTimeout); // Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's // really no reason not to. if ((options & RegexOptions.CultureInvariant) != 0) cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)" else cultureKey = CultureInfo.CurrentCulture.ToString(); var key = new CachedCodeEntryKey(options, cultureKey, pattern); cached = LookupCachedAndUpdate(key); _pattern = pattern; _roptions = options; _internalMatchTimeout = matchTimeout; if (cached == null) { // Parse the input tree = RegexParser.Parse(pattern, _roptions); // Extract the relevant information _capnames = tree._capnames; _capslist = tree._capslist; _code = RegexWriter.Write(tree); _caps = _code._caps; _capsize = _code._capsize; InitializeReferences(); tree = null; if (useCache) cached = CacheCode(key); } else { _caps = cached._caps; _capnames = cached._capnames; _capslist = cached._capslist; _capsize = cached._capsize; _code = cached._code; _runnerref = cached._runnerref; _replref = cached._replref; _refsInitialized = true; } } // Note: "&lt;" is the XML entity for smaller ("<"). /// <summary> /// Validates that the specified match timeout value is valid. /// The valid range is <code>TimeSpan.Zero &lt; matchTimeout &lt;= Regex.MaximumMatchTimeout</code>. /// </summary> /// <param name="matchTimeout">The timeout value to validate.</param> /// <exception cref="System.ArgumentOutOfRangeException">If the specified timeout is not within a valid range. /// </exception> internal static void ValidateMatchTimeout(TimeSpan matchTimeout) { if (InfiniteMatchTimeout == matchTimeout) return; // Change this to make sure timeout is not longer then Environment.Ticks cycle length: if (TimeSpan.Zero < matchTimeout && matchTimeout <= MaximumMatchTimeout) return; throw new ArgumentOutOfRangeException("matchTimeout"); } /// <summary> /// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and /// whitespace) by replacing them with their \ codes. This converts a string so that /// it can be used as a constant within a regular expression safely. (Note that the /// reason # and whitespace must be escaped is so the string can be used safely /// within an expression parsed with x mode. If future Regex features add /// additional metacharacters, developers should depend on Escape to escape those /// characters as well.) /// </summary> public static String Escape(String str) { if (str == null) throw new ArgumentNullException("str"); return RegexParser.Escape(str); } /// <summary> /// Unescapes any escaped characters in the input string. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unescape", Justification = "Already shipped since v1 - can't fix without causing a breaking change")] public static String Unescape(String str) { if (str == null) throw new ArgumentNullException("str"); return RegexParser.Unescape(str); } [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")] public static int CacheSize { get { return s_cacheSize; } set { if (value < 0) throw new ArgumentOutOfRangeException("value"); s_cacheSize = value; if (s_livecode.Count > s_cacheSize) { lock (s_livecode) { while (s_livecode.Count > s_cacheSize) s_livecode.RemoveLast(); } } } } /// <summary> /// Returns the options passed into the constructor /// </summary> public RegexOptions Options { get { return _roptions; } } /// <summary> /// The match timeout used by this Regex instance. /// </summary> public TimeSpan MatchTimeout { get { return _internalMatchTimeout; } } /// <summary> /// Indicates whether the regular expression matches from right to left. /// </summary> public bool RightToLeft { get { return UseOptionR(); } } /// <summary> /// Returns the regular expression pattern passed into the constructor /// </summary> public override string ToString() { return _pattern; } /* * Returns an array of the group names that are used to capture groups * in the regular expression. Only needed if the regex is not known until * runtime, and one wants to extract captured groups. (Probably unusual, * but supplied for completeness.) */ /// <summary> /// Returns the GroupNameCollection for the regular expression. This collection contains the /// set of strings used to name capturing groups in the expression. /// </summary> public String[] GetGroupNames() { String[] result; if (_capslist == null) { int max = _capsize; result = new String[max]; for (int i = 0; i < max; i++) { result[i] = Convert.ToString(i, CultureInfo.InvariantCulture); } } else { result = new String[_capslist.Length]; System.Array.Copy(_capslist, 0, result, 0, _capslist.Length); } return result; } /* * Returns an array of the group numbers that are used to capture groups * in the regular expression. Only needed if the regex is not known until * runtime, and one wants to extract captured groups. (Probably unusual, * but supplied for completeness.) */ /// <summary> /// Returns the integer group number corresponding to a group name. /// </summary> public int[] GetGroupNumbers() { int[] result; if (_caps == null) { int max = _capsize; result = new int[max]; for (int i = 0; i < max; i++) { result[i] = i; } } else { result = new int[_caps.Count]; IDictionaryEnumerator de = _caps.GetEnumerator(); while (de.MoveNext()) { result[(int)de.Value] = (int)de.Key; } } return result; } /* * Given a group number, maps it to a group name. Note that nubmered * groups automatically get a group name that is the decimal string * equivalent of its number. * * Returns null if the number is not a recognized group number. */ /// <summary> /// Retrieves a group name that corresponds to a group number. /// </summary> public String GroupNameFromNumber(int i) { if (_capslist == null) { if (i >= 0 && i < _capsize) return i.ToString(CultureInfo.InvariantCulture); return String.Empty; } else { if (_caps != null) { if (!_caps.ContainsKey(i)) return String.Empty; i = _caps[i]; } if (i >= 0 && i < _capslist.Length) return _capslist[i]; return String.Empty; } } /* * Given a group name, maps it to a group number. Note that nubmered * groups automatically get a group name that is the decimal string * equivalent of its number. * * Returns -1 if the name is not a recognized group name. */ /// <summary> /// Returns a group number that corresponds to a group name. /// </summary> public int GroupNumberFromName(String name) { int result = -1; if (name == null) throw new ArgumentNullException("name"); // look up name if we have a hashtable of names if (_capnames != null) { if (!_capnames.ContainsKey(name)) return -1; return _capnames[name]; } // convert to an int if it looks like a number result = 0; for (int i = 0; i < name.Length; i++) { char ch = name[i]; if (ch > '9' || ch < '0') return -1; result *= 10; result += (ch - '0'); } // return int if it's in range if (result >= 0 && result < _capsize) return result; return -1; } /* * Static version of simple IsMatch call */ /// <summary> /// Searches the input string for one or more occurrences of the text supplied in the given pattern. /// </summary> public static bool IsMatch(String input, String pattern) { return IsMatch(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple IsMatch call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter with matching options supplied in the options /// parameter. /// </summary> public static bool IsMatch(String input, String pattern, RegexOptions options) { return IsMatch(input, pattern, options, DefaultMatchTimeout); } public static bool IsMatch(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).IsMatch(input); } /* * Returns true if the regex finds a match within the specified string */ /// <summary> /// Searches the input string for one or more matches using the previous pattern, /// options, and starting position. /// </summary> public bool IsMatch(String input) { if (input == null) throw new ArgumentNullException("input"); return IsMatch(input, UseOptionR() ? input.Length : 0); } /* * Returns true if the regex finds a match after the specified position * (proceeding leftward if the regex is leftward and rightward otherwise) */ /// <summary> /// Searches the input string for one or more matches using the previous pattern and options, /// with a new starting position. /// </summary> public bool IsMatch(String input, int startat) { if (input == null) throw new ArgumentNullException("input"); return (null == Run(true, -1, input, 0, input.Length, startat)); } /* * Static version of simple Match call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter. /// </summary> public static Match Match(String input, String pattern) { return Match(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Match call */ /// <summary> /// Searches the input string for one or more occurrences of the text /// supplied in the pattern parameter. Matching is modified with an option /// string. /// </summary> public static Match Match(String input, String pattern, RegexOptions options) { return Match(input, pattern, options, DefaultMatchTimeout); } public static Match Match(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Match(input); } /* * Finds the first match for the regular expression starting at the beginning * of the string (or at the end of the string if the regex is leftward) */ /// <summary> /// Matches a regular expression with a string and returns /// the precise result as a RegexMatch object. /// </summary> public Match Match(String input) { if (input == null) throw new ArgumentNullException("input"); return Match(input, UseOptionR() ? input.Length : 0); } /* * Finds the first match, starting at the specified position */ /// <summary> /// Matches a regular expression with a string and returns /// the precise result as a RegexMatch object. /// </summary> public Match Match(String input, int startat) { if (input == null) throw new ArgumentNullException("input"); return Run(false, -1, input, 0, input.Length, startat); } /* * Finds the first match, restricting the search to the specified interval of * the char array. */ /// <summary> /// Matches a regular expression with a string and returns the precise result as a /// RegexMatch object. /// </summary> public Match Match(String input, int beginning, int length) { if (input == null) throw new ArgumentNullException("input"); return Run(false, -1, input, beginning, length, UseOptionR() ? beginning + length : beginning); } /* * Static version of simple Matches call */ /// <summary> /// Returns all the successful matches as if Match were called iteratively numerous times. /// </summary> public static MatchCollection Matches(String input, String pattern) { return Matches(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Matches call */ /// <summary> /// Returns all the successful matches as if Match were called iteratively numerous times. /// </summary> public static MatchCollection Matches(String input, String pattern, RegexOptions options) { return Matches(input, pattern, options, DefaultMatchTimeout); } public static MatchCollection Matches(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Matches(input); } /* * Finds the first match for the regular expression starting at the beginning * of the string Enumerator(or at the end of the string if the regex is leftward) */ /// <summary> /// Returns all the successful matches as if Match was called iteratively numerous times. /// </summary> public MatchCollection Matches(String input) { if (input == null) throw new ArgumentNullException("input"); return Matches(input, UseOptionR() ? input.Length : 0); } /* * Finds the first match, starting at the specified position */ /// <summary> /// Returns all the successful matches as if Match was called iteratively numerous times. /// </summary> public MatchCollection Matches(String input, int startat) { if (input == null) throw new ArgumentNullException("input"); return new MatchCollection(this, input, 0, input.Length, startat); } /* * Static version of simple Replace call */ /// <summary> /// Replaces all occurrences of the pattern with the <paramref name="replacement"/> pattern, starting at /// the first character in the input string. /// </summary> public static String Replace(String input, String pattern, String replacement) { return Replace(input, pattern, replacement, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Replace call */ /// <summary> /// Replaces all occurrences of /// the <paramref name="pattern "/>with the <paramref name="replacement "/> /// pattern, starting at the first character in the input string. /// </summary> public static String Replace(String input, String pattern, String replacement, RegexOptions options) { return Replace(input, pattern, replacement, options, DefaultMatchTimeout); } public static String Replace(String input, String pattern, String replacement, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Replace(input, replacement); } /* * Does the replacement */ /// <summary> /// Replaces all occurrences of the <paramref name="pattern "/> with the /// <paramref name="replacement"/> pattern, starting at the /// first character in the input string, using the previous patten. /// </summary> public String Replace(String input, String replacement) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, replacement, -1, UseOptionR() ? input.Length : 0); } /* * Does the replacement */ /// <summary> /// Replaces all occurrences of the (previously defined) <paramref name="pattern "/>with the /// <paramref name="replacement"/> pattern, starting at the first character in the input string. /// </summary> public String Replace(String input, String replacement, int count) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, replacement, count, UseOptionR() ? input.Length : 0); } /* * Does the replacement */ /// <summary> /// Replaces all occurrences of the <paramref name="pattern "/>with the recent /// <paramref name="replacement"/> pattern, starting at the character position /// <paramref name="startat."/> /// </summary> public String Replace(String input, String replacement, int count, int startat) { if (input == null) throw new ArgumentNullException("input"); if (replacement == null) throw new ArgumentNullException("replacement"); // a little code to grab a cached parsed replacement object RegexReplacement repl = (RegexReplacement)_replref.Get(); if (repl == null || !repl.Pattern.Equals(replacement)) { repl = RegexParser.ParseReplacement(replacement, _caps, _capsize, _capnames, _roptions); _replref.Cache(repl); } return repl.Replace(this, input, count, startat); } /* * Static version of simple Replace call */ /// <summary> /// Replaces all occurrences of the <paramref name="pattern "/> with the /// <paramref name="replacement"/> pattern. /// </summary> public static String Replace(String input, String pattern, MatchEvaluator evaluator) { return Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Replace call */ /// <summary> /// Replaces all occurrences of the <paramref name="pattern "/> with the recent /// <paramref name="replacement"/> pattern, starting at the first character. /// </summary> public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options) { return Replace(input, pattern, evaluator, options, DefaultMatchTimeout); } public static String Replace(String input, String pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator); } /* * Does the replacement */ /// <summary> /// Replaces all occurrences of the <paramref name="pattern "/> with the recent /// <paramref name="replacement"/> pattern, starting at the first character /// position. /// </para> /// </summary> public String Replace(String input, MatchEvaluator evaluator) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, evaluator, -1, UseOptionR() ? input.Length : 0); } /* * Does the replacement */ /// <summary> /// Replaces all occurrences of the <paramref name="pattern "/>with the recent /// <paramref name="replacement"/> pattern, starting at the first character /// position. /// </summary> public String Replace(String input, MatchEvaluator evaluator, int count) { if (input == null) throw new ArgumentNullException("input"); return Replace(input, evaluator, count, UseOptionR() ? input.Length : 0); } /* * Does the replacement */ /// <summary> /// Replaces all occurrences of the (previouly defined) <paramref name="pattern "/>with /// the recent <paramref name="replacement"/> pattern, starting at the character /// position<paramref name=" startat"/>. /// </summary> public String Replace(String input, MatchEvaluator evaluator, int count, int startat) { if (input == null) throw new ArgumentNullException("input"); return RegexReplacement.Replace(evaluator, this, input, count, startat); } /* * Static version of simple Split call */ /// <summary> /// Splits the <paramref name="input "/>string at the position defined /// by <paramref name="pattern"/>. /// </summary> public static String[] Split(String input, String pattern) { return Split(input, pattern, RegexOptions.None, DefaultMatchTimeout); } /* * Static version of simple Split call */ /// <summary> /// Splits the <paramref name="input "/>string at the position defined by <paramref name="pattern"/>. /// </summary> public static String[] Split(String input, String pattern, RegexOptions options) { return Split(input, pattern, options, DefaultMatchTimeout); } public static String[] Split(String input, String pattern, RegexOptions options, TimeSpan matchTimeout) { return new Regex(pattern, options, matchTimeout, true).Split(input); } /* * Does a split */ /// <summary> /// Splits the <paramref name="input "/>string at the position defined by /// a previous <paramref name="pattern"/>. /// </summary> public String[] Split(String input) { if (input == null) throw new ArgumentNullException("input"); return Split(input, 0, UseOptionR() ? input.Length : 0); } /* * Does a split */ /// <summary> /// Splits the <paramref name="input "/>string at the position defined by a previous /// <paramref name="pattern"/>. /// </summary> public String[] Split(String input, int count) { if (input == null) throw new ArgumentNullException("input"); return RegexReplacement.Split(this, input, count, UseOptionR() ? input.Length : 0); } /* * Does a split */ /// <summary> /// Splits the <paramref name="input "/>string at the position defined by a previous /// <paramref name="pattern"/> . /// </summary> public String[] Split(String input, int count, int startat) { if (input == null) throw new ArgumentNullException("input"); return RegexReplacement.Split(this, input, count, startat); } internal void InitializeReferences() { if (_refsInitialized) throw new NotSupportedException(SR.OnlyAllowedOnce); _refsInitialized = true; _runnerref = new ExclusiveReference(); _replref = new SharedReference(); } /* * Internal worker called by all the public APIs */ internal Match Run(bool quick, int prevlen, String input, int beginning, int length, int startat) { Match match; RegexRunner runner = null; if (startat < 0 || startat > input.Length) throw new ArgumentOutOfRangeException("start", SR.BeginIndexNotNegative); if (length < 0 || length > input.Length) throw new ArgumentOutOfRangeException("length", SR.LengthNotNegative); // There may be a cached runner; grab ownership of it if we can. runner = (RegexRunner)_runnerref.Get(); // Create a RegexRunner instance if we need to if (runner == null) { runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture); } try { // Do the scan starting at the requested position match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, _internalMatchTimeout); } finally { // Release or fill the cache slot _runnerref.Release(runner); } #if DEBUG if (Debug && match != null) match.Dump(); #endif return match; } /* * Find code cache based on options+pattern */ private static CachedCodeEntry LookupCachedAndUpdate(CachedCodeEntryKey key) { lock (s_livecode) { for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next) { if (current.Value._key == key) { // If we find an entry in the cache, move it to the head at the same time. s_livecode.Remove(current); s_livecode.AddFirst(current); return current.Value; } } } return null; } /* * Add current code to the cache */ private CachedCodeEntry CacheCode(CachedCodeEntryKey key) { CachedCodeEntry newcached = null; lock (s_livecode) { // first look for it in the cache and move it to the head for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next) { if (current.Value._key == key) { s_livecode.Remove(current); s_livecode.AddFirst(current); return current.Value; } } // it wasn't in the cache, so we'll add a new one. Shortcut out for the case where cacheSize is zero. if (s_cacheSize != 0) { newcached = new CachedCodeEntry(key, _capnames, _capslist, _code, _caps, _capsize, _runnerref, _replref); s_livecode.AddFirst(newcached); if (s_livecode.Count > s_cacheSize) s_livecode.RemoveLast(); } } return newcached; } /* * True if the L option was set */ internal bool UseOptionR() { return (_roptions & RegexOptions.RightToLeft) != 0; } internal bool UseOptionInvariant() { return (_roptions & RegexOptions.CultureInvariant) != 0; } #if DEBUG /* * True if the regex has debugging enabled */ internal bool Debug { get { return (_roptions & RegexOptions.Debug) != 0; } } #endif } /* * Callback class */ public delegate String MatchEvaluator(Match match); /* * Used as a key for CacheCodeEntry */ internal struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey> { private readonly RegexOptions _options; private readonly string _cultureKey; private readonly string _pattern; internal CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern) { _options = options; _cultureKey = cultureKey; _pattern = pattern; } public override bool Equals(object obj) { return obj is CachedCodeEntryKey ? Equals((CachedCodeEntryKey)obj) : false; } public bool Equals(CachedCodeEntryKey other) { return this == other; } public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right) { return left._options == right._options && left._cultureKey == right._cultureKey && left._pattern == right._pattern; } public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right) { return !(left == right); } public override int GetHashCode() { return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode(); } } /* * Used to cache byte codes */ internal sealed class CachedCodeEntry { internal CachedCodeEntryKey _key; internal RegexCode _code; internal Dictionary<Int32, Int32> _caps; internal Dictionary<String, Int32> _capnames; internal String[] _capslist; internal int _capsize; internal ExclusiveReference _runnerref; internal SharedReference _replref; internal CachedCodeEntry(CachedCodeEntryKey key, Dictionary<String, Int32> capnames, String[] capslist, RegexCode code, Dictionary<Int32, Int32> caps, int capsize, ExclusiveReference runner, SharedReference repl) { _key = key; _capnames = capnames; _capslist = capslist; _code = code; _caps = caps; _capsize = capsize; _runnerref = runner; _replref = repl; } } /* * Used to cache one exclusive runner reference */ internal sealed class ExclusiveReference { private RegexRunner _ref; private Object _obj; private int _locked; /* * Return an object and grab an exclusive lock. * * If the exclusive lock can't be obtained, null is returned; * if the object can't be returned, the lock is released. * */ internal Object Get() { // try to obtain the lock if (0 == Interlocked.Exchange(ref _locked, 1)) { // grab reference Object obj = _ref; // release the lock and return null if no reference if (obj == null) { _locked = 0; return null; } // remember the reference and keep the lock _obj = obj; return obj; } return null; } /* * Release an object back to the cache * * If the object is the one that's under lock, the lock * is released. * * If there is no cached object, then the lock is obtained * and the object is placed in the cache. * */ internal void Release(Object obj) { if (obj == null) throw new ArgumentNullException("obj"); // if this reference owns the lock, release it if (_obj == obj) { _obj = null; _locked = 0; return; } // if no reference owns the lock, try to cache this reference if (_obj == null) { // try to obtain the lock if (0 == Interlocked.Exchange(ref _locked, 1)) { // if there's really no reference, cache this reference if (_ref == null) _ref = (RegexRunner)obj; // release the lock _locked = 0; return; } } } } /* * Used to cache a weak reference in a threadsafe way */ internal sealed class SharedReference { private WeakReference _ref = new WeakReference(null); private int _locked; /* * Return an object from a weakref, protected by a lock. * * If the exclusive lock can't be obtained, null is returned; * * Note that _ref.Target is referenced only under the protection * of the lock. (Is this necessary?) */ internal Object Get() { if (0 == Interlocked.Exchange(ref _locked, 1)) { Object obj = _ref.Target; _locked = 0; return obj; } return null; } /* * Suggest an object into a weakref, protected by a lock. * * Note that _ref.Target is referenced only under the protection * of the lock. (Is this necessary?) */ internal void Cache(Object obj) { if (0 == Interlocked.Exchange(ref _locked, 1)) { _ref.Target = obj; _locked = 0; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace imageupload.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal static class ContainedLanguageCodeSupport { public static bool IsValidId(Document document, string identifier) { var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); return syntaxFacts.IsValidIdentifier(identifier); } public static bool TryGetBaseClassName(Document document, string className, CancellationToken cancellationToken, out string baseClassName) { baseClassName = null; var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); if (type == null || type.BaseType == null) { return false; } baseClassName = type.BaseType.ToDisplayString(); return true; } public static string CreateUniqueEventName( Document document, string className, string objectName, string nameOfEvent, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var name = objectName + "_" + nameOfEvent; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var tree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeNode = type.DeclaringSyntaxReferences.Where(r => r.SyntaxTree == tree).Select(r => r.GetSyntax(cancellationToken)).First(); var codeModel = document.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var point = codeModel.GetStartPoint(typeNode, EnvDTE.vsCMPart.vsCMPartBody); var reservedNames = semanticModel.LookupSymbols(point.Value.Position, type).Select(m => m.Name); return NameGenerator.EnsureUniqueness(name, reservedNames, document.Project.LanguageServices.GetService<ISyntaxFactsService>().IsCaseSensitive); } /// <summary> /// Determine what methods of <paramref name=" className"/> could possibly be used as event /// handlers. /// </summary> /// <param name="document">The document containing <paramref name="className"/>.</param> /// <param name="className">The name of the type whose methods should be considered.</param> /// <param name="objectTypeName">The fully qualified name of the type containing a member /// that is an event. (E.g. "System.Web.Forms.Button")</param> /// <param name="nameOfEvent">The name of the member in <paramref name="objectTypeName"/> /// that is the event (E.g. "Clicked")</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The display name of the method, and a unique to for the method.</returns> public static IEnumerable<Tuple<string, string>> GetCompatibleEventHandlers( Document document, string className, string objectTypeName, string nameOfEvent, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = compilation.GetTypeByMetadataName(className); if (type == null) { throw new InvalidOperationException(); } var eventMember = GetEventSymbol(document, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var methods = type.GetMembers().OfType<IMethodSymbol>().Where(m => m.CompatibleSignatureToDelegate((INamedTypeSymbol)eventType)); return methods.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } public static string GetEventHandlerMemberId(Document document, string className, string objectTypeName, string nameOfEvent, string eventHandlerName, CancellationToken cancellationToken) { var nameAndId = GetCompatibleEventHandlers(document, className, objectTypeName, nameOfEvent, cancellationToken).SingleOrDefault(pair => pair.Item1 == eventHandlerName); return nameAndId == null ? null : nameAndId.Item2; } /// <summary> /// Ensure that an event handler exists for a given event. /// </summary> /// <param name="thisDocument">The document corresponding to this operation.</param> /// <param name="targetDocument">The document to generate the event handler in if it doesn't /// exist.</param> /// <param name="className">The name of the type to generate the event handler in.</param> /// <param name="objectName">The name of the event member (if <paramref /// name="useHandlesClause"/> is true)</param> /// <param name="objectTypeName">The name of the type containing the event.</param> /// <param name="nameOfEvent">The name of the event member in <paramref /// name="objectTypeName"/></param> /// <param name="eventHandlerName">The name of the method to be hooked up to the /// event.</param> /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event /// handler in.</param> /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the /// handler.</param> /// <param name="additionalFormattingRule">An additional formatting rule that can be used to /// format the newly inserted method</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Either the unique id of the method if it already exists, or the unique id of /// the to be generated method, the text of the to be generated method, and the position in /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns> public static Tuple<string, string, VsTextSpan> EnsureEventHandler( Document thisDocument, Document targetDocument, string className, string objectName, string objectTypeName, string nameOfEvent, string eventHandlerName, uint itemidInsertionPoint, bool useHandlesClause, IFormattingRule additionalFormattingRule, CancellationToken cancellationToken) { var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var type = thisCompilation.GetTypeByMetadataName(className); var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken); var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName); if (existingHandler != null) { return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan)); } // Okay, it doesn't exist yet. Let's create it. var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>(); var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>(); var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null) { throw new InvalidOperationException(ServicesVSResources.Event_type_is_invalid); } var handlesExpressions = useHandlesClause ? new[] { syntaxFactory.MemberAccessExpression( objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(), syntaxFactory.IdentifierName(nameOfEvent)) } : null; var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod; var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: null, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(), returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSpecialType(SpecialType.System_Void), explicitInterfaceSymbol: null, name: eventHandlerName, typeParameters: null, parameters: invokeMethod.Parameters.ToArray(), statements: null, handlesExpressions: handlesExpressions); var annotation = new SyntaxAnnotation(); newMethod = annotation.AddAnnotationToSymbol(newMethod); var codeModel = targetDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var syntaxFacts = targetDocument.Project.LanguageServices.GetService<ISyntaxFactsService>(); var targetSyntaxTree = targetDocument.GetSyntaxTreeSynchronously(cancellationToken); var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start; var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position); var insertionPoint = codeModel.GetEndPoint(destinationType, EnvDTE.vsCMPart.vsCMPartBody); if (insertionPoint == null) { throw new InvalidOperationException(ServicesVSResources.Can_t_find_where_to_insert_member); } var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken); var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType); newRoot = Simplifier.ReduceAsync( targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetSyntaxRootSynchronously(cancellationToken); var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); newRoot = Formatter.FormatAsync( newRoot, Formatter.Annotation, targetDocument.Project.Solution.Workspace, targetDocument.GetOptionsAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken), formattingRules, cancellationToken).WaitAndGetResult_Venus(cancellationToken); var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single(); var newMemberText = newMember.ToFullString(); // In VB, the final newline is likely a statement terminator in the parent - just add // one on so that things don't get messed. if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { newMemberText += Environment.NewLine; } return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan()); } public static bool TryGetMemberNavigationPoint( Document thisDocument, string className, string uniqueMemberID, out VsTextSpan textSpan, out Document targetDocument, CancellationToken cancellationToken) { targetDocument = null; textSpan = default(VsTextSpan); var type = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var member = LookupMemberId(type, uniqueMemberID); if (member == null) { return false; } var codeModel = thisDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var memberNode = member.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (memberNode != null) { var navigationPoint = codeModel.GetStartPoint(memberNode, EnvDTE.vsCMPart.vsCMPartNavigate); if (navigationPoint != null) { targetDocument = thisDocument.Project.Solution.GetDocument(memberNode.SyntaxTree); textSpan = navigationPoint.Value.ToVsTextSpan(); return true; } } return false; } /// <summary> /// Get the display names and unique ids of all the members of the given type in <paramref /// name="className"/>. /// </summary> public static IEnumerable<Tuple<string, string>> GetMembers( Document document, string className, CODEMEMBERTYPE codeMemberType, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(className); var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var allMembers = codeMemberType == CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS ? semanticModel.LookupSymbols(position: type.Locations[0].SourceSpan.Start, container: type, name: null) : type.GetMembers(); var members = allMembers.Where(m => IncludeMember(m, codeMemberType, compilation)); return members.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } /// <summary> /// Try to do a symbolic rename the specified symbol. /// </summary> /// <returns>False ONLY if it can't resolve the name. Other errors result in the normal /// exception being propagated.</returns> public static bool TryRenameElement( Document document, ContainedLanguageRenameType clrt, string oldFullyQualifiedName, string newFullyQualifiedName, IEnumerable<IRefactorNotifyService> refactorNotifyServices, CancellationToken cancellationToken) { var symbol = FindSymbol(document, clrt, oldFullyQualifiedName, cancellationToken); if (symbol == null) { return false; } if (Workspace.TryGetWorkspace(document.GetTextAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).Container, out var workspace)) { var newName = newFullyQualifiedName.Substring(newFullyQualifiedName.LastIndexOf('.') + 1); var optionSet = document.Project.Solution.Workspace.Options; var newSolution = Renamer.RenameSymbolAsync(document.Project.Solution, symbol, newName, optionSet, cancellationToken).WaitAndGetResult_Venus(cancellationToken); var changedDocuments = newSolution.GetChangedDocuments(document.Project.Solution); var undoTitle = string.Format(EditorFeaturesResources.Rename_0_to_1, symbol.Name, newName); using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoTitle)) { // Notify third parties about the coming rename operation on the workspace, and let // any exceptions propagate through refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); if (!workspace.TryApplyChanges(newSolution)) { Exceptions.ThrowEFail(); } // Notify third parties about the completed rename operation on the workspace, and // let any exceptions propagate through refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); workspaceUndoTransaction.Commit(); } RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); return true; } else { return false; } } private static bool IncludeMember(ISymbol member, CODEMEMBERTYPE memberType, Compilation compilation) { if (!member.CanBeReferencedByName) { return false; } switch (memberType) { case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS: // NOTE: the Dev10 C# codebase just returned if (member.Kind != SymbolKind.Method) { return false; } var method = (IMethodSymbol)member; if (!method.ReturnsVoid) { return false; } if (method.Parameters.Length != 2) { return false; } if (!method.Parameters[0].Type.Equals(compilation.ObjectType)) { return false; } if (!method.Parameters[1].Type.InheritsFromOrEquals(compilation.EventArgsType())) { return false; } return true; case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS: return member.Kind == SymbolKind.Event; case CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS: return member.Kind == SymbolKind.Method; default: throw new ArgumentException("InvalidValue", nameof(memberType)); } } private static ISymbol FindSymbol( Document document, ContainedLanguageRenameType renameType, string fullyQualifiedName, CancellationToken cancellationToken) { switch (renameType) { case ContainedLanguageRenameType.CLRT_CLASS: return document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(fullyQualifiedName); case ContainedLanguageRenameType.CLRT_CLASSMEMBER: var lastDot = fullyQualifiedName.LastIndexOf('.'); var typeName = fullyQualifiedName.Substring(0, lastDot); var memberName = fullyQualifiedName.Substring(lastDot + 1, fullyQualifiedName.Length - lastDot - 1); var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GetTypeByMetadataName(typeName); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var membersOfName = type.GetMembers(memberName); return membersOfName.SingleOrDefault(); case ContainedLanguageRenameType.CLRT_NAMESPACE: var ns = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken).GlobalNamespace; var parts = fullyQualifiedName.Split('.'); for (int i = 0; i < parts.Length && ns != null; i++) { ns = ns.GetNamespaceMembers().SingleOrDefault(n => n.Name == parts[i]); } return ns; case ContainedLanguageRenameType.CLRT_OTHER: throw new NotSupportedException(ServicesVSResources.Can_t_rename_other_elements); default: throw new InvalidOperationException(ServicesVSResources.Unknown_rename_type); } } internal static string ConstructMemberId(ISymbol member) { if (member.Kind == SymbolKind.Method) { return string.Format("{0}({1})", member.Name, string.Join(",", ((IMethodSymbol)member).Parameters.Select(p => p.Type.ToDisplayString()))); } else if (member.Kind == SymbolKind.Event) { return member.Name + "(EVENT)"; } else { throw new NotSupportedException(ServicesVSResources.IDs_are_not_supported_for_this_symbol_type); } } internal static ISymbol LookupMemberId(INamedTypeSymbol type, string uniqueMemberID) { var memberName = uniqueMemberID.Substring(0, uniqueMemberID.IndexOf('(')); var members = type.GetMembers(memberName).Where(m => m.Kind == SymbolKind.Method); foreach (var m in members) { if (ConstructMemberId(m) == uniqueMemberID) { return m; } } return null; } private static ISymbol GetEventSymbol( Document document, string objectTypeName, string nameOfEvent, INamedTypeSymbol type, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult_Venus(cancellationToken); var objectType = compilation.GetTypeByMetadataName(objectTypeName); if (objectType == null) { throw new InvalidOperationException(); } var containingTree = document.GetSyntaxTreeSynchronously(cancellationToken); var typeLocation = type.Locations.FirstOrDefault(d => d.SourceTree == containingTree); if (typeLocation == null) { throw new InvalidOperationException(); } return semanticModel.LookupSymbols(typeLocation.SourceSpan.Start, objectType, nameOfEvent).SingleOrDefault(m => m.Kind == SymbolKind.Event); } } }
// $ANTLR 3.3 Nov 30, 2010 12:45:30 D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g 2011-06-13 03:10:05 // The variable 'variable' is assigned but its value is never used. #pragma warning disable 219 // Unreachable code detected. #pragma warning disable 162 using System.Collections.Generic; using Antlr.Runtime; using Antlr.Runtime.Tree; namespace SheepAspectQueryAnalyzer.Engine.Parser { [System.CodeDom.Compiler.GeneratedCode("ANTLR", "3.3 Nov 30, 2010 12:45:30")] public partial class SaqaParser : Antlr.Runtime.Parser { internal static readonly string[] tokenNames = new string[] { "<invalid>", "<EOR>", "<DOWN>", "<UP>", "ID", "STRING", "COMMENT", "WS", "'='", "'['", "'('", "')'", "']'" }; public const int EOF = -1; public const int T__8 = 8; public const int T__9 = 9; public const int T__10 = 10; public const int T__11 = 11; public const int T__12 = 12; public const int ID = 4; public const int STRING = 5; public const int COMMENT = 6; public const int WS = 7; // delegates // delegators #if ANTLR_DEBUG private static readonly bool[] decisionCanBacktrack = new bool[] { false, // invalid decision false, false }; #else private static readonly bool[] decisionCanBacktrack = new bool[0]; #endif public SaqaParser(ITokenStream input) : this(input, new RecognizerSharedState()) { } public SaqaParser(ITokenStream input, RecognizerSharedState state) : base(input, state) { ITreeAdaptor treeAdaptor = null; CreateTreeAdaptor(ref treeAdaptor); TreeAdaptor = treeAdaptor ?? new CommonTreeAdaptor(); OnCreated(); } // Implement this function in your helper file to use a custom tree adaptor partial void CreateTreeAdaptor(ref ITreeAdaptor adaptor); private ITreeAdaptor adaptor; public ITreeAdaptor TreeAdaptor { get { return adaptor; } set { this.adaptor = value; } } public override string[] TokenNames { get { return SaqaParser.tokenNames; } } public override string GrammarFileName { get { return "D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g"; } } partial void OnCreated(); partial void EnterRule(string ruleName, int ruleIndex); partial void LeaveRule(string ruleName, int ruleIndex); #region Rules public class pointcuts_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<object> { public IEnumerable<PointcutExpression> values; private object _tree; public object Tree { get { return _tree; } set { _tree = value; } } object IAstRuleReturnScope.Tree { get { return Tree; } } } partial void Enter_pointcuts(); partial void Leave_pointcuts(); // $ANTLR start "pointcuts" // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:12:8: public pointcuts returns [IEnumerable<PointcutExpression> values] : (p= pointcut )* ; [GrammarRule("pointcuts")] public SaqaParser.pointcuts_return pointcuts() { Enter_pointcuts(); EnterRule("pointcuts", 1); TraceIn("pointcuts", 1); SaqaParser.pointcuts_return retval = new SaqaParser.pointcuts_return(); retval.Start = (IToken)input.LT(1); object root_0 = null; SaqaParser.pointcut_return p = default(SaqaParser.pointcut_return); var list = new List<PointcutExpression>(); try { DebugEnterRule(GrammarFileName, "pointcuts"); DebugLocation(12, 2); try { // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:14:2: ( (p= pointcut )* ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:14:4: (p= pointcut )* { root_0 = (object)adaptor.Nil(); DebugLocation(14, 4); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:14:4: (p= pointcut )* try { DebugEnterSubRule(1); while (true) { int alt1 = 2; try { DebugEnterDecision(1, decisionCanBacktrack[1]); int LA1_0 = input.LA(1); if ((LA1_0 == ID || LA1_0 == 9)) { alt1 = 1; } } finally { DebugExitDecision(1); } switch (alt1) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:14:5: p= pointcut { DebugLocation(14, 6); PushFollow(Follow._pointcut_in_pointcuts68); p = pointcut(); PopFollow(); adaptor.AddChild(root_0, p.Tree); DebugLocation(14, 16); list.Add((p != null ? p.value : default(PointcutExpression))); } break; default: goto loop1; } } loop1: ; } finally { DebugExitSubRule(1); } DebugLocation(15, 2); retval.values = list; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (object)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input, re); retval.Tree = (object)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("pointcuts", 1); LeaveRule("pointcuts", 1); Leave_pointcuts(); } DebugLocation(17, 2); } finally { DebugExitRule(GrammarFileName, "pointcuts"); } return retval; } // $ANTLR end "pointcuts" public class pointcut_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<object> { public PointcutExpression value; private object _tree; public object Tree { get { return _tree; } set { _tree = value; } } object IAstRuleReturnScope.Tree { get { return Tree; } } } partial void Enter_pointcut(); partial void Leave_pointcut(); // $ANTLR start "pointcut" // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:19:1: pointcut returns [PointcutExpression value] : ( alias '=' )? '[' attribute '(' saql ')' ']' ; [GrammarRule("pointcut")] private SaqaParser.pointcut_return pointcut() { Enter_pointcut(); EnterRule("pointcut", 2); TraceIn("pointcut", 2); SaqaParser.pointcut_return retval = new SaqaParser.pointcut_return(); retval.Start = (IToken)input.LT(1); object root_0 = null; IToken char_literal2 = null; IToken char_literal3 = null; IToken char_literal5 = null; IToken char_literal7 = null; IToken char_literal8 = null; SaqaParser.alias_return alias1 = default(SaqaParser.alias_return); SaqaParser.attribute_return attribute4 = default(SaqaParser.attribute_return); SaqaParser.saql_return saql6 = default(SaqaParser.saql_return); object char_literal2_tree = null; object char_literal3_tree = null; object char_literal5_tree = null; object char_literal7_tree = null; object char_literal8_tree = null; try { DebugEnterRule(GrammarFileName, "pointcut"); DebugLocation(19, 2); try { // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:20:2: ( ( alias '=' )? '[' attribute '(' saql ')' ']' ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:20:4: ( alias '=' )? '[' attribute '(' saql ')' ']' { root_0 = (object)adaptor.Nil(); DebugLocation(20, 4); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:20:4: ( alias '=' )? int alt2 = 2; try { DebugEnterSubRule(2); try { DebugEnterDecision(2, decisionCanBacktrack[2]); int LA2_0 = input.LA(1); if ((LA2_0 == ID)) { alt2 = 1; } } finally { DebugExitDecision(2); } switch (alt2) { case 1: DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:20:5: alias '=' { DebugLocation(20, 5); PushFollow(Follow._alias_in_pointcut89); alias1 = alias(); PopFollow(); adaptor.AddChild(root_0, alias1.Tree); DebugLocation(20, 11); char_literal2 = (IToken)Match(input, 8, Follow._8_in_pointcut91); char_literal2_tree = (object)adaptor.Create(char_literal2); adaptor.AddChild(root_0, char_literal2_tree); } break; } } finally { DebugExitSubRule(2); } DebugLocation(20, 17); char_literal3 = (IToken)Match(input, 9, Follow._9_in_pointcut95); char_literal3_tree = (object)adaptor.Create(char_literal3); adaptor.AddChild(root_0, char_literal3_tree); DebugLocation(20, 21); PushFollow(Follow._attribute_in_pointcut97); attribute4 = attribute(); PopFollow(); adaptor.AddChild(root_0, attribute4.Tree); DebugLocation(20, 31); char_literal5 = (IToken)Match(input, 10, Follow._10_in_pointcut99); char_literal5_tree = (object)adaptor.Create(char_literal5); adaptor.AddChild(root_0, char_literal5_tree); DebugLocation(20, 35); PushFollow(Follow._saql_in_pointcut101); saql6 = saql(); PopFollow(); adaptor.AddChild(root_0, saql6.Tree); DebugLocation(20, 40); char_literal7 = (IToken)Match(input, 11, Follow._11_in_pointcut103); char_literal7_tree = (object)adaptor.Create(char_literal7); adaptor.AddChild(root_0, char_literal7_tree); DebugLocation(20, 44); char_literal8 = (IToken)Match(input, 12, Follow._12_in_pointcut105); char_literal8_tree = (object)adaptor.Create(char_literal8); adaptor.AddChild(root_0, char_literal8_tree); DebugLocation(21, 2); retval.value = new PointcutExpression((alias1 != null ? alias1.value : default(string)), (attribute4 != null ? attribute4.value : default(string)), (saql6 != null ? saql6.value : default(string))); } retval.Stop = (IToken)input.LT(-1); retval.Tree = (object)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input, re); retval.Tree = (object)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("pointcut", 2); LeaveRule("pointcut", 2); Leave_pointcut(); } DebugLocation(23, 2); } finally { DebugExitRule(GrammarFileName, "pointcut"); } return retval; } // $ANTLR end "pointcut" public class alias_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<object> { public string value; private object _tree; public object Tree { get { return _tree; } set { _tree = value; } } object IAstRuleReturnScope.Tree { get { return Tree; } } } partial void Enter_alias(); partial void Leave_alias(); // $ANTLR start "alias" // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:25:1: alias returns [string value] : ID ; [GrammarRule("alias")] private SaqaParser.alias_return alias() { Enter_alias(); EnterRule("alias", 3); TraceIn("alias", 3); SaqaParser.alias_return retval = new SaqaParser.alias_return(); retval.Start = (IToken)input.LT(1); object root_0 = null; IToken ID9 = null; object ID9_tree = null; try { DebugEnterRule(GrammarFileName, "alias"); DebugLocation(25, 27); try { // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:26:2: ( ID ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:26:4: ID { root_0 = (object)adaptor.Nil(); DebugLocation(26, 4); ID9 = (IToken)Match(input, ID, Follow._ID_in_alias122); ID9_tree = (object)adaptor.Create(ID9); adaptor.AddChild(root_0, ID9_tree); DebugLocation(26, 7); retval.value = ID9.Text; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (object)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input, re); retval.Tree = (object)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("alias", 3); LeaveRule("alias", 3); Leave_alias(); } DebugLocation(26, 27); } finally { DebugExitRule(GrammarFileName, "alias"); } return retval; } // $ANTLR end "alias" public class attribute_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<object> { public string value; private object _tree; public object Tree { get { return _tree; } set { _tree = value; } } object IAstRuleReturnScope.Tree { get { return Tree; } } } partial void Enter_attribute(); partial void Leave_attribute(); // $ANTLR start "attribute" // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:28:1: attribute returns [string value] : ID ; [GrammarRule("attribute")] private SaqaParser.attribute_return attribute() { Enter_attribute(); EnterRule("attribute", 4); TraceIn("attribute", 4); SaqaParser.attribute_return retval = new SaqaParser.attribute_return(); retval.Start = (IToken)input.LT(1); object root_0 = null; IToken ID10 = null; object ID10_tree = null; try { DebugEnterRule(GrammarFileName, "attribute"); DebugLocation(28, 26); try { // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:29:2: ( ID ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:29:4: ID { root_0 = (object)adaptor.Nil(); DebugLocation(29, 4); ID10 = (IToken)Match(input, ID, Follow._ID_in_attribute138); ID10_tree = (object)adaptor.Create(ID10); adaptor.AddChild(root_0, ID10_tree); DebugLocation(29, 7); retval.value = ID10.Text; } retval.Stop = (IToken)input.LT(-1); retval.Tree = (object)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input, re); retval.Tree = (object)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("attribute", 4); LeaveRule("attribute", 4); Leave_attribute(); } DebugLocation(29, 26); } finally { DebugExitRule(GrammarFileName, "attribute"); } return retval; } // $ANTLR end "attribute" public class saql_return : ParserRuleReturnScope<IToken>, IAstRuleReturnScope<object> { public string value; private object _tree; public object Tree { get { return _tree; } set { _tree = value; } } object IAstRuleReturnScope.Tree { get { return Tree; } } } partial void Enter_saql(); partial void Leave_saql(); // $ANTLR start "saql" // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:31:1: saql returns [string value] : STRING ; [GrammarRule("saql")] private SaqaParser.saql_return saql() { Enter_saql(); EnterRule("saql", 5); TraceIn("saql", 5); SaqaParser.saql_return retval = new SaqaParser.saql_return(); retval.Start = (IToken)input.LT(1); object root_0 = null; IToken STRING11 = null; object STRING11_tree = null; try { DebugEnterRule(GrammarFileName, "saql"); DebugLocation(31, 44); try { // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:32:2: ( STRING ) DebugEnterAlt(1); // D:\\Dev\\Codeplex\\sheepaop\\SheepAspectQueryAnalyzer\\Engine\\Parser\\Saqa.g:32:4: STRING { root_0 = (object)adaptor.Nil(); DebugLocation(32, 4); STRING11 = (IToken)Match(input, STRING, Follow._STRING_in_saql154); STRING11_tree = (object)adaptor.Create(STRING11); adaptor.AddChild(root_0, STRING11_tree); DebugLocation(32, 11); retval.value = ProcessString(STRING11); } retval.Stop = (IToken)input.LT(-1); retval.Tree = (object)adaptor.RulePostProcessing(root_0); adaptor.SetTokenBoundaries(retval.Tree, retval.Start, retval.Stop); } catch (RecognitionException re) { ReportError(re); Recover(input, re); retval.Tree = (object)adaptor.ErrorNode(input, retval.Start, input.LT(-1), re); } finally { TraceOut("saql", 5); LeaveRule("saql", 5); Leave_saql(); } DebugLocation(32, 44); } finally { DebugExitRule(GrammarFileName, "saql"); } return retval; } // $ANTLR end "saql" #endregion Rules #region Follow sets private static class Follow { public static readonly BitSet _pointcut_in_pointcuts68 = new BitSet(new ulong[] { 0x212UL }); public static readonly BitSet _alias_in_pointcut89 = new BitSet(new ulong[] { 0x100UL }); public static readonly BitSet _8_in_pointcut91 = new BitSet(new ulong[] { 0x200UL }); public static readonly BitSet _9_in_pointcut95 = new BitSet(new ulong[] { 0x10UL }); public static readonly BitSet _attribute_in_pointcut97 = new BitSet(new ulong[] { 0x400UL }); public static readonly BitSet _10_in_pointcut99 = new BitSet(new ulong[] { 0x20UL }); public static readonly BitSet _saql_in_pointcut101 = new BitSet(new ulong[] { 0x800UL }); public static readonly BitSet _11_in_pointcut103 = new BitSet(new ulong[] { 0x1000UL }); public static readonly BitSet _12_in_pointcut105 = new BitSet(new ulong[] { 0x2UL }); public static readonly BitSet _ID_in_alias122 = new BitSet(new ulong[] { 0x2UL }); public static readonly BitSet _ID_in_attribute138 = new BitSet(new ulong[] { 0x2UL }); public static readonly BitSet _STRING_in_saql154 = new BitSet(new ulong[] { 0x2UL }); } #endregion Follow sets } } // namespace SheepAspectQueryAnalyzer.Engine.Parser
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Win32 { using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics.Tracing; using System.Runtime.InteropServices; using System.Security; using System.Text; internal static class UnsafeNativeMethods { [DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)] internal static extern int GetTimeZoneInformation(out Win32Native.TimeZoneInformation lpTimeZoneInformation); [DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)] internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation); // // BOOL GetFileMUIPath( // DWORD dwFlags, // PCWSTR pcwszFilePath, // PWSTR pwszLanguage, // PULONG pcchLanguage, // PWSTR pwszFileMUIPath, // PULONG pcchFileMUIPath, // PULONGLONG pululEnumerator // ); // [DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetFileMUIPath", SetLastError = true, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetFileMUIPath( int flags, [MarshalAs(UnmanagedType.LPWStr)] String filePath, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder language, ref int languageLength, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref Int64 enumerator); internal static unsafe class ManifestEtw { // // Constants error coded returned by ETW APIs // // The event size is larger than the allowed maximum (64k - header). internal const int ERROR_ARITHMETIC_OVERFLOW = 534; // Occurs when filled buffers are trying to flush to disk, // but disk IOs are not happening fast enough. // This happens when the disk is slow and event traffic is heavy. // Eventually, there are no more free (empty) buffers and the event is dropped. internal const int ERROR_NOT_ENOUGH_MEMORY = 8; internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_NOT_SUPPORTED = 50; internal const int ERROR_INVALID_PARAMETER = 0x57; // // ETW Methods // internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0; internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1; internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2; // // Callback // internal unsafe delegate void EtwEnableCallback( [In] ref Guid sourceId, [In] int isEnabled, [In] byte level, [In] long matchAnyKeywords, [In] long matchAllKeywords, [In] EVENT_FILTER_DESCRIPTOR* filterData, [In] void* callbackContext ); // // Registration APIs // [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal static extern unsafe uint EventRegister( [In] ref Guid providerId, [In]EtwEnableCallback enableCallback, [In]void* callbackContext, [In][Out]ref long registrationHandle ); // [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal static extern uint EventUnregister([In] long registrationHandle); [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal static extern unsafe int EventWriteString( [In] long registrationHandle, [In] byte level, [In] long keyword, [In] string msg ); [StructLayout(LayoutKind.Sequential)] unsafe internal struct EVENT_FILTER_DESCRIPTOR { public long Ptr; public int Size; public int Type; }; /// <summary> /// Call the ETW native API EventWriteTransfer and checks for invalid argument error. /// The implementation of EventWriteTransfer on some older OSes (Windows 2008) does not accept null relatedActivityId. /// So, for these cases we will retry the call with an empty Guid. /// </summary> internal static int EventWriteTransferWrapper(long registrationHandle, ref EventDescriptor eventDescriptor, Guid* activityId, Guid* relatedActivityId, int userDataCount, EventProvider.EventData* userData) { int HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, relatedActivityId, userDataCount, userData); if (HResult == ERROR_INVALID_PARAMETER && relatedActivityId == null) { Guid emptyGuid = Guid.Empty; HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, &emptyGuid, userDataCount, userData); } return HResult; } [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] private static extern int EventWriteTransfer( [In] long registrationHandle, [In] ref EventDescriptor eventDescriptor, [In] Guid* activityId, [In] Guid* relatedActivityId, [In] int userDataCount, [In] EventProvider.EventData* userData ); internal enum ActivityControl : uint { EVENT_ACTIVITY_CTRL_GET_ID = 1, EVENT_ACTIVITY_CTRL_SET_ID = 2, EVENT_ACTIVITY_CTRL_CREATE_ID = 3, EVENT_ACTIVITY_CTRL_GET_SET_ID = 4, EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5 }; [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal static extern int EventActivityIdControl([In] ActivityControl ControlCode, [In][Out] ref Guid ActivityId); internal enum EVENT_INFO_CLASS { BinaryTrackInfo, SetEnableAllKeywords, SetTraits, } [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventSetInformation", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal static extern int EventSetInformation( [In] long registrationHandle, [In] EVENT_INFO_CLASS informationClass, [In] void* eventInformation, [In] int informationLength); // Support for EnumerateTraceGuidsEx internal enum TRACE_QUERY_INFO_CLASS { TraceGuidQueryList, TraceGuidQueryInfo, TraceGuidQueryProcess, TraceStackTracingInfo, MaxTraceSetInfoClass }; internal struct TRACE_GUID_INFO { public int InstanceCount; public int Reserved; }; internal struct TRACE_PROVIDER_INSTANCE_INFO { public int NextOffset; public int EnableCount; public int Pid; public int Flags; }; internal struct TRACE_ENABLE_INFO { public int IsEnabled; public byte Level; public byte Reserved1; public ushort LoggerId; public int EnableProperty; public int Reserved2; public long MatchAnyKeyword; public long MatchAllKeyword; }; [DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EnumerateTraceGuidsEx", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] internal static extern int EnumerateTraceGuidsEx( TRACE_QUERY_INFO_CLASS TraceQueryInfoClass, void* InBuffer, int InBufferSize, void* OutBuffer, int OutBufferSize, ref int ReturnLength); } #if FEATURE_COMINTEROP [DllImport("combase.dll", PreserveSig = true)] internal static extern int RoGetActivationFactory( [MarshalAs(UnmanagedType.HString)] string activatableClassId, [In] ref Guid iid, [Out, MarshalAs(UnmanagedType.IInspectable)] out Object factory); #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Core.ViewOnly.Base { /// <summary> /// A simple helper class for build SQL statements /// </summary> public class Sql { private readonly object[] _args; private readonly string _sql; private object[] _argsFinal; private Sql _rhs; private string _sqlFinal; /// <summary> /// Default, empty constructor /// </summary> public Sql() { } /// <summary> /// Construct an SQL statement with the supplied SQL and arguments /// </summary> /// <param name="sql">The SQL statement or fragment</param> /// <param name="args">Arguments to any parameters embedded in the SQL</param> public Sql(string sql, params object[] args) { _sql = sql; _args = args; } /// <summary> /// Instantiate a new SQL Builder object. Weirdly implemented as a property but makes /// for more elegantly readble fluent style construction of SQL Statements /// eg: db.Query(Sql.Builder.Append(....)) /// </summary> public static Sql Builder { get { return new Sql(); } } /// <summary> /// Returns the final SQL statement represented by this builder /// </summary> public string SqlFinal { get { Build(); return _sqlFinal; } } /// <summary> /// Gets the complete, final set of arguments collected by this builder. /// </summary> public object[] Arguments { get { Build(); return _argsFinal; } } private void Build() { // already built? if (_sqlFinal != null) return; // Build it var sb = new StringBuilder(); var args = new List<object>(); Build(sb, args, null); _sqlFinal = sb.ToString(); _argsFinal = args.ToArray(); } /// <summary> /// Append another SQL builder instance to the right-hand-side of this SQL builder /// </summary> /// <param name="sql">A reference to another SQL builder instance</param> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql Append(Sql sql) { if (_rhs != null) _rhs.Append(sql); else _rhs = sql; return this; } /// <summary> /// Append an SQL fragement to the right-hand-side of this SQL builder /// </summary> /// <param name="sql">The SQL statement or fragment</param> /// <param name="args">Arguments to any parameters embedded in the SQL</param> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql Append(string sql, params object[] args) { return Append(new Sql(sql, args)); } private static bool Is(Sql sql, string sqltype) { return sql != null && sql._sql != null && sql._sql.StartsWith(sqltype, StringComparison.InvariantCultureIgnoreCase); } private void Build(StringBuilder sb, List<object> args, Sql lhs) { if (!String.IsNullOrEmpty(_sql)) { // Add SQL to the string if (sb.Length > 0) { sb.Append("\n"); } var sql = ParametersHelper.ProcessParams(_sql, _args, args); if (Is(lhs, "WHERE ") && Is(this, "WHERE ")) sql = "AND " + sql.Substring(6); if (Is(lhs, "ORDER BY ") && Is(this, "ORDER BY ")) sql = ", " + sql.Substring(9); sb.Append(sql); } // Now do rhs if (_rhs != null) _rhs.Build(sb, args, this); } /// <summary> /// Appends an SQL WHERE clause to this SQL builder /// </summary> /// <param name="sql">The condition of the WHERE clause</param> /// <param name="args">Arguments to any parameters embedded in the supplied SQL</param> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql Where(string sql, params object[] args) { return Append(new Sql("WHERE (" + sql + ")", args)); } /// <summary> /// Appends an SQL ORDER BY clause to this SQL builder /// </summary> /// <param name="columns">A collection of SQL column names to order by</param> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql OrderBy(params object[] columns) { return Append(new Sql("ORDER BY " + String.Join(", ", (from x in columns select x.ToString()).ToArray()))); } /// <summary> /// Appends an SQL SELECT clause to this SQL builder /// </summary> /// <param name="columns" /> /// A collection of SQL column names to select /// <param /> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql Select(params object[] columns) { return Append(new Sql("SELECT " + String.Join(", ", (from x in columns select x.ToString()).ToArray()))); } /// <summary> /// Appends an SQL FROM clause to this SQL builder /// </summary> /// <param name="tables">A collection of table names to be used in the FROM clause</param> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql From(params object[] tables) { return Append(new Sql("FROM " + String.Join(", ", (from x in tables select x.ToString()).ToArray()))); } /// <summary> /// Appends an SQL GROUP BY clause to this SQL builder /// </summary> /// <param name="columns">A collection of column names to be grouped by</param> /// <returns>A reference to this builder, allowing for fluent style concatenation</returns> public Sql GroupBy(params object[] columns) { return Append(new Sql("GROUP BY " + String.Join(", ", (from x in columns select x.ToString()).ToArray()))); } private SqlJoinClause Join(string joinType, string table) { return new SqlJoinClause(Append(new Sql(joinType + table))); } /// <summary> /// Appends an SQL INNER JOIN clause to this SQL builder /// </summary> /// <param name="table">The name of the table to join</param> /// <returns>A reference an SqlJoinClause through which the join condition can be specified</returns> public SqlJoinClause InnerJoin(string table) { return Join("INNER JOIN ", table); } /// <summary> /// Appends an SQL LEFT JOIN clause to this SQL builder /// </summary> /// <param name="table">The name of the table to join</param> /// <returns>A reference an SqlJoinClause through which the join condition can be specified</returns> public SqlJoinClause LeftJoin(string table) { return Join("LEFT JOIN ", table); } /// <summary> /// The SqlJoinClause is a simple helper class used in the construction of SQL JOIN statements with the SQL builder /// </summary> public class SqlJoinClause { private readonly Sql _sql; public SqlJoinClause(Sql sql) { _sql = sql; } /// <summary> /// Appends a SQL ON clause after a JOIN statement /// </summary> /// <param name="onClause">The ON clause to be appended</param> /// <param name="args">Arguments to any parameters embedded in the supplied SQL</param> /// <returns>A reference to the parent SQL builder, allowing for fluent style concatenation</returns> public Sql On(string onClause, params object[] args) { return _sql.Append("ON " + onClause, args); } } } }
// 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.Transactions.Tests { // Ported from Mono public class EnlistTest { #region Vol1_Dur0 /* Single volatile resource, SPC happens */ [Fact] public void Vol1_Dur0() { IntResourceManager irm = new IntResourceManager(1); irm.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.CheckSPC("irm"); } [Fact] public void Vol1_Dur0_2PC() { IntResourceManager irm = new IntResourceManager(1); using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.Check2PC("irm"); } /* Single volatile resource, SPC happens */ [Fact] public void Vol1_Dur0_Fail1() { IntResourceManager irm = new IntResourceManager(1); irm.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; /* Not completing this.. scope.Complete ();*/ } irm.Check(0, 0, 0, 1, 0, 0, 0, "irm"); } [Fact] public void Vol1_Dur0_Fail2() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); irm.FailPrepare = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } }); } [Fact] public void Vol1_Dur0_Fail3() { Assert.Throws<TransactionAbortedException>(() => { IntResourceManager irm = new IntResourceManager(1); irm.UseSingle = true; irm.FailSPC = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } }); } #endregion #region Vol2_Dur0 /* >1 volatile, 2PC */ [Fact] public void Vol2_Dur0_SPC() { IntResourceManager irm = new IntResourceManager(1); IntResourceManager irm2 = new IntResourceManager(3); irm.UseSingle = true; irm2.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; irm2.Value = 6; scope.Complete(); } irm.Check2PC("irm"); irm2.Check2PC("irm2"); } #endregion #region Vol0_Dur1 /* 1 durable */ [Fact] public void Vol0_Dur1() { IntResourceManager irm = new IntResourceManager(1); irm.Type = ResourceManagerType.Durable; irm.UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.CheckSPC("irm"); } /* We support only 1 durable with 2PC * On .net, this becomes a distributed transaction */ [ActiveIssue(13532)] //Distributed transactions are not supported. [Fact] public void Vol0_Dur1_2PC() { IntResourceManager irm = new IntResourceManager(1); /* Durable resource enlisted with a IEnlistedNotification * object */ irm.Type = ResourceManagerType.Durable; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } } [Fact] public void Vol0_Dur1_Fail() { IntResourceManager irm = new IntResourceManager(1); /* Durable resource enlisted with a IEnlistedNotification * object */ irm.Type = ResourceManagerType.Durable; irm.FailSPC = true; irm.UseSingle = true; Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } }); irm.Check(1, 0, 0, 0, 0, 0, 0, "irm"); } #endregion #region Vol2_Dur1 /* >1vol + 1 durable */ [Fact] public void Vol2_Dur1() { IntResourceManager[] irm = new IntResourceManager[4]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[2] = new IntResourceManager(5); irm[3] = new IntResourceManager(7); irm[0].Type = ResourceManagerType.Durable; for (int i = 0; i < 4; i++) irm[i].UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; irm[2].Value = 10; irm[3].Value = 14; scope.Complete(); } irm[0].CheckSPC("irm [0]"); /* Volatile RMs get 2PC */ for (int i = 1; i < 4; i++) irm[i].Check2PC("irm [" + i + "]"); } /* >1vol + 1 durable * Durable fails SPC */ [Fact] public void Vol2_Dur1_Fail1() { IntResourceManager[] irm = new IntResourceManager[4]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[2] = new IntResourceManager(5); irm[3] = new IntResourceManager(7); irm[0].Type = ResourceManagerType.Durable; irm[0].FailSPC = true; for (int i = 0; i < 4; i++) irm[i].UseSingle = true; /* Durable RM irm[0] does Abort on SPC, so * all volatile RMs get Rollback */ Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; irm[2].Value = 10; irm[3].Value = 14; scope.Complete(); } }); irm[0].CheckSPC("irm [0]"); /* Volatile RMs get 2PC Prepare, and then get rolled back */ for (int i = 1; i < 4; i++) irm[i].Check(0, 1, 0, 1, 0, 0, 0, "irm [" + i + "]"); } /* >1vol + 1 durable * Volatile fails Prepare */ [Fact] public void Vol2_Dur1_Fail3() { IntResourceManager[] irm = new IntResourceManager[4]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[2] = new IntResourceManager(5); irm[3] = new IntResourceManager(7); irm[0].Type = ResourceManagerType.Durable; irm[2].FailPrepare = true; for (int i = 0; i < 4; i++) irm[i].UseSingle = true; /* Durable RM irm[2] does on SPC, so * all volatile RMs get Rollback */ Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; irm[2].Value = 10; irm[3].Value = 14; scope.Complete(); } }); irm[0].Check(0, 0, 0, 1, 0, 0, 0, "irm [0]"); /* irm [1] & [2] get prepare, * [2] -> ForceRollback, * [1] & [3] get rollback, * [0](durable) gets rollback */ irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]"); irm[2].Check(0, 1, 0, 0, 0, 0, 0, "irm [2]"); irm[3].Check(0, 0, 0, 1, 0, 0, 0, "irm [3]"); } [Fact] public void Vol2_Dur1_Fail4() { IntResourceManager[] irm = new IntResourceManager[2]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[0].Type = ResourceManagerType.Durable; irm[0].FailSPC = true; irm[0].FailWithException = true; for (int i = 0; i < 2; i++) irm[i].UseSingle = true; /* Durable RM irm[2] does on SPC, so * all volatile RMs get Rollback */ TransactionAbortedException e = Assert.Throws<TransactionAbortedException>(() => { using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; scope.Complete(); } }); Assert.IsType<NotSupportedException>(e.InnerException); irm[0].Check(1, 0, 0, 0, 0, 0, 0, "irm [0]"); irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]"); } [Fact] public void Vol2_Dur1_Fail5() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager[] irm = new IntResourceManager[2]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); Transaction.Current = ct; irm[0].Type = ResourceManagerType.Durable; irm[0].FailSPC = true; irm[0].FailWithException = true; for (int i = 0; i < 2; i++) irm[i].UseSingle = true; /* Durable RM irm[2] does on SPC, so * all volatile RMs get Rollback */ using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; scope.Complete(); } TransactionAbortedException tae = Assert.Throws<TransactionAbortedException>(() => ct.Commit()); Assert.IsType<NotSupportedException>(tae.InnerException); irm[0].Check(1, 0, 0, 0, 0, 0, 0, "irm [0]"); irm[1].Check(0, 1, 0, 1, 0, 0, 0, "irm [1]"); InvalidOperationException ioe = Assert.Throws<InvalidOperationException>(() => ct.Commit()); Assert.Null(ioe.InnerException); Transaction.Current = null; } #endregion #region Promotable Single Phase Enlistment [Fact] public void Vol0_Dur0_Pspe1() { IntResourceManager irm = new IntResourceManager(1); irm.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm.Value = 2; scope.Complete(); } irm.Check(1, 0, 0, 0, 0, 1, 0, "irm"); } [Fact] public void Vol1_Dur0_Pspe1() { IntResourceManager irm0 = new IntResourceManager(1); IntResourceManager irm1 = new IntResourceManager(1); irm1.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm0.Value = 2; irm1.Value = 8; scope.Complete(); } irm1.Check(1, 0, 0, 0, 0, 1, 0, "irm1"); } [Fact] public void Vol0_Dur1_Pspe1() { IntResourceManager irm0 = new IntResourceManager(1); IntResourceManager irm1 = new IntResourceManager(1); irm0.Type = ResourceManagerType.Durable; irm0.UseSingle = true; irm1.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm0.Value = 8; irm1.Value = 2; Assert.Equal(0, irm1.NumEnlistFailed); } // TODO: Technically this is not correct. A call to EnlistPromotableSinglePhase is called AFTER a // DurableEnlist for a given transaction will return "false", which should probably be considered // an enlistment failure. An exception is not thrown, but the PSPE still "failed" } [Fact] public void Vol0_Dur0_Pspe2() { IntResourceManager irm0 = new IntResourceManager(1); IntResourceManager irm1 = new IntResourceManager(1); irm0.Type = ResourceManagerType.Promotable; irm1.Type = ResourceManagerType.Promotable; using (TransactionScope scope = new TransactionScope()) { irm0.Value = 8; irm1.Value = 2; Assert.Equal(0, irm1.NumEnlistFailed); } // TODO: Technically this is not correct. A call to EnlistPromotableSinglePhase is called AFTER a // successful EnlistPromotableSinglePhase for a given transaction will return "false", which should // probably be considered an enlistment failure. An exception is not thrown, but the second PSPE still "failed". } #endregion #region Others /* >1vol * > 1 durable, On .net this becomes a distributed transaction * We don't support this in mono yet. */ [ActiveIssue(13532)] //Distributed transactions are not supported. [Fact] public void Vol0_Dur2() { IntResourceManager[] irm = new IntResourceManager[2]; irm[0] = new IntResourceManager(1); irm[1] = new IntResourceManager(3); irm[0].Type = ResourceManagerType.Durable; irm[1].Type = ResourceManagerType.Durable; for (int i = 0; i < 2; i++) irm[i].UseSingle = true; using (TransactionScope scope = new TransactionScope()) { irm[0].Value = 2; irm[1].Value = 6; scope.Complete(); } } [Fact] public void TransactionDispose() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); irm.Type = ResourceManagerType.Durable; ct.Dispose(); irm.Check(0, 0, 0, 0, "Dispose transaction"); } [Fact] public void TransactionDispose2() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); Transaction.Current = ct; irm.Value = 5; try { ct.Dispose(); } finally { Transaction.Current = null; } irm.Check(0, 0, 1, 0, "Dispose transaction"); Assert.Equal(1, irm.Value); } [Fact] public void TransactionDispose3() { CommittableTransaction ct = new CommittableTransaction(); IntResourceManager irm = new IntResourceManager(1); try { Transaction.Current = ct; irm.Value = 5; ct.Commit(); ct.Dispose(); } finally { Transaction.Current = null; } irm.Check(1, 1, 0, 0, "Dispose transaction"); Assert.Equal(5, irm.Value); } #endregion #region TransactionCompleted [Fact] public void TransactionCompleted_Committed() { bool called = false; using (var ts = new TransactionScope()) { var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; ts.Complete(); } Assert.True(called, "TransactionCompleted event handler not called!"); } [Fact] public void TransactionCompleted_Rollback() { bool called = false; using (var ts = new TransactionScope()) { var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; // Not calling ts.Complete() on purpose.. } Assert.True(called, "TransactionCompleted event handler not called!"); } #endregion #region Success/Failure behavior tests #region Success/Failure behavior Vol1_Dur0 Cases [Fact] public void Vol1SPC_Committed() { bool called = false; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { UseSingle = true, Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } rm.Check(1, 0, 0, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol1_Committed() { bool called = false; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { Type = ResourceManagerType.Volatile, }; using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } rm.Check(0, 1, 1, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol1_Rollback() { bool called = false; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { Type = ResourceManagerType.Volatile, }; using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; // Not calling ts.Complete() on purpose.. } rm.Check(0, 0, 0, 1, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol1SPC_Throwing_On_Commit() { bool called = false; Exception ex = null; TransactionStatus status = TransactionStatus.Active; var rm = new IntResourceManager(1) { UseSingle = true, FailSPC = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm.Check(1, 0, 0, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Aborted, status); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException); } [Fact] public void Vol1_Throwing_On_Commit() { bool called = false; TransactionStatus status = TransactionStatus.Active; Exception ex = null; var rm = new IntResourceManager(1) { FailCommit = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm.Check(0, 1, 1, 0, 0, 0, 0, "rm"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.IsType<NotSupportedException>(ex); } [Fact] public void Vol1_Throwing_On_Rollback() { bool called = false; TransactionStatus status = TransactionStatus.Active; Exception ex = null; var rm = new IntResourceManager(1) { FailRollback = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; // Not calling ts.Complete() on purpose.. } } catch (Exception _ex) { ex = _ex; } rm.Check(0, 0, 0, 1, 0, 0, 0, "rm"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); // MS.NET will relay the exception thrown by RM instead of wrapping it on a TransactionAbortedException. Assert.IsType<NotSupportedException>(ex); } [Fact] public void Vol1_Throwing_On_Prepare() { bool called = false; TransactionStatus status = TransactionStatus.Active; Exception ex = null; var rm = new IntResourceManager(1) { FailPrepare = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm.Value = 2; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm.Check(0, 1, 0, 0, 0, 0, 0, "rm"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException); Assert.Equal(TransactionStatus.Aborted, status); } #endregion #region Success/Failure behavior Vol2_Dur0 Cases [Fact] public void Vol2SPC_Committed() { TransactionStatus status = TransactionStatus.Active; bool called = false; var rm1 = new IntResourceManager(1) { UseSingle = true, Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { UseSingle = true, Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } // There can be only one *Single* PC enlistment, // so TM will downgrade both to normal enlistments. rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 1, 0, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol2_Committed() { TransactionStatus status = TransactionStatus.Active; bool called = false; var rm1 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 1, 0, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Committed, status); } [Fact] public void Vol2_Rollback() { TransactionStatus status = TransactionStatus.Active; bool called = false; var rm1 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; // Not calling ts.Complete() on purpose.. } rm1.Check(0, 0, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 1, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol2SPC_Throwing_On_Commit() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { UseSingle = true, FailCommit = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile, }; var rm2 = new IntResourceManager(2) { UseSingle = true, Type = ResourceManagerType.Volatile, }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } // There can be only one *Single* PC enlistment, // so TM will downgrade both to normal enlistments. rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm1.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_Commit() { bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailCommit = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 1, 0, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm1.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_Rollback() { bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailRollback = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => called = true; // Not calling ts.Complete() on purpose.. } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 0, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 0, 0, 0, 0, "rm2"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); // MS.NET will relay the exception thrown by RM instead of wrapping it on a TransactionAbortedException. Assert.Equal(rm1.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_First_Prepare() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailPrepare = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 0, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 1, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<InvalidOperationException>(ex.InnerException); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol2_Throwing_On_Second_Prepare() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { FailPrepare = true, FailWithException = true, Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); Assert.True(called, "TransactionCompleted event handler not called!"); Assert.NotNull(ex); Assert.IsType<TransactionAbortedException>(ex); Assert.NotNull(ex.InnerException); Assert.IsType<NotSupportedException>(ex.InnerException); Assert.Equal(TransactionStatus.Aborted, status); } [Fact] public void Vol2_Throwing_On_First_Prepare_And_Second_Rollback() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailPrepare = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { FailRollback = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm2"), Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 0, 0, 0, 0, "rm1"); rm2.Check(0, 0, 0, 1, 0, 0, 0, "rm2"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm2.ThrowThisException, ex); } [Fact] public void Vol2_Throwing_On_First_Rollback_And_Second_Prepare() { TransactionStatus status = TransactionStatus.Active; bool called = false; Exception ex = null; var rm1 = new IntResourceManager(1) { FailRollback = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm1"), Type = ResourceManagerType.Volatile }; var rm2 = new IntResourceManager(2) { FailPrepare = true, FailWithException = true, ThrowThisException = new InvalidOperationException("rm2"), Type = ResourceManagerType.Volatile }; try { using (var ts = new TransactionScope()) { rm1.Value = 11; rm2.Value = 22; var tr = Transaction.Current; tr.TransactionCompleted += (s, e) => { called = true; status = e.Transaction.TransactionInformation.Status; }; ts.Complete(); } } catch (Exception _ex) { ex = _ex; } rm1.Check(0, 1, 0, 1, 0, 0, 0, "rm1"); rm2.Check(0, 1, 0, 0, 0, 0, 0, "rm2"); // MS.NET won't call TransactionCompleted event in this particular case. Assert.False(called, "TransactionCompleted event handler _was_ called!?!?!"); Assert.NotNull(ex); Assert.Equal(rm1.ThrowThisException, ex); } #endregion #endregion } }
/** * MetroFramework - Modern UI for WinForms * * The MIT License (MIT) * Copyright (c) 2011 Sven Walter, http://github.com/viperneo * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in the * Software without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Windows.Forms; using MetroFramework.Components; using MetroFramework.Drawing; using MetroFramework.Interfaces; using MetroFramework.Native; namespace MetroFramework.Forms { #region Enums public enum MetroFormTextAlign { Left, Center, Right } public enum MetroFormShadowType { None, Flat, DropShadow, SystemShadow, AeroShadow } public enum MetroFormBorderStyle { None, FixedSingle } public enum BackLocation { TopLeft, TopRight, BottomLeft, BottomRight } #endregion public class MetroForm : Form, IMetroForm, IDisposable { #region Interface private MetroColorStyle metroStyle = MetroColorStyle.Blue; [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroColorStyle Style { get { if (StyleManager != null) return StyleManager.Style; return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Light; [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroThemeStyle Theme { get { if (StyleManager != null) return StyleManager.Theme; return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } #endregion #region Fields private MetroFormTextAlign textAlign = MetroFormTextAlign.Left; [Browsable(true)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroFormTextAlign TextAlign { get { return textAlign; } set { textAlign = value; } } [Browsable(false)] public override Color BackColor { get { return MetroPaint.BackColor.Form(Theme); } } private MetroFormBorderStyle formBorderStyle = MetroFormBorderStyle.None; [DefaultValue(MetroFormBorderStyle.None)] [Browsable(true)] [Category(MetroDefaults.PropertyCategory.Appearance)] public MetroFormBorderStyle BorderStyle { get { return formBorderStyle; } set { formBorderStyle = value; } } private bool isMovable = true; [Category(MetroDefaults.PropertyCategory.Appearance)] public bool Movable { get { return isMovable; } set { isMovable = value; } } public new Padding Padding { get { return base.Padding; } set { value.Top = Math.Max(value.Top, DisplayHeader ? 60 : 30); base.Padding = value; } } protected override Padding DefaultPadding { get { return new Padding(20, DisplayHeader ? 60 : 20, 20, 20); } } private bool displayHeader = true; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(true)] public bool DisplayHeader { get { return displayHeader; } set { if (value != displayHeader) { Padding p = base.Padding; p.Top += value ? 30 : -30; base.Padding = p; } displayHeader = value; } } private bool isResizable = true; [Category(MetroDefaults.PropertyCategory.Appearance)] public bool Resizable { get { return isResizable; } set { isResizable = value; } } private MetroFormShadowType shadowType = MetroFormShadowType.Flat; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroFormShadowType.Flat)] public MetroFormShadowType ShadowType { get { return IsMdiChild ? MetroFormShadowType.None : shadowType; } set { shadowType = value; } } [Browsable(false)] public new FormBorderStyle FormBorderStyle { get { return base.FormBorderStyle; } set { base.FormBorderStyle = value; } } public new Form MdiParent { get { return base.MdiParent; } set { if (value != null) { RemoveShadow(); shadowType = MetroFormShadowType.None; } base.MdiParent = value; } } private const int borderWidth = 5; private Bitmap _image = null; private Image backImage; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(null)] public Image BackImage { get { return backImage; } set { backImage = value; if (value != null) _image = ApplyInvert(new Bitmap(value)); Refresh(); } } private Padding backImagePadding; [Category(MetroDefaults.PropertyCategory.Appearance)] public Padding BackImagePadding { get { return backImagePadding; } set { backImagePadding = value; Refresh(); } } private int backMaxSize; [Category(MetroDefaults.PropertyCategory.Appearance)] public int BackMaxSize { get { return backMaxSize; } set { backMaxSize = value; Refresh(); } } private BackLocation backLocation; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(BackLocation.TopLeft)] public BackLocation BackLocation { get { return backLocation; } set { backLocation = value; Refresh(); } } private bool _imageinvert; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(true)] public bool ApplyImageInvert { get { return _imageinvert; } set { _imageinvert = value; Refresh(); } } #endregion #region Constructor public MetroForm() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); FormBorderStyle = FormBorderStyle.None; Name = "MetroForm"; StartPosition = FormStartPosition.CenterScreen; TransparencyKey = Color.Lavender; } protected override void Dispose(bool disposing) { if (disposing) { RemoveShadow(); } base.Dispose(disposing); } #endregion #region Paint Methods public Bitmap ApplyInvert(Bitmap bitmapImage) { byte A, R, G, B; Color pixelColor; for (int y = 0; y < bitmapImage.Height; y++) { for (int x = 0; x < bitmapImage.Width; x++) { pixelColor = bitmapImage.GetPixel(x, y); A = pixelColor.A; R = (byte)(255 - pixelColor.R); G = (byte)(255 - pixelColor.G); B = (byte)(255 - pixelColor.B); if (R <= 0) R = 17; if (G <= 0) G = 17; if (B <= 0) B = 17; //bitmapImage.SetPixel(x, y, Color.FromArgb((int)A, (int)R, (int)G, (int)B)); bitmapImage.SetPixel(x, y, Color.FromArgb((int)R, (int)G, (int)B)); } } return bitmapImage; } protected override void OnPaint(PaintEventArgs e) { Color backColor = MetroPaint.BackColor.Form(Theme); Color foreColor = MetroPaint.ForeColor.Title(Theme); e.Graphics.Clear(backColor); using (SolidBrush b = MetroPaint.GetStyleBrush(Style)) { Rectangle topRect = new Rectangle(0, 0, Width, borderWidth); e.Graphics.FillRectangle(b, topRect); } if (BorderStyle != MetroFormBorderStyle.None) { Color c = MetroPaint.BorderColor.Form(Theme); using (Pen pen = new Pen(c)) { e.Graphics.DrawLines(pen, new[] { new Point(0, borderWidth), new Point(0, Height - 1), new Point(Width - 1, Height - 1), new Point(Width - 1, borderWidth) }); } } if (backImage != null && backMaxSize != 0) { Image img = MetroImage.ResizeImage(backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); if (_imageinvert) { img = MetroImage.ResizeImage((Theme == MetroThemeStyle.Dark) ? _image : backImage, new Rectangle(0, 0, backMaxSize, backMaxSize)); } switch (backLocation) { case BackLocation.TopLeft: e.Graphics.DrawImage(img, 0 + backImagePadding.Left, 0 + backImagePadding.Top); break; case BackLocation.TopRight: e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), 0 + backImagePadding.Top); break; case BackLocation.BottomLeft: e.Graphics.DrawImage(img, 0 + backImagePadding.Left, ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom)); break; case BackLocation.BottomRight: e.Graphics.DrawImage(img, ClientRectangle.Right - (backImagePadding.Right + img.Width), ClientRectangle.Bottom - (img.Height + backImagePadding.Bottom)); break; } } if (displayHeader) { Rectangle bounds = new Rectangle(20, 20, ClientRectangle.Width - 2 * 20, 40); TextFormatFlags flags = TextFormatFlags.EndEllipsis | GetTextFormatFlags(); TextRenderer.DrawText(e.Graphics, Text, MetroFonts.Title, bounds, foreColor, flags); } if (Resizable && (SizeGripStyle == SizeGripStyle.Auto || SizeGripStyle == SizeGripStyle.Show)) { using (SolidBrush b = new SolidBrush(MetroPaint.ForeColor.Button.Disabled(Theme))) { Size resizeHandleSize = new Size(2, 2); e.Graphics.FillRectangles(b, new Rectangle[] { new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-10,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-10), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-14,ClientRectangle.Height-6), resizeHandleSize), new Rectangle(new Point(ClientRectangle.Width-6,ClientRectangle.Height-14), resizeHandleSize) }); } } } private TextFormatFlags GetTextFormatFlags() { switch (TextAlign) { case MetroFormTextAlign.Left: return TextFormatFlags.Left; case MetroFormTextAlign.Center: return TextFormatFlags.HorizontalCenter; case MetroFormTextAlign.Right: return TextFormatFlags.Right; } throw new InvalidOperationException(); } #endregion #region Management Methods protected override void OnClosing(CancelEventArgs e) { if (!(this is MetroTaskWindow)) MetroTaskWindow.ForceClose(); base.OnClosing(e); } protected override void OnClosed(EventArgs e) { if (this.Owner != null) this.Owner = null; RemoveShadow(); base.OnClosed(e); } [SecuritySafeCritical] public bool FocusMe() { return WinApi.SetForegroundWindow(Handle); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DesignMode) return; switch (StartPosition) { case FormStartPosition.CenterParent: CenterToParent(); break; case FormStartPosition.CenterScreen: if (IsMdiChild) { CenterToParent(); } else { CenterToScreen(); } break; } RemoveCloseButton(); if (ControlBox) { AddWindowButton(WindowButtons.Close); if (MaximizeBox) AddWindowButton(WindowButtons.Maximize); if (MinimizeBox) AddWindowButton(WindowButtons.Minimize); UpdateWindowButtonPosition(); } CreateShadow(); } protected override void OnActivated(EventArgs e) { base.OnActivated(e); if (shadowType == MetroFormShadowType.AeroShadow && IsAeroThemeEnabled() && IsDropShadowSupported()) { int val = 2; DwmApi.DwmSetWindowAttribute(Handle, 2, ref val, 4); var m = new DwmApi.MARGINS { cyBottomHeight = 1, cxLeftWidth = 0, cxRightWidth = 0, cyTopHeight = 0 }; DwmApi.DwmExtendFrameIntoClientArea(Handle, ref m); } } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Invalidate(); } protected override void OnResizeEnd(EventArgs e) { base.OnResizeEnd(e); UpdateWindowButtonPosition(); } protected override void WndProc(ref Message m) { if (DesignMode) { base.WndProc(ref m); return; } switch (m.Msg) { case (int)WinApi.Messages.WM_SYSCOMMAND: int sc = m.WParam.ToInt32() & 0xFFF0; switch (sc) { case (int)WinApi.Messages.SC_MOVE: if (!Movable) return; break; case (int)WinApi.Messages.SC_MAXIMIZE: break; case (int)WinApi.Messages.SC_RESTORE: break; } break; case (int)WinApi.Messages.WM_NCLBUTTONDBLCLK: case (int)WinApi.Messages.WM_LBUTTONDBLCLK: if (!MaximizeBox) return; break; case (int)WinApi.Messages.WM_NCHITTEST: WinApi.HitTest ht = HitTestNCA(m.HWnd, m.WParam, m.LParam); if (ht != WinApi.HitTest.HTCLIENT) { m.Result = (IntPtr)ht; return; } break; case (int)WinApi.Messages.WM_DWMCOMPOSITIONCHANGED: break; } base.WndProc(ref m); switch (m.Msg) { case (int)WinApi.Messages.WM_GETMINMAXINFO: OnGetMinMaxInfo(m.HWnd, m.LParam); break; case (int)WinApi.Messages.WM_SIZE: if (windowButtonList != null) { MetroFormButton btn; windowButtonList.TryGetValue(WindowButtons.Maximize, out btn); if (btn == null) return; if (WindowState == FormWindowState.Normal) { if (shadowForm != null) shadowForm.Visible = true; btn.Text = "1"; } if (WindowState == FormWindowState.Maximized) btn.Text = "2"; } break; } } [SecuritySafeCritical] private unsafe void OnGetMinMaxInfo(IntPtr hwnd, IntPtr lParam) { WinApi.MINMAXINFO* pmmi = (WinApi.MINMAXINFO*)lParam; Screen s = Screen.FromHandle(hwnd); pmmi->ptMaxSize.x = s.WorkingArea.Width; pmmi->ptMaxSize.y = s.WorkingArea.Height; pmmi->ptMaxPosition.x = Math.Abs(s.WorkingArea.Left - s.Bounds.Left); pmmi->ptMaxPosition.y = Math.Abs(s.WorkingArea.Top - s.Bounds.Top); //if (MinimumSize.Width > 0) pmmi->ptMinTrackSize.x = MinimumSize.Width; //if (MinimumSize.Height > 0) pmmi->ptMinTrackSize.y = MinimumSize.Height; //if (MaximumSize.Width > 0) pmmi->ptMaxTrackSize.x = MaximumSize.Width; //if (MaximumSize.Height > 0) pmmi->ptMaxTrackSize.y = MaximumSize.Height; } private WinApi.HitTest HitTestNCA(IntPtr hwnd, IntPtr wparam, IntPtr lparam) { //Point vPoint = PointToClient(new Point((int)lparam & 0xFFFF, (int)lparam >> 16 & 0xFFFF)); //Point vPoint = PointToClient(new Point((Int16)lparam, (Int16)((int)lparam >> 16))); Point vPoint = new Point((Int16)lparam, (Int16)((int)lparam >> 16)); int vPadding = Math.Max(Padding.Right, Padding.Bottom); if (Resizable) { if (RectangleToScreen(new Rectangle(ClientRectangle.Width - vPadding, ClientRectangle.Height - vPadding, vPadding, vPadding)).Contains(vPoint)) return WinApi.HitTest.HTBOTTOMRIGHT; } if (RectangleToScreen(new Rectangle(borderWidth, borderWidth, ClientRectangle.Width - 2 * borderWidth, 50)).Contains(vPoint)) return WinApi.HitTest.HTCAPTION; return WinApi.HitTest.HTCLIENT; } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left && Movable) { if (WindowState == FormWindowState.Maximized) return; if (Width - borderWidth > e.Location.X && e.Location.X > borderWidth && e.Location.Y > borderWidth) { MoveControl(); } } } [SecuritySafeCritical] private void MoveControl() { WinApi.ReleaseCapture(); WinApi.SendMessage(Handle, (int)WinApi.Messages.WM_NCLBUTTONDOWN, (int)WinApi.HitTest.HTCAPTION, 0); } [SecuritySafeCritical] private static bool IsAeroThemeEnabled() { if (Environment.OSVersion.Version.Major <= 5) return false; bool aeroEnabled; DwmApi.DwmIsCompositionEnabled(out aeroEnabled); return aeroEnabled; } private static bool IsDropShadowSupported() { return Environment.OSVersion.Version.Major > 5 && SystemInformation.IsDropShadowEnabled; } #endregion #region Window Buttons private enum WindowButtons { Minimize, Maximize, Close } private Dictionary<WindowButtons, MetroFormButton> windowButtonList; private void AddWindowButton(WindowButtons button) { if (windowButtonList == null) windowButtonList = new Dictionary<WindowButtons, MetroFormButton>(); if (windowButtonList.ContainsKey(button)) return; MetroFormButton newButton = new MetroFormButton(); if (button == WindowButtons.Close) { newButton.Text = "r"; } else if (button == WindowButtons.Minimize) { newButton.Text = "0"; } else if (button == WindowButtons.Maximize) { if (WindowState == FormWindowState.Normal) newButton.Text = "1"; else newButton.Text = "2"; } newButton.Style = Style; newButton.Theme = Theme; newButton.Tag = button; newButton.Size = new Size(25, 20); newButton.Anchor = AnchorStyles.Top | AnchorStyles.Right; newButton.TabStop = false; //remove the form controls from the tab stop newButton.Click += WindowButton_Click; Controls.Add(newButton); windowButtonList.Add(button, newButton); } private void WindowButton_Click(object sender, EventArgs e) { var btn = sender as MetroFormButton; if (btn != null) { var btnFlag = (WindowButtons)btn.Tag; if (btnFlag == WindowButtons.Close) { Close(); } else if (btnFlag == WindowButtons.Minimize) { WindowState = FormWindowState.Minimized; } else if (btnFlag == WindowButtons.Maximize) { if (WindowState == FormWindowState.Normal) { WindowState = FormWindowState.Maximized; btn.Text = "2"; } else { WindowState = FormWindowState.Normal; btn.Text = "1"; } } } } private void UpdateWindowButtonPosition() { if (!ControlBox) return; Dictionary<int, WindowButtons> priorityOrder = new Dictionary<int, WindowButtons>(3) { { 0, WindowButtons.Close }, { 1, WindowButtons.Maximize }, { 2, WindowButtons.Minimize } }; Point firstButtonLocation = new Point(ClientRectangle.Width - borderWidth - 25, borderWidth); int lastDrawedButtonPosition = firstButtonLocation.X - 25; MetroFormButton firstButton = null; if (windowButtonList.Count == 1) { foreach (KeyValuePair<WindowButtons, MetroFormButton> button in windowButtonList) { button.Value.Location = firstButtonLocation; } } else { foreach (KeyValuePair<int, WindowButtons> button in priorityOrder) { bool buttonExists = windowButtonList.ContainsKey(button.Value); if (firstButton == null && buttonExists) { firstButton = windowButtonList[button.Value]; firstButton.Location = firstButtonLocation; continue; } if (firstButton == null || !buttonExists) continue; windowButtonList[button.Value].Location = new Point(lastDrawedButtonPosition, borderWidth); lastDrawedButtonPosition = lastDrawedButtonPosition - 25; } } Refresh(); } private class MetroFormButton : Button, IMetroControl { #region Interface [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintBackground; protected virtual void OnCustomPaintBackground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintBackground != null) { CustomPaintBackground(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaint; protected virtual void OnCustomPaint(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaint != null) { CustomPaint(this, e); } } [Category(MetroDefaults.PropertyCategory.Appearance)] public event EventHandler<MetroPaintEventArgs> CustomPaintForeground; protected virtual void OnCustomPaintForeground(MetroPaintEventArgs e) { if (GetStyle(ControlStyles.UserPaint) && CustomPaintForeground != null) { CustomPaintForeground(this, e); } } private MetroColorStyle metroStyle = MetroColorStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroColorStyle.Default)] public MetroColorStyle Style { get { if (DesignMode || metroStyle != MetroColorStyle.Default) { return metroStyle; } if (StyleManager != null && metroStyle == MetroColorStyle.Default) { return StyleManager.Style; } if (StyleManager == null && metroStyle == MetroColorStyle.Default) { return MetroDefaults.Style; } return metroStyle; } set { metroStyle = value; } } private MetroThemeStyle metroTheme = MetroThemeStyle.Default; [Category(MetroDefaults.PropertyCategory.Appearance)] [DefaultValue(MetroThemeStyle.Default)] public MetroThemeStyle Theme { get { if (DesignMode || metroTheme != MetroThemeStyle.Default) { return metroTheme; } if (StyleManager != null && metroTheme == MetroThemeStyle.Default) { return StyleManager.Theme; } if (StyleManager == null && metroTheme == MetroThemeStyle.Default) { return MetroDefaults.Theme; } return metroTheme; } set { metroTheme = value; } } private MetroStyleManager metroStyleManager = null; [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public MetroStyleManager StyleManager { get { return metroStyleManager; } set { metroStyleManager = value; } } private bool useCustomBackColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomBackColor { get { return useCustomBackColor; } set { useCustomBackColor = value; } } private bool useCustomForeColor = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseCustomForeColor { get { return useCustomForeColor; } set { useCustomForeColor = value; } } private bool useStyleColors = false; [DefaultValue(false)] [Category(MetroDefaults.PropertyCategory.Appearance)] public bool UseStyleColors { get { return useStyleColors; } set { useStyleColors = value; } } [Browsable(false)] [Category(MetroDefaults.PropertyCategory.Behaviour)] [DefaultValue(false)] public bool UseSelectable { get { return GetStyle(ControlStyles.Selectable); } set { SetStyle(ControlStyles.Selectable, value); } } #endregion #region Fields private bool isHovered = false; private bool isPressed = false; #endregion #region Constructor public MetroFormButton() { SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); } #endregion #region Paint Methods protected override void OnPaint(PaintEventArgs e) { Color backColor, foreColor; MetroThemeStyle _Theme = Theme; if (Parent != null) { if (Parent is IMetroForm) { _Theme = ((IMetroForm)Parent).Theme; backColor = MetroPaint.BackColor.Form(_Theme); } else if (Parent is IMetroControl) { backColor = MetroPaint.GetStyleColor(Style); } else { backColor = Parent.BackColor; } } else { backColor = MetroPaint.BackColor.Form(_Theme); } if (isHovered && !isPressed && Enabled) { foreColor = MetroPaint.ForeColor.Button.Normal(_Theme); backColor = MetroPaint.BackColor.Button.Normal(_Theme); } else if (isHovered && isPressed && Enabled) { foreColor = MetroPaint.ForeColor.Button.Press(_Theme); backColor = MetroPaint.GetStyleColor(Style); } else if (!Enabled) { foreColor = MetroPaint.ForeColor.Button.Disabled(_Theme); backColor = MetroPaint.BackColor.Button.Disabled(_Theme); } else { foreColor = MetroPaint.ForeColor.Button.Normal(_Theme); } e.Graphics.Clear(backColor); Font buttonFont = new Font("Webdings", 9.25f); TextRenderer.DrawText(e.Graphics, Text, buttonFont, ClientRectangle, foreColor, backColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis); } #endregion #region Mouse Methods protected override void OnMouseEnter(EventArgs e) { isHovered = true; Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { isPressed = true; Invalidate(); } base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { isPressed = false; Invalidate(); base.OnMouseUp(e); } protected override void OnMouseLeave(EventArgs e) { isHovered = false; Invalidate(); base.OnMouseLeave(e); } #endregion } #endregion #region Shadows private const int CS_DROPSHADOW = 0x20000; const int WS_MINIMIZEBOX = 0x20000; protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.Style |= WS_MINIMIZEBOX; if (ShadowType == MetroFormShadowType.SystemShadow) cp.ClassStyle |= CS_DROPSHADOW; return cp; } } private Form shadowForm; private void CreateShadow() { switch (ShadowType) { case MetroFormShadowType.Flat: shadowForm = new MetroFlatDropShadow(this); return; case MetroFormShadowType.DropShadow: shadowForm = new MetroRealisticDropShadow(this); return; case MetroFormShadowType.None: return; default: shadowForm = new MetroFlatDropShadow(this); return; } } private void RemoveShadow() { if (shadowForm == null || shadowForm.IsDisposed) return; shadowForm.Visible = false; Owner = shadowForm.Owner; shadowForm.Owner = null; shadowForm.Dispose(); shadowForm = null; } #region MetroShadowBase protected abstract class MetroShadowBase : Form { protected Form TargetForm { get; private set; } private readonly int shadowSize; private readonly int wsExStyle; protected MetroShadowBase(Form targetForm, int shadowSize, int wsExStyle) { TargetForm = targetForm; this.shadowSize = shadowSize; this.wsExStyle = wsExStyle; TargetForm.Activated += OnTargetFormActivated; TargetForm.ResizeBegin += OnTargetFormResizeBegin; TargetForm.ResizeEnd += OnTargetFormResizeEnd; TargetForm.VisibleChanged += OnTargetFormVisibleChanged; TargetForm.SizeChanged += OnTargetFormSizeChanged; TargetForm.Move += OnTargetFormMove; TargetForm.Resize += OnTargetFormResize; if (TargetForm.Owner != null) Owner = TargetForm.Owner; TargetForm.Owner = this; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false; ShowIcon = false; FormBorderStyle = FormBorderStyle.None; Bounds = GetShadowBounds(); } protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= wsExStyle; return cp; } } private Rectangle GetShadowBounds() { Rectangle r = TargetForm.Bounds; r.Inflate(shadowSize, shadowSize); return r; } protected abstract void PaintShadow(); protected abstract void ClearShadow(); #region Event Handlers private bool isBringingToFront; protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); isBringingToFront = true; } private void OnTargetFormActivated(object sender, EventArgs e) { if (Visible) Update(); if (isBringingToFront) { Visible = true; isBringingToFront = false; return; } BringToFront(); } private void OnTargetFormVisibleChanged(object sender, EventArgs e) { Visible = TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized; Update(); } private long lastResizedOn; private bool IsResizing { get { return lastResizedOn > 0; } } private void OnTargetFormResizeBegin(object sender, EventArgs e) { lastResizedOn = DateTime.Now.Ticks; } private void OnTargetFormMove(object sender, EventArgs e) { if (!TargetForm.Visible || TargetForm.WindowState != FormWindowState.Normal) { Visible = false; } else { Bounds = GetShadowBounds(); } } private void OnTargetFormResize(object sender, EventArgs e) { ClearShadow(); } private void OnTargetFormSizeChanged(object sender, EventArgs e) { Bounds = GetShadowBounds(); if (IsResizing) { return; } PaintShadowIfVisible(); } private void OnTargetFormResizeEnd(object sender, EventArgs e) { lastResizedOn = 0; PaintShadowIfVisible(); } private void PaintShadowIfVisible() { if (TargetForm.Visible && TargetForm.WindowState != FormWindowState.Minimized) PaintShadow(); } #endregion #region Constants protected const int WS_EX_TRANSPARENT = 0x20; protected const int WS_EX_LAYERED = 0x80000; protected const int WS_EX_NOACTIVATE = 0x8000000; private const int TICKS_PER_MS = 10000; private const long RESIZE_REDRAW_INTERVAL = 1000 * TICKS_PER_MS; #endregion } #endregion #region Aero DropShadow protected class MetroAeroDropShadow : MetroShadowBase { public MetroAeroDropShadow(Form targetForm) : base(targetForm, 0, WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { FormBorderStyle = FormBorderStyle.SizableToolWindow; } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { if (specified == BoundsSpecified.Size) return; base.SetBoundsCore(x, y, width, height, specified); } protected override void PaintShadow() { Visible = true; } protected override void ClearShadow() { } } #endregion #region Flat DropShadow protected class MetroFlatDropShadow : MetroShadowBase { private Point Offset = new Point(-6, -6); public MetroFlatDropShadow(Form targetForm) : base(targetForm, 6, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); PaintShadow(); } protected override void OnPaint(PaintEventArgs e) { Visible = true; PaintShadow(); } protected override void PaintShadow() { using (Bitmap getShadow = DrawBlurBorder()) SetBitmap(getShadow, 255); } protected override void ClearShadow() { Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.Clear(Color.Transparent); g.Flush(); g.Dispose(); SetBitmap(img, 255); img.Dispose(); } #region Drawing methods [SecuritySafeCritical] private void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); IntPtr screenDc = WinApi.GetDC(IntPtr.Zero); IntPtr memDc = WinApi.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = WinApi.SelectObject(memDc, hBitmap); WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height); WinApi.POINT pointSource = new WinApi.POINT(0, 0); WinApi.POINT topPos = new WinApi.POINT(Left, Top); WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION(); blend.BlendOp = WinApi.AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = opacity; blend.AlphaFormat = WinApi.AC_SRC_ALPHA; WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA); } finally { WinApi.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { WinApi.SelectObject(memDc, oldBitmap); WinApi.DeleteObject(hBitmap); } WinApi.DeleteDC(memDc); } } private Bitmap DrawBlurBorder() { return (Bitmap)DrawOutsetShadow(Color.Black, new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height)); } private Image DrawOutsetShadow(Color color, Rectangle shadowCanvasArea) { Rectangle rOuter = shadowCanvasArea; Rectangle rInner = new Rectangle(shadowCanvasArea.X + (-Offset.X - 1), shadowCanvasArea.Y + (-Offset.Y - 1), shadowCanvasArea.Width - (-Offset.X * 2 - 1), shadowCanvasArea.Height - (-Offset.Y * 2 - 1)); Bitmap img = new Bitmap(rOuter.Width, rOuter.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; using (Brush bgBrush = new SolidBrush(Color.FromArgb(30, Color.Black))) { g.FillRectangle(bgBrush, rOuter); } using (Brush bgBrush = new SolidBrush(Color.FromArgb(60, Color.Black))) { g.FillRectangle(bgBrush, rInner); } g.Flush(); g.Dispose(); return img; } #endregion } #endregion #region Realistic DropShadow protected class MetroRealisticDropShadow : MetroShadowBase { public MetroRealisticDropShadow(Form targetForm) : base(targetForm, 15, WS_EX_LAYERED | WS_EX_TRANSPARENT | WS_EX_NOACTIVATE) { } protected override void OnLoad(EventArgs e) { base.OnLoad(e); PaintShadow(); } protected override void OnPaint(PaintEventArgs e) { Visible = true; PaintShadow(); } protected override void PaintShadow() { using (Bitmap getShadow = DrawBlurBorder()) SetBitmap(getShadow, 255); } protected override void ClearShadow() { Bitmap img = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.Clear(Color.Transparent); g.Flush(); g.Dispose(); SetBitmap(img, 255); img.Dispose(); } #region Drawing methods [SecuritySafeCritical] private void SetBitmap(Bitmap bitmap, byte opacity) { if (bitmap.PixelFormat != PixelFormat.Format32bppArgb) throw new ApplicationException("The bitmap must be 32ppp with alpha-channel."); IntPtr screenDc = WinApi.GetDC(IntPtr.Zero); IntPtr memDc = WinApi.CreateCompatibleDC(screenDc); IntPtr hBitmap = IntPtr.Zero; IntPtr oldBitmap = IntPtr.Zero; try { hBitmap = bitmap.GetHbitmap(Color.FromArgb(0)); oldBitmap = WinApi.SelectObject(memDc, hBitmap); WinApi.SIZE size = new WinApi.SIZE(bitmap.Width, bitmap.Height); WinApi.POINT pointSource = new WinApi.POINT(0, 0); WinApi.POINT topPos = new WinApi.POINT(Left, Top); WinApi.BLENDFUNCTION blend = new WinApi.BLENDFUNCTION { BlendOp = WinApi.AC_SRC_OVER, BlendFlags = 0, SourceConstantAlpha = opacity, AlphaFormat = WinApi.AC_SRC_ALPHA }; WinApi.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, WinApi.ULW_ALPHA); } finally { WinApi.ReleaseDC(IntPtr.Zero, screenDc); if (hBitmap != IntPtr.Zero) { WinApi.SelectObject(memDc, oldBitmap); WinApi.DeleteObject(hBitmap); } WinApi.DeleteDC(memDc); } } private Bitmap DrawBlurBorder() { return (Bitmap)DrawOutsetShadow(0, 0, 40, 1, Color.Black, new Rectangle(1, 1, ClientRectangle.Width, ClientRectangle.Height)); } private Image DrawOutsetShadow(int hShadow, int vShadow, int blur, int spread, Color color, Rectangle shadowCanvasArea) { Rectangle rOuter = shadowCanvasArea; Rectangle rInner = shadowCanvasArea; rInner.Offset(hShadow, vShadow); rInner.Inflate(-blur, -blur); rOuter.Inflate(spread, spread); rOuter.Offset(hShadow, vShadow); Rectangle originalOuter = rOuter; Bitmap img = new Bitmap(originalOuter.Width, originalOuter.Height, PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(img); g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; var currentBlur = 0; do { var transparency = (rOuter.Height - rInner.Height) / (double)(blur * 2 + spread * 2); var shadowColor = Color.FromArgb(((int)(200 * (transparency * transparency))), color); var rOutput = rInner; rOutput.Offset(-originalOuter.Left, -originalOuter.Top); DrawRoundedRectangle(g, rOutput, currentBlur, Pens.Transparent, shadowColor); rInner.Inflate(1, 1); currentBlur = (int)((double)blur * (1 - (transparency * transparency))); } while (rOuter.Contains(rInner)); g.Flush(); g.Dispose(); return img; } private void DrawRoundedRectangle(Graphics g, Rectangle bounds, int cornerRadius, Pen drawPen, Color fillColor) { int strokeOffset = Convert.ToInt32(Math.Ceiling(drawPen.Width)); bounds = Rectangle.Inflate(bounds, -strokeOffset, -strokeOffset); var gfxPath = new GraphicsPath(); if (cornerRadius > 0) { gfxPath.AddArc(bounds.X, bounds.Y, cornerRadius, cornerRadius, 180, 90); gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y, cornerRadius, cornerRadius, 270, 90); gfxPath.AddArc(bounds.X + bounds.Width - cornerRadius, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 0, 90); gfxPath.AddArc(bounds.X, bounds.Y + bounds.Height - cornerRadius, cornerRadius, cornerRadius, 90, 90); } else { gfxPath.AddRectangle(bounds); } gfxPath.CloseAllFigures(); if (cornerRadius > 5) { using (SolidBrush b = new SolidBrush(fillColor)) { g.FillPath(b, gfxPath); } } if (drawPen != Pens.Transparent) { using (Pen p = new Pen(drawPen.Color)) { p.EndCap = p.StartCap = LineCap.Round; g.DrawPath(p, gfxPath); } } } #endregion } #endregion #endregion #region Helper Methods [SecuritySafeCritical] public void RemoveCloseButton() { IntPtr hMenu = WinApi.GetSystemMenu(Handle, false); if (hMenu == IntPtr.Zero) return; int n = WinApi.GetMenuItemCount(hMenu); if (n <= 0) return; WinApi.RemoveMenu(hMenu, (uint)(n - 1), WinApi.MfByposition | WinApi.MfRemove); WinApi.RemoveMenu(hMenu, (uint)(n - 2), WinApi.MfByposition | WinApi.MfRemove); WinApi.DrawMenuBar(Handle); } private Rectangle MeasureText(Graphics g, Rectangle clientRectangle, Font font, string text, TextFormatFlags flags) { var proposedSize = new Size(int.MaxValue, int.MinValue); var actualSize = TextRenderer.MeasureText(g, text, font, proposedSize, flags); return new Rectangle(clientRectangle.X, clientRectangle.Y, actualSize.Width, actualSize.Height); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Data; using System.Data.Common; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Text.RegularExpressions; namespace PageManagerTree.Massive { public static class ObjectExtensions { /// <summary> /// Extension method for adding in a bunch of parameters /// </summary> public static void AddParams(this DbCommand cmd, params object[] args) { foreach (var item in args) { AddParam(cmd, item); } } /// <summary> /// Extension for adding single parameter /// </summary> public static void AddParam(this DbCommand cmd, object item) { var p = cmd.CreateParameter(); p.ParameterName = string.Format("@{0}", cmd.Parameters.Count); if (item == null) { p.Value = DBNull.Value; } else { if (item.GetType() == typeof(Guid)) { p.Value = item.ToString(); p.DbType = DbType.String; p.Size = 4000; } else if (item.GetType() == typeof(ExpandoObject)) { var d = (IDictionary<string, object>)item; p.Value = d.Values.FirstOrDefault(); } else { p.Value = item; } if (item.GetType() == typeof(string)) p.Size = ((string)item).Length > 4000 ? -1 : 4000; } cmd.Parameters.Add(p); } /// <summary> /// Turns an IDataReader to a Dynamic list of things /// </summary> public static List<dynamic> ToExpandoList(this IDataReader rdr) { var result = new List<dynamic>(); while (rdr.Read()) { result.Add(rdr.RecordToExpando()); } if(rdr != null) { rdr.Close(); } return result; } public static dynamic RecordToExpando(this IDataReader rdr) { dynamic e = new ExpandoObject(); var d = e as IDictionary<string, object>; for (int i = 0; i < rdr.FieldCount; i++) d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]); return e; } /// <summary> /// Turns the object into an ExpandoObject /// </summary> public static dynamic ToExpando(this object o) { var result = new ExpandoObject(); var d = result as IDictionary<string, object>; //work with the Expando as a Dictionary if (o.GetType() == typeof(ExpandoObject)) return o; //shouldn't have to... but just in case if (o.GetType() == typeof(NameValueCollection) || o.GetType().IsSubclassOf(typeof(NameValueCollection))) { var nv = (NameValueCollection)o; nv.Cast<string>().Select(key => new KeyValuePair<string, object>(key, nv[key])).ToList().ForEach(i => d.Add(i)); } else { var props = o.GetType().GetProperties(); foreach (var item in props) { d.Add(item.Name, item.GetValue(o, null)); } } return result; } /// <summary> /// Turns the object into a Dictionary /// </summary> public static IDictionary<string, object> ToDictionary(this object thingy) { return (IDictionary<string, object>)thingy.ToExpando(); } } /// <summary> /// Convenience class for opening/executing data /// </summary> public static class DB { public static DynamicModel Current { get { if (ConfigurationManager.ConnectionStrings.Count > 1) { return new DynamicModel(ConfigurationManager.ConnectionStrings[1].Name); } throw new InvalidOperationException("Need a connection string name - can't determine what it is"); } } } /// <summary> /// A class that wraps your database table in Dynamic Funtime /// </summary> public class DynamicModel : DynamicObject { DbProviderFactory _factory; string ConnectionString; public static DynamicModel Open(string connectionStringName) { dynamic dm = new DynamicModel(connectionStringName); return dm; } public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "", string descriptorField = "") { TableName = tableName == "" ? this.GetType().Name : tableName; PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField; DescriptorField = descriptorField; var _providerName = "System.Data.SqlClient"; if (ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName != null) _providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName; _factory = DbProviderFactories.GetFactory(_providerName); ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; } /// <summary> /// Creates a new Expando from a Form POST - white listed against the columns in the DB /// </summary> public dynamic CreateFrom(NameValueCollection coll) { dynamic result = new ExpandoObject(); var dc = (IDictionary<string, object>)result; var schema = Schema; //loop the collection, setting only what's in the Schema foreach (var item in coll.Keys) { var exists = schema.Any(x => x.COLUMN_NAME.ToLower() == item.ToString().ToLower()); if (exists) { var key = item.ToString(); var val = coll[key]; dc.Add(key, val); } } return result; } /// <summary> /// Gets a default value for the column /// </summary> public dynamic DefaultValue(dynamic column) { dynamic result = null; string def = column.COLUMN_DEFAULT; if (String.IsNullOrEmpty(def)) { result = null; } else if (def == "getdate()" || def == "(getdate())") { result = DateTime.Now.ToShortDateString(); } else if (def == "newid()") { result = Guid.NewGuid().ToString(); } else { result = def.Replace("(", "").Replace(")", ""); } return result; } /// <summary> /// Creates an empty Expando set with defaults from the DB /// </summary> public dynamic Prototype { get { dynamic result = new ExpandoObject(); var schema = Schema; foreach (dynamic column in schema) { var dc = (IDictionary<string, object>)result; dc.Add(column.COLUMN_NAME, DefaultValue(column)); } result._Table = this; return result; } } public string DescriptorField { get; protected set; } /// <summary> /// List out all the schema bits for use with ... whatever /// </summary> IEnumerable<dynamic> _schema; public IEnumerable<dynamic> Schema { get { if (_schema == null) _schema = Query("SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @0", TableName); return _schema; } } /// <summary> /// Enumerates the reader yielding the result - thanks to Jeroen Haegebaert /// </summary> public virtual IEnumerable<dynamic> Query(string sql, params object[] args) { using (var conn = OpenConnection()) { var rdr = CreateCommand(sql, conn, args).ExecuteReader(); while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } //Added by Ashish - Connection Pool Issues if (rdr != null) { rdr.Close(); } } } public virtual IEnumerable<dynamic> Query(string sql, DbConnection connection, params object[] args) { using (var rdr = CreateCommand(sql, connection, args).ExecuteReader()) { while (rdr.Read()) { yield return rdr.RecordToExpando(); ; } //Added by Ashish - Connection Pool Issues if (rdr != null) { rdr.Close(); } } } /// <summary> /// Returns a single result /// </summary> public virtual object Scalar(string sql, params object[] args) { object result = null; using (var conn = OpenConnection()) { result = CreateCommand(sql, conn, args).ExecuteScalar(); } return result; } /// <summary> /// Creates a DBCommand that you can use for loving your database. /// </summary> DbCommand CreateCommand(string sql, DbConnection conn, params object[] args) { var result = _factory.CreateCommand(); result.Connection = conn; result.CommandText = sql; if (args.Length > 0) result.AddParams(args); return result; } /// <summary> /// Returns and OpenConnection /// </summary> public virtual DbConnection OpenConnection() { var result = _factory.CreateConnection(); result.ConnectionString = ConnectionString; result.Open(); return result; } /// <summary> /// Builds a set of Insert and Update commands based on the passed-on objects. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual List<DbCommand> BuildCommands(params object[] things) { var commands = new List<DbCommand>(); foreach (var item in things) { if (HasPrimaryKey(item)) { commands.Add(CreateUpdateCommand(item, GetPrimaryKey(item))); } else { commands.Add(CreateInsertCommand(item)); } } return commands; } public virtual int Execute(DbCommand command) { return Execute(new DbCommand[] { command }); } public virtual int Execute(string sql, params object[] args) { return Execute(CreateCommand(sql, null, args)); } /// <summary> /// Executes a series of DBCommands in a transaction /// </summary> public virtual int Execute(IEnumerable<DbCommand> commands) { var result = 0; using (var conn = OpenConnection()) { using (var tx = conn.BeginTransaction()) { foreach (var cmd in commands) { cmd.Connection = conn; cmd.Transaction = tx; result += cmd.ExecuteNonQuery(); } tx.Commit(); } } return result; } public virtual string PrimaryKeyField { get; set; } /// <summary> /// Conventionally introspects the object passed in for a field that /// looks like a PK. If you've named your PrimaryKeyField, this becomes easy /// </summary> public virtual bool HasPrimaryKey(object o) { return o.ToDictionary().ContainsKey(PrimaryKeyField); } /// <summary> /// If the object passed in has a property with the same name as your PrimaryKeyField /// it is returned here. /// </summary> public virtual object GetPrimaryKey(object o) { object result = null; o.ToDictionary().TryGetValue(PrimaryKeyField, out result); return result; } public virtual string TableName { get; set; } /// <summary> /// Returns all records complying with the passed-in WHERE clause and arguments, /// ordered as specified, limited (TOP) by limit. /// </summary> public virtual IEnumerable<dynamic> All(string where = "", string orderBy = "", int limit = 0, string columns = "*", params object[] args) { string sql = BuildSelect(where, orderBy, limit); return Query(string.Format(sql, columns, TableName), args); } private static string BuildSelect(string where, string orderBy, int limit) { string sql = limit > 0 ? "SELECT TOP " + limit + " {0} FROM {1} " : "SELECT {0} FROM {1} "; if (!string.IsNullOrEmpty(where)) sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : " WHERE " + where; if (!String.IsNullOrEmpty(orderBy)) sql += orderBy.Trim().StartsWith("order by", StringComparison.OrdinalIgnoreCase) ? orderBy : " ORDER BY " + orderBy; return sql; } /// <summary> /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords. /// </summary> public virtual dynamic Paged(string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { return BuildPagedResult(where: where, orderBy: orderBy, columns: columns, pageSize: pageSize, currentPage: currentPage, args: args); } public virtual dynamic Paged(string sql, string primaryKey, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { return BuildPagedResult(sql, primaryKey, where, orderBy, columns, pageSize, currentPage, args); } private dynamic BuildPagedResult(string sql = "", string primaryKeyField = "", string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args) { dynamic result = new ExpandoObject(); var countSQL = ""; if (!string.IsNullOrEmpty(sql)) countSQL = string.Format("SELECT COUNT({0}) FROM ({1}) AS PagedTable", primaryKeyField, sql); else countSQL = string.Format("SELECT COUNT({0}) FROM {1}", PrimaryKeyField, TableName); if (String.IsNullOrEmpty(orderBy)) { orderBy = string.IsNullOrEmpty(primaryKeyField) ? PrimaryKeyField : primaryKeyField; } if (!string.IsNullOrEmpty(where)) { if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase)) { where = " WHERE " + where; } } var query = ""; if (!string.IsNullOrEmpty(sql)) query = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM ({3}) AS PagedTable {4}) AS Paged ", columns, pageSize, orderBy, sql, where); else query = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM {3} {4}) AS Paged ", columns, pageSize, orderBy, TableName, where); var pageStart = (currentPage - 1) * pageSize; query += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize)); countSQL += where; result.TotalRecords = Scalar(countSQL, args); result.TotalPages = result.TotalRecords / pageSize; if (result.TotalRecords % pageSize > 0) result.TotalPages += 1; result.Items = Query(string.Format(query, columns, TableName), args); return result; } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(string where, params object[] args) { var sql = string.Format("SELECT * FROM {0} WHERE {1}", TableName, where); return Query(sql, args).FirstOrDefault(); } /// <summary> /// Returns a single row from the database /// </summary> public virtual dynamic Single(object key, string columns = "*") { var sql = string.Format("SELECT {0} FROM {1} WHERE {2} = @0", columns, TableName, PrimaryKeyField); return Query(sql, key).FirstOrDefault(); } /// <summary> /// This will return a string/object dictionary for dropdowns etc /// </summary> public virtual IDictionary<string, object> KeyValues(string orderBy = "") { if (String.IsNullOrEmpty(DescriptorField)) throw new InvalidOperationException("There's no DescriptorField set - do this in your constructor to describe the text value you want to see"); var sql = string.Format("SELECT {0},{1} FROM {2} ", PrimaryKeyField, DescriptorField, TableName); if (!String.IsNullOrEmpty(orderBy)) sql += "ORDER BY " + orderBy; var results = Query(sql).ToList().Cast<IDictionary<string, object>>(); return results.ToDictionary(key => key[PrimaryKeyField].ToString(), value => value[DescriptorField]); } /// <summary> /// This will return an Expando as a Dictionary /// </summary> public virtual IDictionary<string, object> ItemAsDictionary(ExpandoObject item) { return (IDictionary<string, object>)item; } //Checks to see if a key is present based on the passed-in value public virtual bool ItemContainsKey(string key, ExpandoObject item) { var dc = ItemAsDictionary(item); return dc.ContainsKey(key); } /// <summary> /// Executes a set of objects as Insert or Update commands based on their property settings, within a transaction. /// These objects can be POCOs, Anonymous, NameValueCollections, or Expandos. Objects /// With a PK property (whatever PrimaryKeyField is set to) will be created at UPDATEs /// </summary> public virtual int Save(params object[] things) { foreach (var item in things) { if (!IsValid(item)) { throw new InvalidOperationException("Can't save this item: " + String.Join("; ", Errors.ToArray())); } } var commands = BuildCommands(things); return Execute(commands); } public virtual DbCommand CreateInsertCommand(dynamic expando) { DbCommand result = null; var settings = (IDictionary<string, object>)expando; var sbKeys = new StringBuilder(); var sbVals = new StringBuilder(); var stub = "INSERT INTO {0} ({1}) \r\n VALUES ({2})"; result = CreateCommand(stub, null); int counter = 0; foreach (var item in settings) { sbKeys.AppendFormat("{0},", item.Key); sbVals.AppendFormat("@{0},", counter.ToString()); result.AddParam(item.Value); counter++; } if (counter > 0) { var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 1); var vals = sbVals.ToString().Substring(0, sbVals.Length - 1); var sql = string.Format(stub, TableName, keys, vals); result.CommandText = sql; } else throw new InvalidOperationException("Can't parse this object to the database - there are no properties set"); return result; } /// <summary> /// Creates a command for use with transactions - internal stuff mostly, but here for you to play with /// </summary> public virtual DbCommand CreateUpdateCommand(dynamic expando, object key) { var settings = (IDictionary<string, object>)expando; var sbKeys = new StringBuilder(); var stub = "UPDATE {0} SET {1} WHERE {2} = @{3}"; var args = new List<object>(); var result = CreateCommand(stub, null); int counter = 0; foreach (var item in settings) { var val = item.Value; if (!item.Key.Equals(PrimaryKeyField, StringComparison.OrdinalIgnoreCase) && item.Value != null) { result.AddParam(val); sbKeys.AppendFormat("{0} = @{1}, \r\n", item.Key, counter.ToString()); counter++; } } if (counter > 0) { //add the key result.AddParam(key); //strip the last commas var keys = sbKeys.ToString().Substring(0, sbKeys.Length - 4); result.CommandText = string.Format(stub, TableName, keys, PrimaryKeyField, counter); } else throw new InvalidOperationException("No parsable object was sent in - could not divine any name/value pairs"); return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public virtual DbCommand CreateDeleteCommand(string where = "", object key = null, params object[] args) { var sql = string.Format("DELETE FROM {0} ", TableName); if (key != null) { sql += string.Format("WHERE {0}=@0", PrimaryKeyField); args = new object[] { key }; } else if (!string.IsNullOrEmpty(where)) { sql += where.Trim().StartsWith("where", StringComparison.OrdinalIgnoreCase) ? where : "WHERE " + where; } return CreateCommand(sql, null, args); } public bool IsValid(dynamic item) { Errors.Clear(); Validate(item); return Errors.Count == 0; } //Temporary holder for error messages public IList<string> Errors = new List<string>(); /// <summary> /// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString /// </summary> public virtual dynamic Insert(object o) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't insert: " + String.Join("; ", Errors.ToArray())); } if (BeforeSave(ex)) { using (dynamic conn = OpenConnection()) { var cmd = CreateInsertCommand(ex); cmd.Connection = conn; cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT @@IDENTITY as newID"; ex.ID = cmd.ExecuteScalar(); Inserted(ex); } return ex; } else { return null; } } /// <summary> /// Updates a record in the database. You can pass in an Anonymous object, an ExpandoObject, /// A regular old POCO, or a NameValueCollection from a Request.Form or Request.QueryString /// </summary> public virtual int Update(object o, object key) { var ex = o.ToExpando(); if (!IsValid(ex)) { throw new InvalidOperationException("Can't Update: " + String.Join("; ", Errors.ToArray())); } var result = 0; if (BeforeSave(ex)) { result = Execute(CreateUpdateCommand(ex, key)); Updated(ex); } return result; } /// <summary> /// Removes one or more records from the DB according to the passed-in WHERE /// </summary> public int Delete(object key = null, string where = "", params object[] args) { var deleted = this.Single(key); var result = 0; if (BeforeDelete(deleted)) { result = Execute(CreateDeleteCommand(where: where, key: key, args: args)); Deleted(deleted); } return result; } public void DefaultTo(string key, object value, dynamic item) { if (!ItemContainsKey(key, item)) { var dc = (IDictionary<string, object>)item; dc[key] = value; } } //Hooks public virtual void Validate(dynamic item) { } public virtual void Inserted(dynamic item) { } public virtual void Updated(dynamic item) { } public virtual void Deleted(dynamic item) { } public virtual bool BeforeDelete(dynamic item) { return true; } public virtual bool BeforeSave(dynamic item) { return true; } //validation methods public virtual void ValidatesPresenceOf(object value, string message = "Required") { if (value == null) Errors.Add(message); if (String.IsNullOrEmpty(value.ToString())) Errors.Add(message); } //fun methods public virtual void ValidatesNumericalityOf(object value, string message = "Should be a number") { var type = value.GetType().Name; var numerics = new string[] { "Int32", "Int16", "Int64", "Decimal", "Double", "Single", "Float" }; if (!numerics.Contains(type)) { Errors.Add(message); } } public virtual void ValidateIsCurrency(object value, string message = "Should be money") { if (value == null) Errors.Add(message); decimal val = decimal.MinValue; decimal.TryParse(value.ToString(), out val); if (val == decimal.MinValue) Errors.Add(message); } public int Count() { return Count(TableName); } public int Count(string tableName, string where="") { return (int)Scalar("SELECT COUNT(*) FROM " + tableName+" "+where); } /// <summary> /// A helpful query tool /// </summary> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { //parse the method var constraints = new List<string>(); var counter = 0; var info = binder.CallInfo; // accepting named args only... SKEET! if (info.ArgumentNames.Count != args.Length) { throw new InvalidOperationException("Please use named arguments for this type of query - the column name, orderby, columns, etc"); } //first should be "FindBy, Last, Single, First" var op = binder.Name; var columns = " * "; string orderBy = string.Format(" ORDER BY {0}", PrimaryKeyField); string sql = ""; string where = ""; var whereArgs = new List<object>(); //loop the named args - see if we have order, columns and constraints if (info.ArgumentNames.Count > 0) { for (int i = 0; i < args.Length; i++) { var name = info.ArgumentNames[i].ToLower(); switch (name) { case "orderby": orderBy = " ORDER BY " + args[i]; break; case "columns": columns = args[i].ToString(); break; default: constraints.Add(string.Format(" {0} = @{1}", name, counter)); whereArgs.Add(args[i]); counter++; break; } } } //Build the WHERE bits if (constraints.Count > 0) { where = " WHERE " + string.Join(" AND ", constraints.ToArray()); } //probably a bit much here but... yeah this whole thing needs to be refactored... if (op.ToLower() == "count") { result = Scalar("SELECT COUNT(*) FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "sum") { result = Scalar("SELECT SUM(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "max") { result = Scalar("SELECT MAX(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "min") { result = Scalar("SELECT MIN(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else if (op.ToLower() == "avg") { result = Scalar("SELECT AVG(" + columns + ") FROM " + TableName + where, whereArgs.ToArray()); } else { //build the SQL sql = "SELECT TOP 1 " + columns + " FROM " + TableName + where; var justOne = op.StartsWith("First") || op.StartsWith("Last") || op.StartsWith("Get") || op.StartsWith("Single"); //Be sure to sort by DESC on the PK (PK Sort is the default) if (op.StartsWith("Last")) { orderBy = orderBy + " DESC "; } else { //default to multiple sql = "SELECT " + columns + " FROM " + TableName + where; } if (justOne) { //return a single record result = Query(sql + orderBy, whereArgs.ToArray()).FirstOrDefault(); } else { //return lots result = Query(sql + orderBy, whereArgs.ToArray()); } } return true; } } }
/******************************************************************** Copyright 2015 Microsoft 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. File: SelectGateway.xaml.cs Description: Interface to select gateway server Author: Jin Li, Partner Research Manager Microsoft Research, One Microsoft Way Date: June. 2015 *******************************************************************/ using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.Graphics.Display; using Prajna.Service.CoreServices.Data; using Prajna.AppLibrary; using System.Threading.Tasks; using WindowsApp.Common; using WindowsApp.Data; using Windows.ApplicationModel.Resources; using Windows.Storage; using Windows.Media.Devices; using Windows.Storage.Pickers; using Windows.UI.Xaml.Media.Imaging; using System.Threading; using Windows.Devices.Enumeration; using Windows.Storage.Streams; using Windows.ApplicationModel.Activation; using Windows.Graphics.Imaging; using WindowsApp.Views; namespace WindowsApp.Views { /// <summary> /// Create the page /// </summary> public sealed partial class SelectGateway : Page { private String OldGateway { get; set; } private Int32 MinItemShowed { get; set; } private Int32 NumberItemShowed { get; set; } private Int32 SelectedIndexValue { get; set; } private ConcurrentDictionary<String, OneServerInfo> GatewayAdded { get; set; } internal ObservableCollection<OneServerInfo> GatewayList { get; set; } internal String LastGateway { get; set; } internal Boolean hasSaved = false; private readonly NavigationHelper navigationHelper; private readonly ObservableDictionary defaultViewModel = new ObservableDictionary(); private readonly ResourceLoader resourceLoader = ResourceLoader.GetForCurrentView("Resources"); internal static SelectGateway Current; /// <summary> /// Constructor /// </summary> public SelectGateway() { this.InitializeComponent(); Current = this; this.NavigationCacheMode = NavigationCacheMode.Required; this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += this.NavigationHelper_LoadState; this.navigationHelper.SaveState += this.NavigationHelper_SaveState; } #region Navigation public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } /// <summary> /// Gets the view model for this <see cref="Page"/>. /// This can be changed to a strongly typed view model. /// </summary> public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } /// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/>. /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { // TODO: Create an appropriate data model for your problem domain to replace the sample data var sampleDataGroup = await SampleDataSource.GetGroupAsync("Group-1"); // this.DefaultViewModel[FirstGroupName] = sampleDataGroup; } /// <summary> /// Preserves state associated with this page in case the application is suspended or the /// page is discarded from the navigation cache. Values must conform to the serialization /// requirements of <see cref="SuspensionManager.SessionState"/>. /// </summary> /// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/>.</param> /// <param name="e">Event data that provides an empty dictionary to be populated with /// serializable state.</param> private void NavigationHelper_SaveState(object sender, SaveStateEventArgs e) { // TODO: Save the unique state of the page here. } protected override async void OnNavigatedTo(NavigationEventArgs e) { //base.OnNavigatedTo(e); GatewayList = new ObservableCollection<OneServerInfo>(); GatewayAdded = new ConcurrentDictionary<String, OneServerInfo>(StringComparer.OrdinalIgnoreCase); ViewOfGateway.ItemsSource = this.GatewayList; LastGateway = null; SelectedIndexValue = 0; var scaleFactor = DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; var ScreenHeight = Window.Current.Bounds.Height; var DeviceHeight = ScreenHeight * scaleFactor; NumberItemShowed = (int)Math.Floor((ScreenHeight - 220.0) / 60.0 + 0.5); MinItemShowed = 0; var currentApp = (App)App.Current; OldGateway = currentApp.CurrentGateway; var nRet = await UpdateGatewayInfo(); this.navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { //base.OnNavigatedFrom(e); this.navigationHelper.OnNavigatedFrom(e); } #endregion #region Gateway Operations private void AddGateway(String hostname, String info) { var serverInfo = new OneServerInfo(); serverInfo.HostName = hostname; serverInfo.HostInfo = info; OneServerInfo oldServer; if (GatewayAdded.TryRemove(hostname, out oldServer)) { this.GatewayList.Remove(oldServer); } var priorInfo = this.GatewayAdded.GetOrAdd(hostname, serverInfo); if (Object.ReferenceEquals(priorInfo, serverInfo)) { this.GatewayList.Add(serverInfo); } } private async Task<int> UpdateGatewayInfo() { var errorString = ""; try { var currentApp = (App)App.Current; this.CurrentGateway.Text = currentApp.CurrentGateway; App.VMHub.CurrentGateway = currentApp.CurrentGateway; foreach (var kv in currentApp.GatewayCollection) { AddGateway(kv.Key, kv.Value); } if (String.IsNullOrEmpty(this.LastGateway)) { this.LastGateway = currentApp.CurrentGateway; } var lst = await App.VMHub.GetActiveGateways(); foreach (var item in lst) { AddGateway(item.HostName, item.HostInfo); currentApp.GatewayCollection.GetOrAdd(item.HostName, item.HostInfo); } var cnt = (double)(this.GatewayList.Count); this.ViewOfGateway.Height = cnt * 60.0; return 0; } catch (Exception ex) { errorString = ex.Message; } Frame.Navigate(typeof(NetworkError), errorString); return 0; } private void SelectedGateway_Event(object sender, SelectionChangedEventArgs e) { if (e.AddedItems.Count > 0) { var item = e.AddedItems[0] as OneServerInfo; this.CurrentGateway.Text = item.HostName; var idx = GatewayList.IndexOf(item); var cnt = GatewayList.Count; if (idx >= 0) { var minShow = MinItemShowed; var maxShow = MinItemShowed + NumberItemShowed - 1; var midShow = (minShow + maxShow) / 2; var diff = idx - midShow; if (diff != 0) { var newMinShow = MinItemShowed; OneServerInfo scrollItem = null; if (diff < 0) newMinShow = Math.Max(0, MinItemShowed + diff); else { maxShow = Math.Min(cnt - 1, MinItemShowed + diff + NumberItemShowed - 1); newMinShow = Math.Max(0, maxShow - NumberItemShowed + 1); } if (newMinShow != MinItemShowed) { int scrollidx = 0; if (diff < 0) { scrollItem = GatewayList[newMinShow]; scrollidx = newMinShow; } else { scrollItem = GatewayList[maxShow]; scrollidx = maxShow; } MinItemShowed = newMinShow; this.ViewOfGateway.ScrollIntoView(scrollItem); } } } } } #endregion #region Buttons /// <summary> /// Button click to update gateway selection /// </summary> private async void UpdateGatewaySelection_Click(object sender, RoutedEventArgs e) { var currentApp = (App)App.Current; currentApp.CurrentGateway = this.CurrentGateway.Text; var nRet = await UpdateGatewayInfo(); } /// <summary> /// Button click to save gateway selection /// </summary> private void SaveGatewaySelection_Click(object sender, RoutedEventArgs e) { hasSaved = true; var currentApp = (App)App.Current; currentApp.SaveGatewayInfo(this.CurrentGateway.Text, GatewayList.ToList()); } /// <summary> /// Navigate back to OptionsPage /// </summary> private async void goToHomePage(object sender, RoutedEventArgs e) { //Check if the user has saved the domain selection if (hasSaved) { hasSaved = false; Frame.Navigate(typeof(OptionsPage)); } else { //If the selection has not been saved, make a speechbuble visible //that says "Dont Forget to Save" SpeechBubble.Visibility = Visibility.Visible; await Task.Delay(1500); SpeechBubble.Visibility = Visibility.Collapsed; } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using RAMOutputStream = Lucene.Net.Store.RAMOutputStream; using ArrayUtil = Lucene.Net.Util.ArrayUtil; namespace Lucene.Net.Index { /// <summary>This is a DocFieldConsumer that writes stored fields. </summary> sealed class StoredFieldsWriter { private void InitBlock() { docFreeList = new PerDoc[1]; } internal FieldsWriter fieldsWriter; internal DocumentsWriter docWriter; internal FieldInfos fieldInfos; internal int lastDocID; internal PerDoc[] docFreeList; internal int freeCount; public StoredFieldsWriter(DocumentsWriter docWriter, FieldInfos fieldInfos) { InitBlock(); this.docWriter = docWriter; this.fieldInfos = fieldInfos; } public StoredFieldsWriterPerThread AddThread(DocumentsWriter.DocState docState) { return new StoredFieldsWriterPerThread(docState, this); } public void Flush(SegmentWriteState state) { lock (this) { if (state.numDocsInStore > 0) { // It's possible that all documents seen in this segment // hit non-aborting exceptions, in which case we will // not have yet init'd the FieldsWriter: InitFieldsWriter(); // Fill fdx file to include any final docs that we // skipped because they hit non-aborting exceptions Fill(state.numDocsInStore - docWriter.DocStoreOffset); } if (fieldsWriter != null) fieldsWriter.Flush(); } } private void InitFieldsWriter() { if (fieldsWriter == null) { System.String docStoreSegment = docWriter.DocStoreSegment; if (docStoreSegment != null) { System.Diagnostics.Debug.Assert(docStoreSegment != null); fieldsWriter = new FieldsWriter(docWriter.directory, docStoreSegment, fieldInfos); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.FIELDS_EXTENSION); docWriter.AddOpenFile(docStoreSegment + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); lastDocID = 0; } } } public void CloseDocStore(SegmentWriteState state) { lock (this) { int inc = state.numDocsInStore - lastDocID; if (inc > 0) { InitFieldsWriter(); Fill(state.numDocsInStore - docWriter.DocStoreOffset); } if (fieldsWriter != null) { fieldsWriter.Dispose(); fieldsWriter = null; lastDocID = 0; System.Diagnostics.Debug.Assert(state.docStoreSegmentName != null); state.flushedFiles.Add(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_EXTENSION); state.flushedFiles.Add(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); state.docWriter.RemoveOpenFile(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_EXTENSION); state.docWriter.RemoveOpenFile(state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION); System.String fileName = state.docStoreSegmentName + "." + IndexFileNames.FIELDS_INDEX_EXTENSION; if (4 + ((long) state.numDocsInStore) * 8 != state.directory.FileLength(fileName)) throw new System.SystemException("after flush: fdx size mismatch: " + state.numDocsInStore + " docs vs " + state.directory.FileLength(fileName) + " length in bytes of " + fileName + " file exists?=" + state.directory.FileExists(fileName)); } } } internal int allocCount; internal PerDoc GetPerDoc() { lock (this) { if (freeCount == 0) { allocCount++; if (allocCount > docFreeList.Length) { // Grow our free list up front to make sure we have // enough space to recycle all outstanding PerDoc // instances System.Diagnostics.Debug.Assert(allocCount == 1 + docFreeList.Length); docFreeList = new PerDoc[ArrayUtil.GetNextSize(allocCount)]; } return new PerDoc(this); } else return docFreeList[--freeCount]; } } internal void Abort() { lock (this) { if (fieldsWriter != null) { try { fieldsWriter.Dispose(); } catch (System.Exception) { } fieldsWriter = null; lastDocID = 0; } } } /// <summary>Fills in any hole in the docIDs </summary> internal void Fill(int docID) { int docStoreOffset = docWriter.DocStoreOffset; // We must "catch up" for all docs before us // that had no stored fields: int end = docID + docStoreOffset; while (lastDocID < end) { fieldsWriter.SkipDocument(); lastDocID++; } } internal void FinishDocument(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(docWriter.writer.TestPoint("StoredFieldsWriter.finishDocument start")); InitFieldsWriter(); Fill(perDoc.docID); // Append stored fields to the real FieldsWriter: fieldsWriter.FlushDocument(perDoc.numStoredFields, perDoc.fdt); lastDocID++; perDoc.Reset(); Free(perDoc); System.Diagnostics.Debug.Assert(docWriter.writer.TestPoint("StoredFieldsWriter.finishDocument end")); } } public bool FreeRAM() { return false; } internal void Free(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(freeCount < docFreeList.Length); System.Diagnostics.Debug.Assert(0 == perDoc.numStoredFields); System.Diagnostics.Debug.Assert(0 == perDoc.fdt.Length); System.Diagnostics.Debug.Assert(0 == perDoc.fdt.FilePointer); docFreeList[freeCount++] = perDoc; } } internal class PerDoc:DocumentsWriter.DocWriter { public PerDoc(StoredFieldsWriter enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(StoredFieldsWriter enclosingInstance) { this.enclosingInstance = enclosingInstance; buffer = enclosingInstance.docWriter.NewPerDocBuffer(); fdt = new RAMOutputStream(buffer); } private StoredFieldsWriter enclosingInstance; public StoredFieldsWriter Enclosing_Instance { get { return enclosingInstance; } } internal DocumentsWriter.PerDocBuffer buffer ; internal RAMOutputStream fdt; internal int numStoredFields; internal void Reset() { fdt.Reset(); buffer.Recycle(); numStoredFields = 0; } public override void Abort() { Reset(); Enclosing_Instance.Free(this); } public override long SizeInBytes() { return buffer.SizeInBytes; } public override void Finish() { Enclosing_Instance.FinishDocument(this); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Text { using System; using System.Runtime.Serialization; using System.Security.Permissions; // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. // [Serializable()] ////[System.Runtime.InteropServices.ComVisible( true )] public class ASCIIEncoding : Encoding { public ASCIIEncoding() : base( Encoding.CodePageASCII ) { } internal override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( char[] chars , int index , int count ) { // Validate input parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0, avoid fixed empty array problem if(chars.Length == 0) { return 0; } // Just call the pointer version fixed(char* pChars = chars) { return GetByteCount( pChars + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount( String chars ) { // Validate input if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars" ); #else throw new ArgumentNullException(); #endif } fixed(char* pChars = chars) { return GetByteCount( pChars, chars.Length, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetByteCount( char* chars , int count ) { // Validate Parameters if(chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Call it with empty encoder return GetByteCount( chars, count, null ); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes( String chars , int charIndex , int charCount , byte[] bytes , int byteIndex ) { if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCount" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = chars) { fixed(byte* pBytes = bytes) { return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes( char[] chars , int charIndex , int charCount , byte[] bytes , int byteIndex ) { // Validate parameters if(chars == null || bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( (chars == null ? "chars" : "bytes"), Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charIndex < 0 || charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charIndex < 0 ? "charIndex" : "charCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(chars.Length - charIndex < charCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "chars", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(byteIndex < 0 || byteIndex > bytes.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If nothing to encode return 0, avoid fixed problem if(chars.Length == 0) { return 0; } // Just call pointer version int byteCount = bytes.Length - byteIndex; // Fixed doesn't like empty byte arrays if(bytes.Length == 0) { bytes = new byte[1]; } fixed(char* pChars = chars) { fixed(byte* pBytes = bytes) { // Remember that byteCount is # to decode, not size of array. return GetBytes( pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetBytes( chars, charCount, bytes, byteCount, null ); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount( byte[] bytes , int index , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(index < 0 || count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (index < 0 ? "index" : "count"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - index < count) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input just return 0, fixed doesn't like 0 length arrays if(bytes.Length == 0) { return 0; } // Just call pointer version fixed(byte* pBytes = bytes) { return GetCharCount( pBytes + index, count, null ); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public override unsafe int GetCharCount( byte* bytes , int count ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(count < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "count", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetCharCount( bytes, count, null ); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars( byte[] bytes , int byteIndex , int byteCount , char[] chars , int charIndex ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(charIndex < 0 || charIndex > chars.Length) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charIndex", Environment.GetResourceString( "ArgumentOutOfRange_Index" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // If no input, return 0 & avoid fixed problem if(bytes.Length == 0) { return 0; } // Just call pointer version int charCount = chars.Length - charIndex; // Fixed doesn't like empty char arrays if(chars.Length == 0) { chars = new char[1]; } fixed(byte* pBytes = bytes) { fixed(char* pChars = chars) { // Remember that charCount is # to decode, not size of array return GetChars( pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null ); } } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant( false )] //// [System.Runtime.InteropServices.ComVisible( false )] public unsafe override int GetChars( byte* bytes , int byteCount , char* chars , int charCount ) { // Validate Parameters if(bytes == null || chars == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( bytes == null ? "bytes" : "chars", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(charCount < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (charCount < 0 ? "charCount" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return GetChars( bytes, byteCount, chars, charCount, null ); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe String GetString( byte[] bytes , int byteIndex , int byteCount ) { // Validate Parameters if(bytes == null) { #if EXCEPTION_STRINGS throw new ArgumentNullException( "bytes", Environment.GetResourceString( "ArgumentNull_Array" ) ); #else throw new ArgumentNullException(); #endif } if(byteIndex < 0 || byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( (byteIndex < 0 ? "byteIndex" : "byteCount"), Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } if(bytes.Length - byteIndex < byteCount) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "bytes", Environment.GetResourceString( "ArgumentOutOfRange_IndexCountBuffer" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Avoid problems with empty input buffer if(bytes.Length == 0) { return String.Empty; } fixed(byte* pBytes = bytes) { return String.CreateStringFromEncoding( pBytes + byteIndex, byteCount, this ); } } // // End of standard methods copied from EncodingNLS.cs // // GetByteCount // Note: We start by assuming that the output will be the same as count. Having // an encoder or fallback may change that assumption internal override unsafe int GetByteCount( char* chars , int charCount , EncoderNLS encoder ) { // Just need to ASSERT, this is called by something else internal that checked parameters already BCLDebug.Assert( charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative" ); BCLDebug.Assert( chars != null, "[ASCIIEncoding.GetByteCount]chars is null" ); // Assert because we shouldn't be able to have a null encoder. BCLDebug.Assert( encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder" ); char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // Start by assuming default count, then +/- for fallback characters char* charEnd = chars + charCount; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; if(encoder != null) { charLeftOver = encoder.charLeftOver; BCLDebug.Assert( charLeftOver == 0 || Char.IsHighSurrogate( charLeftOver ), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate" ); fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if(fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( chars, charEnd, encoder, false ); } // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert BCLDebug.Assert( !encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer" ); // if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // If we have an encoder AND we aren't using default fallback, // then we may have a complicated count. if(fallback != null && fallback.MaxCharCount == 1) { // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always // same as input size. // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy. // We could however have 1 extra byte if the last call had an encoder and a funky fallback and // if we don't use the funky fallback this time. // Do we have an extra char left over from last time? if(charLeftOver > 0) { charCount++; } return (charCount); } // Count is more complicated if you have a funky fallback // For fallback we may need a fallback buffer, we know we're not default fallback int byteCount = 0; // We may have a left over character from last time, try and process it. if(charLeftOver > 0) { BCLDebug.Assert( Char.IsHighSurrogate( charLeftOver ), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate" ); BCLDebug.Assert( encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder" ); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize( chars, charEnd, encoder, false ); // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback( charLeftOver, ref chars ); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if(ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // no chars >= 0x80 are allowed. if(ch > 0x7f) { if(fallbackBuffer == null) { // Initialize the buffer if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( charEnd - charCount, charEnd, encoder, false ); } // Get Fallback fallbackBuffer.InternalFallback( ch, ref chars ); continue; } // We'll use this one byteCount++; } BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer" ); return byteCount; } internal override unsafe int GetBytes( char* chars , int charCount , byte* bytes , int byteCount , EncoderNLS encoder ) { // Just need to ASSERT, this is called by something else internal that checked parameters already BCLDebug.Assert( bytes != null, "[ASCIIEncoding.GetBytes]bytes is null" ); BCLDebug.Assert( byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative" ); BCLDebug.Assert( chars != null, "[ASCIIEncoding.GetBytes]chars is null" ); BCLDebug.Assert( charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative" ); // Assert because we shouldn't be able to have a null encoder. BCLDebug.Assert( encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback" ); // Get any left over characters char charLeftOver = (char)0; EncoderReplacementFallback fallback = null; // For fallback we may need a fallback buffer, we know we aren't default fallback. EncoderFallbackBuffer fallbackBuffer = null; // prepare our end char* charEnd = chars + charCount; byte* byteStart = bytes; char* charStart = chars; if(encoder != null) { charLeftOver = encoder.charLeftOver; fallback = encoder.Fallback as EncoderReplacementFallback; // We mustn't have left over fallback data when counting if(encoder.InternalHasFallbackBuffer) { // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary fallbackBuffer = encoder.FallbackBuffer; if(fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow) { #if EXCEPTION_STRINGS throw new ArgumentException( Environment.GetResourceString( "Argument_EncoderFallbackNotEmpty", this.EncodingName, encoder.Fallback.GetType() ) ); #else throw new ArgumentException(); #endif } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize( charStart, charEnd, encoder, true ); } BCLDebug.Assert( charLeftOver == 0 || Char.IsHighSurrogate( charLeftOver ), "[ASCIIEncoding.GetBytes]leftover character should be high surrogate" ); // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert BCLDebug.Assert( !encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer || encoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer" ); // if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer && // encoder.FallbackBuffer.Remaining > 0) // throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty", // this.EncodingName, encoder.Fallback.GetType())); } else { fallback = this.EncoderFallback as EncoderReplacementFallback; } // See if we do the fast default or slightly slower fallback if(fallback != null && fallback.MaxCharCount == 1) { // Fast version char cReplacement = fallback.DefaultString[0]; // Check for replacements in range, otherwise fall back to slow version. if(cReplacement <= (char)0x7f) { // We should have exactly as many output bytes as input bytes, unless there's a left // over character, in which case we may need one more. // If we had a left over character will have to add a ? (This happens if they had a funky // fallback last time, but not this time.) (We can't spit any out though // because with fallback encoder each surrogate is treated as a seperate code point) if(charLeftOver > 0) { // Have to have room // Throw even if doing no throw version because this is just 1 char, // so buffer will never be big enough if(byteCount == 0) { ThrowBytesOverflow( encoder, true ); } // This'll make sure we still have more room and also make sure our return value is correct. *(bytes++) = (byte)cReplacement; byteCount--; // We used one of the ones we were counting. } // This keeps us from overrunning our output buffer if(byteCount < charCount) { // Throw or make buffer smaller? ThrowBytesOverflow( encoder, byteCount < 1 ); // Just use what we can charEnd = chars + byteCount; } // We just do a quick copy while(chars < charEnd) { char ch2 = *(chars++); if(ch2 >= 0x0080) { *(bytes++) = (byte)cReplacement; } else { *(bytes++) = unchecked( (byte)(ch2) ); } } // Clear encoder if(encoder != null) { encoder.charLeftOver = (char)0; encoder.m_charsUsed = (int)(chars - charStart); } return (int)(bytes - byteStart); } } // Slower version, have to do real fallback. // prepare our end byte* byteEnd = bytes + byteCount; // We may have a left over character from last time, try and process it. if(charLeftOver > 0) { // Initialize the buffer BCLDebug.Assert( encoder != null, "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over" ); fallbackBuffer = encoder.FallbackBuffer; fallbackBuffer.InternalInitialize( chars, charEnd, encoder, true ); // Since left over char was a surrogate, it'll have to be fallen back. // Get Fallback // This will fallback a pair if *chars is a low surrogate fallbackBuffer.InternalFallback( charLeftOver, ref chars ); } // Now we may have fallback char[] already from the encoder // Go ahead and do it, including the fallback. char ch; while((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 || chars < charEnd) { // First unwind any fallback if(ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Check for fallback, this'll catch surrogate pairs too. // All characters >= 0x80 must fall back. if(ch > 0x7f) { // Initialize the buffer if(fallbackBuffer == null) { if(encoder == null) { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = encoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( charEnd - charCount, charEnd, encoder, true ); } // Get Fallback fallbackBuffer.InternalFallback( ch, ref chars ); // Go ahead & continue (& do the fallback) continue; } // We'll use this one // Bounds check if(bytes >= byteEnd) { // didn't use this char, we'll throw or use buffer if(fallbackBuffer == null || fallbackBuffer.bFallingBack == false) { BCLDebug.Assert( chars > charStart || bytes == byteStart, "[ASCIIEncoding.GetBytes]Expected chars to have advanced already." ); chars--; // don't use last char } else { fallbackBuffer.MovePrevious(); } // Are we throwing or using buffer? ThrowBytesOverflow( encoder, bytes == byteStart ); // throw? break; // don't throw, stop } // Go ahead and add it *bytes = unchecked( (byte)ch ); bytes++; } // Need to do encoder stuff if(encoder != null) { // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases if(fallbackBuffer != null && !fallbackBuffer.bUsedEncoder) { // Clear it in case of MustFlush encoder.charLeftOver = (char)0; } // Set our chars used count encoder.m_charsUsed = (int)(chars - charStart); } BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0 || (encoder != null && !encoder.m_throwOnOverflow), "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end" ); return (int)(bytes - byteStart); } // This is internal and called by something else, internal override unsafe int GetCharCount( byte* bytes , int count , DecoderNLS decoder ) { // Just assert, we're called internally so these should be safe, checked already BCLDebug.Assert( bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null" ); BCLDebug.Assert( count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative" ); // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if(decoder == null) { fallback = this.DecoderFallback as DecoderReplacementFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; BCLDebug.Assert( !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer" ); } if(fallback != null && fallback.MaxCharCount == 1) { // Just return length, SBCS stay the same length because they don't map to surrogate // pairs and we don't have a decoder fallback. return count; } // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII DecoderFallbackBuffer fallbackBuffer = null; // Have to do it the hard way. // Assume charCount will be == count int charCount = count; byte[] byteBuffer = new byte[1]; // Do it our fast way byte* byteEnd = bytes + count; // Quick loop while(bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *bytes; bytes++; // If unknown we have to do fallback count if(b >= 0x80) { if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( byteEnd - count, null ); } // Use fallback buffer byteBuffer[0] = b; charCount--; // Have to unreserve the one we already allocated for b charCount += fallbackBuffer.InternalFallback( byteBuffer, bytes ); } } // Fallback buffer must be empty BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer" ); // Converted sequence is same length as input return charCount; } internal override unsafe int GetChars( byte* bytes , int byteCount , char* chars , int charCount , DecoderNLS decoder ) { // Just need to ASSERT, this is called by something else internal that checked parameters already BCLDebug.Assert( bytes != null, "[ASCIIEncoding.GetChars]bytes is null" ); BCLDebug.Assert( byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative" ); BCLDebug.Assert( chars != null, "[ASCIIEncoding.GetChars]chars is null" ); BCLDebug.Assert( charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative" ); // Do it fast way if using ? replacement fallback byte* byteEnd = bytes + byteCount; byte* byteStart = bytes; char* charStart = chars; // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f // Only need decoder fallback buffer if not using ? fallback. // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using DecoderReplacementFallback fallback = null; if(decoder == null) { fallback = this.DecoderFallback as DecoderReplacementFallback; } else { fallback = decoder.Fallback as DecoderReplacementFallback; BCLDebug.Assert( !decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0, "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer" ); } if(fallback != null && fallback.MaxCharCount == 1) { // Try it the fast way char replacementChar = fallback.DefaultString[0]; // Need byteCount chars, otherwise too small buffer if(charCount < byteCount) { // Need at least 1 output byte, throw if must throw ThrowCharsOverflow( decoder, charCount < 1 ); // Not throwing, use what we can byteEnd = bytes + charCount; } // Quick loop, just do '?' replacement because we don't have fallbacks for decodings. while(bytes < byteEnd) { byte b = *(bytes++); if(b >= 0x80) { // This is an invalid byte in the ASCII encoding. *(chars++) = replacementChar; } else { *(chars++) = unchecked( (char)b ); } } // bytes & chars used are the same if(decoder != null) { decoder.m_bytesUsed = (int)(bytes - byteStart); } return (int)(chars - charStart); } // Slower way's going to need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; byte[] byteBuffer = new byte[1]; char* charEnd = chars + charCount; // Not quite so fast loop while(bytes < byteEnd) { // Faster if don't use *bytes++; byte b = *(bytes); bytes++; if(b >= 0x80) { // This is an invalid byte in the ASCII encoding. if(fallbackBuffer == null) { if(decoder == null) { fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = decoder.FallbackBuffer; } fallbackBuffer.InternalInitialize( byteEnd - byteCount, charEnd ); } // Use fallback buffer byteBuffer[0] = b; // Note that chars won't get updated unless this succeeds if(!fallbackBuffer.InternalFallback( byteBuffer, bytes, ref chars )) { // May or may not throw, but we didn't get this byte BCLDebug.Assert( bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)" ); bytes--; // unused byte fallbackBuffer.InternalReset(); // Didn't fall this back ThrowCharsOverflow( decoder, chars == charStart ); // throw? break; // don't throw, but stop loop } } else { // Make sure we have buffer space if(chars >= charEnd) { BCLDebug.Assert( bytes > byteStart || chars == charStart, "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)" ); bytes--; // unused byte ThrowCharsOverflow( decoder, chars == charStart ); // throw? break; // don't throw, but stop loop } *(chars) = unchecked( (char)b ); chars++; } } // Might have had decoder fallback stuff. if(decoder != null) { decoder.m_bytesUsed = (int)(bytes - byteStart); } // Expect Empty fallback buffer for GetChars BCLDebug.Assert( fallbackBuffer == null || fallbackBuffer.Remaining == 0, "[ASCIIEncoding.GetChars]Expected Empty fallback buffer" ); return (int)(chars - charStart); } public override int GetMaxByteCount( int charCount ) { if(charCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if(EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if(byteCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "charCount", Environment.GetResourceString( "ArgumentOutOfRange_GetByteCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)byteCount; } public override int GetMaxCharCount( int byteCount ) { if(byteCount < 0) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_NeedNonNegNum" ) ); #else throw new ArgumentOutOfRangeException(); #endif } // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if(DecoderFallback.MaxCharCount > 1) { charCount *= DecoderFallback.MaxCharCount; } if(charCount > 0x7fffffff) { #if EXCEPTION_STRINGS throw new ArgumentOutOfRangeException( "byteCount", Environment.GetResourceString( "ArgumentOutOfRange_GetCharCountOverflow" ) ); #else throw new ArgumentOutOfRangeException(); #endif } return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) //// [System.Runtime.InteropServices.ComVisible( false )] public override bool IsSingleByte { get { return true; } } //// [System.Runtime.InteropServices.ComVisible( false )] public override Decoder GetDecoder() { return new DecoderNLS( this ); } //// [System.Runtime.InteropServices.ComVisible( false )] public override Encoder GetEncoder() { return new EncoderNLS( this ); } } }
using System; using System.Collections.Generic; using System.Data; using System.Web.UI.WebControls; using SRP_DAL; using SRPApp.Classes; using GRA.SRP.ControlRooms; using GRA.SRP.Core.Utilities; using GRA.SRP.Utilities; namespace GRA.SRP.ControlRoom.Modules.Tenant { public partial class TenantGroupsAddEdit : BaseControlRoomPage { protected void Page_Load(object sender, EventArgs e) { MasterPage.IsSecure = true; MasterPage.PageTitle = "SRP - Add / Edit User Groups"; ControlRoomAccessPermission.CheckControlRoomAccessPermission(1000); // User Security; if (!IsPostBack) { List<RibbonPanel> moduleRibbonPanels = StandardModuleRibbons.MasterTenantRibbon(); foreach (var moduleRibbonPanel in moduleRibbonPanels) { MasterPage.PageRibbon.Add(moduleRibbonPanel); } MasterPage.PageRibbon.DataBind(); } if (!IsPostBack ) { lblGID.Text = Session["GID"] == null ? "" : Session["GID"].ToString(); //Session["GID"]= string.Empty; //lblGID.Text = Request["PK"]; dv.ChangeMode(lblGID.Text.Length == 0 ? DetailsViewMode.Insert : DetailsViewMode.Edit); var t = Core.Utilities.Tenant.FetchObject(int.Parse(Session["ATENID"].ToString())); lblOrg.Text = t.AdminName; } } protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e) { string returnURL = "~/ControlRoom/Modules/Tenant/TenantGroupList.aspx"; if (e.CommandName.ToLower() == "back") { Response.Redirect(returnURL); } if (e.CommandName.ToLower() == "refresh") { try { odsSRPGroups.DataBind(); dv.DataBind(); dv.ChangeMode(DetailsViewMode.Edit); MasterPage.PageMessage = SRPResources.RefreshOK; } catch (Exception ex) { MasterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message); } } if (e.CommandName.ToLower() == "add" || e.CommandName.ToLower() == "addandback") { try { SRPGroup obj = new SRPGroup(); //obj.GID = int.Parse( ((Label)((DetailsView)sender).FindControl(".GID")).Text ); obj.GroupName = ((TextBox)((DetailsView)sender).FindControl("GroupName")).Text; obj.GroupDescription = ((TextBox)((DetailsView)sender).FindControl("GroupDescription")).Text; obj.AddedDate = DateTime.Now; obj.AddedUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username; //"N/A"; // Get from session obj.LastModDate = obj.AddedDate; obj.LastModUser = obj.AddedUser; obj.TenID = int.Parse(Session["ATENID"].ToString()); if (obj.IsValid(BusinessRulesValidationMode.INSERT)) { obj.Insert(); if (e.CommandName.ToLower() == "addandback") { Response.Redirect(returnURL); } lblGID.Text = obj.GID.ToString(); odsSRPGroups.DataBind(); dv.DataBind(); dv.ChangeMode(DetailsViewMode.Edit); MasterPage.PageMessage = SRPResources.AddedOK; } else { string message = String.Format(SRPResources.ApplicationError1, "<ul>"); foreach (BusinessRulesValidationMessage m in obj.ErrorCodes) { message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage); } message = string.Format("{0}</ul>", message); MasterPage.PageError = message; } } catch(Exception ex) { MasterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message); } } if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback") { try { SRPGroup obj = new SRPGroup(); int pk = int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text); obj = SRPGroup.Fetch(pk); obj.GroupName = ((TextBox)((DetailsView)sender).FindControl("GroupName")).Text; obj.GroupDescription = ((TextBox)((DetailsView)sender).FindControl("GroupDescription")).Text; obj.LastModDate = DateTime.Now; obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username; //"N/A"; // Get from session if (obj.IsValid(BusinessRulesValidationMode.UPDATE)) { obj.Update(); SaveUsers((DetailsView)sender, obj); SavePermissions((DetailsView)sender, obj); if (e.CommandName.ToLower() == "saveandback") { Response.Redirect(returnURL); } odsSRPGroups.DataBind(); dv.DataBind(); dv.ChangeMode(DetailsViewMode.Edit); MasterPage.PageMessage = SRPResources.SaveOK; MasterPage.PageMessage = SRPResources.AddedOK; } else { string message = String.Format(SRPResources.ApplicationError1, "<ul>"); foreach (BusinessRulesValidationMessage m in obj.ErrorCodes) { message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage); } message = string.Format("{0}</ul>", message); MasterPage.PageError = message; } } catch(Exception ex) { MasterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message); } } } protected void SaveUsers(DetailsView dv, SRPGroup obj) { GridView gv = (GridView)dv.FindControl("gvGroupUsers"); string memberUsers= string.Empty; foreach (GridViewRow row in gv.Rows) { if (((CheckBox)row.FindControl("isMember")).Checked) { memberUsers = string.Format("{0},{1}", memberUsers, ((Label)row.FindControl("UID")).Text); } } if (memberUsers.Length > 0) memberUsers = memberUsers.Substring(1, memberUsers.Length - 1); SRPGroup.UpdateMemberUsers(obj.GID, memberUsers, ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username); } protected void SavePermissions(DetailsView dv, SRPGroup obj) { GridView gv = (GridView)dv.FindControl("gvGroupPermissions"); string groupPermissions= string.Empty; foreach (GridViewRow row in gv.Rows) { if (((CheckBox)row.FindControl("isChecked")).Checked) { groupPermissions = string.Format("{0},{1}", groupPermissions, ((Label)row.FindControl("PermissionID")).Text); } } if (groupPermissions.Length > 0) groupPermissions = groupPermissions.Substring(1, groupPermissions.Length - 1); SRPGroup.UpdatePermissions(obj.GID, groupPermissions, ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username); } } }
// Copyright (c) 2013-2015 Robert Rouhani <[email protected]> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using SharpNav; using SharpNav.Geometry; using SharpNav.Pathfinding; using SharpNav.Crowds; using System.Collections.Generic; //Prevents name collision under the Standalone configuration #if STANDALONE using Vector3 = OpenTK.Vector3; using SVector3 = SharpNav.Geometry.Vector3; #elif OPENTK using SVector3 = OpenTK.Vector3; #endif //Doesn't compile if in an unsupported configuration #if STANDALONE || OPENTK namespace SharpNav.Examples { public partial class ExampleWindow { private int levelVbo, levelNormVbo, heightfieldVoxelVbo, heightfieldVoxelIbo, squareVbo, squareIbo; private int levelNumInds; private bool levelHasNorm; private ObjModel level; private AgentCylinder agentCylinder; private static readonly byte[] squareInds = { 0, 1, 2, 0, 2, 3 }; private static readonly float[] squareVerts = { 0.5f, 0, 0.5f, 0, 1, 0, 0.5f, 0, -0.5f, 0, 1, 0, -0.5f, 0, -0.5f, 0, 1, 0, -0.5f, 0, 0.5f, 0, 1, 0 }; private static readonly byte[] voxelInds = { 0, 2, 1, 0, 3, 2, //-Z 4, 6, 5, 4, 7, 6, //+X 8, 10, 9, 8, 11, 10, //+Z 12, 14, 13, 12, 15, 14, //-X 16, 18, 17, 16, 19, 18, //+Y 20, 22, 21, 20, 23, 22 //-Y }; private static readonly float[] voxelVerts = { //-Z face -0.5f, 0.5f, -0.5f, 0, 0, -1, -0.5f, -0.5f, -0.5f, 0, 0, -1, 0.5f, -0.5f, -0.5f, 0, 0, -1, 0.5f, 0.5f, -0.5f, 0, 0, -1, //+X face 0.5f, 0.5f, -0.5f, 1, 0, 0, 0.5f, -0.5f, -0.5f, 1, 0, 0, 0.5f, -0.5f, 0.5f, 1, 0, 0, 0.5f, 0.5f, 0.5f, 1, 0, 0, //+Z face 0.5f, 0.5f, 0.5f, 0, 0, 1, 0.5f, -0.5f, 0.5f, 0, 0, 1, -0.5f, -0.5f, 0.5f, 0, 0, 1, -0.5f, 0.5f, 0.5f, 0, 0, 1, //-X face -0.5f, 0.5f, 0.5f, -1, 0, 0, -0.5f, -0.5f, 0.5f, -1, 0, 0, -0.5f, -0.5f, -0.5f, -1, 0, 0, -0.5f, 0.5f, -0.5f, -1, 0, 0, //+Y face -0.5f, 0.5f, 0.5f, 0, 1, 0, -0.5f, 0.5f, -0.5f, 0, 1, 0, 0.5f, 0.5f, -0.5f, 0, 1, 0, 0.5f, 0.5f, 0.5f, 0, 1, 0, //-Y face -0.5f, -0.5f, -0.5f, 0, -1, 0, -0.5f, -0.5f, 0.5f, 0, -1, 0, 0.5f, -0.5f, 0.5f, 0, -1, 0, 0.5f, -0.5f, -0.5f, 0, -1, 0 }; private void InitializeOpenGL() { GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); GL.DepthFunc(DepthFunction.Lequal); GL.Enable(EnableCap.CullFace); GL.FrontFace(FrontFaceDirection.Ccw); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); GL.ClearColor(Color4.CornflowerBlue); GL.Enable(EnableCap.Lighting); GL.Enable(EnableCap.Light0); GL.Light(LightName.Light0, LightParameter.Ambient, new Vector4(0.6f, 0.6f, 0.6f, 1f)); GL.Disable(EnableCap.Light0); GL.Disable(EnableCap.Lighting); agentCylinder = new AgentCylinder(12, 0.5f, 2f); } private void LoadLevel() { level = new ObjModel("nav_test.obj"); var levelTris = level.GetTriangles(); var levelNorms = level.GetNormals(); levelNumInds = levelTris.Length * 3; levelHasNorm = levelNorms != null && levelNorms.Length > 0; var bounds = TriangleEnumerable.FromTriangle(levelTris, 0, levelTris.Length).GetBoundingBox(); cam.Position = new Vector3(bounds.Max.X, bounds.Max.Y, bounds.Max.Z) * 1.5f; cam.RotateHeadingTo(-25); cam.RotatePitchTo(315); //TODO fix camera, it breaks with lookat... //cam.LookAt(new Vector3(bounds.Center.X, bounds.Center.Y, bounds.Center.Z)); levelVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, levelVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(levelNumInds * 3 * 4), levelTris, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); if (levelHasNorm) { levelNormVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, levelNormVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(levelNorms.Length * 3 * 4), levelNorms, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); } } private void LoadDebugMeshes() { heightfieldVoxelVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, heightfieldVoxelVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(voxelVerts.Length * 4), voxelVerts, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); heightfieldVoxelIbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, heightfieldVoxelIbo); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)voxelInds.Length, voxelInds, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); squareVbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(squareVerts.Length * 4), squareVerts, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); squareIbo = GL.GenBuffer(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)squareInds.Length, squareInds, BufferUsageHint.StaticDraw); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); } private void UnloadLevel() { GL.DeleteBuffer(levelVbo); GL.DeleteBuffer(levelNormVbo); } private void UnloadDebugMeshes() { GL.DeleteBuffer(heightfieldVoxelVbo); GL.DeleteBuffer(heightfieldVoxelIbo); GL.DeleteBuffer(squareVbo); GL.DeleteBuffer(squareIbo); } private void DrawUI() { GL.PushMatrix(); GL.LoadIdentity(); GL.MatrixMode(MatrixMode.Projection); GL.PushMatrix(); GL.LoadMatrix(ref gwenProjection); GL.FrontFace(FrontFaceDirection.Cw); gwenCanvas.RenderCanvas(); GL.FrontFace(FrontFaceDirection.Ccw); GL.PopMatrix(); GL.MatrixMode(MatrixMode.Modelview); GL.PopMatrix(); } private void DrawLevel() { GL.EnableClientState(ArrayCap.VertexArray); if (levelHasNorm) GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, levelVbo); GL.VertexPointer(3, VertexPointerType.Float, 0, 0); if (levelHasNorm) { GL.BindBuffer(BufferTarget.ArrayBuffer, levelNormVbo); GL.NormalPointer(NormalPointerType.Float, 0, 0); } GL.DrawArrays(BeginMode.Triangles, 0, levelNumInds); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); if (levelHasNorm) GL.DisableClientState(ArrayCap.NormalArray); GL.DisableClientState(ArrayCap.VertexArray); } private void DrawHeightfield() { if (heightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.Enable(EnableCap.Lighting); GL.Enable(EnableCap.Light0); GL.Light(LightName.Light0, LightParameter.Position, new Vector4(0.5f, 1, 0.5f, 0)); GL.BindBuffer(BufferTarget.ArrayBuffer, heightfieldVoxelVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.Color4(0.5f, 0.5f, 0.5f, 1f); GL.BindBuffer(BufferTarget.ElementArrayBuffer, heightfieldVoxelIbo); var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 spanLoc, spanScale; for (int i = 0; i < heightfield.Length; i++) { for (int j = 0; j < heightfield.Width; j++) { var cellLoc = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); var cell = heightfield[j, i]; foreach (var span in cell.Spans) { GL.PushMatrix(); Matrix4.CreateTranslation(cellLoc.X, ((span.Minimum + span.Maximum) * 0.5f) * cellSize.Y + cellLoc.Y, cellLoc.Z, out spanLoc); GL.MultMatrix(ref spanLoc); Matrix4.CreateScale(cellSize.X, cellSize.Y * span.Height, cellSize.Z, out spanScale); GL.MultMatrix(ref spanScale); GL.DrawElements(BeginMode.Triangles, voxelInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.Disable(EnableCap.Light0); GL.Disable(EnableCap.Lighting); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawCompactHeightfield() { if (compactHeightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 squareScale, squareTrans; Vector3 squarePos; Matrix4.CreateScale(cellSize.X, 1, cellSize.Z, out squareScale); for (int i = 0; i < compactHeightfield.Length; i++) { for (int j = 0; j < compactHeightfield.Width; j++) { squarePos = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); var cell = compactHeightfield[j, i]; foreach (var span in cell) { GL.PushMatrix(); int numCons = 0; for (var dir = Direction.West; dir <= Direction.South; dir++) { if (span.IsConnected(dir)) numCons++; } GL.Color4(numCons / 4f, numCons / 4f, numCons / 4f, 1f); var squarePosFinal = new OpenTK.Vector3(squarePos.X, squarePos.Y, squarePos.Z); squarePosFinal.Y += span.Minimum * cellSize.Y; Matrix4.CreateTranslation(ref squarePosFinal, out squareTrans); GL.MultMatrix(ref squareTrans); GL.MultMatrix(ref squareScale); GL.DrawElements(BeginMode.Triangles, squareInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawDistanceField() { if (compactHeightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); int maxdist = compactHeightfield.MaxDistance; var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 squareScale, squareTrans; Vector3 squarePos; Matrix4.CreateScale(cellSize.X, 1, cellSize.Z, out squareScale); for (int i = 0; i < compactHeightfield.Length; i++) { for (int j = 0; j < compactHeightfield.Width; j++) { squarePos = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); var cell = compactHeightfield.Cells[i * compactHeightfield.Width + j]; for (int k = cell.StartIndex, kEnd = cell.StartIndex + cell.Count; k < kEnd; k++) { GL.PushMatrix(); int dist = compactHeightfield.Distances[k]; float val = (float)dist / (float)maxdist; GL.Color4(val, val, val, 1f); var span = compactHeightfield.Spans[k]; var squarePosFinal = new OpenTK.Vector3(squarePos.X, squarePos.Y, squarePos.Z); squarePosFinal.Y += span.Minimum * cellSize.Y; Matrix4.CreateTranslation(ref squarePosFinal, out squareTrans); GL.MultMatrix(ref squareTrans); GL.MultMatrix(ref squareScale); GL.DrawElements(BeginMode.Triangles, squareInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawRegions() { if (compactHeightfield == null) return; GL.EnableClientState(ArrayCap.VertexArray); GL.EnableClientState(ArrayCap.NormalArray); GL.BindBuffer(BufferTarget.ArrayBuffer, squareVbo); GL.VertexPointer(3, VertexPointerType.Float, 6 * 4, 0); GL.NormalPointer(NormalPointerType.Float, 6 * 4, 3 * 4); GL.BindBuffer(BufferTarget.ElementArrayBuffer, squareIbo); int maxdist = compactHeightfield.MaxDistance; var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; Matrix4 squareScale, squareTrans; Vector3 squarePos; Matrix4.CreateScale(cellSize.X, 1, cellSize.Z, out squareScale); for (int i = 0; i < compactHeightfield.Length; i++) { for (int j = 0; j < compactHeightfield.Width; j++) { var cell = compactHeightfield.Cells[i * compactHeightfield.Width + j]; squarePos = new Vector3(j * cellSize.X + halfCellSize.X + heightfield.Bounds.Min.X, heightfield.Bounds.Min.Y, i * cellSize.Z + halfCellSize.Z + heightfield.Bounds.Min.Z); for (int k = cell.StartIndex, kEnd = cell.StartIndex + cell.Count; k < kEnd; k++) { GL.PushMatrix(); var span = compactHeightfield.Spans[k]; int region = span.Region.Id; //if (Region.IsBorder(region)) //region = Region.RemoveFlags(region); Color4 col = regionColors[region]; GL.Color4(col); var squarePosFinal = new OpenTK.Vector3(squarePos.X, squarePos.Y, squarePos.Z); squarePosFinal.Y += span.Minimum * cellSize.Y; Matrix4.CreateTranslation(ref squarePosFinal, out squareTrans); GL.MultMatrix(ref squareTrans); GL.MultMatrix(ref squareScale); GL.DrawElements(BeginMode.Triangles, squareInds.Length, DrawElementsType.UnsignedByte, 0); GL.PopMatrix(); } } } GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindBuffer(BufferTarget.ArrayBuffer, 0); GL.DisableClientState(ArrayCap.VertexArray); GL.DisableClientState(ArrayCap.NormalArray); } private void DrawContours() { if (contourSet == null) return; GL.EnableClientState(ArrayCap.VertexArray); int maxdist = compactHeightfield.MaxDistance; var cellSize = heightfield.CellSize; var halfCellSize = cellSize * 0.5f; GL.PushMatrix(); Matrix4 squareScale, squareTrans; Matrix4.CreateTranslation(heightfield.Bounds.Min.X + cellSize.X * compactHeightfield.BorderSize, heightfield.Bounds.Min.Y, heightfield.Bounds.Min.Z + cellSize.Z * compactHeightfield.BorderSize, out squareTrans); GL.MultMatrix(ref squareTrans); Matrix4.CreateScale(cellSize.X, cellSize.Y, cellSize.Z, out squareScale); GL.MultMatrix(ref squareScale); GL.LineWidth(5f); GL.Begin(BeginMode.Lines); foreach (var c in contourSet) { RegionId region = c.RegionId; //skip border regions if (RegionId.HasFlags(region, RegionFlags.Border)) continue; Color4 col = regionColors[(int)region]; GL.Color4(col); for (int i = 0; i < c.Vertices.Length; i++) { int ni = (i + 1) % c.Vertices.Length; GL.Vertex3(c.Vertices[i].X, c.Vertices[i].Y, c.Vertices[i].Z); GL.Vertex3(c.Vertices[ni].X, c.Vertices[ni].Y, c.Vertices[ni].Z); } } GL.End(); GL.PopMatrix(); GL.DisableClientState(ArrayCap.VertexArray); } private void DrawPolyMesh() { if (polyMesh == null) return; GL.PushMatrix(); Matrix4 squareScale, squareTrans; Matrix4.CreateTranslation(polyMesh.Bounds.Min.X, polyMesh.Bounds.Min.Y, polyMesh.Bounds.Min.Z, out squareTrans); GL.MultMatrix(ref squareTrans); Matrix4.CreateScale(polyMesh.CellSize, polyMesh.CellHeight, polyMesh.CellSize, out squareScale); GL.MultMatrix(ref squareScale); Color4 color = Color4.DarkViolet; color.A = 0.5f; GL.Color4(color); GL.Begin(BeginMode.Triangles); for (int i = 0; i < polyMesh.PolyCount; i++) { if (!polyMesh.Polys[i].Area.IsWalkable) continue; for (int j = 2; j < polyMesh.NumVertsPerPoly; j++) { if (polyMesh.Polys[i].Vertices[j] == PolyMesh.NullId) break; int vertIndex0 = polyMesh.Polys[i].Vertices[0]; int vertIndex1 = polyMesh.Polys[i].Vertices[j - 1]; int vertIndex2 = polyMesh.Polys[i].Vertices[j]; var v = polyMesh.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.DepthMask(false); //neighbor edges GL.Color4(Color4.Purple); GL.LineWidth(1.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < polyMesh.PolyCount; i++) { for (int j = 0; j < polyMesh.NumVertsPerPoly; j++) { if (polyMesh.Polys[i].Vertices[j] == PolyMesh.NullId) break; if (PolyMesh.IsBoundaryEdge(polyMesh.Polys[i].NeighborEdges[j])) continue; int nj = (j + 1 >= polyMesh.NumVertsPerPoly || polyMesh.Polys[i].Vertices[j + 1] == PolyMesh.NullId) ? 0 : j + 1; int vertIndex0 = polyMesh.Polys[i].Vertices[j]; int vertIndex1 = polyMesh.Polys[i].Vertices[nj]; var v = polyMesh.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); //boundary edges GL.LineWidth(3.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < polyMesh.PolyCount; i++) { for (int j = 0; j < polyMesh.NumVertsPerPoly; j++) { if (polyMesh.Polys[i].Vertices[j] == PolyMesh.NullId) break; if (PolyMesh.IsInteriorEdge(polyMesh.Polys[i].NeighborEdges[j])) continue; int nj = (j + 1 >= polyMesh.NumVertsPerPoly || polyMesh.Polys[i].Vertices[j + 1] == PolyMesh.NullId) ? 0 : j + 1; int vertIndex0 = polyMesh.Polys[i].Vertices[j]; int vertIndex1 = polyMesh.Polys[i].Vertices[nj]; var v = polyMesh.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMesh.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.PointSize(4.8f); GL.Begin(BeginMode.Points); for (int i = 0; i < polyMesh.VertCount; i++) { var v = polyMesh.Verts[i]; GL.Vertex3(v.X, v.Y, v.Z); } GL.End(); GL.DepthMask(true); GL.PopMatrix(); } private void DrawPolyMeshDetail() { if (polyMeshDetail == null) return; GL.PushMatrix(); Matrix4 transMatrix = Matrix4.CreateTranslation(0, -polyMesh.CellHeight, 0); GL.MultMatrix(ref transMatrix); Color4 color = Color4.DarkViolet; color.A = 0.5f; GL.Color4(color); GL.Begin(BeginMode.Triangles); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { PolyMeshDetail.MeshData m = polyMeshDetail.Meshes[i]; int vertIndex = m.VertexIndex; int triIndex = m.TriangleIndex; for (int j = 0; j < m.TriangleCount; j++) { var t = polyMeshDetail.Tris[triIndex + j]; var v = polyMeshDetail.Verts[vertIndex + t.VertexHash0]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t.VertexHash1]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t.VertexHash2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.Color4(Color4.Purple); GL.LineWidth(1.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { var m = polyMeshDetail.Meshes[i]; int vertIndex = m.VertexIndex; int triIndex = m.TriangleIndex; for (int j = 0; j < m.TriangleCount; j++) { var t = polyMeshDetail.Tris[triIndex + j]; for (int k = 0, kp = 2; k < 3; kp = k++) { if (((t.Flags >> (kp * 2)) & 0x3) == 0) { if (t[kp] < t[k]) { var v = polyMeshDetail.Verts[vertIndex + t[kp]]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t[k]]; GL.Vertex3(v.X, v.Y, v.Z); } } } } } GL.End(); GL.LineWidth(3.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { var m = polyMeshDetail.Meshes[i]; int vertIndex = m.VertexIndex; int triIndex = m.TriangleIndex; for (int j = 0; j < m.TriangleCount; j++) { var t = polyMeshDetail.Tris[triIndex + j]; for (int k = 0, kp = 2; k < 3; kp = k++) { if (((t.Flags >> (kp * 2)) & 0x3) != 0) { var v = polyMeshDetail.Verts[vertIndex + t[kp]]; GL.Vertex3(v.X, v.Y, v.Z); v = polyMeshDetail.Verts[vertIndex + t[k]]; GL.Vertex3(v.X, v.Y, v.Z); } } } } GL.End(); GL.PointSize(4.8f); GL.Begin(BeginMode.Points); for (int i = 0; i < polyMeshDetail.MeshCount; i++) { var m = polyMeshDetail.Meshes[i]; for (int j = 0; j < m.VertexCount; j++) { var v = polyMeshDetail.Verts[m.VertexIndex + j]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.PopMatrix(); } private void DrawNavMesh() { if (tiledNavMesh == null) return; var tile = tiledNavMesh.GetTileAt(0, 0, 0); GL.PushMatrix(); Color4 color = Color4.DarkViolet; color.A = 0.5f; GL.Color4(color); GL.Begin(BeginMode.Triangles); for (int i = 0; i < tile.Polys.Length; i++) { //if (!tile.Polys[i].Area.IsWalkable) //continue; for (int j = 2; j < PathfindingCommon.VERTS_PER_POLYGON; j++) { if (tile.Polys[i].Verts[j] == 0) break; int vertIndex0 = tile.Polys[i].Verts[0]; int vertIndex1 = tile.Polys[i].Verts[j - 1]; int vertIndex2 = tile.Polys[i].Verts[j]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.DepthMask(false); //neighbor edges GL.Color4(Color4.Purple); GL.LineWidth(1.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < tile.Polys.Length; i++) { for (int j = 0; j < PathfindingCommon.VERTS_PER_POLYGON; j++) { if (tile.Polys[i].Verts[j] == 0) break; if (PolyMesh.IsBoundaryEdge(tile.Polys[i].Neis[j])) continue; int nj = (j + 1 >= PathfindingCommon.VERTS_PER_POLYGON || tile.Polys[i].Verts[j + 1] == 0) ? 0 : j + 1; int vertIndex0 = tile.Polys[i].Verts[j]; int vertIndex1 = tile.Polys[i].Verts[nj]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); //boundary edges GL.LineWidth(3.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < tile.Polys.Length; i++) { for (int j = 0; j < PathfindingCommon.VERTS_PER_POLYGON; j++) { if (tile.Polys[i].Verts[j] == 0) break; if (PolyMesh.IsInteriorEdge(tile.Polys[i].Neis[j])) continue; int nj = (j + 1 >= PathfindingCommon.VERTS_PER_POLYGON || tile.Polys[i].Verts[j + 1] == 0) ? 0 : j + 1; int vertIndex0 = tile.Polys[i].Verts[j]; int vertIndex1 = tile.Polys[i].Verts[nj]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.PointSize(4.8f); GL.Begin(BeginMode.Points); for (int i = 0; i < tile.Verts.Length; i++) { var v = tile.Verts[i]; GL.Vertex3(v.X, v.Y, v.Z); } GL.End(); GL.DepthMask(true); GL.PopMatrix(); } private void DrawPathfinding() { if (path == null) return; GL.PushMatrix(); Color4 color = Color4.Cyan; GL.Begin(BeginMode.Triangles); for (int i = 0; i < path.Count; i++) { if (i == 0) color = Color4.Cyan; else if (i == path.Count - 1) color = Color4.PaleVioletRed; else color = Color4.LightYellow; GL.Color4(color); NavPolyId polyRef = path[i]; NavTile tile; NavPoly poly; tiledNavMesh.TryGetTileAndPolyByRefUnsafe(polyRef, out tile, out poly); for (int j = 2; j < poly.VertCount; j++) { int vertIndex0 = poly.Verts[0]; int vertIndex1 = poly.Verts[j - 1]; int vertIndex2 = poly.Verts[j]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex2]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); GL.DepthMask(false); //neighbor edges GL.LineWidth(1.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < path.Count; i++) { if (i == 0) color = Color4.Blue; else if (i == path.Count - 1) color = Color4.Red; else color = Color4.Yellow; GL.Color4(color); NavPolyId polyRef = path[i]; NavTile tile; NavPoly poly; tiledNavMesh.TryGetTileAndPolyByRefUnsafe(polyRef, out tile, out poly); for (int j = 0; j < poly.VertCount; j++) { int vertIndex0 = poly.Verts[j]; int vertIndex1 = poly.Verts[(j + 1) % poly.VertCount]; var v = tile.Verts[vertIndex0]; GL.Vertex3(v.X, v.Y, v.Z); v = tile.Verts[vertIndex1]; GL.Vertex3(v.X, v.Y, v.Z); } } GL.End(); //steering path GL.Color4(Color4.Black); GL.Begin(BeginMode.Lines); for (int i = 0; i < smoothPath.Count - 1; i++) { SVector3 v0 = smoothPath[i]; GL.Vertex3(v0.X, v0.Y, v0.Z); SVector3 v1 = smoothPath[i + 1]; GL.Vertex3(v1.X, v1.Y, v1.Z); } GL.End(); GL.DepthMask(true); GL.PopMatrix(); } private void DrawCrowd() { if (crowd == null) return; GL.PushMatrix(); //The black line represents the actual path that the agent takes /*GL.Color4(Color4.Black); GL.Begin(BeginMode.Lines); for (int i = 0; i < numActiveAgents; i++) { for (int j = 0; j < numIterations - 1; j++) { SVector3 v0 = trails[i].Trail[j]; GL.Vertex3(v0.X, v0.Y, v0.Z); SVector3 v1 = trails[i].Trail[j + 1]; GL.Vertex3(v1.X, v1.Y, v1.Z); } } GL.End(); //The yellow line represents the ideal path from the start to the target GL.Color4(Color4.Yellow); GL.LineWidth(1.5f); GL.Begin(BeginMode.Lines); for (int i = 0; i < numActiveAgents; i++) { SVector3 v0 = trails[i].Trail[0]; GL.Vertex3(v0.X, v0.Y, v0.Z); SVector3 v1 = trails[i].Trail[AGENT_MAX_TRAIL - 1]; GL.Vertex3(v1.X, v1.Y, v1.Z); } GL.End(); //The cyan point represents the agent's starting location GL.PointSize(100.0f); GL.Color4(Color4.Cyan); GL.Begin(BeginMode.Points); for (int i = 0; i < numActiveAgents; i++) { SVector3 v0 = trails[i].Trail[0]; GL.Vertex3(v0.X, v0.Y, v0.Z); } GL.End(); //The red point represent's the agent's target location GL.Color4(Color4.PaleVioletRed); GL.Begin(BeginMode.Points); for (int i = 0; i < numActiveAgents; i++) { SVector3 v0 = trails[i].Trail[AGENT_MAX_TRAIL - 1]; GL.Vertex3(v0.X, v0.Y, v0.Z); } GL.End();*/ //GL.DepthMask(true); GL.Color4(Color4.PaleVioletRed); GL.PointSize(10); GL.Begin(BeginMode.Points); GL.Color4(Color4.Blue); for (int i = 0; i < numActiveAgents; i++) { SVector3 p = crowd.GetAgent(i).TargetPosition; GL.Vertex3(p.X, p.Y, p.Z); } GL.End(); if (agentCylinder != null) { for (int i = 0; i < numActiveAgents; i++) { SVector3 p = crowd.GetAgent(i).Position; agentCylinder.Draw(new Vector3(p.X, p.Y, p.Z)); } } GL.PopMatrix(); } } } #endif
/* * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net.Config; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Setup; using System.IO; using System.Xml; namespace OpenSim.Region.CoreModules.World.Serialiser.Tests { [TestFixture] public class SerialiserTests { private string xml = @" <SceneObjectGroup> <RootPart> <SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <AllowedDrop>false</AllowedDrop> <CreatorID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></CreatorID> <FolderID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></FolderID> <InventorySerial>1</InventorySerial> <TaskInventory /> <ObjectFlags>0</ObjectFlags> <UUID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></UUID> <LocalId>2698615125</LocalId> <Name>PrimMyRide</Name> <Material>0</Material> <PassTouches>false</PassTouches> <RegionHandle>1099511628032000</RegionHandle> <ScriptAccessPin>0</ScriptAccessPin> <GroupPosition><X>147.23</X><Y>92.698</Y><Z>22.78084</Z></GroupPosition> <OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition> <RotationOffset><X>-4.371139E-08</X><Y>-1</Y><Z>-4.371139E-08</Z><W>0</W></RotationOffset> <Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity> <RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity> <AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity> <Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration> <Description /> <Color /> <Text /> <SitName /> <TouchName /> <LinkNum>0</LinkNum> <ClickAction>0</ClickAction> <Shape> <ProfileCurve>1</ProfileCurve> <TextureEntry>AAAAAAAAERGZmQAAAAAABQCVlZUAAAAAQEAAAABAQAAAAAAAAAAAAAAAAAAAAA==</TextureEntry> <ExtraParams>AA==</ExtraParams> <PathBegin>0</PathBegin> <PathCurve>16</PathCurve> <PathEnd>0</PathEnd> <PathRadiusOffset>0</PathRadiusOffset> <PathRevolutions>0</PathRevolutions> <PathScaleX>100</PathScaleX> <PathScaleY>100</PathScaleY> <PathShearX>0</PathShearX> <PathShearY>0</PathShearY> <PathSkew>0</PathSkew> <PathTaperX>0</PathTaperX> <PathTaperY>0</PathTaperY> <PathTwist>0</PathTwist> <PathTwistBegin>0</PathTwistBegin> <PCode>9</PCode> <ProfileBegin>0</ProfileBegin> <ProfileEnd>0</ProfileEnd> <ProfileHollow>0</ProfileHollow> <Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale> <State>0</State> <ProfileShape>Square</ProfileShape> <HollowShape>Same</HollowShape> <SculptTexture><Guid>00000000-0000-0000-0000-000000000000</Guid></SculptTexture> <SculptType>0</SculptType><SculptData /> <FlexiSoftness>0</FlexiSoftness> <FlexiTension>0</FlexiTension> <FlexiDrag>0</FlexiDrag> <FlexiGravity>0</FlexiGravity> <FlexiWind>0</FlexiWind> <FlexiForceX>0</FlexiForceX> <FlexiForceY>0</FlexiForceY> <FlexiForceZ>0</FlexiForceZ> <LightColorR>0</LightColorR> <LightColorG>0</LightColorG> <LightColorB>0</LightColorB> <LightColorA>1</LightColorA> <LightRadius>0</LightRadius> <LightCutoff>0</LightCutoff> <LightFalloff>0</LightFalloff> <LightIntensity>1</LightIntensity> <FlexiEntry>false</FlexiEntry> <LightEntry>false</LightEntry> <SculptEntry>false</SculptEntry> </Shape> <Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale> <UpdateFlag>0</UpdateFlag> <SitTargetOrientation><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientation> <SitTargetPosition><X>0</X><Y>0</Y><Z>0</Z></SitTargetPosition> <SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL> <SitTargetOrientationLL><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientationLL> <ParentID>0</ParentID> <CreationDate>1211330445</CreationDate> <Category>0</Category> <SalePrice>0</SalePrice> <ObjectSaleType>0</ObjectSaleType> <OwnershipCost>0</OwnershipCost> <GroupID><Guid>00000000-0000-0000-0000-000000000000</Guid></GroupID> <OwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></OwnerID> <LastOwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></LastOwnerID> <BaseMask>2147483647</BaseMask> <OwnerMask>2147483647</OwnerMask> <GroupMask>0</GroupMask> <EveryoneMask>0</EveryoneMask> <NextOwnerMask>2147483647</NextOwnerMask> <Flags>None</Flags> <CollisionSound><Guid>00000000-0000-0000-0000-000000000000</Guid></CollisionSound> <CollisionSoundVolume>0</CollisionSoundVolume> </SceneObjectPart> </RootPart> <OtherParts /> </SceneObjectGroup>"; private string xml2 = @" <SceneObjectGroup> <SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <CreatorID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></CreatorID> <FolderID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></FolderID> <InventorySerial>0</InventorySerial> <TaskInventory /> <ObjectFlags>0</ObjectFlags> <UUID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></UUID> <LocalId>720005</LocalId> <Name>PrimFun</Name> <Material>0</Material> <RegionHandle>1099511628032000</RegionHandle> <ScriptAccessPin>0</ScriptAccessPin> <GroupPosition><X>153.9854</X><Y>121.4908</Y><Z>62.21781</Z></GroupPosition> <OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition> <RotationOffset><X>0</X><Y>0</Y><Z>0</Z><W>1</W></RotationOffset> <Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity> <RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity> <AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity> <Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration> <Description /> <Color /> <Text /> <SitName /> <TouchName /> <LinkNum>0</LinkNum> <ClickAction>0</ClickAction> <Shape> <PathBegin>0</PathBegin> <PathCurve>16</PathCurve> <PathEnd>0</PathEnd> <PathRadiusOffset>0</PathRadiusOffset> <PathRevolutions>0</PathRevolutions> <PathScaleX>200</PathScaleX> <PathScaleY>200</PathScaleY> <PathShearX>0</PathShearX> <PathShearY>0</PathShearY> <PathSkew>0</PathSkew> <PathTaperX>0</PathTaperX> <PathTaperY>0</PathTaperY> <PathTwist>0</PathTwist> <PathTwistBegin>0</PathTwistBegin> <PCode>9</PCode> <ProfileBegin>0</ProfileBegin> <ProfileEnd>0</ProfileEnd> <ProfileHollow>0</ProfileHollow> <Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale> <State>0</State> <ProfileShape>Circle</ProfileShape> <HollowShape>Same</HollowShape> <ProfileCurve>0</ProfileCurve> <TextureEntry>iVVnRyTLQ+2SC0fK7RVGXwJ6yc/SU4RDA5nhJbLUw3R1AAAAAAAAaOw8QQOhPSRAAKE9JEAAAAAAAAAAAAAAAAAAAAA=</TextureEntry> <ExtraParams>AA==</ExtraParams> </Shape> <Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale> <UpdateFlag>0</UpdateFlag> <SitTargetOrientation><w>0</w><x>0</x><y>0</y><z>1</z></SitTargetOrientation> <SitTargetPosition><x>0</x><y>0</y><z>0</z></SitTargetPosition> <SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL> <SitTargetOrientationLL><X>0</X><Y>0</Y><Z>1</Z><W>0</W></SitTargetOrientationLL> <ParentID>0</ParentID> <CreationDate>1216066902</CreationDate> <Category>0</Category> <SalePrice>0</SalePrice> <ObjectSaleType>0</ObjectSaleType> <OwnershipCost>0</OwnershipCost> <GroupID><UUID>00000000-0000-0000-0000-000000000000</UUID></GroupID> <OwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></OwnerID> <LastOwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></LastOwnerID> <BaseMask>2147483647</BaseMask> <OwnerMask>2147483647</OwnerMask> <GroupMask>0</GroupMask> <EveryoneMask>0</EveryoneMask> <NextOwnerMask>2147483647</NextOwnerMask> <Flags>None</Flags> <SitTargetAvatar><UUID>00000000-0000-0000-0000-000000000000</UUID></SitTargetAvatar> </SceneObjectPart> <OtherParts /> </SceneObjectGroup>"; protected Scene m_scene; protected SerialiserModule m_serialiserModule; [TestFixtureSetUp] public void Init() { m_serialiserModule = new SerialiserModule(); m_scene = SceneSetupHelpers.SetupScene(""); SceneSetupHelpers.SetupSceneModules(m_scene, m_serialiserModule); } [Test] public void TestDeserializeXml() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup so = SceneObjectSerializer.FromOriginalXmlFormat(xml); SceneObjectPart rootPart = so.RootPart; Assert.That(rootPart.UUID, Is.EqualTo(new UUID("e6a5a05e-e8cc-4816-8701-04165e335790"))); Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("a6dacf01-4636-4bb9-8a97-30609438af9d"))); Assert.That(rootPart.Name, Is.EqualTo("PrimMyRide")); // TODO: Check other properties } [Test] public void TestSerializeXml() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string rpName = "My Little Donkey"; UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000964"); UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000915"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); // Vector3 groupPosition = new Vector3(10, 20, 30); // Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); // Vector3 offsetPosition = new Vector3(5, 10, 15); SceneObjectPart rp = new SceneObjectPart(); rp.UUID = rpUuid; rp.Name = rpName; rp.CreatorID = rpCreatorId; rp.Shape = shape; SceneObjectGroup so = new SceneObjectGroup(rp); // Need to add the object to the scene so that the request to get script state succeeds m_scene.AddSceneObject(so); string xml = SceneObjectSerializer.ToOriginalXmlFormat(so); XmlTextReader xtr = new XmlTextReader(new StringReader(xml)); xtr.ReadStartElement("SceneObjectGroup"); xtr.ReadStartElement("RootPart"); xtr.ReadStartElement("SceneObjectPart"); UUID uuid = UUID.Zero; string name = null; UUID creatorId = UUID.Zero; while (xtr.Read() && xtr.Name != "SceneObjectPart") { if (xtr.NodeType != XmlNodeType.Element) continue; switch (xtr.Name) { case "UUID": xtr.ReadStartElement("UUID"); uuid = UUID.Parse(xtr.ReadElementString("Guid")); xtr.ReadEndElement(); break; case "Name": name = xtr.ReadElementContentAsString(); break; case "CreatorID": xtr.ReadStartElement("CreatorID"); creatorId = UUID.Parse(xtr.ReadElementString("Guid")); xtr.ReadEndElement(); break; } } xtr.ReadEndElement(); xtr.ReadEndElement(); xtr.ReadStartElement("OtherParts"); xtr.ReadEndElement(); xtr.Close(); // TODO: More checks Assert.That(uuid, Is.EqualTo(rpUuid)); Assert.That(name, Is.EqualTo(rpName)); Assert.That(creatorId, Is.EqualTo(rpCreatorId)); } [Test] public void TestDeserializeXml2() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup so = m_serialiserModule.DeserializeGroupFromXml2(xml2); SceneObjectPart rootPart = so.RootPart; Assert.That(rootPart.UUID, Is.EqualTo(new UUID("9be68fdd-f740-4a0f-9675-dfbbb536b946"))); Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("b46ef588-411e-4a8b-a284-d7dcfe8e74ef"))); Assert.That(rootPart.Name, Is.EqualTo("PrimFun")); // TODO: Check other properties } [Test] public void TestSerializeXml2() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string rpName = "My Little Pony"; UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000064"); UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000015"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); // Vector3 groupPosition = new Vector3(10, 20, 30); // Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); // Vector3 offsetPosition = new Vector3(5, 10, 15); SceneObjectPart rp = new SceneObjectPart(); rp.UUID = rpUuid; rp.Name = rpName; rp.CreatorID = rpCreatorId; rp.Shape = shape; SceneObjectGroup so = new SceneObjectGroup(rp); // Need to add the object to the scene so that the request to get script state succeeds m_scene.AddSceneObject(so); string xml2 = m_serialiserModule.SerializeGroupToXml2(so); XmlTextReader xtr = new XmlTextReader(new StringReader(xml2)); xtr.ReadStartElement("SceneObjectGroup"); xtr.ReadStartElement("SceneObjectPart"); UUID uuid = UUID.Zero; string name = null; UUID creatorId = UUID.Zero; while (xtr.Read() && xtr.Name != "SceneObjectPart") { if (xtr.NodeType != XmlNodeType.Element) continue; switch (xtr.Name) { case "UUID": xtr.ReadStartElement("UUID"); uuid = UUID.Parse(xtr.ReadElementString("Guid")); xtr.ReadEndElement(); break; case "Name": name = xtr.ReadElementContentAsString(); break; case "CreatorID": xtr.ReadStartElement("CreatorID"); creatorId = UUID.Parse(xtr.ReadElementString("Guid")); xtr.ReadEndElement(); break; } } xtr.ReadEndElement(); xtr.ReadStartElement("OtherParts"); xtr.ReadEndElement(); xtr.Close(); // TODO: More checks Assert.That(uuid, Is.EqualTo(rpUuid)); Assert.That(name, Is.EqualTo(rpName)); Assert.That(creatorId, Is.EqualTo(rpCreatorId)); } } }
using System; using Flame.Build; using LLVMSharp; using static LLVMSharp.LLVM; namespace Flame.LLVM { /// <summary> /// Represents an intrinsic value: a well-known value that is injected into /// generated modules. /// </summary> public sealed class IntrinsicValue { /// <summary> /// Creates an intrinsic from the given intrinsic definition. /// </summary> /// <param name="Type">The type of the intrinsic.</param> /// <param name="Declare">Declares the intrinsic in a module.</param> public IntrinsicValue( IType Type, Func<LLVMModuleBuilder, LLVMModuleRef, LLVMValueRef> Declare) { this.Type = Type; this.declareIntrinsic = Declare; } /// <summary> /// Gets the intrinsic's type. /// </summary> /// <returns>The intrinsic's type.</returns> public IType Type { get; private set; } private Func<LLVMModuleBuilder, LLVMModuleRef, LLVMValueRef> declareIntrinsic; /// <summary> /// Declares this intrinsic in the given module. /// </summary> /// <param name="ModuleBuilder">The module builder for the module to declare the intrinsic in.</param> /// <param name="LLVMModule">The module to declare the intrinsic in.</param> /// <returns>The intrinsic's declaration.</returns> public LLVMValueRef Declare(LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return declareIntrinsic(ModuleBuilder, LLVMModule); } /// <summary> /// An intrinsic that represents the '__cxa_allocate_exception' C++ ABI function. /// </summary> /// <remarks> /// Signature: void* __cxa_allocate_exception(size_t thrown_size) throw() /// </remarks> public static readonly IntrinsicValue CxaAllocateException; private static readonly DescribedMethod CxaAllocateExceptionSignature; private static LLVMValueRef DeclareCxaAllocateException( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return DeclareFromSignature(CxaAllocateExceptionSignature, ModuleBuilder, LLVMModule); } /// <summary> /// An intrinsic that represents the '__cxa_throw' C++ ABI function. /// </summary> /// <remarks> /// Signature: void __cxa_throw(void* thrown_object, std::type_info* tinfo, void (*dest)(void*)) /// </remarks> public static readonly IntrinsicValue CxaThrow; private static readonly DescribedMethod CxaThrowSignature; private static LLVMValueRef DeclareCxaThrow( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return DeclareFromSignature(CxaThrowSignature, ModuleBuilder, LLVMModule); } /// <summary> /// An intrinsic that represents the '__cxa_rethrow' C++ ABI function. /// </summary> /// <remarks> /// Signature: void __cxa_rethrow() /// </remarks> public static readonly IntrinsicValue CxaRethrow; private static readonly DescribedMethod CxaRethrowSignature; private static LLVMValueRef DeclareCxaRethrow( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return DeclareFromSignature(CxaRethrowSignature, ModuleBuilder, LLVMModule); } /// <summary> /// An intrinsic that represents the '__cxa_begin_catch' C++ ABI function. /// </summary> /// <remarks> /// Signature: void* __cxa_begin_catch(void* exception_obj) /// </remarks> public static readonly IntrinsicValue CxaBeginCatch; private static readonly DescribedMethod CxaBeginCatchSignature; private static LLVMValueRef DeclareCxaBeginCatch( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return DeclareFromSignature(CxaBeginCatchSignature, ModuleBuilder, LLVMModule); } /// <summary> /// An intrinsic that represents the '__cxa_end_catch' C++ ABI function. /// </summary> /// <remarks> /// Signature: void __cxa_end_catch() /// </remarks> public static readonly IntrinsicValue CxaEndCatch; private static readonly DescribedMethod CxaEndCatchSignature; private static LLVMValueRef DeclareCxaEndCatch( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return DeclareFromSignature(CxaEndCatchSignature, ModuleBuilder, LLVMModule); } /// <summary> /// An intrinsic that represents the '__gxx_personality_v0' C++ ABI function. /// </summary> /// <remarks> /// Signature: declare i32 @__gxx_personality_v0(...) /// </remarks> public static readonly IntrinsicValue GxxPersonalityV0; private static LLVMValueRef DeclareGxxPersonalityV0( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { var funcType = FunctionType(Int32Type(), new LLVMTypeRef[] { }, true); var result = AddFunction(LLVMModule, "__gxx_personality_v0", funcType); return result; } /// <summary> /// An intrinsic that represents the 'void*' C++ RTTI ('_ZTIPv'). /// </summary> /// <remarks> /// Signature: @_ZTIPv = external constant i8* /// </remarks> public static readonly IntrinsicValue CxaVoidPointerRtti; private static LLVMValueRef DeclareCxaVoidPointerRtti( LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { var type = PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer); var result = ModuleBuilder.DeclareGlobal(ModuleBuilder.Declare(type), "_ZTIPv"); result.SetGlobalConstant(true); return result; } static IntrinsicValue() { // Signature: void* __cxa_allocate_exception(size_t thrown_size) throw() CxaAllocateExceptionSignature = new DescribedMethod( "__cxa_allocate_exception", null, PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer), true); CxaAllocateExceptionSignature.AddParameter( new DescribedParameter("thrown_size", PrimitiveTypes.UInt64)); CxaAllocateException = new IntrinsicValue( MethodType.Create(CxaAllocateExceptionSignature), DeclareCxaAllocateException); // Signature: void __cxa_throw(void* thrown_object, std::type_info* tinfo, void (*dest)(void*)) CxaThrowSignature = new DescribedMethod( "__cxa_throw", null, PrimitiveTypes.Void, true); CxaThrowSignature.AddParameter( new DescribedParameter( "thrown_object", PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer))); CxaThrowSignature.AddParameter( new DescribedParameter( "tinfo", PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer))); CxaThrowSignature.AddParameter( new DescribedParameter( "dest", PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer))); CxaThrow = new IntrinsicValue( MethodType.Create(CxaThrowSignature), DeclareCxaThrow); // Signature: void __cxa_rethrow() CxaRethrowSignature = new DescribedMethod( "__cxa_rethrow", null, PrimitiveTypes.Void, true); CxaRethrow = new IntrinsicValue( MethodType.Create(CxaRethrowSignature), DeclareCxaRethrow); // Signature: void* __cxa_begin_catch(void* exception_obj) CxaBeginCatchSignature = new DescribedMethod( "__cxa_begin_catch", null, PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer), true); CxaBeginCatchSignature.AddParameter( new DescribedParameter( "exception_obj", PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer))); CxaBeginCatch = new IntrinsicValue( MethodType.Create(CxaBeginCatchSignature), DeclareCxaBeginCatch); // Signature: void __cxa_end_catch() CxaEndCatchSignature = new DescribedMethod( "__cxa_end_catch", null, PrimitiveTypes.Void, true); CxaEndCatch = new IntrinsicValue( MethodType.Create(CxaEndCatchSignature), DeclareCxaEndCatch); // Signature: declare i32 @__gxx_personality_v0(...) GxxPersonalityV0 = new IntrinsicValue( PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer), DeclareGxxPersonalityV0); // Signature: @_ZTIPv = external constant i8* CxaVoidPointerRtti = new IntrinsicValue( PrimitiveTypes.Void.MakePointerType(PointerKind.TransientPointer), DeclareCxaVoidPointerRtti); } private static LLVMValueRef DeclareFromSignature( IMethod Signature, LLVMModuleBuilder ModuleBuilder, LLVMModuleRef LLVMModule) { return AddFunction( LLVMModule, Signature.Name.ToString(), ModuleBuilder.DeclarePrototype(Signature)); } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Internal.PropertyEditing.Model { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Text; using System.Activities.Presentation; using System.Activities.Presentation.Model; using System.Activities.Presentation.PropertyEditing; using System.Activities.Presentation.Internal.PropertyEditing.Resources; using System.Activities.Presentation.Internal.Properties; using System.Activities.Presentation.Internal.PropertyEditing.Editors; // <summary> // Concrete implementation of PropertyValue that delegates to ModelPropertyEntryBase for // all actions. // </summary> internal class ModelPropertyValue : PropertyValue { // Object used to mark a property value that should be cleared instead of set private static readonly object ClearValueMarker = new object(); // CultureInfo instance we use for formatting values so that they reflect what is in Xaml private static CultureInfo _xamlCultureInfo; // <summary> // Basic ctor // </summary> // <param name="parentProperty">Parent ModelPropertyEntryBase</param> public ModelPropertyValue(ModelPropertyEntryBase parentProperty) : base(parentProperty) { } // <summary> // Returns the source of this property value // </summary> public override PropertyValueSource Source { get { return ParentModelPropertyEntry.Source; } } // <summary> // Returns true if this value represents the default value of the property // </summary> public override bool IsDefaultValue { get { return Source == DependencyPropertyValueSource.DefaultValue; } } // <summary> // Returns true if the value contained by this property is mixed // </summary> public override bool IsMixedValue { get { return ParentModelPropertyEntry.IsMixedValue; } } // <summary> // Returns true if custom TypeConverter exists and if it can convert // the value from string. // </summary> public override bool CanConvertFromString { get { return ParentModelPropertyEntry.Converter != null && ParentModelPropertyEntry.Converter.CanConvertFrom(typeof(string)); } } // <summary> // Gets a flag indicating whether this PropertyValue has sub properties // </summary> public override bool HasSubProperties { get { return ParentModelPropertyEntry.HasSubProperties; } } // <summary> // Gets the sub-properties of the PropertyValue // </summary> public override PropertyEntryCollection SubProperties { get { return ParentModelPropertyEntry.SubProperties; } } // <summary> // Gets a flag indicating whether this PropertyValue represents a collection // </summary> public override bool IsCollection { get { return ParentModelPropertyEntry.IsCollection; } } // <summary> // Gets the collection represented by this PropertyValue // </summary> public override PropertyValueCollection Collection { get { return ParentModelPropertyEntry.Collection; } } // <summary> // This is an internal helper to which we can bind and on which we fire PropertyChanged // event when the Name sub-property (if one exists) changes. More-specifically, // we bind to this property in CollectionEditor to display the Type as well as the // Name of the items in the collection. This property is accessed from XAML. // </summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public PropertyValue NameSensitiveInstance { get { return this; } } // <summary> // Always catch exceptions // </summary> protected override bool CatchExceptions { get { return true; } } // <summary> // Gets an en-us CultureInfo that ignores user-specified settings // </summary> private static CultureInfo XamlCultureInfo { get { if (_xamlCultureInfo == null) { _xamlCultureInfo = new CultureInfo("en-us", false); } return _xamlCultureInfo; } } // Convenience accessor private ModelPropertyEntryBase ParentModelPropertyEntry { get { return (ModelPropertyEntryBase)this.ParentProperty; } } // <summary> // Validates the value using the TypeConverter, if one exists // </summary> // <param name="valueToValidate">Value to validate</param> protected override void ValidateValue(object valueToValidate) { // Noop. We used to rely on TypeConverter.IsValid() here, but it turns out // that a bunch of standard TypeConverters don't really work (eg. Int32TypeConverter // returns true for IsValid("abc") and EnumConverter returns false for // IsValid(MyEnum.One | MyEnum.Two) even if MyEnum if adorned with FlagsAttribute) } // Called when there exists a Name sub-property for this value and it changes internal void OnNameSubPropertyChanged() { // Updates XAML bindings (collection editor item-display-name-template for one) this.OnPropertyChanged("NameSensitiveInstance"); } // <summary> // Convert the specified string to a value // </summary> // <param name="stringToConvert"></param> // <returns></returns> protected override object ConvertStringToValue(string stringToConvert) { if (this.ParentProperty.PropertyType == typeof(string)) { return stringToConvert; } else if (string.IsNullOrEmpty(stringToConvert)) { // If the type of this property is string: // // StringValue of '' -> set Value to '' // StringValue of null -> ClearValue() // // Otherwise // // StringValue of '' -> ClearValue() // StringValue of null -> ClearValue() // if (stringToConvert != null && typeof(string).Equals(this.ParentProperty.PropertyType)) { return null; } else { return ClearValueMarker; } } else if (EditorUtilities.IsNullableEnumType(this.ParentProperty.PropertyType) && stringToConvert.Equals(EditorUtilities.NullString, StringComparison.Ordinal)) { // PS 107537: Special case handling when converting a string to a nullable enum type. return null; } else if (this.ParentModelPropertyEntry.Converter != null && this.ParentModelPropertyEntry.Converter.CanConvertFrom(typeof(string))) { return this.ParentModelPropertyEntry.Converter.ConvertFromString(null, XamlCultureInfo, stringToConvert); } throw FxTrace.Exception.AsError(new InvalidOperationException(string.Format( CultureInfo.CurrentCulture, Resources.PropertyEditing_NoStringToValueConversion, this.ParentProperty.DisplayName))); } // <summary> // Convert the specified value to a string // </summary> // <param name="valueToConvert"></param> // <returns></returns> protected override string ConvertValueToString(object valueToConvert) { string stringValue = string.Empty; if (valueToConvert == null) { if (typeof(IList).IsAssignableFrom(this.ParentProperty.PropertyType)) { stringValue = Resources.PropertyEditing_DefaultCollectionStringValue; } else if (EditorUtilities.IsNullableEnumType(this.ParentProperty.PropertyType)) { // PS 107537: Special case handling when converting a nullable enum type to a string. return EditorUtilities.NullString; } return stringValue; } else if ((stringValue = valueToConvert as string) != null) { return stringValue; } TypeConverter typeConverter = this.ParentModelPropertyEntry.Converter; if (valueToConvert is Array) { stringValue = Resources.PropertyEditing_DefaultArrayStringValue; } else if (valueToConvert is IList || valueToConvert is ICollection || ModelUtilities.ImplementsICollection(valueToConvert.GetType()) || ModelUtilities.ImplementsIList(valueToConvert.GetType())) { stringValue = Resources.PropertyEditing_DefaultCollectionStringValue; } else if (valueToConvert is IEnumerable) { stringValue = Resources.PropertyEditing_DefaultEnumerableStringValue; } else if (typeConverter != null && typeConverter.CanConvertTo(typeof(string))) { stringValue = typeConverter.ConvertToString(null, XamlCultureInfo, valueToConvert); } else { stringValue = valueToConvert.ToString(); } return stringValue ?? string.Empty; } // <summary> // Redirect the call to parent PropertyEntry // </summary> // <returns></returns> protected override object GetValueCore() { return ParentModelPropertyEntry.GetValueCore(); } // <summary> // Redirect the call to parent PropertyEntry // </summary> // <param name="value"></param> protected override void SetValueCore(object value) { if (value == ClearValueMarker) { ParentModelPropertyEntry.ClearValue(); } else { ParentModelPropertyEntry.SetValueCore(value); } } // <summary> // Apply the FlowDirection to the resource. // </summary> private void CheckAndSetFlowDirectionResource() { // Check if the value being edited is FlowDirection // and if so, reset the resource to the current value that the user is setting. // This will refresh the property inspector and all the string editors, showing "string" properties, // would have their FlowDirection set to the current value. if (ParentModelPropertyEntry.PropertyName.Equals(FrameworkElement.FlowDirectionProperty.Name)) { object value = Value; if (value != null) { PropertyInspectorResources.GetResources()["SelectedControlFlowDirectionRTL"] = value; } } } // <summary> // Redirect the call to parent PropertyEntry // </summary> public override void ClearValue() { ParentModelPropertyEntry.ClearValue(); } // <summary> // Fires the appropriate PropertyChanged events // </summary> public void OnUnderlyingModelChanged() { CheckAndSetFlowDirectionResource(); this.NotifyRootValueChanged(); } // <summary> // Fires the appropriate PropertyChanged events // </summary> public void OnUnderlyingSubModelChanged() { this.NotifySubPropertyChanged(); } // <summary> // Called when there is an error setting or getting a PropertyValue. // Displays an error dialog. // </summary> // <param name="e"></param> protected override void OnPropertyValueException(PropertyValueExceptionEventArgs e) { if (e.Source == PropertyValueExceptionSource.Set) { if (e.Exception != null) { Debug.WriteLine(e.Exception.ToString()); } ErrorReporting.ShowErrorMessage(e.Exception.Message); base.OnPropertyValueException(e); } else { base.OnPropertyValueException(e); } } // <summary> // Debuging-friendly ToString() // </summary> // <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public override string ToString() { try { string value; if (this.Value == null) { value = "{null}"; } else { value = this.StringValue; if (string.IsNullOrEmpty(value)) { value = "{empty}"; } } return string.Format(CultureInfo.CurrentCulture, "{0} (PropertyValue)", value ?? "{null}"); } catch { return base.ToString(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ReplicationProtectionContainersOperations. /// </summary> public static partial class ReplicationProtectionContainersOperationsExtensions { /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> public static ProtectionContainer SwitchProtection(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput) { return operations.SwitchProtectionAsync(fabricName, protectionContainerName, switchInput).GetAwaiter().GetResult(); } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> SwitchProtectionAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SwitchProtectionWithHttpMessagesAsync(fabricName, protectionContainerName, switchInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> public static void Delete(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName) { operations.DeleteAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server.) /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> public static ProtectionContainer DiscoverProtectableItem(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest) { return operations.DiscoverProtectableItemAsync(fabricName, protectionContainerName, discoverProtectableItemRequest).GetAwaiter().GetResult(); } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server.) /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> DiscoverProtectableItemAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.DiscoverProtectableItemWithHttpMessagesAsync(fabricName, protectionContainerName, discoverProtectableItemRequest, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the protection container details. /// </summary> /// <remarks> /// Gets the details of a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> public static ProtectionContainer Get(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName) { return operations.GetAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Gets the protection container details. /// </summary> /// <remarks> /// Gets the details of a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> GetAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> public static ProtectionContainer Create(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput) { return operations.CreateAsync(fabricName, protectionContainerName, creationInput).GetAwaiter().GetResult(); } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> CreateAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(fabricName, protectionContainerName, creationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> public static IPage<ProtectionContainer> ListByReplicationFabrics(this IReplicationProtectionContainersOperations operations, string fabricName) { return operations.ListByReplicationFabricsAsync(fabricName).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListByReplicationFabricsAsync(this IReplicationProtectionContainersOperations operations, string fabricName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationFabricsWithHttpMessagesAsync(fabricName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<ProtectionContainer> List(this IReplicationProtectionContainersOperations operations) { return operations.ListAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListAsync(this IReplicationProtectionContainersOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> public static ProtectionContainer BeginSwitchProtection(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput) { return operations.BeginSwitchProtectionAsync(fabricName, protectionContainerName, switchInput).GetAwaiter().GetResult(); } /// <summary> /// Switches protection from one container to another or one replication /// provider to another. /// </summary> /// <remarks> /// Operation to switch protection from one container to another or one /// replication provider to another. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric name. /// </param> /// <param name='protectionContainerName'> /// Protection container name. /// </param> /// <param name='switchInput'> /// Switch protection input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> BeginSwitchProtectionAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, SwitchProtectionInput switchInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginSwitchProtectionWithHttpMessagesAsync(fabricName, protectionContainerName, switchInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> public static void BeginDelete(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName) { operations.BeginDeleteAsync(fabricName, protectionContainerName).GetAwaiter().GetResult(); } /// <summary> /// Removes a protection container. /// </summary> /// <remarks> /// Operation to remove a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(fabricName, protectionContainerName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server.) /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> public static ProtectionContainer BeginDiscoverProtectableItem(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest) { return operations.BeginDiscoverProtectableItemAsync(fabricName, protectionContainerName, discoverProtectableItemRequest).GetAwaiter().GetResult(); } /// <summary> /// Adds a protectable item to the replication protection container. /// </summary> /// <remarks> /// The operation to a add a protectable item to a protection container(Add /// physical server.) /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// The name of the fabric. /// </param> /// <param name='protectionContainerName'> /// The name of the protection container. /// </param> /// <param name='discoverProtectableItemRequest'> /// The request object to add a protectable item. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> BeginDiscoverProtectableItemAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, DiscoverProtectableItemRequest discoverProtectableItemRequest, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginDiscoverProtectableItemWithHttpMessagesAsync(fabricName, protectionContainerName, discoverProtectableItemRequest, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> public static ProtectionContainer BeginCreate(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput) { return operations.BeginCreateAsync(fabricName, protectionContainerName, creationInput).GetAwaiter().GetResult(); } /// <summary> /// Create a protection container. /// </summary> /// <remarks> /// Operation to create a protection container. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='fabricName'> /// Unique fabric ARM name. /// </param> /// <param name='protectionContainerName'> /// Unique protection container ARM name. /// </param> /// <param name='creationInput'> /// Creation input. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ProtectionContainer> BeginCreateAsync(this IReplicationProtectionContainersOperations operations, string fabricName, string protectionContainerName, CreateProtectionContainerInput creationInput, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(fabricName, protectionContainerName, creationInput, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ProtectionContainer> ListByReplicationFabricsNext(this IReplicationProtectionContainersOperations operations, string nextPageLink) { return operations.ListByReplicationFabricsNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of protection container for a fabric. /// </summary> /// <remarks> /// Lists the protection containers in the specified fabric. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListByReplicationFabricsNextAsync(this IReplicationProtectionContainersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByReplicationFabricsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<ProtectionContainer> ListNext(this IReplicationProtectionContainersOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the list of all protection containers in a vault. /// </summary> /// <remarks> /// Lists the protection containers in a vault. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ProtectionContainer>> ListNextAsync(this IReplicationProtectionContainersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Linq; using System.Text; using ESRI.ArcGIS.Geometry; namespace DnrGps_Wkt { /// <summary> /// Transform ESRI geometries to the Well-known Text representation, as defined in /// section 7 of http://www.opengeospatial.org/standards/sfa (version 1.2.1 dated 2011-05-28) /// </summary> public static class WktGeometryExtensions { public static string ToWellKnownText(this IGeometry geometry) { return BuildWellKnownText(geometry); } public static IGeometry ToGeometry(this string wkt) { return BuildGeometry(wkt, CreateDefaultSpatialReference()); } public static IGeometry ToGeometry(this string wkt, ISpatialReference spatialReference) { return BuildGeometry(wkt, spatialReference); } #region Private methods for WKT construction private static string BuildWellKnownText(IGeometry geometry) { if (geometry is IPoint) return BuildWellKnownText(geometry as IPoint); if (geometry is IMultipoint) return BuildWellKnownText(geometry as IMultipoint); if (geometry is IPolyline) return BuildWellKnownText(geometry as IPolyline); if (geometry is IPolygon) return BuildWellKnownText(geometry as IPolygon); if (geometry is IGeometryBag) throw new NotImplementedException("Geometry bags to well known text is not yet supported"); return string.Empty; } private static string BuildWellKnownText(IPoint point) { return string.Format("POINT ({0} {1})", point.X, point.Y); } private static string BuildWellKnownText(IMultipoint points) { //Example - MULTIPOINT ((10 40), (40 30), (20 20), (30 10)) //Example - MULTIPOINT (10 40, 40 30, 20 20, 30 10) return "MULTIPOINT " + BuildWellKnownText(points as IPointCollection); } private static string BuildWellKnownText(IPolyline polyline) { //Example - LINESTRING (30 10, 10 30, 40 40) //Example - MULTILINESTRING ((10 10, 20 20, 10 40),(40 40, 30 30, 40 20, 30 10)) var geometryCollection = polyline as IGeometryCollection; if (geometryCollection == null) return string.Empty; int partCount = geometryCollection.GeometryCount; if (partCount == 0) return string.Empty; if (partCount == 1) return "LINESTRING " + BuildWellKnownText(polyline as IPointCollection); return "MULTILINESTRING " + BuildWellKnownText(geometryCollection); } private static string BuildWellKnownText(IPolygon polygon) { //Example - POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10)) //Example - POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10),(20 30, 35 35, 30 20, 20 30)) //Example - MULTIPOLYGON (((30 20, 10 40, 45 40, 30 20)),((15 5, 40 10, 10 20, 5 10, 15 5))) //Example - MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 45 20, 30 5, 10 10, 10 30, 20 35),(30 20, 20 25, 20 15, 30 20))) var geometryCollection = polygon as IGeometryCollection; if (geometryCollection == null) return string.Empty; int partCount = geometryCollection.GeometryCount; if (partCount == 0) return string.Empty; //FIXME - ArcObjects does not have a "multipolygon", however a polygon with multiple exterior rings needs to be a multipolygon in WKT //ArcGIS does not differentiate multi-ring polygons and multipolygons //Each polygon is simply a collection of rings in any order. //in ArcObjects a ring is clockwise for outer, and counterclockwise for inner (interior is on your right) //FIXME - In Wkt, exterior rings are counterclockwise, and interior are clockwise (interior is on your left) //FIXME - In Wkt, a polygon is one exterior, and zero or more interior rings //if (polygon.ExteriorRingCount > 1) // return "MULTIPOLYGON " + BuildWellKnownText(geometryCollection); return "POLYGON " + BuildWellKnownText(geometryCollection); } private static string BuildWellKnownText(IGeometryCollection geometries) { //Example ((10 10, 20 20, 10 40)) //Example ((10 10, 20 20, 10 40),(40 40, 30 30, 40 20, 30 10)) var sb = new StringBuilder(); int partCount = geometries.GeometryCount; if (partCount < 1) return string.Empty; sb.AppendFormat("({0}", BuildWellKnownText(geometries.Geometry[0] as IPointCollection)); for (int i = 1; i < partCount; i++) sb.AppendFormat(",{0}", BuildWellKnownText(geometries.Geometry[i] as IPointCollection)); sb.Append(")"); return sb.ToString(); } private static string BuildWellKnownText(IPointCollection points) { //Example - (10 40) //Example - (10 40, 40 30, 20 20, 30 10) var sb = new StringBuilder(); int pointCount = points.PointCount; if (pointCount < 1) return string.Empty; sb.AppendFormat("({0} {1}", points.Point[0].X, points.Point[0].Y); for (int i = 1; i < pointCount; i++) sb.AppendFormat(",{0} {1}", points.Point[i].X, points.Point[i].Y); sb.Append(")"); return sb.ToString(); } #endregion #region Private methods for IGeometry construction private static IGeometry BuildGeometry(string s, ISpatialReference spatialReference) { var wkt = new WktText(s); switch (wkt.Type) { case WktType.None: return null; case WktType.Point: return BuildPoint(wkt, spatialReference); case WktType.LineString: return BuildPolyline(wkt, spatialReference); case WktType.Polygon: return BuildPolygon(wkt, spatialReference); case WktType.Triangle: return BuildPolygon(wkt, spatialReference); case WktType.PolyhedralSurface: return BuildMultiPatch(wkt, spatialReference); case WktType.Tin: return BuildMultiPolygon(wkt, spatialReference); case WktType.MultiPoint: return BuildMultiPoint(wkt, spatialReference); case WktType.MultiLineString: return BuildMultiPolyline(wkt, spatialReference); case WktType.MultiPolygon: return BuildMultiPolygon(wkt, spatialReference); case WktType.GeometryCollection: return BuildGeometryCollection(wkt, spatialReference); default: throw new ArgumentOutOfRangeException("s", "Unsupported geometry type: " + wkt.Type); } } private static IGeometry BuildPoint(WktText wkt, ISpatialReference spatialReference) { return BuildPoint(wkt.Token, wkt, spatialReference); } private static IGeometry BuildMultiPoint(WktText wkt, ISpatialReference spatialReference) { var multiPoint = (IPointCollection)new MultipointClass(); if (spatialReference != null) ((IGeometry)multiPoint).SpatialReference = spatialReference; foreach (var point in wkt.Token.Tokens) { multiPoint.AddPoint(BuildPoint(point, wkt, spatialReference)); } ((ITopologicalOperator)multiPoint).Simplify(); var geometry = multiPoint as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IGeometry BuildPolyline(WktText wkt, ISpatialReference spatialReference) { var multiPath = (IGeometryCollection)new PolylineClass(); if (spatialReference != null) ((IGeometry)multiPath).SpatialReference = spatialReference; var path = BuildPath(wkt.Token, wkt, spatialReference); ((ITopologicalOperator)multiPath).Simplify(); multiPath.AddGeometry(path); var geometry = multiPath as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IGeometry BuildMultiPolyline(WktText wkt, ISpatialReference spatialReference) { var multiPath = (IGeometryCollection)new PolylineClass(); if (spatialReference != null) ((IGeometry)multiPath).SpatialReference = spatialReference; foreach (var lineString in wkt.Token.Tokens) { var path = BuildPath(lineString, wkt, spatialReference); multiPath.AddGeometry(path); } ((ITopologicalOperator)multiPath).Simplify(); var geometry = multiPath as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IGeometry BuildPolygon(WktText wkt, ISpatialReference spatialReference) { var multiRing = (IGeometryCollection)new PolygonClass(); if (spatialReference != null) ((IGeometry)multiRing).SpatialReference = spatialReference; foreach (var ringString in wkt.Token.Tokens) { var ring = BuildRing(ringString, wkt, spatialReference); multiRing.AddGeometry(ring); } ((ITopologicalOperator)multiRing).Simplify(); var geometry = multiRing as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IGeometry BuildMultiPolygon(WktText wkt, ISpatialReference spatialReference) { var multiRing = (IGeometryCollection)new PolygonClass(); if (spatialReference != null) ((IGeometry)multiRing).SpatialReference = spatialReference; foreach (var polygonString in wkt.Token.Tokens) { foreach (var ringString in polygonString.Tokens) { var ring = BuildRing(ringString, wkt, spatialReference); multiRing.AddGeometry(ring); } } ((ITopologicalOperator)multiRing).Simplify(); var geometry = multiRing as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IGeometry BuildMultiPatch(WktText wkt, ISpatialReference spatialReference) { var multiPatch = (IGeometryCollection)new MultiPatchClass(); if (spatialReference != null) ((IGeometry)multiPatch).SpatialReference = spatialReference; foreach (var polygonString in wkt.Token.Tokens) { bool isOuter = true; foreach (var ringString in polygonString.Tokens) { var ring = BuildRing(ringString, wkt, spatialReference); multiPatch.AddGeometry(ring); ((IMultiPatch)multiPatch).PutRingType(ring, isOuter ? esriMultiPatchRingType.esriMultiPatchOuterRing : esriMultiPatchRingType.esriMultiPatchInnerRing); isOuter = false; } } ((ITopologicalOperator)multiPatch).Simplify(); var geometry = multiPatch as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IGeometry BuildGeometryCollection(WktText wkt, ISpatialReference spatialReference) { var geometryBag = (IGeometryCollection)new GeometryBagClass(); if (spatialReference != null) ((IGeometryBag)geometryBag).SpatialReference = spatialReference; foreach (var geomToken in wkt.Token.Tokens) { var geom = BuildGeometry(geomToken.ToString(), spatialReference); geometryBag.AddGeometry(geom); } var geometry = geometryBag as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return geometry; } private static IPath BuildPath(WktToken token, WktText wkt, ISpatialReference spatialReference) { var path = (IPointCollection)new PathClass(); if (spatialReference != null) ((IGeometry)path).SpatialReference = spatialReference; foreach (var point in token.Tokens) { path.AddPoint(BuildPoint(point, wkt, spatialReference)); } var geometry = path as IGeometry; MakeZmAware(geometry, wkt.HasZ, wkt.HasM); return (IPath)path; } private static IRing BuildRing(WktToken token, WktText wkt, ISpatialReference spatialReference) { var ring = (IPointCollection)new RingClass(); if (spatialReference != null) ((IGeometry)ring).SpatialReference = spatialReference; foreach (var point in token.Tokens) { ring.AddPoint(BuildPoint(point, wkt, spatialReference)); } MakeZmAware((IGeometry)ring, wkt.HasZ, wkt.HasM); return (IRing)ring; } private static IPoint BuildPoint(WktToken token, WktText wkt, ISpatialReference spatialReference) { var coordinates = token.Coords.ToArray(); int partCount = coordinates.Length; if (!wkt.HasZ && !wkt.HasM && partCount != 2) throw new ArgumentException("Mal-formed WKT, wrong number of elements, expecting x and y"); if (wkt.HasZ && !wkt.HasM && partCount != 3) throw new ArgumentException("Mal-formed WKT, wrong number of elements, expecting x y z"); if (!wkt.HasZ && wkt.HasM && partCount != 3) throw new ArgumentException("Mal-formed WKT, wrong number of elements, expecting x y m"); if (wkt.HasZ && wkt.HasM && partCount != 4) throw new ArgumentException("Mal-formed WKT, wrong number of elements, expecting x y z m"); var point = (IPoint)new PointClass(); if (spatialReference != null) point.SpatialReference = spatialReference; point.PutCoords(coordinates[0], coordinates[1]); if (wkt.HasZ) point.Z = coordinates[2]; if (wkt.HasM && !wkt.HasZ) point.M = coordinates[2]; if (wkt.HasZ && wkt.HasM) point.M = coordinates[3]; MakeZmAware(point, wkt.HasZ, wkt.HasM); return point; } private static void MakeZmAware(IGeometry geometry, bool hasZ, bool hasM) { if (hasZ) ((IZAware)geometry).ZAware = true; if (hasM) ((IMAware)geometry).MAware = true; } private static ISpatialReference CreateDefaultSpatialReference() { ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); var spatialReference = (ISpatialReference)spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_World_PlateCarree); var controlPrecision = spatialReference as IControlPrecision2; controlPrecision.IsHighPrecision = false; var spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); var spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); return spatialReference; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="RequestQueue.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // // Request Queue // queues up the requests to avoid thread pool starvation, // making sure that there are always available threads to process requests // namespace System.Web { using System.Threading; using System.Collections; using System.Web.Util; using System.Web.Hosting; using System.Web.Configuration; internal class RequestQueue { // configuration params private int _minExternFreeThreads; private int _minLocalFreeThreads; private int _queueLimit; private TimeSpan _clientConnectedTime; private bool _iis6; // two queues -- one for local requests, one for external private Queue _localQueue = new Queue(); private Queue _externQueue = new Queue(); // total count private int _count; // work items queued to pick up new work private WaitCallback _workItemCallback; private int _workItemCount; private const int _workItemLimit = 2; private bool _draining; // timer to drain the queue private readonly TimeSpan _timerPeriod = new TimeSpan(0, 0, 10); // 10 seconds private Timer _timer; // helpers private static bool IsLocal(HttpWorkerRequest wr) { String remoteAddress = wr.GetRemoteAddress(); // check if localhost if (remoteAddress == "127.0.0.1" || remoteAddress == "::1") return true; // if unknown, assume not local if (String.IsNullOrEmpty(remoteAddress)) return false; // compare with local address if (remoteAddress == wr.GetLocalAddress()) return true; return false; } private void QueueRequest(HttpWorkerRequest wr, bool isLocal) { lock (this) { if (isLocal) { _localQueue.Enqueue(wr); } else { _externQueue.Enqueue(wr); } _count++; } PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_QUEUED); PerfCounters.IncrementCounter(AppPerfCounter.REQUESTS_IN_APPLICATION_QUEUE); if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_REQ_QUEUED, wr); } private HttpWorkerRequest DequeueRequest(bool localOnly) { HttpWorkerRequest wr = null; while (_count > 0) { lock (this) { if (_localQueue.Count > 0) { wr = (HttpWorkerRequest)_localQueue.Dequeue(); _count--; } else if (!localOnly && _externQueue.Count > 0) { wr = (HttpWorkerRequest)_externQueue.Dequeue(); _count--; } } if (wr == null) { break; } else { PerfCounters.DecrementGlobalCounter(GlobalPerfCounter.REQUESTS_QUEUED); PerfCounters.DecrementCounter(AppPerfCounter.REQUESTS_IN_APPLICATION_QUEUE); if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.Infrastructure)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_REQ_DEQUEUED, wr); if (!CheckClientConnected(wr)) { HttpRuntime.RejectRequestNow(wr, true); wr = null; PerfCounters.IncrementGlobalCounter(GlobalPerfCounter.REQUESTS_DISCONNECTED); PerfCounters.IncrementCounter(AppPerfCounter.APP_REQUEST_DISCONNECTED); } else { break; } } } return wr; } // This method will check to see if the client is still connected. // The checks are only done if it's an in-proc Isapi request AND the request has been waiting // more than the configured clientConenctedCheck time. private bool CheckClientConnected(HttpWorkerRequest wr) { if (DateTime.UtcNow - wr.GetStartTime() > _clientConnectedTime) return wr.IsClientConnected(); else return true; } // ctor internal RequestQueue(int minExternFreeThreads, int minLocalFreeThreads, int queueLimit, TimeSpan clientConnectedTime) { _minExternFreeThreads = minExternFreeThreads; _minLocalFreeThreads = minLocalFreeThreads; _queueLimit = queueLimit; _clientConnectedTime = clientConnectedTime; _workItemCallback = new WaitCallback(this.WorkItemCallback); _timer = new Timer(new TimerCallback(this.TimerCompletionCallback), null, _timerPeriod, _timerPeriod); _iis6 = HostingEnvironment.IsUnderIIS6Process; // set the minimum number of requests that must be executing in order to detect a deadlock int maxWorkerThreads, maxIoThreads; ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIoThreads); UnsafeNativeMethods.SetMinRequestsExecutingToDetectDeadlock(maxWorkerThreads - minExternFreeThreads); } // method called from HttpRuntime for incoming requests internal HttpWorkerRequest GetRequestToExecute(HttpWorkerRequest wr) { int workerThreads, ioThreads; ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads); int freeThreads; if (_iis6) freeThreads = workerThreads; // ignore IO threads to avoid starvation from Indigo TCP requests else freeThreads = (ioThreads > workerThreads) ? workerThreads : ioThreads; // fast path when there are threads available and nothing queued if (freeThreads >= _minExternFreeThreads && _count == 0) return wr; bool isLocal = IsLocal(wr); // fast path when there are threads for local requests available and nothing queued if (isLocal && freeThreads >= _minLocalFreeThreads && _count == 0) return wr; // reject if queue limit exceeded if (_count >= _queueLimit) { HttpRuntime.RejectRequestNow(wr, false); return null; } // can't execute the current request on the current thread -- need to queue QueueRequest(wr, isLocal); // maybe can execute a request previously queued if (freeThreads >= _minExternFreeThreads) { wr = DequeueRequest(false); // enough threads to process even external requests } else if (freeThreads >= _minLocalFreeThreads) { wr = DequeueRequest(true); // enough threads to process only local requests } else { wr = null; // not enough threads -> do nothing on this thread ScheduleMoreWorkIfNeeded(); // try to schedule to worker thread } return wr; } // method called from HttpRuntime at the end of request internal void ScheduleMoreWorkIfNeeded() { // too late for more work if draining if (_draining) return; // is queue empty? if (_count == 0) return; // already scheduled enough work items if (_workItemCount >= _workItemLimit) return; // enough worker threads? int workerThreads, ioThreads; ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads); if (workerThreads < _minLocalFreeThreads) return; // queue the work item Interlocked.Increment(ref _workItemCount); ThreadPool.QueueUserWorkItem(_workItemCallback); } // is empty property internal bool IsEmpty { get { return (_count == 0); } } // method called to pick up more work private void WorkItemCallback(Object state) { Interlocked.Decrement(ref _workItemCount); // too late for more work if draining if (_draining) return; // is queue empty? if (_count == 0) return; int workerThreads, ioThreads; ThreadPool.GetAvailableThreads(out workerThreads, out ioThreads); // not enough worker threads to do anything if (workerThreads < _minLocalFreeThreads) return; // pick up request from the queue HttpWorkerRequest wr = DequeueRequest(workerThreads < _minExternFreeThreads); if (wr == null) return; // let another work item through before processing the request ScheduleMoreWorkIfNeeded(); // call the runtime to process request HttpRuntime.ProcessRequestNow(wr); } // periodic timer to pick up more work private void TimerCompletionCallback(Object state) { ScheduleMoreWorkIfNeeded(); } // reject all requests internal void Drain() { // set flag before killing timer to shorten the code path // in the callback after the timer is disposed _draining = true; // stop the timer if (_timer != null) { ((IDisposable)_timer).Dispose(); _timer = null; } // wait for all work items to finish while (_workItemCount > 0) Thread.Sleep(100); // is queue empty? if (_count == 0) return; // reject the remaining requests for (;;) { HttpWorkerRequest wr = DequeueRequest(false); if (wr == null) break; HttpRuntime.RejectRequestNow(wr, false); } } } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using Microsoft.Research.Naiad.Serialization; using Microsoft.Research.Naiad.Dataflow; using Microsoft.Research.Naiad.Dataflow.Channels; using Microsoft.Research.Naiad.Runtime.Progress; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Research.Naiad.Diagnostics; using Microsoft.Research.Naiad.Input; namespace Microsoft.Research.Naiad { /// <summary> /// A Computation with an internal Controller which cannot be re-used for other Computations. /// </summary> public interface OneOffComputation : Computation { /// <summary> /// The configuration used by this controller. /// </summary> Configuration Configuration { get; } /// <summary> /// The workers associated with this controller. /// </summary> WorkerGroup WorkerGroup { get; } /// <summary> /// The default placement of new stages. /// </summary> Placement DefaultPlacement { get; } } internal class InternalOneOffComputation : OneOffComputation { private readonly Controller controller; private readonly Computation computation; public InternalOneOffComputation(Configuration configuration) { this.controller = NewController.FromConfig(configuration); this.computation = controller.NewComputation(); } public void Join() { this.computation.Join(); this.controller.Join(); } public void Dispose() { this.computation.Dispose(); this.controller.Dispose(); } public Configuration Configuration { get { return this.controller.Configuration; } } public WorkerGroup WorkerGroup { get { return this.controller.WorkerGroup; } } public Placement DefaultPlacement { get { return this.controller.DefaultPlacement; } } public Stream<TRecord, Epoch> NewInput<TRecord>(DataSource<TRecord> source) { return this.computation.NewInput<TRecord>(source); } public Stream<TRecord, Epoch> NewInput<TRecord>(DataSource<TRecord> source, string name) { return this.computation.NewInput<TRecord>(source, name); } public event EventHandler<FrontierChangedEventArgs> OnFrontierChange { add { this.computation.OnFrontierChange += value; } remove { this.computation.OnFrontierChange -= value; } } public event EventHandler OnStartup { add { this.computation.OnStartup += value; } remove { this.computation.OnStartup -= value; } } public event EventHandler OnShutdown { add { this.computation.OnShutdown += value; } remove { this.computation.OnShutdown -= value; } } public void Sync(int epoch) { this.computation.Sync(epoch); } public void Activate() { this.computation.Activate(); } public Controller Controller { get { return this.controller; } } } /// <summary> /// Manages the construction and execution of an individual dataflow computation. /// </summary> /// <remarks> /// A Computation manages the execution of a single Naiad computation. /// To construct an instance of this interface, use the /// <see cref="Microsoft.Research.Naiad.Controller.NewComputation"/> method. /// </remarks> public interface Computation : IDisposable { /// <summary> /// Creates a new input stage from the given <see cref="DataSource"/>. /// </summary> /// <typeparam name="TRecord">record type</typeparam> /// <param name="source">data source</param> /// <returns>A new input stage</returns> Stream<TRecord, Epoch> NewInput<TRecord>(DataSource<TRecord> source); /// <summary> /// Creates a new input stage from the given <see cref="DataSource"/>. /// </summary> /// <typeparam name="TRecord">record type</typeparam> /// <param name="source">data source</param> /// <param name="name">name for the input</param> /// <returns>A new input stage</returns> Stream<TRecord, Epoch> NewInput<TRecord>(DataSource<TRecord> source, string name); /// <summary> /// An event that is raised each time the frontier changes. /// </summary> /// <remarks> /// This event provides a hook for debugging statements that track the progress of /// a computation. /// </remarks> /// <example> /// computation.OnFrontierChange += (c, f) => /// { /// Console.WriteLine("New frontier: {0}", string.Join(", ", f.NewFrontier)); /// }; /// </example> event EventHandler<FrontierChangedEventArgs> OnFrontierChange; /// <summary> /// An event that is raised once the graph is started. /// </summary> event EventHandler OnStartup; /// <summary> /// An event that is raised once the graph is shut down. /// </summary> event EventHandler OnShutdown; /// <summary> /// Blocks until all subscriptions have processed all inputs up to the supplied epoch. /// If the computation has no subscriptions, no synchronization occurs. /// </summary> /// <param name="epoch">The epoch.</param> /// <remarks> /// This method is commonly used along with <see cref="Input.BatchedDataSource{TRecord}"/> to /// process epochs of input data in batches, or with a bounded number of outstanding /// epochs. /// /// If the computation contains many inputs and outputs that are stimulated asynchronously, /// the <see cref="Subscription.Sync"/> method provides a mechanism to synchronize on an individual /// subscription. /// </remarks> /// <example> /// var source = new BatchedDataSource&lt;int&gt;(); /// var subscription = computation.NewInput(source) /// /* ... */ /// .Subscribe(); /// /// for (int i = 0; i &lt; numEpochs; ++i) /// { /// source.OnNext(i); /// computation.Sync(i); // Alternatively subscription.Sync(i); /// } /// </example> /// <seealso cref="Input.BatchedDataSource{TRecord}"/> /// <seealso cref="Subscription.Sync"/> void Sync(int epoch); /// <summary> /// Blocks until all computation in this graph has termintaed. /// </summary> /// <remarks> /// This method must be called after calling <see cref="Activate"/> and before calling Dispose() /// or an error will be raised. /// </remarks> /// <example> /// The typical usage of Join is before the end of the <c>using</c> block for a /// Computation: /// <code> /// using (Computation computation = controller.NewComputation()) /// { /// /* Dataflow graph defined here. */ /// /// computation.Activate(); /// /// /* Inputs supplied here. */ /// /// computation.Join(); /// } /// </code> /// </example> /// <seealso cref="Microsoft.Research.Naiad.Controller.NewComputation"/> /// <seealso cref="Join"/> void Join(); /// <summary> /// Starts computation in this graph. /// </summary> /// <remarks> /// This method must be called after the entire dataflow graph has been constructed, and before calling <see cref="Join"/>, /// or an error will be raised. /// </remarks> /// <example> /// The typical usage of Activate is between the definition of the dataflow graph and /// before inputs are supplied to the graph: /// <code> /// using (Computation computation = controller.NewComputation()) /// { /// /* Dataflow graph defined here. */ /// /// computation.Activate(); /// /// /* Inputs supplied here. */ /// /// computation.Join(); /// } /// </code> /// </example> /// <see cref="Microsoft.Research.Naiad.Controller.NewComputation"/> /// <seealso cref="Activate"/> void Activate(); /// <summary> /// The <see cref="Controller"/> that hosts this graph. /// </summary> Controller Controller { get; } } /// <summary> /// The subgraph manager holds on to data related to a specific executable graph. /// Much of this functionality used to exist in the controller, but we extract out /// the /// </summary> internal enum InternalComputationState { Inactive, Active, Complete, Failed } internal interface InternalComputation { int Index { get; } InternalComputationState CurrentState { get; } void Cancel(Exception dueTo); Exception Exception { get; } InternalController Controller { get; } SerializationFormat SerializationFormat { get; } Runtime.Progress.ProgressTracker ProgressTracker { get; } Runtime.Progress.Reachability Reachability { get; } // TODO these are only used for reporting; could swap over to new DataSource-based approach. Dataflow.InputStage<R> NewInput<R>(); Dataflow.InputStage<R> NewInput<R>(string name); IEnumerable<Dataflow.InputStage> Inputs { get; } IEnumerable<Subscription> Outputs { get; } IEnumerable<KeyValuePair<int, Dataflow.Stage>> Stages { get; } IEnumerable<KeyValuePair<int, Dataflow.Edge>> Edges { get; } void Register(Subscription sub); int Register(Dataflow.Stage stage); int Register(Dataflow.Edge edge); Placement DefaultPlacement { get; } Dataflow.ITimeContextManager ContextManager { get; } void SignalShutdown(); int AllocateNewGraphIdentifier(); void Activate(); void MaterializeAll(); // used by Controller.Restore(); perhaps can hide. void Connect<S, T>(Dataflow.StageOutput<S, T> stream, Dataflow.StageInput<S, T> recvPort, Action<S[], int[], int> key, Channel.Flags flags) where T : Time<T>; void Connect<S, T>(Dataflow.StageOutput<S, T> stream, Dataflow.StageInput<S, T> recvPort, Action<S[], int[], int> key) where T : Time<T>; void Connect<S, T>(Dataflow.StageOutput<S, T> stream, Dataflow.StageInput<S, T> recvPort) where T : Time<T>; Computation ExternalComputation { get; } } internal class BaseComputation : Computation, InternalComputation, IDisposable { private readonly int index; public int Index { get { return this.index; } } public SerializationFormat SerializationFormat { get { return this.Controller.SerializationFormat; } } public Computation ExternalComputation { get { return this; } } public void Cancel(Exception e) { Logging.Error("Cancelling execution of graph {0}, due to exception:\n{1}", this.Index, e); lock (this) { if (this.currentState == InternalComputationState.Failed) return; this.currentState = InternalComputationState.Failed; this.Exception = e; if (this.Controller.NetworkChannel != null) { MessageHeader header = MessageHeader.GraphFailure(this.index); SendBufferPage page = SendBufferPage.CreateSpecialPage(header, 0); BufferSegment segment = page.Consume(); Logging.Error("Broadcasting graph failure message"); this.Controller.NetworkChannel.BroadcastBufferSegment(header, segment); } this.ProgressTracker.Cancel(); } } private InternalComputationState currentState = InternalComputationState.Inactive; public InternalComputationState CurrentState { get { return this.currentState; } } private Exception exception = null; public Exception Exception { get { return this.exception; } private set { lock (this) { if (this.exception == null) this.exception = value; else if (!(this.exception is AggregateException)) this.exception = new AggregateException(this.exception, value); else { List<Exception> innerExceptions = new List<Exception>((this.exception as AggregateException).InnerExceptions); innerExceptions.Add(value); this.exception = new AggregateException(innerExceptions); } } } } private readonly InternalController controller; public InternalController Controller { get { return this.controller; } } Controller Computation.Controller { get { return this.controller.ExternalController; } } private readonly ProgressTracker progressTracker; public ProgressTracker ProgressTracker { get { return this.progressTracker; } } private readonly Reachability reachability = new Reachability(); public Reachability Reachability { get { return this.reachability; } } public event EventHandler<FrontierChangedEventArgs> OnFrontierChange { add { this.progressTracker.OnFrontierChanged += value; } remove { this.progressTracker.OnFrontierChanged -= value; } } public event EventHandler OnStartup; protected void NotifyOnStartup() { if (this.OnStartup != null) this.OnStartup(this, new EventArgs()); } public event EventHandler OnShutdown; protected void NotifyOnShutdown() { if (this.OnShutdown != null) this.OnShutdown(this, new EventArgs()); } protected readonly List<Dataflow.InputStage> inputs = new List<Dataflow.InputStage>(); public IEnumerable<Dataflow.InputStage> Inputs { get { return this.inputs; } } protected readonly List<Subscription> outputs = new List<Subscription>(); public IEnumerable<Subscription> Outputs { get { return this.outputs; } } public void Register(Subscription sub) { outputs.Add(sub); } protected readonly Dictionary<int, Dataflow.Stage> stages = new Dictionary<int, Dataflow.Stage>(); public IEnumerable<KeyValuePair<int, Dataflow.Stage>> Stages { get { return this.stages; } } protected readonly Dictionary<int, Dataflow.Edge> edges = new Dictionary<int, Dataflow.Edge>(); public IEnumerable<KeyValuePair<int, Dataflow.Edge>> Edges { get { return this.edges; } } /// <summary> /// Constructs and registers a new input collection of type R. /// </summary> /// <typeparam name="R">Record</typeparam> /// <returns>New input collection</returns> public Dataflow.InputStage<R> NewInput<R>() { string generatedName = string.Format("__Input{0}", this.inputs.Count); return this.NewInput<R>(generatedName); } public Dataflow.InputStage<R> NewInput<R>(string name) { Dataflow.InputStage<R> ret = new Dataflow.InputStage<R>(this.DefaultPlacement, this, name); this.inputs.Add(ret); return ret; } private readonly List<DataSource> streamingInputs = new List<DataSource>(); public Stream<R, Epoch> NewInput<R>(DataSource<R> source) { string generatedName = string.Format("__Input{0}", this.inputs.Count); return this.NewInput(source, generatedName); } public Stream<R, Epoch> NewInput<R>(DataSource<R> source, string name) { Dataflow.StreamingInputStage<R> ret = new Dataflow.StreamingInputStage<R>(source, this.DefaultPlacement, this, name); this.inputs.Add(ret); this.streamingInputs.Add(source); return ret; } public int Register(Dataflow.Stage stage) { int ret = AllocateNewGraphIdentifier(); this.stages.Add(ret, stage); return ret; } public int Register(Dataflow.Edge edge) { int ret = AllocateNewGraphIdentifier(); this.edges.Add(ret, edge); return ret; } private int nextGraphIdentifier; public int AllocateNewGraphIdentifier() { return nextGraphIdentifier++; } public int AllocatedGraphIdentifiers { get { return nextGraphIdentifier; } } public void Connect<S, T>(Dataflow.StageOutput<S, T> stream, Dataflow.StageInput<S, T> recvPort, Action<S[], int[], int> key, Channel.Flags flags) where T : Time<T> { stream.ForStage.Targets.Add(new Dataflow.Edge<S, T>(stream, recvPort, key, flags)); } public void Connect<S, T>(Dataflow.StageOutput<S, T> stream, Dataflow.StageInput<S, T> recvPort, Action<S[], int[], int> key) where T : Time<T> { this.Connect(stream, recvPort, key, Channel.Flags.None); } public void Connect<S, T>(Dataflow.StageOutput<S, T> stream, Dataflow.StageInput<S, T> recvPort) where T : Time<T> { this.Connect(stream, recvPort, null, Channel.Flags.None); } private readonly Dataflow.TimeContextManager contextManager; internal void InitializeReporting(bool makeDomain, bool makeInline, bool doAggregate) { this.contextManager.InitializeReporting(makeDomain, makeInline, doAggregate); } private bool isJoined = false; private readonly bool DomainReporting = false; protected Dataflow.InputStage<string> RootDomainStatisticsStage { get { return this.contextManager.Reporting.domainReportingIngress; } } /// <summary> /// Blocks until all computation is complete and resources are released. /// </summary> public void Join() { if (this.CurrentState == InternalComputationState.Inactive) { throw new Exception("Joining graph manager before calling Activate()"); } else { if (this.DomainReporting) { foreach (var input in this.streamingInputs) input.Join(); var largestRealInputEpoch = this.inputs.Max(x => x.CurrentEpoch); Logging.Info("Largest real epoch " + largestRealInputEpoch + " current stats " + RootDomainStatisticsStage.CurrentEpoch); while (this.RootDomainStatisticsStage.CurrentEpoch < largestRealInputEpoch) { this.RootDomainStatisticsStage.OnNext(new string[] { }); } Logging.Info("New stats " + RootDomainStatisticsStage.CurrentEpoch); // wait until all real inputs have drained (possibly generating new logging) if (largestRealInputEpoch > 0) { Logging.Info("Syncing stats " + (largestRealInputEpoch - 1)); this.Sync(largestRealInputEpoch - 1); } // now shut down the reporting Console.WriteLine("Calling reporting completed"); this.RootDomainStatisticsStage.OnCompleted(); } else { foreach (var input in this.streamingInputs) input.Join(); } // Wait for all progress updates to drain (or an exception to occur). this.ProgressTracker.BlockUntilComplete(); // The shutdown counter will not be signalled in an exceptional case, // so test the exception here. if (this.exception != null) { this.currentState = InternalComputationState.Failed; throw new Exception("Error during Naiad execution", this.exception); } // We terminated successfully, so wait until all shutdown routines have // finished. this.ShutdownCounter.Wait(); NotifyOnShutdown(); this.isJoined = true; this.currentState = InternalComputationState.Complete; } } private Placement defaultPlacement; public Placement DefaultPlacement { get { return this.defaultPlacement; } } public BaseComputation(InternalController controller, int index) { this.controller = controller; this.defaultPlacement = this.controller.DefaultPlacement; this.index = index; this.ShutdownCounter = new CountdownEvent(controller.Workers.Count); this.contextManager = new Microsoft.Research.Naiad.Dataflow.TimeContextManager(this); if (this.controller.Configuration.DistributedProgressTracker) this.progressTracker = new DistributedProgressTracker(this); else this.progressTracker = new CentralizedProgressTracker(this); this.InitializeReporting(this.controller.Configuration.DomainReporting, this.controller.Configuration.InlineReporting, this.controller.Configuration.AggregateReporting); } /// <summary> /// Blocks until all computation associated with the supplied epoch have been retired. /// </summary> /// <param name="epoch">Epoch to wait for</param> public void Sync(int epoch) { foreach (Dataflow.InputStage input in this.inputs) { if (!input.IsCompleted && input.CurrentEpoch <= epoch) { Logging.Debug("Syncing at epoch ({0}) in the future of {1}.", epoch, input); } } if (this.outputs.Count == 0) Logging.Debug("Syncing a computation with no subscriptions; no synchronization performed."); foreach (var subscription in this.Outputs) subscription.Sync(epoch); } bool activated = false; bool materialized = false; public void Activate() { if (activated) return; Logging.Progress("Activating Computation"); activated = true; this.Reachability.UpdateReachabilityPartialOrder(this); this.MaterializeAll(); this.Controller.DoStartupBarrier(); this.currentState = InternalComputationState.Active; this.Controller.Workers.WakeUp(); foreach (var streamingInput in this.streamingInputs) streamingInput.Activate(); this.NotifyOnStartup(); } public void MaterializeAll() { if (this.materialized) return; foreach (var stage in this.Stages) stage.Value.Materialize(); foreach (var edge in this.Edges) edge.Value.Materialize(); this.materialized = true; } private CountdownEvent ShutdownCounter; public void SignalShutdown() { this.ShutdownCounter.Signal(); } public Dataflow.ITimeContextManager ContextManager { get { return this.contextManager; } } public void Dispose() { if (this.activated && !this.isJoined) { Logging.Error("Attempted to dispose Computation before joining."); Logging.Error("You must call Computation.Join() before disposing/exiting the using block."); //System.Environment.Exit(-1); } this.ContextManager.ShutDown(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.PdbUtilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; using System.Reflection; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104)] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135)] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var runtime = CreateRuntime(source, compileReferences, runtimeReferences); var context = CreateMethodContext(runtime, "C.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143)] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"))); var context = CreateMethodContext( runtime, "C.M"); var aliases = ImmutableArray.Create( VariableAlias("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), VariableAlias("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime")); string error; var testData = new CompilationTestData(); context.CompileExpression( "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, aliases, out error, testData); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } [WorkItem(1117084)] [Fact] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml"))); var context = CreateMethodContext(runtime, "C.M"); string error; ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var testData = new CompilationTestData(); var result = context.CompileExpression( "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, NoAliases, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); var expectedAssemblyIdentity = WinRtRefs.Single(r => r.Display == "System.Runtime.WindowsRuntime.dll").GetAssemblyIdentity(); Assert.Equal(expectedAssemblyIdentity, missingAssemblyIdentities.Single()); } [WorkItem(1154988)] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var runtime = CreateRuntime(source, ImmutableArray.Create(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml"))); string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); } private RuntimeInstance CreateRuntime( string source, ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences) { var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: compileReferences); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); return CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), runtimeReferences.AddIntrinsicAssembly(), exeBytes, new SymReader(pdbBytes)); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
// Copyright (c) Costin Morariu. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using MvvmToolkit; using MvvmToolkit.Commands; using MvvmToolkit.Messages; using MvvmToolkit.Services; using Problemator.Core.Dtos; using Problemator.Core.Messages; using Problemator.Core.Models; using Problemator.Core.Utils; namespace Problemator.Core.ViewModels { public class TickDetailsViewModel : IHandle<TickAddedMesage>, IActivable, INotifyPropertyChanged { #pragma warning disable CS0067 // Is used by Fody to add NotifyPropertyChanged on properties. public event PropertyChangedEventHandler PropertyChanged; public bool Busy { get; private set; } public bool IsDirty { get; private set; } public Tick Tick { get; private set; } private int _triesCount; public int TriesCount { get { return _triesCount; } set { _triesCount = value; UpdateDirty(); } } private Grade _selectedGrade; public Grade SelectedGrade { get { return _selectedGrade; } set { _selectedGrade = value; UpdateDirty(); } } public IList<Grade> Grades { get; private set; } private string _selectedAscentType; public string SelectedAscentType { get { return _selectedAscentType; } set { _selectedAscentType = value; UpdateDirty(); } } private TimeSpan _sendTime; public TimeSpan SendTime { get { return _sendTime; } set { _sendTime = value; UpdateDirty(); } } private DateTime SendTimestamp => (Tick.Timestamp.Date + SendTime).AddSeconds(Tick.Timestamp.Second); private void UpdateDirty() { if (Tick == null || TriesCount == 0 || SelectedGrade == null || SelectedAscentType == null) { return; } IsDirty = Tick.Tries != TriesCount || Tick.Timestamp != SendTimestamp || Tick.AscentTypeId != _session.GetSportAscentTypeId(SelectedAscentType) || Tick.GradeOpinionId == null && Tick.GradeId != Grades.GetByName(SelectedGrade.Name).Id || Tick.GradeOpinionId != null && Tick.GradeOpinionId != Grades.GetByName(SelectedGrade.Name).Id; } public IList<string> AscentTypes { get; private set; } public ProblemDetails Problem { get; private set; } private readonly Ticks _ticks; private readonly Problem _problem; private readonly Session _session; private readonly Sections _sections; private readonly IEventAggregator _eventAggregator; private readonly INavigationService _navigationService; public TickDetailsViewModel( Ticks ticks, Problem problem, Session session, Sections sections, IEventAggregator eventAggregator, INavigationService navigationService) { _ticks = ticks; _problem = problem; _session = session; _sections = sections; _eventAggregator = eventAggregator; _navigationService = navigationService; } public void Activate(object parameter) { Tick = (Tick) parameter; } private RelayCommand _loadComand; public RelayCommand LoadCommand => _loadComand ?? (_loadComand = new RelayCommand(async () => await LoadAsync())); private async Task LoadAsync() { _eventAggregator.Subscribe(this); Busy = true; await LoadSessionAsync(); UpdateFieldsFromTick(); await LoadDetailsAsync(); IsDirty = false; Busy = false; } private async Task LoadSessionAsync() { await _session.LoadAsync(false); Grades = await _session.GetGradesAsync(); AscentTypes = _session.GetSportAscentTypes(); SelectedAscentType = await _session.GetUserSportAscentType(); } private void UpdateFieldsFromTick() { TriesCount = Tick.Tries; SendTime = Tick.Timestamp.TimeOfDay; SelectedAscentType = _session.GetSportAscentType(Tick.AscentTypeId); SelectedGrade = Grades.GetById(Tick.GradeOpinionId ?? Tick.GradeId); } private async Task LoadDetailsAsync() { Problem = await _problem.GetDetailsAsync(Tick.ProblemId); } private RelayCommand _unloadComand; public RelayCommand UnloadCommand => _unloadComand ?? (_unloadComand = new RelayCommand(Unload)); private void Unload() { _eventAggregator.Unsubscribe(this); } private RelayCommand _saveComand; public RelayCommand SaveCommand => _saveComand ?? (_saveComand = new RelayCommand(async () => await SaveAsync(), () => IsDirty && !Busy)); private async Task SaveAsync() { Busy = true; Tick.Tries = TriesCount; Tick.Timestamp = SendTimestamp; Tick.AscentTypeId = _session.GetSportAscentTypeId(SelectedAscentType); Tick.GradeOpinionId = Grades.GetByName(SelectedGrade.Name).Id; await _ticks.SaveTickAsync(Tick); Busy = false; } public void Handle(TickAddedMesage message) { _navigationService.GoBack(); } } }
using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Terraria; using Terraria.ModLoader; namespace ExampleMod.Projectiles { //imported from my tAPI mod because I'm lazy public class OctopusArm : ModProjectile { public float width { get { return projectile.ai[0]; } set { projectile.ai[0] = value; } } public float length { get { return projectile.ai[1]; } set { projectile.ai[1] = value; } } public float minAngle { get { return projectile.localAI[0]; } set { projectile.localAI[0] = value; } } public float maxAngle { get { return projectile.localAI[1]; } set { projectile.localAI[1] = value; } } public float angleSpeed = 0f; public float lengthSpeed = 0f; public int octopus = -1; private int netUpdateCounter = 0; private const float maxAngleSpeed = 0.01f; private const float angleBuffer = (float)Math.PI / 12f; public const float minLength = 80f; private const float maxLength = 400f; private const float maxLengthSpeed = 1f; public override void SetDefaults() { projectile.name = "Octopus Arm"; projectile.width = 1; projectile.height = 1; projectile.hostile = true; projectile.timeLeft = 2; projectile.penetrate = -1; projectile.tileCollide = false; projectile.ignoreWater = true; } public override void AI() { NPC npc = Main.npc[octopus]; if (!npc.active || npc.type != mod.NPCType("Octopus")) { return; } projectile.timeLeft = 2; Player player = Main.player[npc.target]; projectile.position = npc.Center; Vector2 offset = player.Center - projectile.position; float distance = offset.Length() + 32f; Angle currAngle = new Angle(projectile.rotation); Angle angleToPlayer = new Angle((float)Math.Atan2(offset.Y, offset.X)); Angle min = new Angle(minAngle); Angle max = new Angle(maxAngle); Angle limit = new Angle((minAngle + maxAngle) / 2f); if (limit.Between(min, max)) { limit = limit.Opposite(); } Angle buffer = new Angle(angleBuffer); if (angleToPlayer.Between(min - buffer, max + buffer)) { if (currAngle.Between(max, limit)) { angleSpeed -= maxAngleSpeed / 10f; } else if (currAngle.Between(limit, min)) { angleSpeed += maxAngleSpeed / 10f; } else if (currAngle.ClockwiseFrom(angleToPlayer)) { angleSpeed += maxAngleSpeed / 10f; } else { angleSpeed -= maxAngleSpeed / 10f; } if (length > maxLength) { lengthSpeed -= maxLengthSpeed / 10f; } else if (length < minLength) { lengthSpeed += maxLengthSpeed / 10f; } else if (distance > length) { lengthSpeed += maxLengthSpeed / 10f; } else if (distance < length) { lengthSpeed -= maxLengthSpeed / 10f; } } else { if (currAngle.Between(max, limit)) { angleSpeed -= maxAngleSpeed / 10f; } else if (currAngle.Between(limit, min)) { angleSpeed += maxAngleSpeed / 10f; } else if (angleSpeed > 0f) { angleSpeed += maxAngleSpeed / 20f; } else if (angleSpeed < 0f) { angleSpeed -= maxAngleSpeed / 20f; } else { angleSpeed = maxAngleSpeed / 20f; } if (length > minLength) { lengthSpeed -= maxLengthSpeed / 10f; } else { lengthSpeed += maxLengthSpeed / 10f; } } if (angleSpeed > maxAngleSpeed) { angleSpeed = maxAngleSpeed; } else if (angleSpeed < -maxAngleSpeed) { angleSpeed = -maxAngleSpeed; } if (lengthSpeed > maxLengthSpeed) { lengthSpeed = maxLengthSpeed; } else if (lengthSpeed < -maxLengthSpeed) { lengthSpeed = -maxLengthSpeed; } projectile.rotation += angleSpeed; length += lengthSpeed; if (Main.netMode == 2) { netUpdateCounter++; if (netUpdateCounter >= 300) { projectile.netUpdate = true; netUpdateCounter = 0; } } } public override void SendExtraAI(BinaryWriter writer) { writer.Write(projectile.rotation); writer.Write(minAngle); writer.Write(maxAngle); writer.Write(angleSpeed); writer.Write(lengthSpeed); writer.Write((short)octopus); } public override void ReceiveExtraAI(BinaryReader reader) { projectile.rotation = reader.ReadSingle(); minAngle = reader.ReadSingle(); maxAngle = reader.ReadSingle(); angleSpeed = reader.ReadSingle(); lengthSpeed = reader.ReadSingle(); octopus = reader.ReadInt16(); } public override bool? Colliding(Rectangle projHitbox, Rectangle targetHitbox) { float point = 0f; return Collision.CheckAABBvLineCollision(new Vector2(targetHitbox.X, targetHitbox.Y), new Vector2(targetHitbox.Width, targetHitbox.Height), projectile.position, projectile.position + length * new Vector2((float)Math.Cos(projectile.rotation), (float)Math.Sin(projectile.rotation)), width, ref point); } public override void ModifyHitPlayer(Player target, ref int damage, ref bool crit) { projectile.rotation %= 2f * (float)Math.PI; if (projectile.rotation % (float)Math.PI == 0f) { projectile.direction = -target.direction; } else if (projectile.rotation % (float)Math.PI / 2f == 0f) { projectile.direction = target.Center.X < projectile.position.X ? -1 : 1; } else { float yOffset = target.Center.Y - projectile.position.Y; float x = projectile.position.X + yOffset / (float)Math.Tan(projectile.rotation); projectile.direction = target.Center.X < x ? -1 : 1; } } public override bool PreDraw(SpriteBatch spriteBatch, Color lightColor) { Texture2D unit = Main.projectileTexture[projectile.type]; int unitLength = unit.Width; int numUnits = (int)Math.Ceiling(length / unitLength); float increment = 0f; if (numUnits > 1) { increment = (length - unitLength) / (numUnits - 1); } Vector2 direction = new Vector2((float)Math.Cos(projectile.rotation), (float)Math.Sin(projectile.rotation)); SpriteEffects effects = SpriteEffects.None; if (projectile.spriteDirection == -1) { effects = SpriteEffects.FlipVertically; } for (int k = 1; k <= numUnits; k++) { Texture2D image = unit; if (k == numUnits) { image = mod.GetTexture("Projectiles/OctopusArmTip"); } Vector2 pos = projectile.position + direction * (increment * (k - 1) + unitLength / 2f); Color color = Lighting.GetColor((int)(pos.X / 16f), (int)(pos.Y / 16f)); spriteBatch.Draw(image, pos - Main.screenPosition, null, projectile.GetAlpha(color), projectile.rotation, new Vector2(unit.Width / 2, unit.Height / 2), 1f, effects, 0f); } return false; } public override void PostDraw(SpriteBatch sb, Color lightColor) { Main.instance.DrawNPC(octopus, false); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace EveOPreview.UI { public partial class ThumbnailView : Form, IThumbnailView { #region Private fields private readonly ThumbnailOverlay _overlay; // Part of the logic (namely current size / position management) // was moved to the view due to the performance reasons private bool _isThumbnailSetUp; private bool _isOverlayVisible; private bool _isTopMost; private bool _isPositionChanged; private bool _isSizeChanged; private bool _isCustomMouseModeActive; private bool _isHighlightEnabled; private int _highlightWidth; private DateTime _suppressResizeEventsTimestamp; private DWM_THUMBNAIL_PROPERTIES _thumbnail; private IntPtr _thumbnailHandle; private Size _baseZoomSize; private Point _baseZoomLocation; private Point _baseMousePosition; private Size _baseZoomMaximumSize; private HotkeyHandler _hotkeyHandler; #endregion public ThumbnailView() { this.IsEnabled = true; this.IsActive = false; this.IsOverlayEnabled = false; this._isThumbnailSetUp = false; this._isOverlayVisible = false; this._isTopMost = false; this._isPositionChanged = true; this._isSizeChanged = true; this._isCustomMouseModeActive = false; this._isHighlightEnabled = false; this._suppressResizeEventsTimestamp = DateTime.UtcNow; InitializeComponent(); this._overlay = new ThumbnailOverlay(this, this.MouseDown_Handler); } public IntPtr Id { get; set; } public string Title { get { return this.Text; } set { this.Text = value; this._overlay.SetOverlayLabel(value); } } public bool IsEnabled { get; set; } public bool IsActive { get; set; } public bool IsOverlayEnabled { get; set; } public Point ThumbnailLocation { get { return this.Location; } set { if ((value.X > 0) || (value.Y > 0)) { this.StartPosition = FormStartPosition.Manual; } this.Location = value; } } public Size ThumbnailSize { get { return this.ClientSize; } set { this.ClientSize = value; } } public Action<IntPtr> ThumbnailResized { get; set; } public Action<IntPtr> ThumbnailMoved { get; set; } public Action<IntPtr> ThumbnailFocused { get; set; } public Action<IntPtr> ThumbnailLostFocus { get; set; } public Action<IntPtr> ThumbnailActivated { get; set; } public new void Show() { base.Show(); this._isPositionChanged = true; this._isSizeChanged = true; this._isOverlayVisible = false; // Thumbnail will be properly registered during the Manager's Refresh cycle this.Refresh(); this.IsActive = true; } public new void Hide() { this.IsActive = false; this._overlay.Hide(); base.Hide(); } public new void Close() { this.IsActive = false; this.UnregisterThumbnail(this._thumbnailHandle); this._overlay.Close(); base.Close(); } // This method is used to determine if the provided Handle is related to client or its thumbnail public bool IsKnownHandle(IntPtr handle) { return (this.Id == handle) || (this.Handle == handle) || (this._overlay.Handle == handle); } public void SetSizeLimitations(Size minimumSize, Size maximumSize) { this.MinimumSize = minimumSize; this.MaximumSize = maximumSize; } public void SetOpacity(double opacity) { this.Opacity = opacity; // Overlay opacity settings // Of the thumbnail's opacity is almost full then set the overlay's one to // full. Otherwise set it to half of the thumnail opacity // Opacity value is stored even if the overlay is not displayed atm this._overlay.Opacity = this.Opacity > 0.9 ? 1.0 : 1.0 - (1.0 - this.Opacity) / 2; } public void SetFrames(bool enable) { FormBorderStyle style = enable ? FormBorderStyle.SizableToolWindow : FormBorderStyle.None; // No need to change the borders style if it is ALREADY correct if (this.FormBorderStyle == style) { return; } // Fix for WinForms issue with the Resize event being fired with inconsistent ClientSize value // Any Resize events fired before this timestamp will be ignored this._suppressResizeEventsTimestamp = DateTime.UtcNow.AddMilliseconds(450); this.FormBorderStyle = style; // Notify about possible contents position change this._isSizeChanged = true; } public void SetTopMost(bool enableTopmost) { // IMO WinForms could check this too if (this._isTopMost == enableTopmost) { return; } this.TopMost = enableTopmost; this._overlay.TopMost = enableTopmost; this._isTopMost = enableTopmost; } public void SetHighlight(bool enabled, Color color, int width) { if (this._isHighlightEnabled == enabled) { return; } if (enabled) { this._isHighlightEnabled = true; this._highlightWidth = width; this.BackColor = color; } else { this._isHighlightEnabled = false; this.BackColor = SystemColors.Control; } this._isSizeChanged = true; } public void ZoomIn(ViewZoomAnchor anchor, int zoomFactor) { int oldWidth = this._baseZoomSize.Width; int oldHeight = this._baseZoomSize.Height; int locationX = this.Location.X; int locationY = this.Location.Y; int newWidth = (zoomFactor * this.ClientSize.Width) + (this.Size.Width - this.ClientSize.Width); int newHeight = (zoomFactor * this.ClientSize.Height) + (this.Size.Height - this.ClientSize.Height); // First change size, THEN move the window // Otherwise there is a chance to fail in a loop // Zoom requied -> Moved the windows 1st -> Focus is lost -> Window is moved back -> Focus is back on -> Zoom required -> ... this.MaximumSize = new Size(0, 0); this.Size = new Size(newWidth, newHeight); switch (anchor) { case ViewZoomAnchor.NW: break; case ViewZoomAnchor.N: this.Location = new Point(locationX - newWidth / 2 + oldWidth / 2, locationY); break; case ViewZoomAnchor.NE: this.Location = new Point(locationX - newWidth + oldWidth, locationY); break; case ViewZoomAnchor.W: this.Location = new Point(locationX, locationY - newHeight / 2 + oldHeight / 2); break; case ViewZoomAnchor.C: this.Location = new Point(locationX - newWidth / 2 + oldWidth / 2, locationY - newHeight / 2 + oldHeight / 2); break; case ViewZoomAnchor.E: this.Location = new Point(locationX - newWidth + oldWidth, locationY - newHeight / 2 + oldHeight / 2); break; case ViewZoomAnchor.SW: this.Location = new Point(locationX, locationY - newHeight + this._baseZoomSize.Height); break; case ViewZoomAnchor.S: this.Location = new Point(locationX - newWidth / 2 + oldWidth / 2, locationY - newHeight + oldHeight); break; case ViewZoomAnchor.SE: this.Location = new Point(locationX - newWidth + oldWidth, locationY - newHeight + oldHeight); break; } } public void ZoomOut() { this.RestoreWindowSizeAndLocation(); } public void RegisterHotkey(Keys hotkey) { if (this._hotkeyHandler != null) { this.UnregisterHotkey(); } if (hotkey == Keys.None) { return; } this._hotkeyHandler = new HotkeyHandler(this.Handle, hotkey); this._hotkeyHandler.Pressed += HotkeyPressed_Handler; try { this._hotkeyHandler.Register(); } catch (Exception) { // There can be a lot of possible exception reasons here // In case of any of them the hotkey setting is silently ignored } } public void UnregisterHotkey() { if (this._hotkeyHandler == null) { return; } this._hotkeyHandler.Unregister(); this._hotkeyHandler.Pressed -= HotkeyPressed_Handler; this._hotkeyHandler.Dispose(); this._hotkeyHandler = null; } public void Refresh(bool forceRefresh) { // To prevent flickering the old broken thumbnail is removed AFTER the new shiny one is created IntPtr obsoleteThumbnailHanlde = forceRefresh ? this._thumbnailHandle : IntPtr.Zero; if ((this._isThumbnailSetUp == false) || forceRefresh) { this.RegisterThumbnail(); } bool sizeChanged = this._isSizeChanged || forceRefresh; bool locationChanged = this._isPositionChanged || forceRefresh; if (sizeChanged) { // This approach would work only for square-shaped thumbnail window // To get PROPER results we have to do some crazy math //int delta = this._isHighlightEnabled ? this._highlightWidth : 0; //this._thumbnail.rcDestination = new RECT(0 + delta, 0 + delta, this.ClientSize.Width - delta, this.ClientSize.Height - delta); if (this._isHighlightEnabled) { int baseWidth = this.ClientSize.Width; int baseHeight = this.ClientSize.Height; double baseAspectRatio = ((double)baseWidth) / baseHeight; int actualHeight = baseHeight - 2 * this._highlightWidth; double desiredWidth = actualHeight * baseAspectRatio; int actualWidth = (int)Math.Round(desiredWidth, MidpointRounding.AwayFromZero); int highlightWidthLeft = (baseWidth - actualWidth) / 2; int highlightWidthRight = baseWidth - actualWidth - highlightWidthLeft; this._thumbnail.rcDestination = new RECT(0 + highlightWidthLeft, 0 + this._highlightWidth, baseWidth - highlightWidthRight, baseHeight - this._highlightWidth); } else { //No highlighting enables, so no odd math required this._thumbnail.rcDestination = new RECT(0, 0, this.ClientSize.Width, this.ClientSize.Height); } try { WindowManagerNativeMethods.DwmUpdateThumbnailProperties(this._thumbnailHandle, this._thumbnail); } catch (ArgumentException) { //This exception will be thrown if the EVE client disappears while this method is running } this._isSizeChanged = false; } if (obsoleteThumbnailHanlde != IntPtr.Zero) { this.UnregisterThumbnail(obsoleteThumbnailHanlde); } this._overlay.EnableOverlayLabel(this.IsOverlayEnabled); if (!this._isOverlayVisible) { // One-time action to show the Overlay before it is set up // Otherwise its position won't be set this._overlay.Show(); this._isOverlayVisible = true; } else { if (!(sizeChanged || locationChanged)) { // No need to adjust in the overlay location if it is already visible and properly set return; } } Size overlaySize = this.ClientSize; Point overlayLocation = this.Location; int borderWidth = (this.Size.Width - this.ClientSize.Width) / 2; overlayLocation.X += borderWidth; overlayLocation.Y += (this.Size.Height - this.ClientSize.Height) - borderWidth; this._isPositionChanged = false; this._overlay.Size = overlaySize; this._overlay.Location = overlayLocation; this._overlay.Refresh(); } #region GUI events protected override CreateParams CreateParams { get { var Params = base.CreateParams; Params.ExStyle |= (int)WindowManagerNativeMethods.WS_EX_TOOLWINDOW; return Params; } } private void Move_Handler(object sender, EventArgs e) { this._isPositionChanged = true; this.ThumbnailMoved?.Invoke(this.Id); } private void Resize_Handler(object sender, EventArgs e) { if (DateTime.UtcNow < this._suppressResizeEventsTimestamp) { return; } this._isSizeChanged = true; this.ThumbnailResized?.Invoke(this.Id); } private void MouseEnter_Handler(object sender, EventArgs e) { this.ExitCustomMouseMode(); this.SaveWindowSizeAndLocation(); this.ThumbnailFocused?.Invoke(this.Id); } private void MouseLeave_Handler(object sender, EventArgs e) { this.ThumbnailLostFocus?.Invoke(this.Id); } private void MouseDown_Handler(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { this.ThumbnailActivated?.Invoke(this.Id); } if ((e.Button == MouseButtons.Right) || (e.Button == (MouseButtons.Left | MouseButtons.Right))) { this.EnterCustomMouseMode(); } } private void MouseMove_Handler(object sender, MouseEventArgs e) { if (this._isCustomMouseModeActive) { this.ProcessCustomMouseMode(e.Button.HasFlag(MouseButtons.Left), e.Button.HasFlag(MouseButtons.Right)); } } private void MouseUp_Handler(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { this.ExitCustomMouseMode(); } } private void HotkeyPressed_Handler(object sender, HandledEventArgs e) { this.ThumbnailActivated?.Invoke(this.Id); e.Handled = true; } #endregion #region Thumbnail management private void RegisterThumbnail() { this._thumbnailHandle = WindowManagerNativeMethods.DwmRegisterThumbnail(this.Handle, this.Id); this._thumbnail = new DWM_THUMBNAIL_PROPERTIES(); this._thumbnail.dwFlags = DWM_TNP_CONSTANTS.DWM_TNP_VISIBLE + DWM_TNP_CONSTANTS.DWM_TNP_OPACITY + DWM_TNP_CONSTANTS.DWM_TNP_RECTDESTINATION + DWM_TNP_CONSTANTS.DWM_TNP_SOURCECLIENTAREAONLY; this._thumbnail.opacity = 255; this._thumbnail.fVisible = true; this._thumbnail.fSourceClientAreaOnly = true; this._isThumbnailSetUp = true; } private void UnregisterThumbnail(IntPtr thumbnailHandle) { try { WindowManagerNativeMethods.DwmUnregisterThumbnail(thumbnailHandle); } catch (ArgumentException) { } } #endregion #region Custom Mouse mode // This pair of methods saves/restores certain window propeties // Methods are used to remove the 'Zoom' effect (if any) when the // custom resize/move mode is activated // Methods are kept on this level because moving to the presenter // the code that responds to the mouse events like movement // seems like a huge overkill private void SaveWindowSizeAndLocation() { this._baseZoomSize = this.Size; this._baseZoomLocation = this.Location; this._baseZoomMaximumSize = this.MaximumSize; } private void RestoreWindowSizeAndLocation() { this.Size = this._baseZoomSize; this.MaximumSize = this._baseZoomMaximumSize; this.Location = this._baseZoomLocation; } private void EnterCustomMouseMode() { this.RestoreWindowSizeAndLocation(); this._isCustomMouseModeActive = true; this._baseMousePosition = Control.MousePosition; } private void ProcessCustomMouseMode(bool leftButton, bool rightButton) { Point mousePosition = Control.MousePosition; int offsetX = mousePosition.X - this._baseMousePosition.X; int offsetY = mousePosition.Y - this._baseMousePosition.Y; this._baseMousePosition = mousePosition; // Left + Right buttons trigger thumbnail resize // Right button only trigger thumbnail movement if (leftButton && rightButton) { this.Size = new Size(this.Size.Width + offsetX, this.Size.Height + offsetY); this._baseZoomSize = this.Size; } else { this.Location = new Point(this.Location.X + offsetX, this.Location.Y + offsetY); this._baseZoomLocation = this.Location; } } private void ExitCustomMouseMode() { this._isCustomMouseModeActive = false; } #endregion } }
using System.Windows.Forms; namespace NuGet.Options { partial class PackageSourcesOptionsControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PackageSourcesOptionsControl)); this.HeaderLabel = new System.Windows.Forms.Label(); this.PackageSourcesContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components); this.CopyPackageSourceStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.removeButton = new System.Windows.Forms.Button(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.MoveUpButton = new System.Windows.Forms.Button(); this.MoveDownButton = new System.Windows.Forms.Button(); this.packageListToolTip = new System.Windows.Forms.ToolTip(this.components); this.addButton = new System.Windows.Forms.Button(); this.BrowseButton = new System.Windows.Forms.Button(); this.NewPackageSource = new System.Windows.Forms.TextBox(); this.NewPackageSourceLabel = new System.Windows.Forms.Label(); this.NewPackageName = new System.Windows.Forms.TextBox(); this.NewPackageNameLabel = new System.Windows.Forms.Label(); this.PackageSourcesListBox = new System.Windows.Forms.ListBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.imageList2 = new System.Windows.Forms.ImageList(this.components); this.PackageSourcesContextMenu.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // HeaderLabel // resources.ApplyResources(this.HeaderLabel, "HeaderLabel"); this.tableLayoutPanel1.SetColumnSpan(this.HeaderLabel, 2); this.HeaderLabel.Name = "HeaderLabel"; // // PackageSourcesContextMenu // this.PackageSourcesContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.CopyPackageSourceStripMenuItem}); this.PackageSourcesContextMenu.Name = "contextMenuStrip1"; resources.ApplyResources(this.PackageSourcesContextMenu, "PackageSourcesContextMenu"); this.PackageSourcesContextMenu.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.PackageSourcesContextMenu_ItemClicked); // // CopyPackageSourceStripMenuItem // this.CopyPackageSourceStripMenuItem.Name = "CopyPackageSourceStripMenuItem"; resources.ApplyResources(this.CopyPackageSourceStripMenuItem, "CopyPackageSourceStripMenuItem"); // // removeButton // resources.ApplyResources(this.removeButton, "removeButton"); this.removeButton.ImageList = this.imageList1; this.removeButton.Name = "removeButton"; this.removeButton.UseVisualStyleBackColor = true; this.removeButton.Click += new System.EventHandler(this.OnRemoveButtonClick); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "uparrow.png"); this.imageList1.Images.SetKeyName(1, "downarrow.png"); this.imageList1.Images.SetKeyName(2, "Delete.png"); // // MoveUpButton // resources.ApplyResources(this.MoveUpButton, "MoveUpButton"); this.MoveUpButton.ImageList = this.imageList1; this.MoveUpButton.Name = "MoveUpButton"; this.MoveUpButton.UseVisualStyleBackColor = true; // // MoveDownButton // resources.ApplyResources(this.MoveDownButton, "MoveDownButton"); this.MoveDownButton.ImageList = this.imageList1; this.MoveDownButton.Name = "MoveDownButton"; this.MoveDownButton.UseVisualStyleBackColor = true; // // addButton // resources.ApplyResources(this.addButton, "addButton"); this.addButton.Name = "addButton"; this.addButton.UseVisualStyleBackColor = true; this.addButton.Click += new System.EventHandler(this.OnAddButtonClick); // // BrowseButton // resources.ApplyResources(this.BrowseButton, "BrowseButton"); this.BrowseButton.Name = "BrowseButton"; this.BrowseButton.UseVisualStyleBackColor = true; this.BrowseButton.Click += new System.EventHandler(this.OnBrowseButtonClicked); // // NewPackageSource // resources.ApplyResources(this.NewPackageSource, "NewPackageSource"); this.NewPackageSource.Name = "NewPackageSource"; // // NewPackageSourceLabel // resources.ApplyResources(this.NewPackageSourceLabel, "NewPackageSourceLabel"); this.NewPackageSourceLabel.Name = "NewPackageSourceLabel"; // // NewPackageName // resources.ApplyResources(this.NewPackageName, "NewPackageName"); this.NewPackageName.Name = "NewPackageName"; // // NewPackageNameLabel // resources.ApplyResources(this.NewPackageNameLabel, "NewPackageNameLabel"); this.NewPackageNameLabel.Name = "NewPackageNameLabel"; // // PackageSourcesListBox // resources.ApplyResources(this.PackageSourcesListBox, "PackageSourcesListBox"); this.PackageSourcesListBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tableLayoutPanel1.SetColumnSpan(this.PackageSourcesListBox, 4); this.PackageSourcesListBox.ContextMenuStrip = this.PackageSourcesContextMenu; this.PackageSourcesListBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.PackageSourcesListBox.FormattingEnabled = true; this.PackageSourcesListBox.Name = "PackageSourcesListBox"; this.PackageSourcesListBox.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.PackageSourcesListBox_DrawItem); this.PackageSourcesListBox.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.PackageSourcesListBox_MeasureItem); this.PackageSourcesListBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.PackageSourcesListBox_KeyUp); this.PackageSourcesListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.PackageSourcesListBox_MouseMove); this.PackageSourcesListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.PackageSourcesListBox_MouseUp); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 2, 0); this.tableLayoutPanel1.Controls.Add(this.HeaderLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this.PackageSourcesListBox, 0, 1); this.tableLayoutPanel1.Controls.Add(this.NewPackageNameLabel, 0, 2); this.tableLayoutPanel1.Controls.Add(this.NewPackageName, 1, 2); this.tableLayoutPanel1.Controls.Add(this.NewPackageSourceLabel, 0, 3); this.tableLayoutPanel1.Controls.Add(this.NewPackageSource, 1, 3); this.tableLayoutPanel1.Controls.Add(this.BrowseButton, 2, 3); this.tableLayoutPanel1.Controls.Add(this.addButton, 3, 3); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel1.SetColumnSpan(this.tableLayoutPanel2, 2); this.tableLayoutPanel2.Controls.Add(this.removeButton, 0, 0); this.tableLayoutPanel2.Controls.Add(this.MoveUpButton, 1, 0); this.tableLayoutPanel2.Controls.Add(this.MoveDownButton, 2, 0); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // imageList2 // this.imageList2.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList2.ImageStream"))); this.imageList2.TransparentColor = System.Drawing.Color.Transparent; this.imageList2.Images.SetKeyName(0, "uparrow.png"); this.imageList2.Images.SetKeyName(1, "downarrow.png"); this.imageList2.Images.SetKeyName(2, "delete.png"); // // PackageSourcesOptionsControl // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tableLayoutPanel1); this.Name = "PackageSourcesOptionsControl"; this.PackageSourcesContextMenu.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label HeaderLabel; private System.Windows.Forms.Button removeButton; private ContextMenuStrip PackageSourcesContextMenu; private ToolStripMenuItem CopyPackageSourceStripMenuItem; private Button MoveUpButton; private Button MoveDownButton; private ToolTip packageListToolTip; private Button addButton; private Button BrowseButton; private TextBox NewPackageSource; private Label NewPackageSourceLabel; private TextBox NewPackageName; private TableLayoutPanel tableLayoutPanel1; private ListBox PackageSourcesListBox; private Label NewPackageNameLabel; private TableLayoutPanel tableLayoutPanel2; private ImageList imageList1; private ImageList imageList2; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Text; using Xunit; namespace System.Collections.HashtableTests { public class AddTests { [Fact] public void TestAddBasic() { Hashtable ht = null; string[] keys = { "key_0", "key_1"}; string[] values = { "val_0", "val_1" }; var k1 = new StringBuilder(keys[0]); var k2 = new StringBuilder(keys[1]); var v1 = new StringBuilder(values[0]); var v2 = new StringBuilder(values[1]); ht = new Hashtable(); ht.Add(k1, v1); ht.Add(k2, v2); Assert.True(ht.ContainsKey(k2)); Assert.True(ht.ContainsValue(v2)); ICollection allkeys = ht.Keys; Assert.Equal(allkeys.Count, ht.Count); IEnumerator allkeysEnum = allkeys.GetEnumerator(); int index = 0; string[] ary = new string[2]; while (allkeysEnum.MoveNext()) { ary[index++] = allkeysEnum.Current.ToString(); } // Not necessary the same order if (keys[0] == ary[0]) { Assert.Equal(keys[1], ary[1]); } else { Assert.Equal(keys[0], ary[1]); } ICollection allvalues = ht.Values; Assert.Equal(allvalues.Count, ht.Count); IEnumerator allvaluesEnum = allvalues.GetEnumerator(); index = 0; while (allvaluesEnum.MoveNext()) { ary[index++] = (string)allvaluesEnum.Current.ToString(); } if (values[0] == ary[0]) { Assert.Equal(values[1], ary[1]); } else { Assert.Equal(values[0], ary[1]); } } [Fact] public void TestAddBasic01() { Hashtable ht2 = null; int[] in4a = new int[9]; string str5 = null; string str6 = null; string str7 = null; // Construct ht2 = new Hashtable(); // Add the first obj str5 = "key_150"; str6 = "value_150"; ht2.Add(str5, str6); in4a[0] = ht2.Count; Assert.Equal(in4a[0], 1); str7 = (string)ht2[str5]; Assert.Equal(str7 ,str6); // Add another obj, verify the previously added pair still exists. str5 = "key_130"; str6 = "value_130"; //equiv. to <i>"value_130";</i> ht2.Add(str5, str6); in4a[2] = ht2.Count; // size verification Assert.Equal(in4a[2], 2); // verify the Values added str7 = (string)ht2["key_150"]; Assert.NotNull(str7); Assert.Equal("value_150", str7); str7 = (string)ht2[str5]; Assert.NotNull(str7); Assert.Equal(str7, str6); // Cause expected exception by attempting to add duplicate keys. Assert.Throws<ArgumentException>(() => { ht2.Add(str5, str6 + "_b"); }); // Only the key is dupl. // Cause expected exception by attempting to add null key. str5 = null; str6 = "value_null"; Assert.Throws<ArgumentNullException>(() => { ht2.Add(str5, str6); }); } [Fact] public void TestAddWithReferenceTypeValues() { StringBuilder sbl3 = new StringBuilder(99); StringBuilder sbl4 = new StringBuilder(99); StringBuilder sbl5 = new StringBuilder(99); StringBuilder sblWork1 = new StringBuilder(99); // Examine whether this Collection stores a ref to the provided object or a copy of the object (should store ref). var ht2 = new Hashtable(); sbl3.Length = 0; sbl3.Append("key_f3"); sbl4.Length = 0; sbl4.Append("value_f3"); ht2.Add(sbl3, sbl4); sbl4.Length = 0; sbl4.Append("value_f4"); // Modify object referenced by ht2, changing its value. sblWork1 = (StringBuilder)ht2[sbl3]; Assert.True(sblWork1.ToString().Equals(sbl4.ToString())); // Examine "backdoor duplicate" behavior - should be ok as both // GetHashCode && Equals are checked before insert/get in the current impl. ht2 = new Hashtable(); sbl3.Length = 0; sbl3.Append("key_m5"); sbl4.Length = 0; sbl4.Append("value_m5"); ht2.Add(sbl3, sbl4); sbl5 = new StringBuilder("key_p7"); //new memory SBL Obj sbl4.Length = 0; sbl4.Append("value_p7"); ht2.Add(sbl5, sbl4); sbl5.Length = 0; //"No Object" key Assert.Equal(2, ht2.Count); sbl5.Append("key_m5"); // Backdoor duplicate! sblWork1 = (StringBuilder)ht2[sbl5]; Assert.True(ht2.ContainsKey(sbl5)); ht2.Clear(); } [Fact] public void TestAddClearRepeatedly() { int inLoops0 = 2; int inLoops1 = 2; var ht2 = new Hashtable(); for (int aa = 0; aa < inLoops0; aa++) { for (int bb = 0; bb < inLoops1; bb++) { ht2.Add("KEY: aa==" + aa + " ,bb==" + bb, "VALUE: aa==" + aa + " ,bb==" + bb); } Assert.Equal(inLoops1, ht2.Count); ht2.Clear(); } } const int iterations = 1600; [Fact] public void TestDuplicatedKeysWithInitialCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var ht = new Hashtable(200); for (int i = 0; i < iterations; i += 2) { ht.Add(new BadHashCode(i), i.ToString()); ht.Add(new BadHashCode(i + 1), (i + 1).ToString()); ht.Remove(new BadHashCode(i)); ht.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < iterations; i++) { ht.Add(i.ToString(), i); } for (int i = 0; i < iterations; i++) { Assert.Equal(i, (int)ht[i.ToString()]); } } [Fact] public void TestDuplicatedKeysWithDefaultCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var ht = new Hashtable(); for (int i = 0; i < iterations; i += 2) { ht.Add(new BadHashCode(i), i.ToString()); ht.Add(new BadHashCode(i + 1), (i + 1).ToString()); ht.Remove(new BadHashCode(i)); ht.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < iterations; i++) { ht.Add(i.ToString(), i); } for (int i = 0; i < iterations; i++) { Assert.Equal(i, (int)ht[i.ToString()]); } } } public class BadHashCode { private uint _value; public BadHashCode(int value) { _value = (uint)value; } public override bool Equals(object o) { BadHashCode rhValue = o as BadHashCode; if (null != rhValue) { return _value.Equals(rhValue); } else { throw new ArgumentException("o", "is not BadHashCode type actual " + o.GetType()); } } public override int GetHashCode() { // Return 0 for everything to force hash collisions. return 0; } public override string ToString() { return _value.ToString(); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace ECM.DocumentLibrariesWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System.Runtime.Remoting; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core; using Umbraco.Core.Exceptions; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Services; using Umbraco.Tests.CodeFirst.TestModels.Composition; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class ContentTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { IContentType contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); IContent contentItem = MockedContent.CreateTextpageContent(contentType1, "Testing", -1); ServiceContext.ContentService.SaveAndPublishWithStatus(contentItem); var initProps = contentItem.Properties.Count; var initPropTypes = contentItem.PropertyTypes.Count(); //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); //re-load it from the db contentItem = ServiceContext.ContentService.GetById(contentItem.Id); Assert.AreEqual(initPropTypes - 1, contentItem.PropertyTypes.Count()); Assert.AreEqual(initProps - 1, contentItem.Properties.Count); } [Test] public void Rebuild_Content_Xml_On_Alias_Change() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); var contentType2 = MockedContentTypes.CreateTextpageContentType("test2", "Test2"); ServiceContext.ContentTypeService.Save(contentType1); ServiceContext.ContentTypeService.Save(contentType2); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); var contentItems2 = MockedContent.CreateTextpageContent(contentType2, -1, 5).ToArray(); contentItems2.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); //only update the contentType1 alias which will force an xml rebuild for all content of that type contentType1.Alias = "newAlias"; ServiceContext.ContentTypeService.Save(contentType1); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<newAlias")); } foreach (var c in contentItems2) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same } } [Test] public void Rebuild_Content_Xml_On_Property_Removal() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublishWithStatus(x)); var alias = contentType1.PropertyTypes.First().Alias; var elementToMatch = "<" + alias + ">"; foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); var reQueried = ServiceContext.ContentTypeService.GetContentType(contentType1.Id); var reContent = ServiceContext.ContentService.GetById(contentItems1.First().Id); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } } [Test] public void Get_Descendants() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.Descendants(); //Assert Assert.AreEqual(10, descendants.Count()); } [Test] public void Get_Descendants_And_Self() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.DescendantsAndSelf(); //Assert Assert.AreEqual(11, descendants.Count()); } [Test] public void Get_With_Missing_Guid() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; //Act var result = contentTypeService.GetMediaType(Guid.NewGuid()); //Assert Assert.IsNull(result); } [Test] public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); for (var i = 0; i < hierarchy.Count(); i++) { if (i == 0) continue; Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } [Test] public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange var cs = ServiceContext.ContentService; var cts = ServiceContext.ContentTypeService; var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); var ctBase = new ContentType(-1) { Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png" }; ctBase.AddPropertyType(new PropertyType(dtdYesNo, Constants.Conventions.Content.NaviHide) { Name = "Hide From Navigation", } /*,"Navigation"*/); cts.Save(ctBase); const string contentTypeAlias = "HomePage"; var ctHomePage = new ContentType(ctBase, contentTypeAlias) { Name = "Home Page", Alias = contentTypeAlias, Icon = "settingDomain.gif", Thumbnail = "folder.png", AllowedAsRoot = true }; ctHomePage.AddPropertyType(new PropertyType(dtdYesNo, "someProperty") { Name = "Some property" } /*,"Navigation"*/); cts.Save(ctHomePage); // Act var homeDoc = cs.CreateContent("Home Page", -1, contentTypeAlias); cs.SaveAndPublishWithStatus(homeDoc); // Assert Assert.That(ctBase.HasIdentity, Is.True); Assert.That(ctHomePage.HasIdentity, Is.True); Assert.That(homeDoc.HasIdentity, Is.True); Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); } [Test] public void Create_Content_Type_Ensures_Sort_Orders() { var service = ServiceContext.ContentTypeService; var contentType = new ContentType(-1) { Alias = "test", Name = "Test", Description = "ContentType used for simple text pages", Icon = ".sprTreeDoc3", Thumbnail = "doc2.png", SortOrder = 1, CreatorId = 0, Trashed = false }; contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, DataTypeDefinitionId = -88 }); contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TinyMCEAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, DataTypeDefinitionId = -87 }); contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "Name of the author", Mandatory = false, DataTypeDefinitionId = -88 }); service.Save(contentType); var sortOrders = contentType.PropertyTypes.Select(x => x.SortOrder).ToArray(); Assert.AreEqual(1, sortOrders.Count(x => x == 0)); Assert.AreEqual(1, sortOrders.Count(x => x == 1)); Assert.AreEqual(1, sortOrders.Count(x => x == 2)); } [Test] public void Can_Create_And_Save_ContentType_Composition() { /* * Global * - Components * - Category */ var service = ServiceContext.ContentTypeService; var global = MockedContentTypes.CreateSimpleContentType("global", "Global"); service.Save(global); var components = MockedContentTypes.CreateSimpleContentType("components", "Components", global, true); service.Save(components); var component = MockedContentTypes.CreateSimpleContentType("component", "Component", components, true); service.Save(component); var category = MockedContentTypes.CreateSimpleContentType("category", "Category", global, true); service.Save(category); var success = category.AddContentType(component); Assert.That(success, Is.False); } [Test] public void Can_Delete_Parent_ContentType_When_Child_Has_Content() { var cts = ServiceContext.ContentTypeService; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true); cts.Save(contentType); var childContentType = MockedContentTypes.CreateSimpleContentType("childPage", "Child Page", contentType, true, "Child Content"); cts.Save(childContentType); var cs = ServiceContext.ContentService; var content = cs.CreateContent("Page 1", -1, childContentType.Alias); cs.Save(content); cts.Delete(contentType); Assert.IsNotNull(content.Id); Assert.AreNotEqual(0, content.Id); Assert.IsNotNull(childContentType.Id); Assert.AreNotEqual(0, childContentType.Id); Assert.IsNotNull(contentType.Id); Assert.AreNotEqual(0, contentType.Id); var deletedContent = cs.GetById(content.Id); var deletedChildContentType = cts.GetContentType(childContentType.Id); var deletedContentType = cts.GetContentType(contentType.Id); Assert.IsNull(deletedChildContentType); Assert.IsNull(deletedContent); Assert.IsNull(deletedContentType); } [Test] public void Can_Create_Container() { // Arrange var cts = ServiceContext.ContentTypeService; // Act var container = new EntityContainer(Constants.ObjectTypes.DocumentTypeGuid); container.Name = "container1"; cts.SaveContentTypeContainer(container); // Assert var createdContainer = cts.GetContentTypeContainer(container.Id); Assert.IsNotNull(createdContainer); } [Test] public void Can_Get_All_Containers() { // Arrange var cts = ServiceContext.ContentTypeService; // Act var container1 = new EntityContainer(Constants.ObjectTypes.DocumentTypeGuid); container1.Name = "container1"; cts.SaveContentTypeContainer(container1); var container2 = new EntityContainer(Constants.ObjectTypes.DocumentTypeGuid); container2.Name = "container2"; cts.SaveContentTypeContainer(container2); // Assert var containers = cts.GetContentTypeContainers(new int[0]); Assert.AreEqual(2, containers.Count()); } [Test] public void Deleting_ContentType_Sends_Correct_Number_Of_DeletedEntities_In_Events() { var cts = ServiceContext.ContentTypeService; var deletedEntities = 0; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page"); cts.Save(contentType); ContentTypeService.DeletedContentType += (sender, args) => { deletedEntities += args.DeletedEntities.Count(); }; cts.Delete(contentType); Assert.AreEqual(deletedEntities, 1); } [Test] public void Deleting_Multiple_ContentTypes_Sends_Correct_Number_Of_DeletedEntities_In_Events() { var cts = ServiceContext.ContentTypeService; var deletedEntities = 0; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page"); cts.Save(contentType); var contentType2 = MockedContentTypes.CreateSimpleContentType("otherPage", "Other page"); cts.Save(contentType2); ContentTypeService.DeletedContentType += (sender, args) => { deletedEntities += args.DeletedEntities.Count(); }; cts.Delete(contentType); cts.Delete(contentType2); Assert.AreEqual(2, deletedEntities); } [Test] public void Deleting_ContentType_With_Child_Sends_Correct_Number_Of_DeletedEntities_In_Events() { var cts = ServiceContext.ContentTypeService; var deletedEntities = 0; var contentType = MockedContentTypes.CreateSimpleContentType("page", "Page"); cts.Save(contentType); var contentType2 = MockedContentTypes.CreateSimpleContentType("subPage", "Sub page"); contentType2.ParentId = contentType.Id; cts.Save(contentType2); ContentTypeService.DeletedContentType += (sender, args) => { deletedEntities += args.DeletedEntities.Count(); }; cts.Delete(contentType); Assert.AreEqual(2, deletedEntities); } [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { //Test for U4-2234 var cts = ServiceContext.ContentTypeService; //Arrange var component = CreateComponent(); cts.Save(component); var banner = CreateBannerComponent(component); cts.Save(banner); var site = CreateSite(); cts.Save(site); var homepage = CreateHomepage(site); cts.Save(homepage); //Add banner to homepage var added = homepage.AddContentType(banner); cts.Save(homepage); //Assert composition var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); //Remove banner from homepage var removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); //Assert composition var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); } [Test] public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var sut = simpleContentType.DeepCloneWithResetIdentities("newcategory"); service.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); var contentType = service.GetContentType(sut.Id); var category = service.GetContentType(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); Assert.AreEqual(contentType.Level, category.Level); Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); Assert.AreNotEqual(contentType.Id, category.Id); Assert.AreNotEqual(contentType.Key, category.Key); Assert.AreNotEqual(contentType.Path, category.Path); Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2", null, true); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1, true); service.Save(simpleContentType); // Act var clone = simpleContentType.DeepCloneWithResetIdentities("newcategory"); clone.RemoveContentType("parent1"); clone.AddContentType(parentContentType2); clone.ParentId = parentContentType2.Id; service.Save(clone); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id); } [Test] public void Can_Copy_ContentType_With_Service_To_Root() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var clone = service.Copy(simpleContentType, "newcategory", "new category"); // Assert Assert.That(clone.HasIdentity, Is.True); var cloned = service.GetContentType(clone.Id); var original = service.GetContentType(categoryId); Assert.That(cloned.CompositionAliases().Any(x => x.Equals("meta")), Is.False); //it's been copied to root Assert.AreEqual(cloned.ParentId, -1); Assert.AreEqual(cloned.Level, 1); Assert.AreEqual(cloned.PropertyTypes.Count(), original.PropertyTypes.Count()); Assert.AreEqual(cloned.PropertyGroups.Count(), original.PropertyGroups.Count()); for (int i = 0; i < cloned.PropertyGroups.Count; i++) { Assert.AreEqual(cloned.PropertyGroups[i].PropertyTypes.Count, original.PropertyGroups[i].PropertyTypes.Count); foreach (var propertyType in cloned.PropertyGroups[i].PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } } foreach (var propertyType in cloned.PropertyTypes) { Assert.IsTrue(propertyType.HasIdentity); } Assert.AreNotEqual(cloned.Id, original.Id); Assert.AreNotEqual(cloned.Key, original.Key); Assert.AreNotEqual(cloned.Path, original.Path); Assert.AreNotEqual(cloned.SortOrder, original.SortOrder); Assert.AreNotEqual(cloned.PropertyTypes.First(x => x.Alias.Equals("title")).Id, original.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(cloned.PropertyGroups.First(x => x.Name.Equals("Content")).Id, original.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } [Test] public void Can_Copy_ContentType_To_New_Parent_With_Service() { // Arrange var service = ServiceContext.ContentTypeService; var parentContentType1 = MockedContentTypes.CreateSimpleContentType("parent1", "Parent1"); service.Save(parentContentType1); var parentContentType2 = MockedContentTypes.CreateSimpleContentType("parent2", "Parent2", null, true); service.Save(parentContentType2); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", parentContentType1, true); service.Save(simpleContentType); // Act var clone = service.Copy(simpleContentType, "newAlias", "new alias", parentContentType2); // Assert Assert.That(clone.HasIdentity, Is.True); var clonedContentType = service.GetContentType(clone.Id); var originalContentType = service.GetContentType(simpleContentType.Id); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent2")), Is.True); Assert.That(clonedContentType.CompositionAliases().Any(x => x.Equals("parent1")), Is.False); Assert.AreEqual(clonedContentType.Path, "-1," + parentContentType2.Id + "," + clonedContentType.Id); Assert.AreEqual(clonedContentType.PropertyTypes.Count(), originalContentType.PropertyTypes.Count()); Assert.AreNotEqual(clonedContentType.ParentId, originalContentType.ParentId); Assert.AreEqual(clonedContentType.ParentId, parentContentType2.Id); Assert.AreNotEqual(clonedContentType.Id, originalContentType.Id); Assert.AreNotEqual(clonedContentType.Key, originalContentType.Key); Assert.AreNotEqual(clonedContentType.Path, originalContentType.Path); Assert.AreNotEqual(clonedContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id, originalContentType.PropertyTypes.First(x => x.Alias.StartsWith("title")).Id); Assert.AreNotEqual(clonedContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id, originalContentType.PropertyGroups.First(x => x.Name.StartsWith("Content")).Id); } [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_To_Referenced_Composition() { //Related the second issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange var service = ServiceContext.ContentTypeService; var parent = MockedContentTypes.CreateSimpleContentType(); service.Save(parent); var child = MockedContentTypes.CreateSimpleContentType("simpleChildPage", "Simple Child Page", parent, true); service.Save(child); var composition = MockedContentTypes.CreateMetaContentType(); service.Save(composition); //Adding Meta-composition to child doc type child.AddContentType(composition); service.Save(child); // Act var duplicatePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var added = composition.AddPropertyType(duplicatePropertyType, "Meta"); // Assert Assert.That(added, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(composition)); Assert.DoesNotThrow(() => service.GetContentType("simpleChildPage")); } [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_In_Composition_Graph() { // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateSimpleContentType("basePage", "Base Page", null, true); service.Save(basePage); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true); service.Save(advancedPage); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); var seoComposition = MockedContentTypes.CreateSeoContentType(); service.Save(seoComposition); var metaAdded = contentPage.AddContentType(metaComposition); service.Save(contentPage); var seoAdded = advancedPage.AddContentType(seoComposition); service.Save(advancedPage); // Act var duplicatePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var addedToBasePage = basePage.AddPropertyType(duplicatePropertyType, "Content"); var addedToAdvancedPage = advancedPage.AddPropertyType(duplicatePropertyType, "Content"); var addedToMeta = metaComposition.AddPropertyType(duplicatePropertyType, "Meta"); var addedToSeo = seoComposition.AddPropertyType(duplicatePropertyType, "Seo"); // Assert Assert.That(metaAdded, Is.True); Assert.That(seoAdded, Is.True); Assert.That(addedToBasePage, Is.True); Assert.That(addedToAdvancedPage, Is.False); Assert.That(addedToMeta, Is.True); Assert.That(addedToSeo, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(basePage)); Assert.Throws<InvalidCompositionException>(() => service.Save(metaComposition)); Assert.Throws<InvalidCompositionException>(() => service.Save(seoComposition)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); Assert.DoesNotThrow(() => service.GetContentType("meta")); Assert.DoesNotThrow(() => service.GetContentType("seo")); } [Test] public void Cannot_Add_Duplicate_PropertyType_Alias_At_Root_Which_Conflicts_With_Third_Levels_Composition() { /* * BasePage, gets 'Title' added but should not be allowed * -- Content Page * ---- Advanced Page -> Content Meta * Content Meta :: Composition, has 'Title' * * Content Meta has 'Title' PropertyType * Adding 'Title' to BasePage should fail */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var compositionAdded = advancedPage.AddContentType(contentMetaComposition); service.Save(advancedPage); //NOTE: It should not be possible to Save 'BasePage' with the Title PropertyType added var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(compositionAdded, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(basePage)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); } [Test] public void Cannot_Save_ContentType_With_Empty_Name() { // Arrange var contentType = MockedContentTypes.CreateSimpleContentType("contentType", string.Empty); // Act & Assert Assert.Throws<ArgumentException>(() => ServiceContext.ContentTypeService.Save(contentType)); } [Test] public void Cannot_Rename_PropertyType_Alias_On_Composition_Which_Would_Cause_Conflict_In_Other_Composition() { /* * Meta renames alias to 'title' * Seo has 'Title' * BasePage * -- ContentPage * ---- AdvancedPage -> Seo * ------ MoreAdvanedPage -> Meta */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var moreAdvancedPage = MockedContentTypes.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); service.Save(moreAdvancedPage); var seoComposition = MockedContentTypes.CreateSeoContentType(); service.Save(seoComposition); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); service.Save(advancedPage); var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); service.Save(seoComposition); var seoCompositionAdded = advancedPage.AddContentType(seoComposition); var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); service.Save(advancedPage); service.Save(moreAdvancedPage); var keywordsPropertyType = metaComposition.PropertyTypes.First(x => x.Alias.Equals("metakeywords")); keywordsPropertyType.Alias = "title"; // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(seoCompositionAdded, Is.True); Assert.That(metaCompositionAdded, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(metaComposition)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); Assert.DoesNotThrow(() => service.GetContentType("moreAdvancedPage")); } [Test] public void Can_Add_Additional_Properties_On_Composition_Once_Composition_Has_Been_Saved() { /* * Meta renames alias to 'title' * Seo has 'Title' * BasePage * -- ContentPage * ---- AdvancedPage -> Seo * ------ MoreAdvancedPage -> Meta */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var moreAdvancedPage = MockedContentTypes.CreateBasicContentType("moreAdvancedPage", "More Advanced Page", advancedPage); service.Save(moreAdvancedPage); var seoComposition = MockedContentTypes.CreateSeoContentType(); service.Save(seoComposition); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = advancedPage.AddPropertyType(subtitlePropertyType, "Content"); service.Save(advancedPage); var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = seoComposition.AddPropertyType(titlePropertyType, "Content"); service.Save(seoComposition); var seoCompositionAdded = advancedPage.AddContentType(seoComposition); var metaCompositionAdded = moreAdvancedPage.AddContentType(metaComposition); service.Save(advancedPage); service.Save(moreAdvancedPage); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(seoCompositionAdded, Is.True); Assert.That(metaCompositionAdded, Is.True); var testPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "test") { Name = "Test", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var testAdded = seoComposition.AddPropertyType(testPropertyType, "Content"); service.Save(seoComposition); Assert.That(testAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); Assert.DoesNotThrow(() => service.GetContentType("moreAdvancedPage")); } [Test] public void Cannot_Rename_PropertyGroup_On_Child_Avoiding_Conflict_With_Parent_PropertyGroup() { // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true, "Content"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true, "Content_"); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true, "Details"); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); //Change the name of the tab on the "root" content type 'page'. var propertyGroup = contentPage.PropertyGroups["Content_"]; Assert.Throws<Exception>(() => contentPage.PropertyGroups.Add(new PropertyGroup { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 })); // Assert Assert.That(compositionAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); } [Test] public void Cannot_Rename_PropertyType_Alias_Causing_Conflicts_With_Parents() { // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); // Act var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = basePage.AddPropertyType(titlePropertyType, "Content"); var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content"); var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content"); service.Save(basePage); service.Save(contentPage); service.Save(advancedPage); //Rename the PropertyType to something that already exists in the Composition - NOTE this should not be allowed and Saving should throw an exception var authorPropertyTypeToRename = advancedPage.PropertyTypes.First(x => x.Alias.Equals("author")); authorPropertyTypeToRename.Alias = "title"; // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(titleAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.Throws<InvalidCompositionException>(() => service.Save(advancedPage)); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); } [Test] public void Can_Add_PropertyType_Alias_Which_Exists_In_Composition_Outside_Graph() { /* * Meta (Composition) * Content Meta (Composition) has 'Title' -> Meta * BasePage * -- ContentPage gets 'Title' added -> Meta * ---- Advanced Page */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateSimpleContentType("basePage", "Base Page", null, true); service.Save(basePage); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", basePage, true); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true); service.Save(advancedPage); var metaComposition = MockedContentTypes.CreateMetaContentType(); service.Save(metaComposition); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); var metaAdded = contentPage.AddContentType(metaComposition); service.Save(contentPage); var metaAddedToComposition = contentMetaComposition.AddContentType(metaComposition); service.Save(contentMetaComposition); // Act var propertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var addedToContentPage = contentPage.AddPropertyType(propertyType, "Content"); // Assert Assert.That(metaAdded, Is.True); Assert.That(metaAddedToComposition, Is.True); Assert.That(addedToContentPage, Is.True); Assert.DoesNotThrow(() => service.Save(contentPage)); } [Test] public void Can_Rename_PropertyGroup_With_Inherited_PropertyGroups() { //Related the first issue in screencast from this post http://issues.umbraco.org/issue/U4-5986 // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, false, "Content_"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true); service.Save(contentPage); var composition = MockedContentTypes.CreateMetaContentType(); composition.AddPropertyGroup("Content"); service.Save(composition); //Adding Meta-composition to child doc type contentPage.AddContentType(composition); service.Save(contentPage); // Act var propertyTypeOne = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "testTextbox") { Name = "Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var firstOneAdded = contentPage.AddPropertyType(propertyTypeOne, "Content_"); var propertyTypeTwo = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "anotherTextbox") { Name = "Another Test Textbox", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var secondOneAdded = contentPage.AddPropertyType(propertyTypeTwo, "Content"); service.Save(contentPage); Assert.That(page.PropertyGroups.Contains("Content_"), Is.True); var propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup{ Id = propertyGroup.Id, Name = "ContentTab", SortOrder = 0}); service.Save(page); // Assert Assert.That(firstOneAdded, Is.True); Assert.That(secondOneAdded, Is.True); var contentType = service.GetContentType("contentPage"); Assert.That(contentType, Is.Not.Null); var compositionPropertyGroups = contentType.CompositionPropertyGroups; // now it is still 1, because we don't propagate renames anymore Assert.That(compositionPropertyGroups.Count(x => x.Name.Equals("Content_")), Is.EqualTo(1)); var propertyTypeCount = contentType.PropertyTypes.Count(); var compPropertyTypeCount = contentType.CompositionPropertyTypes.Count(); Assert.That(propertyTypeCount, Is.EqualTo(5)); Assert.That(compPropertyTypeCount, Is.EqualTo(10)); } [Test] public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true, "Content_"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true, "Contentx"); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateSimpleContentType("advancedPage", "Advanced Page", contentPage, true, "Contenty"); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = contentPage.AddPropertyType(bodyTextPropertyType, "Content_");//Will be added to the parent tab var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content");//Will be added to the "Content Meta" composition service.Save(contentPage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var descriptionPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "description") { Name = "Description", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var keywordsPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "keywords") { Name = "Keywords", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = advancedPage.AddPropertyType(authorPropertyType, "Content_");//Will be added to an ancestor tab var descriptionAdded = advancedPage.AddPropertyType(descriptionPropertyType, "Contentx");//Will be added to a parent tab var keywordsAdded = advancedPage.AddPropertyType(keywordsPropertyType, "Content");//Will be added to the "Content Meta" composition service.Save(advancedPage); //Change the name of the tab on the "root" content type 'page'. var propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); service.Save(page); // Assert Assert.That(compositionAdded, Is.True); Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(descriptionAdded, Is.True); Assert.That(keywordsAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); var advancedPageReloaded = service.GetContentType("advancedPage"); var contentUnderscoreTabExists = advancedPageReloaded.CompositionPropertyGroups.Any(x => x.Name.Equals("Content_")); // now is true, because we don't propagate renames anymore Assert.That(contentUnderscoreTabExists, Is.True); var numberOfContentTabs = advancedPageReloaded.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(4)); } [Test] public void Can_Rename_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups_v2() { // Arrange var service = ServiceContext.ContentTypeService; var page = MockedContentTypes.CreateSimpleContentType("page", "Page", null, true, "Content_"); service.Save(page); var contentPage = MockedContentTypes.CreateSimpleContentType("contentPage", "Content Page", page, true, "Content"); service.Save(contentPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var subtitlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "subtitle") { Name = "Subtitle", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = page.AddPropertyType(bodyTextPropertyType, "Content_"); var subtitleAdded = contentPage.AddPropertyType(subtitlePropertyType, "Content"); var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content_"); service.Save(page); service.Save(contentPage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); //Change the name of the tab on the "root" content type 'page'. var propertyGroup = page.PropertyGroups["Content_"]; page.PropertyGroups.Add(new PropertyGroup { Id = propertyGroup.Id, Name = "Content", SortOrder = 0 }); service.Save(page); // Assert Assert.That(compositionAdded, Is.True); Assert.That(bodyTextAdded, Is.True); Assert.That(subtitleAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); } [Test] public void Can_Remove_PropertyGroup_On_Parent_Without_Causing_Duplicate_PropertyGroups() { // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); basePage.RemovePropertyGroup("Content"); service.Save(basePage); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(compositionAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); var contentType = service.GetContentType("contentPage"); var propertyGroup = contentType.PropertyGroups["Content"]; } [Test] public void Can_Remove_PropertyGroup_Without_Removing_Property_Types() { var service = ServiceContext.ContentTypeService; var basePage = (IContentType)MockedContentTypes.CreateBasicContentType(); basePage.AddPropertyGroup("Content"); basePage.AddPropertyGroup("Meta"); service.Save(basePage); var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = basePage.AddPropertyType(authorPropertyType, "Content"); var titlePropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var titleAdded = basePage.AddPropertyType(authorPropertyType, "Meta"); service.Save(basePage); basePage = service.GetContentType(basePage.Id); var totalPt = basePage.PropertyTypes.Count(); basePage.RemovePropertyGroup("Content"); service.Save(basePage); basePage = service.GetContentType(basePage.Id); Assert.AreEqual(totalPt, basePage.PropertyTypes.Count()); } [Test] public void Can_Add_PropertyGroup_With_Same_Name_On_Parent_and_Child() { /* * BasePage * - Content Page * -- Advanced Page * Content Meta :: Composition */ // Arrange var service = ServiceContext.ContentTypeService; var basePage = MockedContentTypes.CreateBasicContentType(); service.Save(basePage); var contentPage = MockedContentTypes.CreateBasicContentType("contentPage", "Content Page", basePage); service.Save(contentPage); var advancedPage = MockedContentTypes.CreateBasicContentType("advancedPage", "Advanced Page", contentPage); service.Save(advancedPage); var contentMetaComposition = MockedContentTypes.CreateContentMetaContentType(); service.Save(contentMetaComposition); // Act var authorPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var authorAdded = contentPage.AddPropertyType(authorPropertyType, "Content"); service.Save(contentPage); var bodyTextPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }; var bodyTextAdded = basePage.AddPropertyType(bodyTextPropertyType, "Content"); service.Save(basePage); var compositionAdded = contentPage.AddContentType(contentMetaComposition); service.Save(contentPage); // Assert Assert.That(bodyTextAdded, Is.True); Assert.That(authorAdded, Is.True); Assert.That(compositionAdded, Is.True); Assert.DoesNotThrow(() => service.GetContentType("contentPage")); Assert.DoesNotThrow(() => service.GetContentType("advancedPage")); var contentType = service.GetContentType("contentPage"); var propertyGroup = contentType.PropertyGroups["Content"]; var numberOfContentTabs = contentType.CompositionPropertyGroups.Count(x => x.Name.Equals("Content")); Assert.That(numberOfContentTabs, Is.EqualTo(3)); //Ensure that adding a new PropertyType to the "Content"-tab also adds it to the right group var descriptionPropertyType = new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext) { Alias = "description", Name = "Description", Description = "", Mandatory = false, SortOrder = 1,DataTypeDefinitionId = -88 }; var descriptionAdded = contentType.AddPropertyType(descriptionPropertyType, "Content"); service.Save(contentType); Assert.That(descriptionAdded, Is.True); var contentPageReloaded = service.GetContentType("contentPage"); var propertyGroupReloaded = contentPageReloaded.PropertyGroups["Content"]; var hasDescriptionPropertyType = propertyGroupReloaded.PropertyTypes.Contains("description"); Assert.That(hasDescriptionPropertyType, Is.True); var descriptionPropertyTypeReloaded = propertyGroupReloaded.PropertyTypes["description"]; Assert.That(descriptionPropertyTypeReloaded.PropertyGroupId.IsValueCreated, Is.False); } private ContentType CreateComponent() { var component = new ContentType(-1) { Alias = "component", Name = "Component", Description = "ContentType used for Component grouping", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "componentGroup") { Name = "Component Group", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; } private ContentType CreateBannerComponent(ContentType parent) { const string contentTypeAlias = "banner"; var banner = new ContentType(parent, contentTypeAlias) { Alias = contentTypeAlias, Name = "Banner Component", Description = "ContentType used for Banner Component", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var propertyType = new PropertyType("test", DataTypeDatabaseType.Ntext, "bannerName") { Name = "Banner Name", Description = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -88 }; banner.AddPropertyType(propertyType, "Component"); return banner; } private ContentType CreateSite() { var site = new ContentType(-1) { Alias = "site", Name = "Site", Description = "ContentType used for Site inheritence", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 2, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "hostname") { Name = "Hostname", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; } private ContentType CreateHomepage(ContentType parent) { const string contentTypeAlias = "homepage"; var contentType = new ContentType(parent, contentTypeAlias) { Alias = contentTypeAlias, Name = "Homepage", Description = "ContentType used for the Homepage", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "title") { Name = "Title", Description = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "bodyText") { Name = "Body Text", Description = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext, "author") { Name = "Author", Description = "Name of the author", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); return contentType; } private IContentType[] CreateContentTypeHierarchy() { //create the master type var masterContentType = MockedContentTypes.CreateSimpleContentType("masterContentType", "MasterContentType"); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ServiceContext.ContentTypeService.Save(masterContentType); //add the one we just created var list = new List<IContentType> { masterContentType }; for (var i = 0; i < 10; i++) { var contentType = MockedContentTypes.CreateSimpleContentType("childType" + i, "ChildType" + i, //make the last entry in the list, this one's parent list.Last(), true); list.Add(contentType); } return list.ToArray(); } } }
// 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.Linq; namespace WebsitePanel.Providers.Web.Handlers { using System; using System.Collections.Generic; using System.Text; using Microsoft.Web.Administration; using WebsitePanel.Providers.Web.Iis.Common; using Microsoft.Web.Management.Server; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; internal sealed class HandlersModuleService : ConfigurationModuleService { public void AddFastCgiApplication(string processorPath, string arguments) { // using (var srvman = GetServerManager()) { var config = srvman.GetApplicationHostConfiguration(); // FastCgiSection section = (FastCgiSection)config.GetSection(Constants.FactCgiSection, typeof(FastCgiSection)); FastCgiApplicationCollection applications = section.Applications; // if (applications[processorPath, arguments] == null) { applications.Add(processorPath, arguments); } // srvman.CommitChanges(); } } public void AddIsapiAndCgiRestriction(string processorPath, bool allowed) { // using (var srvman = GetServerManager()) { var config = srvman.GetApplicationHostConfiguration(); // IsapiCgiRestrictionSection section = (IsapiCgiRestrictionSection)config.GetSection( "system.webServer/security/isapiCgiRestriction", typeof(IsapiCgiRestrictionSection)); // IsapiCgiRestrictionCollection isapiCgiRestrictions = section.IsapiCgiRestrictions; // if (isapiCgiRestrictions[processorPath] == null) { isapiCgiRestrictions.Add(processorPath, true); } else { isapiCgiRestrictions[processorPath].Allowed = true; } // srvman.CommitChanges(); } } public void SetHandlersAccessPolicy(ServerManager srvman, string fqPath, HandlerAccessPolicy policy) { var config = srvman.GetWebConfiguration(fqPath); // HandlersSection section = (HandlersSection)config.GetSection(Constants.HandlersSection, typeof(HandlersSection)); // section.AccessPolicy = policy; } public HandlerAccessPolicy GetHandlersAccessPolicy(ServerManager srvman, string fqPath) { var config = srvman.GetWebConfiguration(fqPath); // HandlersSection section = (HandlersSection)config.GetSection(Constants.HandlersSection, typeof(HandlersSection)); // return section.AccessPolicy; } /// <summary> /// Adds non existent script maps. /// </summary> /// <param name="installedHandlers">Already installed scrip maps.</param> /// <param name="extensions">Extensions to check.</param> /// <param name="processor">Extensions processor.</param> internal void AddScriptMaps(WebVirtualDirectory virtualDir, IEnumerable<string> extensions, string processor, string scName, string scModule) { // Empty processor is out of interest... if (String.IsNullOrEmpty(processor)) return; // This section helps to overcome "legacy" issues //using (var srvman = GetServerManager()) //{ // var config = srvman.GetWebConfiguration(virtualDir.FullQualifiedPath); // // // var handlersSection = config.GetSection(Constants.HandlersSection); // // Do a complete section cleanup // handlersSection.RevertToParent(); // // // srvman.CommitChanges(); //} // using (var srvman = GetServerManager()) { var config = srvman.GetApplicationHostConfiguration(); // var handlersSection = config.GetSection(Constants.HandlersSection, virtualDir.FullQualifiedPath); var handlersCollection = handlersSection.GetCollection(); // Iterate over extensions in order to setup non-existent handlers foreach (string extension in extensions) { var extParts = extension.Split(','); var path = extParts[0]; var existentHandler = FindHandlerAction(handlersCollection, path, processor); // No need to add an existing handler if (existentHandler != null) continue; // Create a new handler var handler = handlersCollection.CreateElement(); // build script mapping name var scriptMappingName = String.Format(scName, path); // handler["name"] = scriptMappingName; handler["path"] = "*" + path; handler["verb"] = "GET,HEAD,POST,DEBUG"; handler["scriptProcessor"] = processor; handler["resourceType"] = ResourceType.File; handler["modules"] = scModule; // add handler handlersCollection.AddAt(0, handler); } // srvman.CommitChanges(); } // Allow a script module... switch (scModule) { case Constants.CgiModule: // Allow either ISAPI or CGI module case Constants.IsapiModule: AddIsapiAndCgiRestriction(processor, true); break; case Constants.FastCgiModule: // Allow FastCGI module AddFastCgiApplication(processor, String.Empty); break; default: Log.WriteWarning("Unknown Script Module has been requested to allow: {0};", scModule); break; } } internal void InheritScriptMapsFromParent(string fqPath) { if (String.IsNullOrEmpty(fqPath)) return; // using (var srvman = GetServerManager()) { var config = srvman.GetApplicationHostConfiguration(); // var handlersSection = config.GetSection(Constants.HandlersSection, fqPath); // handlersSection.RevertToParent(); // srvman.CommitChanges(); } } internal void RemoveScriptMaps(WebVirtualDirectory virtualDir, IEnumerable<string> extensions, string processor) { if (String.IsNullOrEmpty(processor)) return; // if (virtualDir == null) return; // using (var srvman = GetServerManager()) { var config = srvman.GetApplicationHostConfiguration(); // var handlersSection = config.GetSection(Constants.HandlersSection, virtualDir.FullQualifiedPath); var handlersCollection = handlersSection.GetCollection(); // foreach (string extension in extensions) { var extParts = extension.Split(','); var path = extParts[0]; var existentHandler = FindHandlerAction(handlersCollection, path, processor); // remove handler if exists if (existentHandler != null) handlersCollection.Remove(existentHandler); } // srvman.CommitChanges(); } } private ConfigurationElement FindHandlerAction(ConfigurationElementCollection handlers, string path, string processor) { foreach (ConfigurationElement action in handlers) { // match handler path mapping bool pathMatches = (String.Compare((string)action["path"], path, true) == 0) || (String.Compare((string)action["path"], String.Format("*{0}", path), true) == 0); // match handler processor bool processorMatches = (String.Compare(FileUtils.EvaluateSystemVariables((string)action["scriptProcessor"]), FileUtils.EvaluateSystemVariables(processor), true) == 0); // return handler action when match is exact if (pathMatches && processorMatches) return action; } // return null; } internal void CopyInheritedHandlers(string siteName, string vDirPath) { if (string.IsNullOrEmpty(siteName)) { return; } if (string.IsNullOrEmpty(vDirPath)) { vDirPath = "/"; } using (var srvman = GetServerManager()) { var config = srvman.GetWebConfiguration(siteName, vDirPath); var handlersSection = (HandlersSection)config.GetSection(Constants.HandlersSection, typeof(HandlersSection)); var handlersCollection = handlersSection.Handlers; var list = new HandlerAction[handlersCollection.Count]; ((System.Collections.ICollection) handlersCollection).CopyTo(list, 0); handlersCollection.Clear(); foreach (var handler in list) { handlersCollection.AddCopy(handler); } srvman.CommitChanges(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using FileHelpers.Options; namespace FileHelpers { /// <summary> /// Base class for all Field Types. /// Implements all the basic functionality of a field in a typed file. /// </summary> public abstract class FieldBase : ICloneable { #region " Private & Internal Fields " // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// type of object to be created, eg DateTime /// </summary> public Type FieldType { get; private set; } /// <summary> /// Provider to convert to and from text /// </summary> public ConverterBase Converter { get; private set; } /// <summary> /// Number of extra characters used, delimiters and quote characters /// </summary> internal virtual int CharsToDiscard { get { return 0; } } /// <summary> /// Field type of an array or it is just fieldType. /// What actual object will be created /// </summary> internal Type FieldTypeInternal { get; set; } /// <summary> /// Is this field an array? /// </summary> public bool IsArray { get; private set; } /// <summary> /// Array must have this many entries /// </summary> public int ArrayMinLength { get; set; } /// <summary> /// Array may have this many entries, if equal to ArrayMinLength then /// it is a fixed length array /// </summary> public int ArrayMaxLength { get; set; } /// <summary> /// Seems to be duplicate of FieldTypeInternal except it is ONLY set /// for an array /// </summary> internal Type ArrayType { get; set; } /// <summary> /// Do we process this field but not store the value /// </summary> public bool Discarded { get; set; } /// <summary> /// Unused! /// </summary> internal bool TrailingArray { get; set; } /// <summary> /// Value to use if input is null or empty /// </summary> internal object NullValue { get; set; } /// <summary> /// Are we a simple string field we can just assign to /// </summary> internal bool IsStringField { get; set; } /// <summary> /// Details about the extraction criteria /// </summary> internal FieldInfo FieldInfo { get; set; } /// <summary> /// indicates whether we trim leading and/or trailing whitespace /// </summary> public TrimMode TrimMode { get; set; } /// <summary> /// Character to chop off front and / rear of the string /// </summary> internal char[] TrimChars { get; set; } /// <summary> /// The field may not be present on the input data (line not long enough) /// </summary> public bool IsOptional { get; set; } /// <summary> /// The next field along is optional, optimise processing next records /// </summary> internal bool NextIsOptional { get { if (Parent.FieldCount > ParentIndex + 1) return Parent.Fields[ParentIndex + 1].IsOptional; return false; } } /// <summary> /// Am I the first field in an array list /// </summary> internal bool IsFirst { get { return ParentIndex == 0; } } /// <summary> /// Am I the last field in the array list /// </summary> internal bool IsLast { get { return ParentIndex == Parent.FieldCount - 1; } } /// <summary> /// Set from the FieldInNewLIneAtribute. This field begins on a new /// line of the file /// </summary> internal bool InNewLine { get; set; } /// <summary> /// Order of the field in the file layout /// </summary> internal int? FieldOrder { get; set; } /// <summary> /// Can null be assigned to this value type, for example not int or /// DateTime /// </summary> internal bool IsNullableType { get; private set; } /// <summary> /// Name of the field without extra characters (eg property) /// </summary> internal string FieldFriendlyName { get; set; } /// <summary> /// The validations that the field must pass to import successfully. /// </summary> public List<Interfaces.IFieldValidate> Validators { get; private set; } /// <summary> /// Caption of the field displayed in header row (see EngineBase.GetFileHeader) /// </summary> internal string FieldCaption { get; set; } // -------------------------------------------------------------- // WARNING !!! // Remember to add each of these fields to the clone method !! // -------------------------------------------------------------- /// <summary> /// Fieldname of the field we are storing /// </summary> public string FieldName { get { return FieldInfo.Name; } } /* private static readonly char[] mWhitespaceChars = new[] { '\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', '\u200b', '\u3000', '\ufeff' */ #endregion #region " CreateField " /// <summary> /// Check the Attributes on the field and return a structure containing /// the settings for this file. /// </summary> /// <param name="fi">Information about this field</param> /// <param name="recordAttribute">Type of record we are reading</param> /// <returns>Null if not used</returns> public static FieldBase CreateField(FieldInfo fi, TypedRecordAttribute recordAttribute) { FieldBase res = null; MemberInfo mi = fi; var memberName = "The field: '" + fi.Name; Type fieldType = fi.FieldType; string fieldFriendlyName = AutoPropertyName(fi); if (string.IsNullOrEmpty(fieldFriendlyName)==false) { var prop = fi.DeclaringType.GetProperty(fieldFriendlyName); if (prop != null) { memberName = "The property: '" + prop.Name; mi = prop; } else { fieldFriendlyName = null; } } // If ignored, return null #pragma warning disable 612,618 // disable obsolete warning if (mi.IsDefined(typeof (FieldNotInFileAttribute), true) || mi.IsDefined(typeof (FieldIgnoredAttribute), true) || mi.IsDefined(typeof (FieldHiddenAttribute), true)) #pragma warning restore 612,618 return null; var attributes = (FieldAttribute[]) mi.GetCustomAttributes(typeof (FieldAttribute), true); // CHECK USAGE ERRORS !!! // Fixed length record and no attributes at all if (recordAttribute is FixedLengthRecordAttribute && attributes.Length == 0) { throw new BadUsageException(memberName + "' must be marked the FieldFixedLength attribute because the record class is marked with FixedLengthRecord."); } if (attributes.Length > 1) { throw new BadUsageException(memberName + "' has a FieldFixedLength and a FieldDelimiter attribute."); } if (recordAttribute is DelimitedRecordAttribute && mi.IsDefined(typeof (FieldAlignAttribute), false)) { throw new BadUsageException(memberName + "' can't be marked with FieldAlign attribute, it is only valid for fixed length records and are used only for write purpose."); } if (fieldType.IsArray == false && mi.IsDefined(typeof (FieldArrayLengthAttribute), false)) { throw new BadUsageException(memberName + "' can't be marked with FieldArrayLength attribute is only valid for array fields."); } // PROCESS IN NORMAL CONDITIONS if (attributes.Length > 0) { FieldAttribute fieldAttb = attributes[0]; if (fieldAttb is FieldFixedLengthAttribute) { // Fixed Field if (recordAttribute is DelimitedRecordAttribute) { throw new BadUsageException(memberName + "' can't be marked with FieldFixedLength attribute, it is only for the FixedLengthRecords not for delimited ones."); } var attbFixedLength = (FieldFixedLengthAttribute) fieldAttb; var attbAlign = Attributes.GetFirst<FieldAlignAttribute>(mi); res = new FixedLengthField(fi, attbFixedLength.Length, attbAlign); ((FixedLengthField) res).FixedMode = ((FixedLengthRecordAttribute) recordAttribute).FixedMode; } else if (fieldAttb is FieldDelimiterAttribute) { // Delimited Field if (recordAttribute is FixedLengthRecordAttribute) { throw new BadUsageException(memberName + "' can't be marked with FieldDelimiter attribute, it is only for DelimitedRecords not for fixed ones."); } res = new DelimitedField(fi, ((FieldDelimiterAttribute) fieldAttb).Delimiter); } else { throw new BadUsageException( "Custom field attributes are not currently supported. Unknown attribute: " + fieldAttb.GetType().Name + " on field: " + fi.Name); } } else // attributes.Length == 0 { var delimitedRecordAttribute = recordAttribute as DelimitedRecordAttribute; if (delimitedRecordAttribute != null) { res = new DelimitedField(fi, delimitedRecordAttribute.Separator); } } if (res != null) { // FieldDiscarded res.Discarded = mi.IsDefined(typeof (FieldValueDiscardedAttribute), false); // FieldTrim Attributes.WorkWithFirst<FieldTrimAttribute>(mi, (x) => { res.TrimMode = x.TrimMode; res.TrimChars = x.TrimChars; }); // FieldQuoted Attributes.WorkWithFirst<FieldQuotedAttribute>(mi, (x) => { if (res is FixedLengthField) { throw new BadUsageException( memberName + "' can't be marked with FieldQuoted attribute, it is only for the delimited records."); } ((DelimitedField) res).QuoteChar = x.QuoteChar; ((DelimitedField) res).QuoteMode = x.QuoteMode; ((DelimitedField) res).QuoteMultiline = x.QuoteMultiline; }); // FieldOrder Attributes.WorkWithFirst<FieldOrderAttribute>(mi, x => res.FieldOrder = x.Order); // FieldCaption Attributes.WorkWithFirst<FieldCaptionAttribute>(mi, x => res.FieldCaption = x.Caption); // FieldOptional res.IsOptional = mi.IsDefined(typeof(FieldOptionalAttribute), false); // FieldInNewLine res.InNewLine = mi.IsDefined(typeof(FieldInNewLineAttribute), false); // FieldValidatorAttributes - for use in custom validation of fields res.Validators = new List<Interfaces.IFieldValidate>((FieldValidateAttribute[])mi.GetCustomAttributes(typeof(FieldValidateAttribute), false)); // FieldArrayLength if (fieldType.IsArray) { res.IsArray = true; res.ArrayType = fieldType.GetElementType(); // MinValue indicates that there is no FieldArrayLength in the array res.ArrayMinLength = int.MinValue; res.ArrayMaxLength = int.MaxValue; Attributes.WorkWithFirst<FieldArrayLengthAttribute>(mi, (x) => { res.ArrayMinLength = x.MinLength; res.ArrayMaxLength = x.MaxLength; if (res.ArrayMaxLength < res.ArrayMinLength || res.ArrayMinLength < 0 || res.ArrayMaxLength <= 0) { throw new BadUsageException(memberName + " has invalid length values in the [FieldArrayLength] attribute."); } }); } } if (string.IsNullOrEmpty(res.FieldFriendlyName)) res.FieldFriendlyName = res.FieldName; return res; } internal RecordOptions Parent { get; set; } internal int ParentIndex { get; set; } internal static string AutoPropertyName(FieldInfo fi) { if (fi.IsDefined(typeof(CompilerGeneratedAttribute), false)) { if (fi.Name.EndsWith("__BackingField") && fi.Name.StartsWith("<") && fi.Name.Contains(">")) return fi.Name.Substring(1, fi.Name.IndexOf(">") - 1); } return ""; } internal bool IsAutoProperty { get; set; } #endregion #region " Constructor " /// <summary> /// Create a field base without any configuration /// </summary> internal FieldBase() { IsNullableType = false; TrimMode = TrimMode.None; FieldOrder = null; InNewLine = false; //NextIsOptional = false; IsOptional = false; TrimChars = null; NullValue = null; TrailingArray = false; IsArray = false; Validators = null; } /// <summary> /// Create a field base from a fieldinfo object /// Verify the settings against the actual field to ensure it will work. /// </summary> /// <param name="fi">Field Info Object</param> internal FieldBase(FieldInfo fi) : this() { FieldInfo = fi; FieldType = FieldInfo.FieldType; MemberInfo attibuteTarget = fi; this.FieldFriendlyName = AutoPropertyName(fi); if (string.IsNullOrEmpty(FieldFriendlyName) == false) { var prop = fi.DeclaringType.GetProperty(this.FieldFriendlyName); if (prop == null) { this.FieldFriendlyName = null; } else { this.IsAutoProperty = true; attibuteTarget = prop; } } if (FieldType.IsArray) FieldTypeInternal = FieldType.GetElementType(); else FieldTypeInternal = FieldType; IsStringField = FieldTypeInternal == typeof (string); object[] attribs = attibuteTarget.GetCustomAttributes(typeof (FieldConverterAttribute), true); if (attribs.Length > 0) { var conv = (FieldConverterAttribute) attribs[0]; this.Converter = conv.Converter; conv.ValidateTypes(FieldInfo); } else this.Converter = ConvertHelpers.GetDefaultConverter(FieldFriendlyName ?? fi.Name, FieldType); if (this.Converter != null) this.Converter.mDestinationType = FieldTypeInternal; attribs = attibuteTarget.GetCustomAttributes(typeof (FieldNullValueAttribute), true); if (attribs.Length > 0) { NullValue = ((FieldNullValueAttribute) attribs[0]).NullValue; // mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite; if (NullValue != null) { if (!FieldTypeInternal.IsAssignableFrom(NullValue.GetType())) { throw new BadUsageException("The NullValue is of type: " + NullValue.GetType().Name + " that is not asignable to the field " + FieldInfo.Name + " of type: " + FieldTypeInternal.Name); } } } IsNullableType = FieldTypeInternal.IsValueType && FieldTypeInternal.IsGenericType && FieldTypeInternal.GetGenericTypeDefinition() == typeof (Nullable<>); } #endregion #region " MustOverride (String Handling) " /// <summary> /// Extract the string from the underlying data, removes quotes /// characters for example /// </summary> /// <param name="line">Line to parse data from</param> /// <returns>Slightly processed string from the data</returns> internal abstract ExtractedInfo ExtractFieldString(LineInfo line); /// <summary> /// Create a text block containing the field from definition /// </summary> /// <param name="sb">Append string to output</param> /// <param name="fieldValue">Field we are adding</param> /// <param name="isLast">Indicates if we are processing last field</param> internal abstract void CreateFieldString(StringBuilder sb, object fieldValue, bool isLast); /// <summary> /// Convert a field value to a string representation /// </summary> /// <param name="fieldValue">Object containing data</param> /// <returns>String representation of field</returns> internal string CreateFieldString(object fieldValue) { if (this.Converter == null) { if (fieldValue == null) return string.Empty; else return fieldValue.ToString(); } else return this.Converter.FieldToString(fieldValue); } #endregion #region " ExtractValue " /// <summary> /// Get the data out of the records /// </summary> /// <param name="line">Line handler containing text</param> /// <returns></returns> internal object ExtractFieldValue(LineInfo line) { //-> extract only what I need if (InNewLine) { // Any trailing characters, terminate if (line.EmptyFromPos() == false) { throw new BadUsageException(line, "Text '" + line.CurrentString + "' found before the new line of the field: " + FieldInfo.Name + " (this is not allowed when you use [FieldInNewLine])"); } line.ReLoad(line.mReader.ReadNextLine()); if (line.mLineStr == null) { throw new BadUsageException(line, "End of stream found parsing the field " + FieldInfo.Name + ". Please check the class record."); } } if (IsArray == false) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; //total; if (Discarded) return GetDiscardedNullValue(); else return AssignFromString(info, line).Value; } else { if (ArrayMinLength <= 0) ArrayMinLength = 0; int i = 0; var res = new ArrayList(Math.Max(ArrayMinLength, 10)); while (line.mCurrentPos - CharsToDiscard < line.mLineStr.Length && i < ArrayMaxLength) { ExtractedInfo info = ExtractFieldString(line); if (info.mCustomExtractedString == null) line.mCurrentPos = info.ExtractedTo + 1; line.mCurrentPos += CharsToDiscard; try { var value = AssignFromString(info, line); if (value.NullValueUsed && i == 0 && line.IsEOL()) break; res.Add(value.Value); } catch (NullValueNotFoundException) { if (i == 0) break; else throw; } i++; } if (res.Count < ArrayMinLength) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has only {3} values, less than the minimum length of {4}", line.mReader.LineNumber.ToString(), line.mCurrentPos.ToString(), FieldInfo.Name, res.Count, ArrayMinLength)); } else if (IsLast && line.IsEOL() == false) { throw new InvalidOperationException( string.Format( "Line: {0} Column: {1} Field: {2}. The array has more values than the maximum length of {3}", line.mReader.LineNumber, line.mCurrentPos, FieldInfo.Name, ArrayMaxLength)); } // TODO: is there a reason we go through all the array processing then discard it if (Discarded) return null; else return res.ToArray(ArrayType); } } #region " AssignFromString " private struct AssignResult { public object Value; public bool NullValueUsed; } /// <summary> /// Create field object after extracting the string from the underlying /// input data /// </summary> /// <param name="fieldString">Information extracted?</param> /// <param name="line">Underlying input data</param> /// <returns>Object to assign to field</returns> private AssignResult AssignFromString(ExtractedInfo fieldString, LineInfo line) { object val; var extractedString = fieldString.ExtractedString(); try { if (Validators != null && Validators.Count > 0) { foreach (Interfaces.IFieldValidate validator in Validators) { if ((validator.ValidateNullValue || !string.IsNullOrEmpty(extractedString)) && !validator.Validate(extractedString)) { throw new InvalidOperationException(validator.Message); } } } if (this.Converter == null) { if (IsStringField) val = TrimString(extractedString); else { extractedString = extractedString.Trim(); if (extractedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else val = Convert.ChangeType(extractedString, FieldTypeInternal, null); } } else { var trimmedString = extractedString.Trim(); if (this.Converter.CustomNullHandling == false && trimmedString.Length == 0) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } else { if (TrimMode == TrimMode.Both) val = this.Converter.StringToField(trimmedString); else val = this.Converter.StringToField(TrimString(extractedString)); if (val == null) { return new AssignResult { Value = GetNullValue(line), NullValueUsed = true }; } } } return new AssignResult { Value = val }; } catch (ConvertException ex) { ex.FieldName = FieldInfo.Name; ex.LineNumber = line.mReader.LineNumber; ex.ColumnNumber = fieldString.ExtractedFrom + 1; throw; } catch (BadUsageException) { throw; } catch (Exception ex) { if (this.Converter == null || this.Converter.GetType().Assembly == typeof (FieldBase).Assembly) { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, ex.Message, ex); } else { throw new ConvertException(extractedString, FieldTypeInternal, FieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1, "Your custom converter: " + this.Converter.GetType().Name + " throws an " + ex.GetType().Name + " with the message: " + ex.Message, ex); } } } private String TrimString(string extractedString) { switch (TrimMode) { case TrimMode.None: return extractedString; case TrimMode.Both: return extractedString.Trim(); case TrimMode.Left: return extractedString.TrimStart(); case TrimMode.Right: return extractedString.TrimEnd(); default: throw new Exception("Trim mode invalid in FieldBase.TrimString -> " + TrimMode.ToString()); } } /// <summary> /// Convert a null value into a representation, /// allows for a null value override /// </summary> /// <param name="line">input line to read, used for error messages</param> /// <returns>Null value for object</returns> private object GetNullValue(LineInfo line) { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "Not value found for the value type field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "'. " + Environment.NewLine + "You must use the [FieldNullValue] attribute because this is a value type and can't be null or use a Nullable Type instead of the current type."; throw new NullValueNotFoundException(line, msg); } else return null; } else return NullValue; } /// <summary> /// Get the null value that represent a discarded value /// </summary> /// <returns>null value of discard?</returns> private object GetDiscardedNullValue() { if (NullValue == null) { if (FieldTypeInternal.IsValueType) { if (IsNullableType) return null; string msg = "The field: '" + FieldInfo.Name + "' Class: '" + FieldInfo.DeclaringType.Name + "' is from a value type: " + FieldInfo.FieldType.Name + " and is discarded (null) you must provide a [FieldNullValue] attribute."; throw new BadUsageException(msg); } else return null; } else return NullValue; } #endregion #region " CreateValueForField " /// <summary> /// Convert a field value into a write able value /// </summary> /// <param name="fieldValue">object value to convert</param> /// <returns>converted value</returns> public object CreateValueForField(object fieldValue) { object val = null; if (fieldValue == null) { if (NullValue == null) { if (FieldTypeInternal.IsValueType && Nullable.GetUnderlyingType(FieldTypeInternal) == null) { throw new BadUsageException( "Null Value found. You must specify a FieldNullValueAttribute in the " + FieldInfo.Name + " field of type " + FieldTypeInternal.Name + ", because this is a ValueType."); } else val = null; } else val = NullValue; } else if (FieldTypeInternal == fieldValue.GetType()) val = fieldValue; else { if (this.Converter == null) val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); else { try { if (Nullable.GetUnderlyingType(FieldTypeInternal) != null && Nullable.GetUnderlyingType(FieldTypeInternal) == fieldValue.GetType()) val = fieldValue; else val = Convert.ChangeType(fieldValue, FieldTypeInternal, null); } catch { val = Converter.StringToField(fieldValue.ToString()); } } } return val; } #endregion #endregion #region " AssignToString " /// <summary> /// convert field to string value and assign to a string builder /// buffer for output /// </summary> /// <param name="sb">buffer to collect record</param> /// <param name="fieldValue">value to convert</param> internal void AssignToString(StringBuilder sb, object fieldValue) { if (this.InNewLine == true) sb.Append(StringHelper.NewLine); if (IsArray) { if (fieldValue == null) { if (0 < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array is null, but the minimum length is {1}", FieldInfo.Name, ArrayMinLength)); } return; } var array = (IList) fieldValue; if (array.Count < this.ArrayMinLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the minimum length is {2}", FieldInfo.Name, array.Count, ArrayMinLength)); } if (array.Count > this.ArrayMaxLength) { throw new InvalidOperationException( string.Format("Field: {0}. The array has {1} values, but the maximum length is {2}", FieldInfo.Name, array.Count, ArrayMaxLength)); } for (int i = 0; i < array.Count; i++) { object val = array[i]; CreateFieldString(sb, val, IsLast && i == array.Count - 1); } } else CreateFieldString(sb, fieldValue, IsLast); } #endregion /// <summary> /// Copy the field object /// </summary> /// <returns>a complete copy of the Field object</returns> object ICloneable.Clone() { var res = CreateClone(); res.FieldType = FieldType; res.Converter = this.Converter; res.FieldTypeInternal = FieldTypeInternal; res.IsArray = IsArray; res.ArrayType = ArrayType; res.ArrayMinLength = ArrayMinLength; res.ArrayMaxLength = ArrayMaxLength; res.TrailingArray = TrailingArray; res.NullValue = NullValue; res.IsStringField = IsStringField; res.FieldInfo = FieldInfo; res.TrimMode = TrimMode; res.TrimChars = TrimChars; res.IsOptional = IsOptional; //res.NextIsOptional = NextIsOptional; res.InNewLine = InNewLine; res.FieldOrder = FieldOrder; res.IsNullableType = IsNullableType; res.Discarded = Discarded; res.FieldFriendlyName = FieldFriendlyName; res.Validators = Validators; res.FieldCaption = FieldCaption; res.Parent = Parent; res.ParentIndex = ParentIndex; return res; } /// <summary> /// Add the extra details that derived classes create /// </summary> /// <returns>field clone of right type</returns> protected abstract FieldBase CreateClone(); } }
// Keep this file CodeMaid organised and cleaned using ClosedXML.Excel.Ranges.Index; using System; using System.Collections.Generic; namespace ClosedXML.Excel { using System.Collections; using System.Linq; internal class XLDataValidations : IXLDataValidations { private readonly XLRangeIndex<XLDataValidationIndexEntry> _dataValidationIndex; private readonly List<IXLDataValidation> _dataValidations = new List<IXLDataValidation>(); private readonly XLWorksheet _worksheet; /// <summary> /// The flag used to avoid unnecessary check for splitting intersected ranges when we already /// are performing the splitting. /// </summary> private bool _skipSplittingExistingRanges = false; public XLDataValidations(XLWorksheet worksheet) { _worksheet = worksheet ?? throw new ArgumentNullException(nameof(worksheet)); _dataValidationIndex = new XLRangeIndex<XLDataValidationIndexEntry>(_worksheet); } internal XLWorksheet Worksheet => _worksheet; #region IXLDataValidations Members IXLWorksheet IXLDataValidations.Worksheet => _worksheet; public IXLDataValidation Add(IXLDataValidation dataValidation) { return Add(dataValidation, skipIntersectionsCheck: false); } public Boolean ContainsSingle(IXLRange range) { Int32 count = 0; foreach (var xlDataValidation in _dataValidations.Where(dv => dv.Ranges.Contains(range))) { count++; if (count > 1) return false; } return count == 1; } public void Delete(Predicate<IXLDataValidation> predicate) { var dataValidationsToRemove = _dataValidations.Where(dv => predicate(dv)) .ToList(); dataValidationsToRemove.ForEach(Delete); } public void Delete(IXLDataValidation dataValidation) { if (!_dataValidations.Remove(dataValidation)) return; var xlDataValidation = dataValidation as XLDataValidation; xlDataValidation.RangeAdded -= OnRangeAdded; xlDataValidation.RangeRemoved -= OnRangeRemoved; foreach (var range in dataValidation.Ranges) { ProcessRangeRemoved(range); } } public void Delete(IXLRange range) { if (range == null) throw new ArgumentNullException(nameof(range)); var dataValidationsToRemove = _dataValidationIndex.GetIntersectedRanges((XLRangeAddress)range.RangeAddress) .Select(e => e.DataValidation) .Distinct() .ToList(); dataValidationsToRemove.ForEach(Delete); } /// <summary> /// Get all data validation rules applied to ranges that intersect the specified range. /// </summary> public IEnumerable<IXLDataValidation> GetAllInRange(IXLRangeAddress rangeAddress) { if (rangeAddress == null || !rangeAddress.IsValid) return Enumerable.Empty<IXLDataValidation>(); return _dataValidationIndex.GetIntersectedRanges((XLRangeAddress)rangeAddress) .Select(indexEntry => indexEntry.DataValidation) .Distinct(); } public IEnumerator<IXLDataValidation> GetEnumerator() { return _dataValidations.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Get the data validation rule for the range with the specified address if it exists. /// </summary> /// <param name="rangeAddress">A range address.</param> /// <param name="dataValidation">Data validation rule which ranges collection includes the specified /// address. The specified range should be fully covered with the data validation rule. /// For example, if the rule is applied to ranges A1:A3,C1:C3 then this method will /// return True for ranges A1:A3, C1:C2, A2:A3, and False for ranges A1:C3, A1:C1, etc.</param> /// <returns>True is the data validation rule was found, false otherwise.</returns> public bool TryGet(IXLRangeAddress rangeAddress, out IXLDataValidation dataValidation) { dataValidation = null; if (rangeAddress == null || !rangeAddress.IsValid) return false; var candidates = _dataValidationIndex.GetIntersectedRanges((XLRangeAddress)rangeAddress) .Where(c => c.RangeAddress.Contains(rangeAddress.FirstAddress) && c.RangeAddress.Contains(rangeAddress.LastAddress)); if (!candidates.Any()) return false; dataValidation = candidates.First().DataValidation; return true; } internal IXLDataValidation Add(IXLDataValidation dataValidation, bool skipIntersectionsCheck) { if (dataValidation == null) throw new ArgumentNullException(nameof(dataValidation)); XLDataValidation xlDataValidation; if (!(dataValidation is XLDataValidation) || dataValidation.Ranges.Any(r => r.Worksheet != Worksheet)) { xlDataValidation = new XLDataValidation(dataValidation, Worksheet); } else { xlDataValidation = (XLDataValidation)dataValidation; } xlDataValidation.RangeAdded += OnRangeAdded; xlDataValidation.RangeRemoved += OnRangeRemoved; foreach (var range in xlDataValidation.Ranges) { ProcessRangeAdded(range, xlDataValidation, skipIntersectionsCheck); } _dataValidations.Add(xlDataValidation); return xlDataValidation; } #endregion IXLDataValidations Members public void Consolidate() { Func<IXLDataValidation, IXLDataValidation, bool> areEqual = (dv1, dv2) => { return dv1.IgnoreBlanks == dv2.IgnoreBlanks && dv1.InCellDropdown == dv2.InCellDropdown && dv1.ShowErrorMessage == dv2.ShowErrorMessage && dv1.ShowInputMessage == dv2.ShowInputMessage && dv1.InputTitle == dv2.InputTitle && dv1.InputMessage == dv2.InputMessage && dv1.ErrorTitle == dv2.ErrorTitle && dv1.ErrorMessage == dv2.ErrorMessage && dv1.ErrorStyle == dv2.ErrorStyle && dv1.AllowedValues == dv2.AllowedValues && dv1.Operator == dv2.Operator && dv1.MinValue == dv2.MinValue && dv1.MaxValue == dv2.MaxValue && dv1.Value == dv2.Value; }; var rules = _dataValidations.ToList(); rules.ForEach(Delete); while (rules.Any()) { var similarRules = rules.Where(r => areEqual(rules.First(), r)).ToList(); similarRules.ForEach(r => rules.Remove(r)); var consRule = similarRules.First(); var ranges = similarRules.SelectMany(dv => dv.Ranges).ToList(); IXLRanges consolidatedRanges = new XLRanges(); ranges.ForEach(r => consolidatedRanges.Add(r)); consolidatedRanges = consolidatedRanges.Consolidate(); consRule.ClearRanges(); consRule.AddRanges(consolidatedRanges); Add(consRule); } } private void OnRangeAdded(object sender, RangeEventArgs e) { ProcessRangeAdded(e.Range, sender as XLDataValidation, skipIntersectionCheck: false); } private void OnRangeRemoved(object sender, RangeEventArgs e) { ProcessRangeRemoved(e.Range); } private void ProcessRangeAdded(IXLRange range, XLDataValidation dataValidation, bool skipIntersectionCheck) { if (!skipIntersectionCheck) { SplitExistingRanges(range.RangeAddress); } var indexEntry = new XLDataValidationIndexEntry(range.RangeAddress, dataValidation); _dataValidationIndex.Add(indexEntry); } private void ProcessRangeRemoved(IXLRange range) { var entry = _dataValidationIndex.GetIntersectedRanges((XLRangeAddress)range.RangeAddress) .SingleOrDefault(e => Equals(e.RangeAddress, range.RangeAddress)); if (entry != null) { _dataValidationIndex.Remove(entry.RangeAddress); } } private void SplitExistingRanges(IXLRangeAddress rangeAddress) { if (_skipSplittingExistingRanges) return; try { _skipSplittingExistingRanges = true; var entries = _dataValidationIndex.GetIntersectedRanges((XLRangeAddress)rangeAddress) .ToList(); foreach (var entry in entries) { entry.DataValidation.SplitBy(rangeAddress); } } finally { _skipSplittingExistingRanges = false; } //TODO Remove empty data validations } /// <summary> /// Class used for indexing data validation rules. /// </summary> private class XLDataValidationIndexEntry : IXLAddressable { public XLDataValidationIndexEntry(IXLRangeAddress rangeAddress, XLDataValidation dataValidation) { RangeAddress = rangeAddress; DataValidation = dataValidation; } public XLDataValidation DataValidation { get; } /// <summary> /// Gets an object with the boundaries of this range. /// </summary> public IXLRangeAddress RangeAddress { get; } } } }
/* Microsoft Automatic Graph Layout,MSAGL Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.DebugHelpers; using Microsoft.Msagl.Drawing; using Microsoft.Msagl.Layout.LargeGraphLayout; using Microsoft.Msagl.Routing; using Color = Microsoft.Msagl.Drawing.Color; using Edge = Microsoft.Msagl.Drawing.Edge; using Ellipse = Microsoft.Msagl.Core.Geometry.Curves.Ellipse; using LineSegment = Microsoft.Msagl.Core.Geometry.Curves.LineSegment; using Point = Microsoft.Msagl.Core.Geometry.Point; using Polyline = Microsoft.Msagl.Core.Geometry.Curves.Polyline; using Rectangle = Microsoft.Msagl.Core.Geometry.Rectangle; using Size = System.Windows.Size; namespace Microsoft.Msagl.WpfGraphControl { internal class VEdge : IViewerEdge, IInvalidatable { internal FrameworkElement LabelFrameworkElement; public VEdge(Edge edge, FrameworkElement labelFrameworkElement) { Edge = edge; CurvePath = new Path { Data = GetICurveWpfGeometry(edge.GeometryEdge.Curve), Tag = this }; EdgeAttrClone = edge.Attr.Clone(); if (edge.Attr.ArrowAtSource) SourceArrowHeadPath = new Path { Data = DefiningSourceArrowHead(), Tag = this }; if (edge.Attr.ArrowAtTarget) TargetArrowHeadPath = new Path { Data = DefiningTargetArrowHead(Edge.GeometryEdge.EdgeGeometry, PathStrokeThickness), Tag = this }; SetPathStroke(); if (labelFrameworkElement != null) { LabelFrameworkElement = labelFrameworkElement; Common.PositionFrameworkElement(LabelFrameworkElement, edge.Label.Center, 1); } edge.Attr.VisualsChanged += (a, b) => Invalidate(); edge.IsVisibleChanged += obj => { foreach (var frameworkElement in FrameworkElements) { frameworkElement.Visibility = edge.IsVisible ? Visibility.Visible : Visibility.Hidden; } }; } internal IEnumerable<FrameworkElement> FrameworkElements { get { if (SourceArrowHeadPath != null) yield return this.SourceArrowHeadPath; if (TargetArrowHeadPath != null) yield return TargetArrowHeadPath; if (CurvePath != null) yield return CurvePath; if ( LabelFrameworkElement != null) yield return LabelFrameworkElement; } } internal EdgeAttr EdgeAttrClone { get; set; } internal static Geometry DefiningTargetArrowHead(EdgeGeometry edgeGeometry, double thickness) { if (edgeGeometry.TargetArrowhead == null || edgeGeometry.Curve==null) return null; var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { AddArrow(context, edgeGeometry.Curve.End, edgeGeometry.TargetArrowhead.TipPosition, thickness); return streamGeometry; } } Geometry DefiningSourceArrowHead() { var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { AddArrow(context, Edge.GeometryEdge.Curve.Start, Edge.GeometryEdge.EdgeGeometry.SourceArrowhead.TipPosition, PathStrokeThickness); return streamGeometry; } } double PathStrokeThickness { get { return PathStrokeThicknessFunc != null ? PathStrokeThicknessFunc() : this.Edge.Attr.LineWidth; } } internal Path CurvePath { get; set; } internal Path SourceArrowHeadPath { get; set; } internal Path TargetArrowHeadPath { get; set; } static internal Geometry GetICurveWpfGeometry(ICurve curve) { var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { FillStreamGeometryContext(context, curve); return streamGeometry; } } static void FillStreamGeometryContext(StreamGeometryContext context, ICurve curve) { if (curve == null) return; FillContextForICurve(context, curve); } static internal void FillContextForICurve(StreamGeometryContext context,ICurve iCurve) { context.BeginFigure(Common.WpfPoint(iCurve.Start),false,false); var c = iCurve as Curve; if(c != null) FillContexForCurve(context,c); else { var cubicBezierSeg = iCurve as CubicBezierSegment; if(cubicBezierSeg != null) context.BezierTo(Common.WpfPoint(cubicBezierSeg.B(1)),Common.WpfPoint(cubicBezierSeg.B(2)), Common.WpfPoint(cubicBezierSeg.B(3)),true,false); else { var ls = iCurve as LineSegment; if(ls != null) context.LineTo(Common.WpfPoint(ls.End),true,false); else { var rr = iCurve as RoundedRect; if(rr != null) FillContexForCurve(context,rr.Curve); else { var poly = iCurve as Polyline; if (poly != null) FillContexForPolyline(context, poly); else { var ellipse = iCurve as Ellipse; if (ellipse != null) { // context.LineTo(Common.WpfPoint(ellipse.End),true,false); double sweepAngle = EllipseSweepAngle(ellipse); bool largeArc = Math.Abs(sweepAngle) >= Math.PI; Rectangle box = ellipse.FullBox(); context.ArcTo(Common.WpfPoint(ellipse.End), new Size(box.Width/2, box.Height/2), sweepAngle, largeArc, sweepAngle < 0 ? SweepDirection.Counterclockwise : SweepDirection.Clockwise, true, true); } else { throw new NotImplementedException(); } } } } } } } static void FillContexForPolyline(StreamGeometryContext context,Polyline poly) { for(PolylinePoint pp = poly.StartPoint.Next;pp != null;pp = pp.Next) context.LineTo(Common.WpfPoint(pp.Point),true,false); } static void FillContexForCurve(StreamGeometryContext context,Curve c) { foreach(ICurve seg in c.Segments) { var bezSeg = seg as CubicBezierSegment; if(bezSeg != null) { context.BezierTo(Common.WpfPoint(bezSeg.B(1)), Common.WpfPoint(bezSeg.B(2)),Common.WpfPoint(bezSeg.B(3)),true,false); } else { var ls = seg as LineSegment; if(ls != null) context.LineTo(Common.WpfPoint(ls.End),true,false); else { var ellipse = seg as Ellipse; if(ellipse != null) { // context.LineTo(Common.WpfPoint(ellipse.End),true,false); double sweepAngle = EllipseSweepAngle(ellipse); bool largeArc = Math.Abs(sweepAngle) >= Math.PI; Rectangle box = ellipse.FullBox(); context.ArcTo(Common.WpfPoint(ellipse.End), new Size(box.Width / 2,box.Height / 2), sweepAngle, largeArc, sweepAngle < 0 ? SweepDirection.Counterclockwise : SweepDirection.Clockwise, true,true); } else throw new NotImplementedException(); } } } } public static double EllipseSweepAngle(Ellipse ellipse) { double sweepAngle = ellipse.ParEnd - ellipse.ParStart; return ellipse.OrientedCounterclockwise() ? sweepAngle : -sweepAngle; } static void AddArrow(StreamGeometryContext context,Point start,Point end, double thickness) { if(thickness > 1) { Point dir = end - start; Point h = dir; double dl = dir.Length; if(dl < 0.001) return; dir /= dl; var s = new Point(-dir.Y,dir.X); double w = 0.5 * thickness; Point s0 = w * s; s *= h.Length * HalfArrowAngleTan; s += s0; double rad = w / HalfArrowAngleCos; context.BeginFigure(Common.WpfPoint(start + s),true,true); context.LineTo(Common.WpfPoint(start - s),true,false); context.LineTo(Common.WpfPoint(end - s0),true,false); context.ArcTo(Common.WpfPoint(end + s0),new Size(rad,rad), Math.PI - ArrowAngle,false,SweepDirection.Clockwise,true,false); } else { Point dir = end - start; double dl = dir.Length; //take into account the widths double delta = Math.Min(dl / 2, thickness + thickness / 2); dir *= (dl - delta) / dl; end = start + dir; dir = dir.Rotate(Math.PI / 2); Point s = dir * HalfArrowAngleTan; context.BeginFigure(Common.WpfPoint(start + s),true,true); context.LineTo(Common.WpfPoint(end),true,true); context.LineTo(Common.WpfPoint(start - s),true,true); } } static readonly double HalfArrowAngleTan = Math.Tan(ArrowAngle * 0.5 * Math.PI / 180.0); static readonly double HalfArrowAngleCos = Math.Cos(ArrowAngle * 0.5 * Math.PI / 180.0); const double ArrowAngle = 30.0; //degrees #region Implementation of IViewerObject public DrawingObject DrawingObject { get { return Edge; } } public bool MarkedForDragging { get; set; } public event EventHandler MarkedForDraggingEvent; public event EventHandler UnmarkedForDraggingEvent; #endregion #region Implementation of IViewerEdge public Edge Edge { get; private set; } public IViewerNode Source { get; private set; } public IViewerNode Target { get; private set; } public double RadiusOfPolylineCorner { get; set; } public VLabel VLabel { get; set; } #endregion internal void Invalidate(FrameworkElement fe, Rail rail, byte edgeTransparency) { var path = fe as Path; if (path != null) SetPathStrokeToRailPath(rail, path, edgeTransparency); } public void Invalidate() { var vis = Edge.IsVisible ? Visibility.Visible : Visibility.Hidden; foreach (var fe in FrameworkElements) fe.Visibility = vis; if (vis == Visibility.Hidden) return; CurvePath.Data = GetICurveWpfGeometry(Edge.GeometryEdge.Curve); if (Edge.Attr.ArrowAtSource) SourceArrowHeadPath.Data = DefiningSourceArrowHead(); if (Edge.Attr.ArrowAtTarget) TargetArrowHeadPath.Data = DefiningTargetArrowHead(Edge.GeometryEdge.EdgeGeometry, PathStrokeThickness); SetPathStroke(); if (VLabel != null) ((IInvalidatable) VLabel).Invalidate(); } void SetPathStroke() { SetPathStrokeToPath(CurvePath); if (SourceArrowHeadPath != null) { SourceArrowHeadPath.Stroke = SourceArrowHeadPath.Fill = Common.BrushFromMsaglColor(Edge.Attr.Color); SourceArrowHeadPath.StrokeThickness = PathStrokeThickness; } if (TargetArrowHeadPath != null) { TargetArrowHeadPath.Stroke = TargetArrowHeadPath.Fill = Common.BrushFromMsaglColor(Edge.Attr.Color); TargetArrowHeadPath.StrokeThickness = PathStrokeThickness; } } void SetPathStrokeToRailPath(Rail rail, Path path, byte transparency) { path.Stroke = SetStrokeColorForRail(transparency, rail); path.StrokeThickness = PathStrokeThickness; foreach (var style in Edge.Attr.Styles) { if (style == Drawing.Style.Dotted) { path.StrokeDashArray = new DoubleCollection {1, 1}; } else if (style == Drawing.Style.Dashed) { var f = DashSize(); path.StrokeDashArray = new DoubleCollection {f, f}; //CurvePath.StrokeDashOffset = f; } } } Brush SetStrokeColorForRail(byte transparency, Rail rail) { return rail.IsHighlighted == false ? new SolidColorBrush(new System.Windows.Media.Color { A = transparency, R = Edge.Attr.Color.R, G = Edge.Attr.Color.G, B = Edge.Attr.Color.B }) : Brushes.Red; } void SetPathStrokeToPath(Path path) { path.Stroke = Common.BrushFromMsaglColor(Edge.Attr.Color); path.StrokeThickness = PathStrokeThickness; foreach (var style in Edge.Attr.Styles) { if (style == Drawing.Style.Dotted) { path.StrokeDashArray = new DoubleCollection {1, 1}; } else if (style == Drawing.Style.Dashed) { var f = DashSize(); path.StrokeDashArray = new DoubleCollection {f, f}; //CurvePath.StrokeDashOffset = f; } } } public override string ToString() { return Edge.ToString(); } internal static double dashSize = 0.05; //inches internal Func<double> PathStrokeThicknessFunc; public VEdge(Edge edge, LgLayoutSettings lgSettings) { Edge = edge; EdgeAttrClone = edge.Attr.Clone(); } internal double DashSize() { var w = PathStrokeThickness; var dashSizeInPoints = dashSize * GraphViewer.DpiXStatic; return dashSize = dashSizeInPoints / w; } internal void RemoveItselfFromCanvas(Canvas graphCanvas) { if(CurvePath!=null) graphCanvas.Children.Remove(CurvePath); if (SourceArrowHeadPath != null) graphCanvas.Children.Remove(SourceArrowHeadPath); if (TargetArrowHeadPath != null) graphCanvas.Children.Remove(TargetArrowHeadPath); if(VLabel!=null) graphCanvas.Children.Remove(VLabel.FrameworkElement ); } public FrameworkElement CreateFrameworkElementForRail(Rail rail, byte edgeTransparency) { var iCurve = rail.Geometry as ICurve; Path fe; if (iCurve != null) { fe = (Path)CreateFrameworkElementForRailCurve(rail, iCurve, edgeTransparency); } else { var arrowhead = rail.Geometry as Arrowhead; if (arrowhead != null) { fe = (Path)CreateFrameworkElementForRailArrowhead(rail, arrowhead, rail.CurveAttachmentPoint, edgeTransparency); } else throw new InvalidOperationException(); } fe.Tag = rail; return fe; } FrameworkElement CreateFrameworkElementForRailArrowhead(Rail rail, Arrowhead arrowhead, Point curveAttachmentPoint, byte edgeTransparency) { var streamGeometry = new StreamGeometry(); using (StreamGeometryContext context = streamGeometry.Open()) { AddArrow(context, curveAttachmentPoint, arrowhead.TipPosition, PathStrokeThickness); } var path=new Path { Data = streamGeometry, Tag = this }; SetPathStrokeToRailPath(rail, path,edgeTransparency); return path; } FrameworkElement CreateFrameworkElementForRailCurve(Rail rail, ICurve iCurve, byte transparency) { var path = new Path { Data = GetICurveWpfGeometry(iCurve), }; SetPathStrokeToRailPath(rail, path, transparency); return path; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using FileHelpers.Dynamic; using NUnit.Framework; namespace FileHelpers.Tests.Dynamic { [TestFixture] public class DelimitedClassBuilderTests { private FileHelperEngine mEngine; [Test] [Category("Dynamic")] public void FullClassBuilding() { var cb = new DelimitedClassBuilder("Customers", ","); cb.IgnoreFirstLines = 1; cb.IgnoreEmptyLines = true; cb.AddField("Field1", typeof(DateTime)); cb.LastField.TrimMode = TrimMode.Both; cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted; cb.LastField.FieldNullValue = DateTime.Today; cb.AddField("Field2", typeof(string)); cb.LastField.FieldQuoted = true; cb.LastField.QuoteChar = '"'; cb.AddField("Field3", typeof(int)); mEngine = new FileHelperEngine(cb.CreateRecordClass()); DataTable dt = mEngine.ReadFileAsDT(TestCommon.GetPath("Good", "Test2.txt")); Assert.AreEqual(4, dt.Rows.Count); Assert.AreEqual(4, mEngine.TotalRecords); Assert.AreEqual(0, mEngine.ErrorManager.ErrorCount); Assert.AreEqual("Field1", dt.Columns[0].ColumnName); Assert.AreEqual("Field2", dt.Columns[1].ColumnName); Assert.AreEqual("Field3", dt.Columns[2].ColumnName); Assert.AreEqual("Hola", dt.Rows[0][1]); Assert.AreEqual(DateTime.Today, dt.Rows[2][0]); } [Test] [Category("Dynamic")] public void TestingNameAndTypes() { var cb = new DelimitedClassBuilder("Customers", ","); cb.IgnoreFirstLines = 1; cb.IgnoreEmptyLines = true; cb.AddField("Field1", typeof (DateTime)); cb.LastField.TrimMode = TrimMode.Both; cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted; cb.LastField.FieldNullValue = DateTime.Today; cb.AddField("Field2", typeof (string)); cb.LastField.FieldQuoted = true; cb.LastField.QuoteChar = '"'; cb.AddField("Field3", typeof (int)); mEngine = new FileHelperEngine(cb.CreateRecordClass()); DataTable dt = mEngine.ReadFileAsDT(TestCommon.GetPath("Good", "Test2.txt")); Assert.AreEqual("Field1", dt.Columns[0].ColumnName); Assert.AreEqual(typeof (DateTime), dt.Columns[0].DataType); Assert.AreEqual("Field2", dt.Columns[1].ColumnName); Assert.AreEqual(typeof (string), dt.Columns[1].DataType); Assert.AreEqual("Field3", dt.Columns[2].ColumnName); Assert.AreEqual(typeof (int), dt.Columns[2].DataType); } [Test] public void SaveLoadXmlFileDelimited() { var cb = new DelimitedClassBuilder("Customers", ","); cb.IgnoreFirstLines = 1; cb.IgnoreEmptyLines = true; cb.AddField("Field1", typeof(DateTime)); cb.LastField.TrimMode = TrimMode.Both; cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted; cb.LastField.FieldNullValue = DateTime.Today; cb.AddField("FieldTwo", typeof(string)); cb.LastField.FieldQuoted = true; cb.LastField.QuoteChar = '"'; cb.AddField("Field333", typeof(int)); cb.SaveToXml(@"dynamic.xml"); var loaded = (DelimitedClassBuilder)ClassBuilder.LoadFromXml(@"dynamic.xml"); Assert.AreEqual("Field1", loaded.FieldByIndex(0).FieldName); Assert.AreEqual("FieldTwo", loaded.FieldByIndex(1).FieldName); Assert.AreEqual("Field333", loaded.FieldByIndex(2).FieldName); Assert.AreEqual("System.DateTime", loaded.FieldByIndex(0).FieldType); Assert.AreEqual("System.String", loaded.FieldByIndex(1).FieldType); Assert.AreEqual("System.Int32", loaded.FieldByIndex(2).FieldType); Assert.AreEqual(QuoteMode.AlwaysQuoted, loaded.FieldByIndex(0).QuoteMode); Assert.AreEqual(false, loaded.FieldByIndex(0).FieldQuoted); Assert.AreEqual('"', loaded.FieldByIndex(1).QuoteChar); Assert.AreEqual(true, loaded.FieldByIndex(1).FieldQuoted); } [Test] [Category("Dynamic")] public void SaveLoadXmlFileDelimited2() { var cb = new DelimitedClassBuilder("Customers", ","); cb.IgnoreFirstLines = 1; cb.IgnoreEmptyLines = true; cb.AddField("Field1", typeof(DateTime)); cb.LastField.TrimMode = TrimMode.Both; cb.LastField.QuoteMode = QuoteMode.AlwaysQuoted; cb.LastField.FieldNullValue = DateTime.Today; cb.AddField("FieldTwo", typeof(string)); cb.LastField.FieldQuoted = true; cb.LastField.QuoteChar = '"'; cb.AddField("Field333", typeof(int)); cb.SaveToXml(@"dynamic.xml"); mEngine = new FileHelperEngine(ClassBuilder.ClassFromXmlFile("dynamic.xml")); Assert.AreEqual("Customers", mEngine.RecordType.Name); Assert.AreEqual(3, mEngine.RecordType.GetFields().Length); Assert.AreEqual("Field1", mEngine.RecordType.GetFields()[0].Name); } [Test] public void SaveLoadXmlOptions() { var cbOrig = new DelimitedClassBuilder("Customers", ","); cbOrig.AddField("Field1", typeof(DateTime)); cbOrig.AddField("FieldTwo", typeof(string)); cbOrig.RecordCondition.Condition = RecordCondition.ExcludeIfMatchRegex; cbOrig.RecordCondition.Selector = @"\w*"; cbOrig.IgnoreCommentedLines.CommentMarker = "//"; cbOrig.IgnoreCommentedLines.InAnyPlace = false; cbOrig.IgnoreEmptyLines = true; cbOrig.IgnoreFirstLines = 123; cbOrig.IgnoreLastLines = 456; cbOrig.SealedClass = false; cbOrig.SaveToXml(@"dynamic.xml"); cbOrig.SaveToXml(@"dynamic.xml"); ClassBuilder cb2 = ClassBuilder.LoadFromXml("dynamic.xml"); Assert.AreEqual("Customers", cb2.ClassName); Assert.AreEqual(2, cb2.FieldCount); Assert.AreEqual("Field1", cb2.Fields[0].FieldName); Assert.AreEqual(RecordCondition.ExcludeIfMatchRegex, cb2.RecordCondition.Condition); Assert.AreEqual(@"\w*", cb2.RecordCondition.Selector); Assert.AreEqual("//", cb2.IgnoreCommentedLines.CommentMarker); Assert.AreEqual(false, cb2.IgnoreCommentedLines.InAnyPlace); Assert.AreEqual(false, cb2.SealedClass); Assert.AreEqual(true, cb2.IgnoreEmptyLines); Assert.AreEqual(123, cb2.IgnoreFirstLines); Assert.AreEqual(456, cb2.IgnoreLastLines); } [Test] public void SaveLoadXmlOptionsString() { var cbOrig = new DelimitedClassBuilder("Customers", ","); cbOrig.AddField("Field1", typeof(DateTime)); cbOrig.AddField("FieldTwo", typeof(string)); cbOrig.RecordCondition.Condition = RecordCondition.ExcludeIfMatchRegex; cbOrig.RecordCondition.Selector = @"\w*"; cbOrig.IgnoreCommentedLines.CommentMarker = "//"; cbOrig.IgnoreCommentedLines.InAnyPlace = false; cbOrig.IgnoreEmptyLines = true; cbOrig.IgnoreFirstLines = 123; cbOrig.IgnoreLastLines = 456; cbOrig.SealedClass = false; string xml = cbOrig.SaveToXmlString(); ClassBuilder cb2 = ClassBuilder.LoadFromXmlString(xml); Assert.AreEqual("Customers", cb2.ClassName); Assert.AreEqual(2, cb2.FieldCount); Assert.AreEqual("Field1", cb2.Fields[0].FieldName); Assert.AreEqual(RecordCondition.ExcludeIfMatchRegex, cb2.RecordCondition.Condition); Assert.AreEqual(@"\w*", cb2.RecordCondition.Selector); Assert.AreEqual("//", cb2.IgnoreCommentedLines.CommentMarker); Assert.AreEqual(false, cb2.IgnoreCommentedLines.InAnyPlace); Assert.AreEqual(false, cb2.SealedClass); Assert.AreEqual(true, cb2.IgnoreEmptyLines); Assert.AreEqual(123, cb2.IgnoreFirstLines); Assert.AreEqual(456, cb2.IgnoreLastLines); } public class MyCustomConverter : ConverterBase { public override object StringToField(string from) { if (from == "NaN") return null; else return Convert.ToInt32(Int32.Parse(from)); } public override string FieldToString(object fieldValue) { if (fieldValue == null) return "NaN"; else return fieldValue.ToString(); } } [Test] [Category("Dynamic")] public void ReadAsDataTableWithCustomConverter() { var fields = new[] { "FirstName", "LastName", "StreetNumber", "StreetAddress", "Unit", "City", "State", }; var cb = new DelimitedClassBuilder("ImportContact", ","); // Add assembly reference cb.AdditionalReferences.Add(typeof(MyCustomConverter).Assembly); foreach (var f in fields) { cb.AddField(f, typeof(string)); cb.LastField.TrimMode = TrimMode.Both; cb.LastField.FieldQuoted = false; } cb.AddField("Zip", typeof(int?)); cb.LastField.Converter.TypeName = "FileHelpers.Tests.Dynamic.DelimitedClassBuilderTests.MyCustomConverter"; mEngine = new FileHelperEngine(cb.CreateRecordClass()); string source = "Alex & Jen,Bouquet,1815,Bell Rd,, Batavia,OH,45103" + Environment.NewLine + "Mark & Lisa K ,Arlinghaus,1817,Bell Rd,, Batavia,OH,NaN" + Environment.NewLine + "Ed & Karen S ,Craycraft,1819,Bell Rd,, Batavia,OH,45103" + Environment.NewLine; var contactData = mEngine.ReadString(source); Assert.AreEqual(3, contactData.Length); var zip = mEngine.RecordType.GetFields()[7]; Assert.AreEqual("Zip", zip.Name); Assert.IsNull(zip.GetValue(contactData[1])); Assert.AreEqual((decimal)45103, zip.GetValue(contactData[2])); } [Test] [Category("Dynamic")] public void LoopingFields() { var cb = new DelimitedClassBuilder("MyClass", ","); string[] lst = { "fieldOne", "fieldTwo", "fieldThree" }; for (int i = 0; i < lst.Length; i++) cb.AddField(lst[i], typeof(string)); mEngine = new FileHelperEngine(cb.CreateRecordClass()); } [Test] public void GotchClassName1() { new DelimitedClassBuilder(" MyClass", ","); } [Test] public void GotchClassName2() { new DelimitedClassBuilder(" MyClass ", ","); } [Test] public void GotchClassName3() { new DelimitedClassBuilder("MyClass ", ","); } [Test] public void GotchClassName4() { new DelimitedClassBuilder("_MyClass2", ","); } [Test] public void BadClassName1() { Assert.Throws<FileHelpersException>(() => new DelimitedClassBuilder("2yClass", ",")); } [Test] public void BadClassName2() { Assert.Throws<FileHelpersException>(() => new DelimitedClassBuilder("My Class", ",")); } [Test] public void BadClassName3() { Assert.Throws<FileHelpersException>(() => new DelimitedClassBuilder("", ",")); } } }
// // RoundedFrame.cs // // Authors: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Cairo; using Hyena.Gui; using Hyena.Gui.Theming; namespace Hyena.Widgets { public class RoundedFrame : Bin, IScrollableImplementor { private Theme theme; protected Theme Theme { get { if (theme == null) { InitTheme (); } return theme; } } private void InitTheme () { theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this); frame_width = (int)theme.Context.Radius + 1; } private Widget child; private Gdk.Rectangle child_allocation; private bool fill_color_set; private Cairo.Color fill_color; private bool draw_border = true; private Pattern fill_pattern; private int frame_width; // Ugh, this is to avoid the GLib.MissingIntPtrCtorException seen by some; BGO #552169 protected RoundedFrame (IntPtr ptr) : base (ptr) { } public RoundedFrame () { } public void SetFillColor (Cairo.Color color) { fill_color = color; fill_color_set = true; QueueDraw (); } public void UnsetFillColor () { fill_color_set = false; QueueDraw (); } public Pattern FillPattern { get { return fill_pattern; } set { if (fill_pattern == value) { return; } if (fill_pattern != null) { fill_pattern.Dispose (); } fill_pattern = value; QueueDraw (); } } public bool DrawBorder { get { return draw_border; } set { draw_border = value; QueueDraw (); } } public Gtk.ScrollablePolicy HscrollPolicy { get; set; } public Gtk.ScrollablePolicy VscrollPolicy { get; set; } public Gtk.Adjustment Vadjustment { get; set; } public Gtk.Adjustment Hadjustment { get; set; } #region Gtk.Widget Overrides protected override void OnStyleUpdated () { base.OnStyleUpdated (); InitTheme (); } protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height) { base.OnGetPreferredHeight (out minimum_height, out natural_height); var requisition = SizeRequested (); minimum_height = natural_height = requisition.Height; } protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width) { base.OnGetPreferredWidth (out minimum_width, out natural_width); var requisition = SizeRequested (); minimum_width = natural_width = requisition.Width; } protected Requisition SizeRequested () { var requisition = new Requisition (); if (child != null && child.Visible) { // Add the child's width/height Requisition child_requisition, nat_requisition; child.GetPreferredSize (out child_requisition, out nat_requisition); requisition.Width = Math.Max (0, child_requisition.Width); requisition.Height = child_requisition.Height; } else { requisition.Width = 0; requisition.Height = 0; } // Add the frame border requisition.Width += ((int)BorderWidth + frame_width) * 2; requisition.Height += ((int)BorderWidth + frame_width) * 2; return requisition; } protected override void OnSizeAllocated (Gdk.Rectangle allocation) { base.OnSizeAllocated (allocation); child_allocation = new Gdk.Rectangle (); if (child == null || !child.Visible) { return; } child_allocation.X = (int)BorderWidth + frame_width; child_allocation.Y = (int)BorderWidth + frame_width; child_allocation.Width = (int)Math.Max (1, Allocation.Width - child_allocation.X * 2); child_allocation.Height = (int)Math.Max (1, Allocation.Height - child_allocation.Y - (int)BorderWidth - frame_width); child_allocation.X += Allocation.X; child_allocation.Y += Allocation.Y; child.SizeAllocate (child_allocation); } protected override bool OnDrawn (Cairo.Context cr) { CairoHelper.TransformToWindow (cr, this, Window); DrawFrame (cr); if (child != null) { PropagateDraw (child, cr); } return false; } private void DrawFrame (Cairo.Context cr) { int x = child_allocation.X - frame_width; int y = child_allocation.Y - frame_width; int width = child_allocation.Width + 2 * frame_width; int height = child_allocation.Height + 2 * frame_width; Gdk.Rectangle rect = new Gdk.Rectangle (x, y, width, height); Theme.Context.ShowStroke = draw_border; if (fill_color_set) { Theme.DrawFrameBackground (cr, rect, fill_color); } else if (fill_pattern != null) { Theme.DrawFrameBackground (cr, rect, fill_pattern); } else { Theme.DrawFrameBackground (cr, rect, true); Theme.DrawFrameBorder (cr, rect); } } #endregion #region Gtk.Container Overrides protected override void OnAdded (Widget widget) { child = widget; base.OnAdded (widget); } protected override void OnRemoved (Widget widget) { if (child == widget) { child = null; } base.OnRemoved (widget); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Xml; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class XNodeReaderFunctionalTests : TestModule { public partial class XNodeReaderTests : XLinqTestCase { public partial class TCDepth : BridgeHelpers { //[Variation("XmlReader Depth at the Root", Priority = 0)] public void TestDepth1() { XmlReader DataReader = GetReader(); int iDepth = 0; PositionOnElement(DataReader, "PLAY"); TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth); DataReader.Dispose(); } //[Variation("XmlReader Depth at Empty Tag")] public void TestDepth2() { XmlReader DataReader = GetReader(); int iDepth = 2; PositionOnElement(DataReader, "EMPTY1"); TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth); } //[Variation("XmlReader Depth at Empty Tag with Attributes")] public void TestDepth3() { XmlReader DataReader = GetReader(); int iDepth = 2; PositionOnElement(DataReader, "ACT1"); TestLog.Compare(DataReader.Depth, iDepth, "Element Depth should be " + (iDepth).ToString()); while (DataReader.MoveToNextAttribute() == true) { TestLog.Compare(DataReader.Depth, iDepth + 1, "Attr Depth should be " + (iDepth + 1).ToString()); } } //[Variation("XmlReader Depth at Non Empty Tag with Text")] public void TestDepth4() { XmlReader DataReader = GetReader(); int iDepth = 2; PositionOnElement(DataReader, "NONEMPTY1"); TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth); while (true == DataReader.Read()) { if (DataReader.NodeType == XmlNodeType.Text) TestLog.Compare(DataReader.Depth, iDepth + 1, "Depth should be " + (iDepth + 1).ToString()); if (DataReader.Name == "NONEMPTY1" && (DataReader.NodeType == XmlNodeType.EndElement)) break; } TestLog.Compare(DataReader.Depth, iDepth, "Depth should be " + iDepth); } } public partial class TCNamespace : BridgeHelpers { public static string pNONAMESPACE = "NONAMESPACE"; //[Variation("Namespace test within a scope (no nested element)", Priority = 0)] public void TestNamespace1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE0"); while (true == DataReader.Read()) { if (DataReader.Name == "NAMESPACE1") break; if (DataReader.NodeType == XmlNodeType.Element) { TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace"); TestLog.Compare(DataReader.Name, "bar:check", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, "bar", "Compare Prefix"); } } } //[Variation("Namespace test within a scope (with nested element)", Priority = 0)] public void TestNamespace2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE1"); while (true == DataReader.Read()) { if (DataReader.Name == "NONAMESPACE") break; if ((DataReader.NodeType == XmlNodeType.Element) && (DataReader.LocalName == "check")) { TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace"); TestLog.Compare(DataReader.Name, "bar:check", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, "bar", "Compare Prefix"); } } TestLog.Compare(DataReader.NamespaceURI, string.Empty, "Compare Namespace with String.Empty"); } //[Variation("Namespace test immediately outside the Namespace scope")] public void TestNamespace3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, pNONAMESPACE); TestLog.Compare(DataReader.NamespaceURI, string.Empty, "Compare Namespace with EmptyString"); TestLog.Compare(DataReader.Name, pNONAMESPACE, "Compare Name"); TestLog.Compare(DataReader.LocalName, pNONAMESPACE, "Compare LocalName"); TestLog.Compare(DataReader.Prefix, string.Empty, "Compare Prefix"); } //[Variation("Namespace test Attribute should has no default namespace", Priority = 0)] public void TestNamespace4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONAMESPACE1"); TestLog.Compare(DataReader.NamespaceURI, "1000", "Compare Namespace for Element"); if (DataReader.MoveToFirstAttribute()) { TestLog.Compare(DataReader.NamespaceURI, string.Empty, "Compare Namespace for Attr"); } } //[Variation("Namespace test with multiple Namespace declaration", Priority = 0)] public void TestNamespace5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE2"); while (true == DataReader.Read()) { if (DataReader.Name == "NAMESPACE3") break; if ((DataReader.NodeType == XmlNodeType.Element) && (DataReader.LocalName == "check")) { TestLog.Compare(DataReader.NamespaceURI, "2", "Compare Namespace"); TestLog.Compare(DataReader.Name, "bar:check", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, "bar", "Compare Prefix"); } } } //[Variation("Namespace test with multiple Namespace declaration, including default namespace")] public void TestNamespace6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE3"); while (true == DataReader.Read()) { if (DataReader.Name == "NONAMESPACE") break; if (DataReader.NodeType == XmlNodeType.Element) { if (DataReader.LocalName == "check") { TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace"); TestLog.Compare(DataReader.Name, "check", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, string.Empty, "Compare Prefix"); } else if (DataReader.LocalName == "check1") { TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace"); TestLog.Compare(DataReader.Name, "check1", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check1", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, string.Empty, "Compare Prefix"); } else if (DataReader.LocalName == "check8") { TestLog.Compare(DataReader.NamespaceURI, "8", "Compare Namespace"); TestLog.Compare(DataReader.Name, "d:check8", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check8", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, "d", "Compare Prefix"); } else if (DataReader.LocalName == "check100") { TestLog.Compare(DataReader.NamespaceURI, "100", "Compare Namespace"); TestLog.Compare(DataReader.Name, "check100", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check100", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, string.Empty, "Compare Prefix"); } else if (DataReader.LocalName == "check5") { TestLog.Compare(DataReader.NamespaceURI, "5", "Compare Namespace"); TestLog.Compare(DataReader.Name, "d:check5", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check5", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, "d", "Compare Prefix"); } else if (DataReader.LocalName == "check14") { TestLog.Compare(DataReader.NamespaceURI, "14", "Compare Namespace"); TestLog.Compare(DataReader.Name, "check14", "Compare Name"); TestLog.Compare(DataReader.LocalName, "check14", "Compare LocalName"); TestLog.Compare(DataReader.Prefix, string.Empty, "Compare Prefix"); } else if (DataReader.LocalName == "a13") { TestLog.Compare(DataReader.NamespaceURI, "1", "Compare Namespace1"); TestLog.Compare(DataReader.Name, "a13", "Compare Name1"); TestLog.Compare(DataReader.LocalName, "a13", "Compare LocalName1"); TestLog.Compare(DataReader.Prefix, string.Empty, "Compare Prefix1"); DataReader.MoveToFirstAttribute(); TestLog.Compare(DataReader.NamespaceURI, "13", "Compare Namespace2"); TestLog.Compare(DataReader.Name, "a:check", "Compare Name2"); TestLog.Compare(DataReader.LocalName, "check", "Compare LocalName2"); TestLog.Compare(DataReader.Prefix, "a", "Compare Prefix2"); TestLog.Compare(DataReader.Value, "Namespace=13", "Compare Name2"); } } } } //[Variation("Namespace URI for xml prefix", Priority = 0)] public void TestNamespace7() { string strxml = "<ROOT xml:space='preserve'/>"; XmlReader DataReader = GetReader(new StringReader(strxml)); PositionOnElement(DataReader, "ROOT"); DataReader.MoveToFirstAttribute(); TestLog.Compare(DataReader.NamespaceURI, "http://www.w3.org/XML/1998/namespace", "xml"); } } public partial class TCLookupNamespace : BridgeHelpers { //[Variation("LookupNamespace test within EmptyTag")] public void LookupNamespace1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY_NAMESPACE"); do { TestLog.Compare(DataReader.LookupNamespace("bar"), "1", "Compare LookupNamespace"); } while (DataReader.MoveToNextAttribute() == true); } //[Variation("LookupNamespace test with Default namespace within EmptyTag", Priority = 0)] public void LookupNamespace2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY_NAMESPACE1"); do { TestLog.Compare(DataReader.LookupNamespace(string.Empty), "14", "Compare LookupNamespace"); } while (DataReader.MoveToNextAttribute() == true); } //[Variation("LookupNamespace test within a scope (no nested element)", Priority = 0)] public void LookupNamespace3() { XmlReader DataReader = GetReader(); while (true == DataReader.Read()) { if (DataReader.Name == "NAMESPACE0") break; TestLog.Compare(DataReader.LookupNamespace("bar"), null, "Compare LookupNamespace"); } while (true == DataReader.Read()) { TestLog.Compare(DataReader.LookupNamespace("bar"), "1", "Compare LookupNamespace"); if (DataReader.Name == "NAMESPACE0" && DataReader.NodeType == XmlNodeType.EndElement) break; } } //[Variation("LookupNamespace test within a scope (with nested element)", Priority = 0)] public void LookupNamespace4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE1"); while (true == DataReader.Read()) { TestLog.Compare(DataReader.LookupNamespace("bar"), "1", "Compare LookupNamespace"); if (DataReader.Name == "NAMESPACE1" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } TestLog.Compare(DataReader.LookupNamespace("bar"), null, "Compare LookupNamespace with String.Empty"); } //[Variation("LookupNamespace test immediately outside the Namespace scope")] public void LookupNamespace5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONAMESPACE"); TestLog.Compare(DataReader.LookupNamespace("bar"), null, "Compare LookupNamespace with null"); } //[Variation("LookupNamespace test with multiple Namespace declaration", Priority = 0)] public void LookupNamespace6() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE2"); string strValue = "1"; while (true == DataReader.Read()) { if (DataReader.Name == "c") { strValue = "2"; TestLog.Compare(DataReader.LookupNamespace("bar"), strValue, "Compare LookupNamespace-a"); if (DataReader.NodeType == XmlNodeType.EndElement) strValue = "1"; } else TestLog.Compare(DataReader.LookupNamespace("bar"), strValue, "Compare LookupNamespace-a"); if (DataReader.Name == "NAMESPACE2" && DataReader.NodeType == XmlNodeType.EndElement) { TestLog.Compare(DataReader.LookupNamespace("bar"), strValue, "Compare LookupNamespace-a"); DataReader.Read(); break; } } } void CompareAllNS(XmlReader DataReader, string strDef, string strA, string strB, string strC, string strD, string strE, string strF, string strG, string strH) { TestLog.Compare(DataReader.LookupNamespace(string.Empty), strDef, "Compare LookupNamespace-default"); TestLog.Compare(DataReader.LookupNamespace("a"), strA, "Compare LookupNamespace-a"); TestLog.Compare(DataReader.LookupNamespace("b"), strB, "Compare LookupNamespace-b"); TestLog.Compare(DataReader.LookupNamespace("c"), strC, "Compare LookupNamespace-c"); TestLog.Compare(DataReader.LookupNamespace("d"), strD, "Compare LookupNamespace-d"); TestLog.Compare(DataReader.LookupNamespace("e"), strE, "Compare LookupNamespace-e"); TestLog.Compare(DataReader.LookupNamespace("f"), strF, "Compare LookupNamespace-f"); TestLog.Compare(DataReader.LookupNamespace("g"), strG, "Compare LookupNamespace-g"); TestLog.Compare(DataReader.LookupNamespace("h"), strH, "Compare LookupNamespace-h"); } //[Variation("Namespace test with multiple Namespace declaration, including default namespace")] public void LookupNamespace7() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NAMESPACE3"); string strDef = "1"; string strA = null; string strB = null; string strC = null; string strD = null; string strE = null; string strF = null; string strG = null; string strH = null; while (true == DataReader.Read()) { if (DataReader.Name == "a") { strA = "2"; strB = "3"; strC = "4"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.NodeType == XmlNodeType.EndElement) { strA = null; strB = null; strC = null; } } else if (DataReader.Name == "b") { strD = "5"; strE = "6"; strF = "7"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.NodeType == XmlNodeType.EndElement) { strD = null; strE = null; strF = null; } } else if (DataReader.Name == "c") { strD = "8"; strE = "9"; strF = "10"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.NodeType == XmlNodeType.EndElement) { strD = "5"; strE = "6"; strF = "7"; } } else if (DataReader.Name == "d") { strG = "11"; strH = "12"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.NodeType == XmlNodeType.EndElement) { strG = null; strH = null; } } else if (DataReader.Name == "testns") { strDef = "100"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.NodeType == XmlNodeType.EndElement) { strDef = "1"; } } else if (DataReader.Name == "a13") { strA = "13"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); do { CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); } while (DataReader.MoveToNextAttribute() == true); strA = null; } else if (DataReader.Name == "check14") { strDef = "14"; CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.NodeType == XmlNodeType.EndElement) { strDef = "1"; } } else CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); if (DataReader.Name == "NAMESPACE3" && DataReader.NodeType == XmlNodeType.EndElement) { CompareAllNS(DataReader, strDef, strA, strB, strC, strD, strE, strF, strG, strH); DataReader.Read(); break; } } } //[Variation("LookupNamespace on whitespace node PreserveWhitespaces = true", Priority = 0)] public void LookupNamespace8() { string strxml = "<ROOT xmlns:p='1'>\n<E1/></ROOT>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnNodeType(DataReader, XmlNodeType.Text); string ns = DataReader.LookupNamespace("p"); TestLog.Compare(ns, "1", "ln"); } //[Variation("Different prefix on inner element for the same namespace", Priority = 0)] public void LookupNamespace9() { string ns = "http://www.w3.org/1999/XMLSchema"; string filename = Path.Combine("TestData", "XmlReader", "Common", "bug_57723.xml"); XmlReader DataReader = GetReader(filename); PositionOnElement(DataReader, "element"); TestLog.Compare(DataReader.LookupNamespace("q1"), ns, "q11"); TestLog.Compare(DataReader.LookupNamespace("q2"), null, "q21"); DataReader.Read(); PositionOnElement(DataReader, "element"); TestLog.Compare(DataReader.LookupNamespace("q1"), ns, "q12"); TestLog.Compare(DataReader.LookupNamespace("q2"), ns, "q22"); } //[Variation("LookupNamespace when Namespaces = false", Priority = 0)] public void LookupNamespace10() { string strxml = "<ROOT xmlns:p='1'>\n<E1/></ROOT>"; XmlReader DataReader = GetReaderStr(strxml); PositionOnElement(DataReader, "ROOT"); TestLog.Compare(DataReader.LookupNamespace("p"), "1", "ln ROOT"); PositionOnElement(DataReader, "E1"); TestLog.Compare(DataReader.LookupNamespace("p"), "1", "ln E1"); DataReader.Read(); TestLog.Compare(DataReader.LookupNamespace("p"), "1", "ln /ROOT"); } } public partial class TCHasValue : BridgeHelpers { //[Variation("HasValue On None")] public void TestHasValueNodeType_None() { XmlReader DataReader = GetReader(); bool b = DataReader.HasValue; if (b) throw new TestException(TestResult.Failed, ""); } //[Variation("HasValue On Element", Priority = 0)] public void TestHasValueNodeType_Element() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Element)) { bool b = DataReader.HasValue; if (b) throw new TestFailedException("HasValue returns True"); else return; } } //[Variation("Get node with a scalar value, verify the value with valid ReadString")] public void TestHasValue1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); DataReader.Read(); TestLog.Compare(DataReader.HasValue, true, "HasValue test"); } //[Variation("HasValue On Attribute", Priority = 0)] public void TestHasValueNodeType_Attribute() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Attribute)) { bool b = DataReader.HasValue; if (!b) throw new TestFailedException("HasValue for Attribute returns false"); else return; } } //[Variation("HasValue On Text", Priority = 0)] public void TestHasValueNodeType_Text() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Text)) { bool b = DataReader.HasValue; if (!b) throw new TestFailedException("HasValue for Text returns false"); else return; } } //[Variation("HasValue On CDATA", Priority = 0)] public void TestHasValueNodeType_CDATA() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.CDATA)) { bool b = DataReader.HasValue; if (!b) throw new TestFailedException("HasValue for CDATA returns false"); else return; } } //[Variation("HasValue On ProcessingInstruction", Priority = 0)] public void TestHasValueNodeType_ProcessingInstruction() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction)) { bool b = DataReader.HasValue; if (!b) throw new TestException(TestResult.Failed, "HasValue for PI returns false"); else return; } } //[Variation("HasValue On Comment", Priority = 0)] public void TestHasValueNodeType_Comment() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Comment)) { bool b = DataReader.HasValue; if (!b) throw new TestException(TestResult.Failed, "HasValue for Comment returns false"); else return; } } //[Variation("HasValue On DocumentType", Priority = 0)] public void TestHasValueNodeType_DocumentType() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.DocumentType)) { bool b = DataReader.HasValue; if (!b) throw new TestException(TestResult.Failed, "HasValue returns True"); else return; } } //[Variation("HasValue On Whitespace PreserveWhitespaces = true", Priority = 0)] public void TestHasValueNodeType_Whitespace() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Whitespace)) { bool b = DataReader.HasValue; if (!b) throw new TestException(TestResult.Failed, "HasValue returns False"); else return; } } //[Variation("HasValue On EndElement")] public void TestHasValueNodeType_EndElement() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.EndElement)) { bool b = DataReader.HasValue; if (b) throw new TestException(TestResult.Failed, "HasValue returns True"); else return; } } //[Variation("HasValue On XmlDeclaration", Priority = 0)] public void TestHasValueNodeType_XmlDeclaration() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.XmlDeclaration)) { bool b = DataReader.HasValue; if (!b) throw new TestException(TestResult.Failed, "HasValue returns False"); else return; } } //[Variation("HasValue On EntityReference")] public void TestHasValueNodeType_EntityReference() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.EntityReference)) { bool b = DataReader.HasValue; if (b) throw new TestException(TestResult.Failed, "HasValue returns True"); else return; } } //[Variation("HasValue On EndEntity")] public void TestHasValueNodeType_EndEntity() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.EndEntity)) { bool b = DataReader.HasValue; if (b) throw new TestException(TestResult.Failed, "HasValue returns True"); else return; } } //[Variation("PI Value containing surrogates", Priority = 0)] public void v13() { string strxml = "<root><?target \uD800\uDC00\uDBFF\uDFFF?></root>"; XmlReader DataReader = GetReaderStr(strxml); DataReader.Read(); DataReader.Read(); TestLog.Compare(DataReader.NodeType, XmlNodeType.ProcessingInstruction, "nt"); TestLog.Compare(DataReader.Value, "\uD800\uDC00\uDBFF\uDFFF", "piv"); } } public partial class TCIsEmptyElement2 : BridgeHelpers { //[Variation("Set and Get an element that ends with />", Priority = 0)] public void TestEmpty1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY1"); bool b = DataReader.IsEmptyElement; if (!b) throw new TestException(TestResult.Failed, "DataReader is NOT_EMPTY, supposed to be EMPTY"); } //[Variation("Set and Get an element with an attribute that ends with />", Priority = 0)] public void TestEmpty2() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY2"); bool b = DataReader.IsEmptyElement; if (!b) throw new TestException(TestResult.Failed, "DataReader is NOT_EMPTY, supposed to be EMPTY"); } //[Variation("Set and Get an element that ends without />", Priority = 0)] public void TestEmpty3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY1"); bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, "DataReader is EMPTY, supposed to be NOT_EMPTY"); } //[Variation("Set and Get an element with an attribute that ends with />", Priority = 0)] public void TestEmpty4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NONEMPTY2"); bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, "DataReader is EMPTY, supposed to be NOT_EMPTY"); } //[Variation("IsEmptyElement On Element", Priority = 0)] public void TestEmptyNodeType_Element() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Element)) { bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); else return; } } //[Variation("IsEmptyElement On None")] public void TestEmptyNodeType_None() { XmlReader DataReader = GetReader(); bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, ""); } //[Variation("IsEmptyElement On Text")] public void TestEmptyNodeType_Text() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Text)) { bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); else return; } } //[Variation("IsEmptyElement On CDATA")] public void TestEmptyNodeType_CDATA() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.CDATA)) { bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); else return; } } //[Variation("IsEmptyElement On ProcessingInstruction")] public void TestEmptyNodeType_ProcessingInstruction() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.ProcessingInstruction)) { bool b = DataReader.IsEmptyElement; if (b) throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); else return; } } //[Variation("IsEmptyElement On Comment")] public void TestEmptyNodeType_Comment() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Comment)) { bool b = DataReader.IsEmptyElement; if (!b) return; else throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); } } //[Variation("IsEmptyElement On DocumentType")] public void TestEmptyNodeType_DocumentType() { XmlReader DataReader = GetReader(); if (FindNodeType(DataReader, XmlNodeType.DocumentType)) { bool b = DataReader.IsEmptyElement; if (!b) return; else throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); } } //[Variation("IsEmptyElement On Whitespace PreserveWhitespaces = true")] public void TestEmptyNodeType_Whitespace() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.Whitespace)) { bool b = DataReader.IsEmptyElement; if (!b) return; else throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); } } //[Variation("IsEmptyElement On EndElement")] public void TestEmptyNodeType_EndElement() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.EndElement)) { bool b = DataReader.IsEmptyElement; if (!b) return; else throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); } } //[Variation("IsEmptyElement On EntityReference")] public void TestEmptyNodeType_EntityReference() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.EntityReference)) { bool b = DataReader.IsEmptyElement; if (!b) return; else throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); } } //[Variation("IsEmptyElement On EndEntity")] public void TestEmptyNodeType_EndEntity() { XmlReader DataReader = GetReader(); while (FindNodeType(DataReader, XmlNodeType.EndEntity)) { bool b = DataReader.IsEmptyElement; if (!b) return; else throw new TestException(TestResult.Failed, "IsEmptyElement returns True"); } } } public partial class TCXmlSpace : BridgeHelpers { //[Variation("XmlSpace test within EmptyTag")] public void TestXmlSpace1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY_XMLSPACE"); do { TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default"); } while (DataReader.MoveToNextAttribute() == true); } //[Variation("Xmlspace test within a scope (no nested element)", Priority = 0)] public void TestXmlSpace2() { XmlReader DataReader = GetReader(); while (true == DataReader.Read()) { if (DataReader.Name == "XMLSPACE1") break; TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace with None"); } while (true == DataReader.Read()) { if (DataReader.Name == "XMLSPACE1" && (DataReader.NodeType == XmlNodeType.EndElement)) break; TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default"); } } //[Variation("Xmlspace test within a scope (with nested element)", Priority = 0)] public void TestXmlSpace3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "XMLSPACE2"); while (true == DataReader.Read()) { if (DataReader.Name == "NOSPACE") break; TestLog.Compare(DataReader.XmlSpace, XmlSpace.Preserve, "Compare XmlSpace with Preserve"); } TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace outside scope"); } //[Variation("Xmlspace test immediately outside the XmlSpace scope")] public void TestXmlSpace4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NOSPACE"); TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace with None"); } //[Variation("XmlSpace test with multiple XmlSpace declaration")] public void TestXmlSpace5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "XMLSPACE2A"); while (true == DataReader.Read()) { if (DataReader.Name == "XMLSPACE3") break; TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default"); } while (true == DataReader.Read()) { if (DataReader.Name == "XMLSPACE4") { while (true == DataReader.Read()) { TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default"); if (DataReader.Name == "XMLSPACE4" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } } TestLog.Compare(DataReader.XmlSpace, XmlSpace.Preserve, "Compare XmlSpace with Preserve"); if (DataReader.Name == "XMLSPACE3" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } do { TestLog.Compare(DataReader.XmlSpace, XmlSpace.Default, "Compare XmlSpace with Default"); if (DataReader.Name == "XMLSPACE2A" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } while (true == DataReader.Read()); TestLog.Compare(DataReader.XmlSpace, XmlSpace.None, "Compare XmlSpace outside scope"); } } public partial class TCXmlLang : BridgeHelpers { //[Variation("XmlLang test within EmptyTag")] public void TestXmlLang1() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "EMPTY_XMLLANG"); do { TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with en-US"); } while (DataReader.MoveToNextAttribute() == true); } //[Variation("XmlLang test within a scope (no nested element)", Priority = 0)] public void TestXmlLang2() { XmlReader DataReader = GetReader(); while (true == DataReader.Read()) { if (DataReader.Name == "XMLLANG0") break; TestLog.Compare(DataReader.XmlLang, string.Empty, "Compare XmlLang with String.Empty"); } while (true == DataReader.Read()) { if (DataReader.Name == "XMLLANG0" && (DataReader.NodeType == XmlNodeType.EndElement)) break; if (DataReader.NodeType == XmlNodeType.EntityReference) { TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with EntityRef"); if (DataReader.CanResolveEntity) { DataReader.ResolveEntity(); TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang after ResolveEntity"); while (DataReader.Read() && DataReader.NodeType != XmlNodeType.EndEntity) { TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang While Read "); } if (DataReader.NodeType == XmlNodeType.EndEntity) { TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang at EndEntity "); } } } else TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with Preserve"); } } //[Variation("XmlLang test within a scope (with nested element)", Priority = 0)] public void TestXmlLang3() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "XMLLANG1"); while (true == DataReader.Read()) { if (DataReader.Name == "NOXMLLANG") break; TestLog.Compare(DataReader.XmlLang, "en-GB", "Compare XmlLang with en-GB"); } } //[Variation("XmlLang test immediately outside the XmlLang scope")] public void TestXmlLang4() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "NOXMLLANG"); TestLog.Compare(DataReader.XmlLang, string.Empty, "Compare XmlLang with EmptyString"); } //[Variation("XmlLang test with multiple XmlLang declaration")] public void TestXmlLang5() { XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "XMLLANG2"); while (true == DataReader.Read()) { if (DataReader.Name == "XMLLANG1") break; TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with Preserve"); } while (true == DataReader.Read()) { if (DataReader.Name == "XMLLANG0") { while (true == DataReader.Read()) { TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with en-US"); if (DataReader.Name == "XMLLANG0" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } } TestLog.Compare(DataReader.XmlLang, "en-GB", "Compare XmlLang with en_GB"); if (DataReader.Name == "XMLLANG1" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } do { TestLog.Compare(DataReader.XmlLang, "en-US", "Compare XmlLang with en-US"); if (DataReader.Name == "XMLLANG2" && DataReader.NodeType == XmlNodeType.EndElement) { DataReader.Read(); break; } } while (true == DataReader.Read()); } // XML 1.0 SE //[Variation("XmlLang valid values", Priority = 0)] public void TestXmlLang6() { const string ST_VALIDXMLLANG = "VALIDXMLLANG"; string[] aValidLang = { "a", "", "ab-cd-", "a b-cd" }; XmlReader DataReader = GetReader(); for (int i = 0; i < aValidLang.Length; i++) { string strelem = ST_VALIDXMLLANG + i; PositionOnElement(DataReader, strelem); //DataReader.Read(); TestLog.Compare(DataReader.XmlLang, aValidLang[i], "XmlLang"); } } // XML 1.0 SE //[Variation("More XmlLang valid values")] public void TestXmlTextReaderLang1() { string[] aValidLang = { "", "ab-cd-", "abcdefghi", "ab-cdefghijk", "a b-cd", "ab-c d" }; for (int i = 0; i < aValidLang.Length; i++) { string strxml = string.Format("<ROOT xml:lang='{0}'/>", aValidLang[i]); XmlReader DataReader = GetReaderStr(strxml); while (DataReader.Read()) ; } } } public partial class TCSkip : BridgeHelpers { public bool VerifySkipOnNodeType(XmlNodeType testNodeType) { bool bPassed = false; XmlNodeType actNodeType; string strActName; string strActValue; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, testNodeType); DataReader.Read(); actNodeType = DataReader.NodeType; strActName = DataReader.Name; strActValue = DataReader.Value; DataReader = GetReader(); PositionOnNodeType(DataReader, testNodeType); DataReader.Skip(); bPassed = VerifyNode(DataReader, actNodeType, strActName, strActValue); return bPassed; } //[Variation("Call Skip on empty element", Priority = 0)] public void TestSkip1() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP1"); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP1", string.Empty); BoolToLTMResult(bPassed); } //[Variation("Call Skip on element", Priority = 0)] public void TestSkip2() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP2"); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP2", string.Empty); BoolToLTMResult(bPassed); } //[Variation("Call Skip on element with content", Priority = 0)] public void TestSkip3() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP3"); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.Element, "AFTERSKIP3", string.Empty); BoolToLTMResult(bPassed); } //[Variation("Call Skip on text node (leave node)", Priority = 0)] public void TestSkip4() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP3"); PositionOnElement(DataReader, "ELEM2"); DataReader.Read(); bPassed = (DataReader.NodeType == XmlNodeType.Text); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.EndElement, "ELEM2", string.Empty) && bPassed; BoolToLTMResult(bPassed); } //[Variation("Call Skip in while read loop", Priority = 0)] public void skip307543() { XmlReader DataReader = GetReader(Path.Combine("TestData", "XmlReader", "Common", "skip307543.xml")); while (DataReader.Read()) DataReader.Skip(); } //[Variation("Call Skip on text node with another element: <elem2>text<elem3></elem3></elem2>")] public void TestSkip5() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "SKIP4"); PositionOnElement(DataReader, "ELEM2"); DataReader.Read(); bPassed = (DataReader.NodeType == XmlNodeType.Text); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.Element, "ELEM3", string.Empty) && bPassed; BoolToLTMResult(bPassed); } //[Variation("Call Skip on attribute", Priority = 0)] public void TestSkip6() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_ENTTEST_NAME); bPassed = DataReader.MoveToFirstAttribute(); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.Element, "ENTITY2", string.Empty) && bPassed; BoolToLTMResult(bPassed); } //[Variation("Call Skip on text node of attribute")] public void TestSkip7() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, ST_ENTTEST_NAME); bPassed = DataReader.MoveToFirstAttribute(); bPassed = DataReader.ReadAttributeValue() && bPassed; bPassed = (DataReader.NodeType == XmlNodeType.Text) && bPassed; DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.Element, "ENTITY2", string.Empty) && bPassed; BoolToLTMResult(bPassed); } //[Variation("Call Skip on CDATA", Priority = 0)] public void TestSkip8() { XmlReader DataReader = GetReader(); BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.CDATA)); } //[Variation("Call Skip on Processing Instruction", Priority = 0)] public void TestSkip9() { BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.ProcessingInstruction)); } //[Variation("Call Skip on Comment", Priority = 0)] public void TestSkip10() { BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.Comment)); } //[Variation("Call Skip on Whitespace", Priority = 0)] public void TestSkip12() { XmlReader DataReader = GetReader(); BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.Whitespace)); } //[Variation("Call Skip on EndElement", Priority = 0)] public void TestSkip13() { BoolToLTMResult(VerifySkipOnNodeType(XmlNodeType.EndElement)); } //[Variation("Call Skip on root Element")] public void TestSkip14() { bool bPassed; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Element); DataReader.Skip(); bPassed = VerifyNode(DataReader, XmlNodeType.None, string.Empty, string.Empty); BoolToLTMResult(bPassed); } //[Variation("XmlTextReader ArgumentOutOfRangeException when handling ampersands")] public void XmlTextReaderDoesNotThrowWhenHandlingAmpersands() { string xmlStr = @"<a> fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff &gt; fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff fffffffffffffffffffffffffffffffffffffff &amp; </a> "; XmlReader DataReader = GetReader(new StringReader(xmlStr)); PositionOnElement(DataReader, "a"); DataReader.Skip(); } } public partial class TCIsDefault : BridgeHelpers { } public partial class TCBaseURI : BridgeHelpers { //[Variation("BaseURI for element node", Priority = 0)] public void TestBaseURI1() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Element); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for attribute node", Priority = 0)] public void TestBaseURI2() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Attribute); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for text node", Priority = 0)] public void TestBaseURI3() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Text); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for CDATA node")] public void TestBaseURI4() { XmlReader DataReader = GetReader(); bool bPassed = false; PositionOnNodeType(DataReader, XmlNodeType.CDATA); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for PI node")] public void TestBaseURI6() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.ProcessingInstruction); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for Comment node")] public void TestBaseURI7() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Comment); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for Whitespace node PreserveWhitespaces = true")] public void TestBaseURI9() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.Whitespace); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for EndElement node")] public void TestBaseURI10() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnNodeType(DataReader, XmlNodeType.EndElement); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, Variation.Desc); BoolToLTMResult(bPassed); } //[Variation("BaseURI for external General Entity")] public void TestTextReaderBaseURI4() { bool bPassed = false; XmlReader DataReader = GetReader(); PositionOnElement(DataReader, "ENTITY5"); DataReader.Read(); bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, "Before ResolveEntity"); bPassed = VerifyNode(DataReader, XmlNodeType.Text, string.Empty, ST_GEN_ENT_VALUE) && bPassed; bPassed = TestLog.Equals(DataReader.BaseURI, string.Empty, "After ResolveEntity"); BoolToLTMResult(bPassed); } } } } }
using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Index { using Lucene.Net.Support; /* * 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 FlushedSegment = Lucene.Net.Index.DocumentsWriterPerThread.FlushedSegment; /// <summary> /// @lucene.internal /// </summary> internal class DocumentsWriterFlushQueue { private readonly LinkedList<FlushTicket> Queue = new LinkedList<FlushTicket>(); // we track tickets separately since count must be present even before the ticket is // constructed ie. queue.size would not reflect it. private readonly AtomicInteger TicketCount_Renamed = new AtomicInteger(); private readonly ReentrantLock PurgeLock = new ReentrantLock(); internal virtual void AddDeletes(DocumentsWriterDeleteQueue deleteQueue) { lock (this) { IncTickets(); // first inc the ticket count - freeze opens // a window for #anyChanges to fail bool success = false; try { Queue.AddLast(new GlobalDeletesTicket(deleteQueue.FreezeGlobalBuffer(null))); success = true; } finally { if (!success) { DecTickets(); } } } } private void IncTickets() { int numTickets = TicketCount_Renamed.IncrementAndGet(); Debug.Assert(numTickets > 0); } private void DecTickets() { int numTickets = TicketCount_Renamed.DecrementAndGet(); Debug.Assert(numTickets >= 0); } internal virtual SegmentFlushTicket AddFlushTicket(DocumentsWriterPerThread dwpt) { lock (this) { // Each flush is assigned a ticket in the order they acquire the ticketQueue // lock IncTickets(); bool success = false; try { // prepare flush freezes the global deletes - do in synced block! SegmentFlushTicket ticket = new SegmentFlushTicket(dwpt.PrepareFlush()); Queue.AddLast(ticket); success = true; return ticket; } finally { if (!success) { DecTickets(); } } } } internal virtual void AddSegment(SegmentFlushTicket ticket, FlushedSegment segment) { lock (this) { // the actual flush is done asynchronously and once done the FlushedSegment // is passed to the flush ticket ticket.Segment = segment; } } internal virtual void MarkTicketFailed(SegmentFlushTicket ticket) { lock (this) { // to free the queue we mark tickets as failed just to clean up the queue. ticket.SetFailed(); } } internal virtual bool HasTickets() { Debug.Assert(TicketCount_Renamed.Get() >= 0, "ticketCount should be >= 0 but was: " + TicketCount_Renamed.Get()); return TicketCount_Renamed.Get() != 0; } private int InnerPurge(IndexWriter writer) { //Debug.Assert(PurgeLock.HeldByCurrentThread); int numPurged = 0; while (true) { FlushTicket head; bool canPublish; lock (this) { head = Queue.Count <= 0 ? null : Queue.First.Value; canPublish = head != null && head.CanPublish(); // do this synced } if (canPublish) { numPurged++; try { /* * if we block on publish -> lock IW -> lock BufferedDeletes we don't block * concurrent segment flushes just because they want to append to the queue. * the downside is that we need to force a purge on fullFlush since ther could * be a ticket still in the queue. */ head.Publish(writer); } finally { lock (this) { // finally remove the published ticket from the queue FlushTicket poll = Queue.First.Value; Queue.RemoveFirst(); TicketCount_Renamed.DecrementAndGet(); Debug.Assert(poll == head); } } } else { break; } } return numPurged; } internal virtual int ForcePurge(IndexWriter writer) { //Debug.Assert(!Thread.HoldsLock(this)); //Debug.Assert(!Thread.holdsLock(writer)); PurgeLock.@Lock(); try { return InnerPurge(writer); } finally { PurgeLock.Unlock(); } } internal virtual int TryPurge(IndexWriter writer) { //Debug.Assert(!Thread.holdsLock(this)); //Debug.Assert(!Thread.holdsLock(writer)); if (PurgeLock.TryLock()) { try { return InnerPurge(writer); } finally { PurgeLock.Unlock(); } } return 0; } public virtual int TicketCount { get { return TicketCount_Renamed.Get(); } } internal virtual void Clear() { lock (this) { Queue.Clear(); TicketCount_Renamed.Set(0); } } internal abstract class FlushTicket { protected internal FrozenBufferedUpdates FrozenUpdates; protected internal bool Published = false; protected internal FlushTicket(FrozenBufferedUpdates frozenUpdates) { Debug.Assert(frozenUpdates != null); this.FrozenUpdates = frozenUpdates; } protected internal abstract void Publish(IndexWriter writer); protected internal abstract bool CanPublish(); /// <summary> /// Publishes the flushed segment, segment private deletes (if any) and its /// associated global delete (if present) to IndexWriter. The actual /// publishing operation is synced on IW -> BDS so that the <seealso cref="SegmentInfo"/>'s /// delete generation is always GlobalPacket_deleteGeneration + 1 /// </summary> protected internal void PublishFlushedSegment(IndexWriter indexWriter, FlushedSegment newSegment, FrozenBufferedUpdates globalPacket) { Debug.Assert(newSegment != null); Debug.Assert(newSegment.SegmentInfo != null); FrozenBufferedUpdates segmentUpdates = newSegment.SegmentUpdates; //System.out.println("FLUSH: " + newSegment.segmentInfo.info.name); if (indexWriter.infoStream.IsEnabled("DW")) { indexWriter.infoStream.Message("DW", "publishFlushedSegment seg-private updates=" + segmentUpdates); } if (segmentUpdates != null && indexWriter.infoStream.IsEnabled("DW")) { indexWriter.infoStream.Message("DW", "flush: push buffered seg private updates: " + segmentUpdates); } // now publish! indexWriter.PublishFlushedSegment(newSegment.SegmentInfo, segmentUpdates, globalPacket); } protected internal void FinishFlush(IndexWriter indexWriter, FlushedSegment newSegment, FrozenBufferedUpdates bufferedUpdates) { // Finish the flushed segment and publish it to IndexWriter if (newSegment == null) { Debug.Assert(bufferedUpdates != null); if (bufferedUpdates != null && bufferedUpdates.Any()) { indexWriter.PublishFrozenUpdates(bufferedUpdates); if (indexWriter.infoStream.IsEnabled("DW")) { indexWriter.infoStream.Message("DW", "flush: push buffered updates: " + bufferedUpdates); } } } else { PublishFlushedSegment(indexWriter, newSegment, bufferedUpdates); } } } internal sealed class GlobalDeletesTicket : FlushTicket { protected internal GlobalDeletesTicket(FrozenBufferedUpdates frozenUpdates) : base(frozenUpdates) { } protected internal override void Publish(IndexWriter writer) { Debug.Assert(!Published, "ticket was already publised - can not publish twice"); Published = true; // its a global ticket - no segment to publish FinishFlush(writer, null, FrozenUpdates); } protected internal override bool CanPublish() { return true; } } internal sealed class SegmentFlushTicket : FlushTicket { internal FlushedSegment Segment_Renamed; internal bool Failed = false; protected internal SegmentFlushTicket(FrozenBufferedUpdates frozenDeletes) : base(frozenDeletes) { } protected internal override void Publish(IndexWriter writer) { Debug.Assert(!Published, "ticket was already publised - can not publish twice"); Published = true; FinishFlush(writer, Segment_Renamed, FrozenUpdates); } protected internal FlushedSegment Segment { set { Debug.Assert(!Failed); this.Segment_Renamed = value; } } protected internal void SetFailed() { Debug.Assert(Segment_Renamed == null); Failed = true; } protected internal override bool CanPublish() { return Segment_Renamed != null || Failed; } } } }
namespace BackgroundJobAndNotificationsDemo.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class AbpZero_Initial : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), UserName = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), EmailAddress = c.String(nullable: false, maxLength: 256), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 128), PasswordResetCode = c.String(maxLength: 128), LastLoginTime = c.DateTime(), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), TenancyName = c.String(nullable: false, maxLength: 64), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); } public override void Down() { DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpSettings", new[] { "TenantId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpUsers", new[] { "TenantId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "TenantId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings"); DropTable("dbo.AbpUserRoles"); DropTable("dbo.AbpUserLogins"); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
using System; using System.Text; using System.Text.RegularExpressions; namespace Vexe.Runtime.Extensions { public static class StringExtensions { /// <summary> /// Eg MY_INT_VALUE => MyIntValue /// </summary> public static string ToTitleCase(this string input) { var builder = new StringBuilder(); for (int i = 0; i < input.Length; i++) { var current = input[i]; if (current == '_' && i + 1 < input.Length) { var next = input[i + 1]; if (char.IsLower(next)) next = char.ToUpper(next); builder.Append(next); i++; } else builder.Append(current); } return builder.ToString(); } /// <summary> /// Performs a simple char-by-char comparison to see if input ends with postfix /// </summary> /// <returns></returns> public static bool IsPostfix(this string input, string postfix) { if (input == null) throw new ArgumentNullException("input"); if (postfix == null) throw new ArgumentNullException("postfix"); if (input.Length < postfix.Length) return false; for (int i = input.Length - 1, j = postfix.Length - 1; j >= 0; i--, j--) if (input[i] != postfix[j]) return false; return true; } /// <summary> /// Performs a simple char-by-char comparison to see if input starts with prefix /// </summary> /// <returns></returns> public static bool IsPrefix(this string input, string prefix) { if (input == null) throw new ArgumentNullException("input"); if (prefix == null) throw new ArgumentNullException("prefix"); if (input.Length < prefix.Length) return false; for (int i = 0; i < prefix.Length; i++) if (input[i] != prefix[i]) return false; return true; } public static Enum ToEnum(this string str, Type enumType) { return Enum.Parse(enumType, str) as Enum; } public static T ToEnum<T>(this string str) { return (T)Enum.Parse(typeof(T), str); } public static string FormatWith(this string str, params object[] args) { return string.Format(str, args); } /// <summary> /// Parses the specified string to the enum value of type T /// </summary> public static T ParseEnum<T>(this string value) { return (T)Enum.Parse(typeof(T), value, false); } /// <summary> /// Parses the specified string to the enum whose type is specified by enumType /// </summary> public static Enum ParseEnum(this string value, Type enumType) { return (Enum)Enum.Parse(enumType, value, false); } /// <summary> /// Returns the Nth index of the specified character in this string /// </summary> public static int IndexOfNth(this string str, char c, int n) { int s = -1; for (int i = 0; i < n; i++) { s = str.IndexOf(c, s + 1); if (s == -1) break; } return s; } /// <summary> /// Removes the last occurance of the specified string from this string. /// Returns the modified version. /// </summary> public static string RemoveLastOccurance(this string s, string what) { return s.Substring(0, s.LastIndexOf(what)); } /// <summary> /// Removes the type extension. ex "Medusa.mp3" => "Medusa" /// </summary> public static string RemoveExtension(this string s) { return s.Substring(0, s.LastIndexOf('.')); } /// <summary> /// Returns whether or not the specified string is contained with this string /// Credits to JaredPar http://stackoverflow.com/questions/444798/case-insensitive-containsstring/444818#444818 /// </summary> public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; } /// <summary> /// "tHiS is a sTring TesT" -> "This Is A String Test" /// Credits: http://extensionmethod.net/csharp/string/topropercase /// </summary> public static string ToProperCase(this string text) { System.Globalization.CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture; System.Globalization.TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(text); } /// <summary> /// Ex: "thisIsCamelCase" -> "this Is Camel Case" /// Credits: http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array /// </summary> public static string SplitCamelCase(this string input) { return Regex.Replace(input, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 "); } /// <summary> /// Ex: "thisIsCamelCase" -> "This Is Camel Case" /// </summary> public static string SplitPascalCase(this string input) { return string.IsNullOrEmpty(input) ? input : input.SplitCamelCase().ToUpperAt(0); } /// <summary> /// Nomalizes this string by replacing all '/' with '\' and returns the normalized string instance /// </summary> public static string NormalizePath(this string input) { return input.NormalizePath('/', '\\'); } /// <summary> /// Normalizes this string by replacing all 'from's by 'to's and returns the normalized instance /// Ex: "path/to\dir".NormalizePath('/', '\\') => "path\\to\\dir" /// </summary> public static string NormalizePath(this string input, char from, char to) { return input.Replace(from, to); } /// <summary> /// Replaces the character specified by the passed index with newChar and returns the new string instance /// </summary> public static string ReplaceAt(this string input, int index, char newChar) { if (input == null) { throw new ArgumentNullException("input"); } var builder = new StringBuilder(input); builder[index] = newChar; return builder.ToString(); } /// <summary> /// Uppers the character specified by the passed index and returns the new string instance /// </summary> public static string ToUpperAt(this string input, int index) { return input.ReplaceAt(index, char.ToUpper(input[index])); } /// <summary> /// Returns true if this string is null or empty /// </summary> public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if UNIX /* This code was generated by the tools\ResxGen\ResxGen.ps1 run against PowerShell.Core.Instrumentation.man. To add or change logged events and the associated resources, edit PowerShell.Core.Instrumentation.man then rerun ResxGen.ps1 to produce an updated CS and Resx file. */ using System.Collections.Generic; using System.Management.Automation.Internal; using System.Runtime.InteropServices; namespace System.Management.Automation.Tracing { /// <summary> /// Provides a class for describing a message resource for an ETW event. /// </summary> internal static class EventResource { // Defines the resource id of the message to use when an event id is not valid. private const string MissingEventIdResourceName = "MissingEventIdMessage"; /// <summary> /// Gets the name of the message resource to use for event ids that are not found. /// is not found. /// </summary> /// <remarks> /// This method is called when GetMessage returns a null value indicating the passed /// in event id was not found. The message should be used as the format string /// with the event id as the single variable argument. /// <remarks> public static string GetMissingEventMessage(out int parameterCount) { parameterCount = 1; return MissingEventIdResourceName; } /// <summary> /// Gets the message resource id for the specified event id. /// </summary> /// <param name="eventId">The event id for the message resource to retrieve.</param> /// <param name="parameterCount">The number of parameters required by the message resource.</param> /// <returns>The string resource id of the associated event message; otherwise, a null reference if the event id is not valid.</returns> public static string GetMessage(int eventId, out int parameterCount) { switch (eventId) { case 4097: parameterCount = 0; return "PS_PROVIDEReventE_O_CMDLETS_HOSTNAMERESOLVE"; case 4098: parameterCount = 0; return "PS_PROVIDEReventE_O_CMDLETS_SCHEMERESOLVE"; case 4099: parameterCount = 0; return "PS_PROVIDEReventE_O_CMDLETS_SHELLRESOLVE"; case 4100: parameterCount = 3; return "PS_PROVIDEReventE_O_COMMAND_HEALTH"; case 4101: parameterCount = 3; return "PS_PROVIDEReventE_O_ENGINE_HEALTH"; case 4102: parameterCount = 3; return "PS_PROVIDEReventE_O_PROVIDER_HEALTH"; case 4103: parameterCount = 3; return "PS_PROVIDEReventE_O_PIPELINE_DETAIL"; case 4104: parameterCount = 5; return "PS_PROVIDEReventE_O_SCRIPTBLOCK_CREATE_DETAIL"; case 4105: parameterCount = 2; return "PS_PROVIDEReventE_O_SCRIPTBLOCK_INVOKE_START_DETAIL"; case 4106: parameterCount = 2; return "PS_PROVIDEReventE_O_SCRIPTBLOCK_INVOKE_COMPLETE_DETAIL"; case 7937: parameterCount = 3; return "PS_PROVIDEReventE_A_COMMAND_LIFECYCLE"; case 7938: parameterCount = 3; return "PS_PROVIDEReventE_A_ENGINE_LIFECYCLE"; case 7939: parameterCount = 3; return "PS_PROVIDEReventE_A_PROVIDER_LIFECYCLE"; case 7940: parameterCount = 3; return "PS_PROVIDEReventE_A_SETTINGS"; case 7941: parameterCount = 2; return "PS_PROVIDEReventE_A_WriteTransferEvent"; case 7942: parameterCount = 8; return "PS_PROVIDEReventE_A_ENGINE_TRACE"; case 8193: parameterCount = 1; return "PS_PROVIDEReventE_O_RUNSPACE_CONSTRUCTOR"; case 8194: parameterCount = 3; return "PS_PROVIDEReventE_O_RUNSPACEPOOL_CONSTRUCTOR"; case 8195: parameterCount = 0; return "PS_PROVIDEReventE_O_RUNSPACEPOOL_OPEN"; case 8196: parameterCount = 0; return "PS_PROVIDEReventE_O_RUNSPACEPOOL_TRANSFER"; case 8197: parameterCount = 1; return "PS_PROVIDEReventE_O_RUNSPACE_STATE_CHANGE"; case 8198: parameterCount = 3; return "PS_PROVIDEReventE_O_REMOTE_RUNSPACE_CREATE_RETRY"; case 12033: parameterCount = 1; return "PS_PROVIDEReventE_A_RUNSPACE_PORT"; case 12034: parameterCount = 1; return "PS_PROVIDEReventE_A_RUNSPACE_APPNAME"; case 12035: parameterCount = 1; return "PS_PROVIDEReventE_A_RUNSPACE_COMPUTERNAME"; case 12036: parameterCount = 1; return "PS_PROVIDEReventE_A_RUNSPACE_SCHEME"; case 12037: parameterCount = 0; return "PS_PROVIDEReventE_A_RUNSPACE_TEST"; case 12038: parameterCount = 9; return "PS_PROVIDEReventE_A_RUNSPACE_WSMANCONNECTIONINFO"; case 12039: parameterCount = 0; return "PS_PROVIDEReventE_A_RUNSPACEPOOL_TRANSFER"; case 12289: parameterCount = 2; return "PS_PROVIDEReventE_O_ExperimentalFeatureInvalidName"; case 12290: parameterCount = 3; return "PS_PROVIDEReventE_O_ExperimentalFeatureReadConfigError"; case 24577: parameterCount = 1; return "PS_PROVIDEReventE_O_ISEExecuteScript"; case 24578: parameterCount = 1; return "PS_PROVIDEReventE_O_ISEExecuteSelection"; case 24579: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEStopCommand"; case 24580: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEResumeDebugger"; case 24581: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEStopDebugger"; case 24582: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEDebuggerStepInto"; case 24583: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEDebuggerStepOver"; case 24584: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEDebuggerStepOut"; case 24592: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEEnableAllBreakpoints"; case 24593: parameterCount = 0; return "PS_PROVIDEReventE_O_ISEDisableAllBreakpoints"; case 24594: parameterCount = 0; return "PS_PROVIDEReventE_O_ISERemoveAllBreakpoints"; case 24595: parameterCount = 2; return "PS_PROVIDEReventE_O_ISESetBreakpoint"; case 24596: parameterCount = 2; return "PS_PROVIDEReventE_O_ISERemoveBreakpoint"; case 24597: parameterCount = 2; return "PS_PROVIDEReventE_O_ISEEnableBreakpoint"; case 24598: parameterCount = 2; return "PS_PROVIDEReventE_O_ISEDisableBreakpoint"; case 24599: parameterCount = 2; return "PS_PROVIDEReventE_O_ISEHitBreakpoint"; case 28673: parameterCount = 3; return "PS_PROVIDEReventE_A_SERIALIZER_REHYDRATION_SUCCESS"; case 28674: parameterCount = 4; return "PS_PROVIDEReventE_A_SERIALIZER_REHYDRATION_FAILURE"; case 28675: parameterCount = 4; return "PS_PROVIDEReventE_A_SERIALIZER_DEPTH_OVERRIDE"; case 28676: parameterCount = 2; return "PS_PROVIDEReventE_A_SERIALIZER_MODE_OVERRIDE"; case 28677: parameterCount = 3; return "PS_PROVIDEReventE_A_SERIALIZER_SCRIPT_PROPERTY_WITHOUT_RUNSPACE"; case 28678: parameterCount = 4; return "PS_PROVIDEReventE_A_SERIALIZER_PROPERTY_GETTER_FAILED"; case 28679: parameterCount = 2; return "PS_PROVIDEReventE_A_SERIALIZER_ENUMERATION_FAILED"; case 28680: parameterCount = 2; return "PS_PROVIDEReventE_A_SERIALIZER_TOSTRING_FAILED"; case 28682: parameterCount = 3; return "PS_PROVIDEReventE_A_SERIALIZER_MAX_DEPTH_WHEN_SERIALIZING"; case 28683: parameterCount = 3; return "PS_PROVIDEReventE_A_SERIALIZER_XMLEXCEPTION_WHEN_DESERIALIZING"; case 28684: parameterCount = 2; return "PS_PROVIDEReventE_A_SERIALIZER_SPECIFIC_PROPERTY_MISSING"; case 32769: parameterCount = 5; return "PS_PROVIDEReventE_A_TRANSPORT_RCVDOBJ"; case 32775: parameterCount = 3; return "PS_PROVIDEReventE_A_APPDOMAIN_UNHANDLED_EXCEPTION"; case 32776: parameterCount = 5; return "PS_PROVIDEReventE_A_TRANSPORT_ERROR"; case 32777: parameterCount = 3; return "PS_PROVIDEReventE_O_APPDOMAIN_UNHANDLED_EXCEPTION"; case 32784: parameterCount = 5; return "PS_PROVIDEReventE_O_TRANSPORT_ERROR"; case 32785: parameterCount = 1; return "PS_PROVIDEReventE_A_TRANSPORT_CONNECT"; case 32786: parameterCount = 1; return "PS_PROVIDEReventE_A_TRANSPORT_SHELL_CONNECT_CALLBACK"; case 32787: parameterCount = 1; return "PS_PROVIDEReventE_A_TRANSPORT_SHELL_CLOSE"; case 32788: parameterCount = 1; return "PS_PROVIDEReventE_A_TRANSPORT_SHELL_CLOSE_CALLBACK"; case 32789: parameterCount = 3; return "PS_PROVIDEReventE_A_TRANSPORT_SEND_DATA"; case 32790: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_SEND_DATA_CALLBACK"; case 32791: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_RECEIVE_DATA"; case 32792: parameterCount = 3; return "PS_PROVIDEReventE_A_TRANSPORT_RECEIVE_DATA_CALLBACK"; case 32793: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_CMD_CONNECT"; case 32800: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_CMD_CONNECT_CALLBACK"; case 32801: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_CMD_CLOSE"; case 32802: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_CMD_CLOSE_CALLBACK"; case 32803: parameterCount = 3; return "PS_PROVIDEReventE_A_TRANSPORT_SIGNAL"; case 32804: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_SIGNAL_CALLBACK"; case 32805: parameterCount = 2; return "PS_PROVIDEReventE_A_TRANSPORT_URI_REDIRECTION"; case 32849: parameterCount = 5; return "PS_PROVIDEReventE_A_TRANSPORT_SERVER_SEND_DATA"; case 32850: parameterCount = 3; return "PS_PROVIDEReventE_A_CREATE_SERVER_REMOTESESSION"; case 32851: parameterCount = 1; return "PS_PROVIDEReventE_A_REPORT_CONTEXT"; case 32852: parameterCount = 4; return "PS_PROVIDEReventE_A_REPORT_OPERATION_COMPLETE"; case 32853: parameterCount = 2; return "PS_PROVIDEReventE_A_CREATE_COMMAND_REMOTESESSION"; case 32854: parameterCount = 3; return "PS_PROVIDEReventE_A_STOP_COMMAND"; case 32855: parameterCount = 3; return "PS_PROVIDEReventE_A_SERVER_RECEIVED_DATA"; case 32856: parameterCount = 3; return "PS_PROVIDEReventE_A_SERVER_RECEIVE_REQUEST"; case 32857: parameterCount = 3; return "PS_PROVIDEReventE_A_SERVER_CLOSE_OPERATION"; case 32865: parameterCount = 2; return "PS_PROVIDEReventE_A_LOAD_PSCUSTOMSHELL_ASSEMBLY"; case 32866: parameterCount = 2; return "PS_PROVIDEReventE_A_LOAD_PSCUSTOMSHELL_TYPE"; case 32867: parameterCount = 6; return "PS_PROVIDEReventE_A_RECEIVED_FRAGMENT"; case 32868: parameterCount = 6; return "PS_PROVIDEReventE_A_SENT_FRAGMENT"; case 32869: parameterCount = 0; return "PS_PROVIDEReventE_A_SHUTTING_DOWN"; case 40961: parameterCount = 0; return "PS_PROVIDEReventE_O_PowershellConsoleStartupStart"; case 40962: parameterCount = 0; return "PS_PROVIDEReventE_O_PowershellConsoleStartupStop"; case 45057: parameterCount = 8; return "PS_PROVIDEReventE_D_Powershell_ErrorRecord"; case 45058: parameterCount = 3; return "PS_PROVIDEReventE_D_Powershell_Exception"; case 45059: parameterCount = 0; return "PS_PROVIDEReventE_O_Powershell_PSObject"; case 45060: parameterCount = 6; return "PS_PROVIDEReventE_D_Powershell_Job"; case 45061: parameterCount = 1; return "PS_PROVIDEReventE_D_MESSAGE"; case 45062: parameterCount = 9; return "PS_PROVIDEReventE_A_RUNSPACE_WSMANCONNECTIONINFO"; case 45063: parameterCount = 5; return "PS_PROVIDEReventE_O_M3PWorkflowPluginStarted"; case 45064: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowExecutionStarted"; case 45065: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PWorkflowStateChanged"; case 45072: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowPluginRequestedToShutdown"; case 45073: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowPluginRestarted"; case 45074: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowWorkflowsResuming"; case 45075: parameterCount = 4; return "PS_PROVIDEReventE_O_M3PWorkflowQuotaViolationDetected"; case 45076: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowWorkflowsResumed"; case 45078: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowRunspacePoolCreated"; case 45079: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowActivityExecutionQueued"; case 45080: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowActivityExecutionStarted"; case 45081: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowImportingFromXaml"; case 45082: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowImportedFromXaml"; case 45083: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowImportFromXamlError"; case 45084: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowImportFromXamlValidationStarted"; case 45085: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowImportFromXamlValidationFinishedSuccessfully"; case 45086: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowImportFromXamlValidationFinishedWithError"; case 45087: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PWorkflowImportFromXamlActivityValidated"; case 45088: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PWorkflowImportFromXamlActivityValidationFailed"; case 45089: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PWorkflowActivityExecutionFailed"; case 45090: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowRunspaceAvailabilityChanged"; case 45091: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PWorkflowRunspaceStateChanged"; case 45092: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowLoadedForExecution"; case 45093: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowUnloaded"; case 45094: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowCancelled"; case 45095: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowAborted"; case 45096: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowCleanup"; case 45097: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowLoadedFromDisk"; case 45098: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowDeletedFromDisk"; case 45100: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PRemoveJobStarted"; case 45101: parameterCount = 4; return "PS_PROVIDEReventE_O_M3PJobStateChanged"; case 45102: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PJobError"; case 45104: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PWorkflowJobCreated"; case 45105: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PParentJobCreated"; case 45106: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PJobCreationCompleted"; case 45107: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PJobRemoved"; case 45108: parameterCount = 4; return "PS_PROVIDEReventE_O_M3PJobRemoveError"; case 45109: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PLoadingWorkflowForExecution"; case 45110: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowExecutionFinished"; case 45111: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PCancellingWorkflowExecution"; case 45112: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PAbortingWorkflowExecution"; case 45113: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PUnloadingWorkflow"; case 45114: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PForcedWorkflowShutdownStarted"; case 45115: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PForcedWorkflowShutdownFinished"; case 45116: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PForcedWorkflowShutdownError"; case 45117: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PPersistingWorkflow"; case 45118: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowPersisted"; case 45119: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowActivityExecutionFinished"; case 45120: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PWorkflowExecutionError"; case 45121: parameterCount = 3; return "PS_PROVIDEReventE_O_M3PEndpointRegistered"; case 45122: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PEndpointModified"; case 45123: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PEndpointUnregistered"; case 45124: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PEndpointDisabled"; case 45125: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PEndpointEnabled"; case 45126: parameterCount = 1; return "PS_PROVIDEReventE_O_M3POutOfProcessRunspaceStarted"; case 45127: parameterCount = 2; return "PS_PROVIDEReventE_O_M3PParameterSplattingWasPerformed"; case 45128: parameterCount = 1; return "PS_PROVIDEReventE_O_M3PWorkflowEngineStarted"; case 45129: parameterCount = 4; return "PS_PROVIDEReventE_D_M3PWORKFLOW_MANAGER_CHECKPOINTPATH"; case 46337: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginStartWorkflowApplication"; case 46338: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndStartWorkflowApplication"; case 46339: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginCreateNewJob"; case 46340: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndCreateNewJob"; case 46341: parameterCount = 2; return "PS_PROVIDEReventE_D_M3PTrackingGuidContainerParentJobCorrelation"; case 46342: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginJobLogic"; case 46343: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndJobLogic"; case 46344: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginWorkflowExecution"; case 46345: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndWorkflowExecution"; case 46346: parameterCount = 2; return "PS_PROVIDEReventE_D_M3PChildWorkflowJobAddition"; case 46347: parameterCount = 2; return "PS_PROVIDEReventE_D_M3PProxyJobRemoteJobAssociation"; case 46348: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginContainerParentJobExecution"; case 46349: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndContainerParentJobExecution"; case 46350: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginProxyJobExecution"; case 46351: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndProxyJobExecution"; case 46352: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginProxyJobEventHandler"; case 46353: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndProxyJobEventHandler"; case 46354: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PBeginProxyChildJobEventHandler"; case 46355: parameterCount = 1; return "PS_PROVIDEReventE_D_M3PEndProxyChildJobEventHandler"; case 46356: parameterCount = 0; return "PS_PROVIDEReventE_D_M3PBeginRunGarbageCollection"; case 46357: parameterCount = 0; return "PS_PROVIDEReventE_D_M3PEndRunGarbageCollection"; case 46358: parameterCount = 0; return "PS_PROVIDEReventE_O_M3PPERSISTENCE_STORE_MAXSIZE_REACHED"; case 49152: parameterCount = 1; return "PS_PROVIDEReventE_D_DebugMessage"; case 49153: parameterCount = 2; return "PS_PROVIDEReventE_D_MESSAGE2"; case 53249: parameterCount = 2; return "PS_PROVIDEReventE_O_ScheduledJobStarted"; case 53250: parameterCount = 3; return "PS_PROVIDEReventE_O_ScheduledJobCompleted"; case 53251: parameterCount = 4; return "PS_PROVIDEReventE_O_ScheduledJobException"; case 53504: parameterCount = 2; return "PS_PROVIDEReventE_O_REMOTE_NAMEDPIPE_LISTENER_START"; case 53505: parameterCount = 2; return "PS_PROVIDEReventE_O_REMOTE_NAMEDPIPE_LISTENER_END"; case 53506: parameterCount = 3; return "PS_PROVIDEReventE_O_REMOTE_NAMEDPIPE_LISTENER_ERROR"; case 53507: parameterCount = 3; return "PS_PROVIDEReventE_O_REMOTE_NAMEDPIPE_CONNECT"; case 53508: parameterCount = 3; return "PS_PROVIDEReventE_O_REMOTE_NAMEDPIPE_DISCONNECT"; } parameterCount = 0; return null; } } } #endif
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the GuardiaGrupoEtareoC2 class. /// </summary> [Serializable] public partial class GuardiaGrupoEtareoC2Collection : ReadOnlyList<GuardiaGrupoEtareoC2, GuardiaGrupoEtareoC2Collection> { public GuardiaGrupoEtareoC2Collection() {} } /// <summary> /// This is Read-only wrapper class for the GUARDIA_GrupoEtareoC2 view. /// </summary> [Serializable] public partial class GuardiaGrupoEtareoC2 : ReadOnlyRecord<GuardiaGrupoEtareoC2>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("GUARDIA_GrupoEtareoC2", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarFechaIngreso = new TableSchema.TableColumn(schema); colvarFechaIngreso.ColumnName = "fechaIngreso"; colvarFechaIngreso.DataType = DbType.AnsiString; colvarFechaIngreso.MaxLength = 10; colvarFechaIngreso.AutoIncrement = false; colvarFechaIngreso.IsNullable = true; colvarFechaIngreso.IsPrimaryKey = false; colvarFechaIngreso.IsForeignKey = false; colvarFechaIngreso.IsReadOnly = false; schema.Columns.Add(colvarFechaIngreso); TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = false; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; schema.Columns.Add(colvarId); TableSchema.TableColumn colvar1 = new TableSchema.TableColumn(schema); colvar1.ColumnName = "<1"; colvar1.DataType = DbType.Int32; colvar1.MaxLength = 0; colvar1.AutoIncrement = false; colvar1.IsNullable = true; colvar1.IsPrimaryKey = false; colvar1.IsForeignKey = false; colvar1.IsReadOnly = false; schema.Columns.Add(colvar1); TableSchema.TableColumn colvar_1 = new TableSchema.TableColumn(schema); colvar_1.ColumnName = "1"; colvar_1.DataType = DbType.Int32; colvar_1.MaxLength = 0; colvar_1.AutoIncrement = false; colvar_1.IsNullable = true; colvar_1.IsPrimaryKey = false; colvar_1.IsForeignKey = false; colvar_1.IsReadOnly = false; schema.Columns.Add(colvar_1); TableSchema.TableColumn colvar2A4 = new TableSchema.TableColumn(schema); colvar2A4.ColumnName = "2 a 4"; colvar2A4.DataType = DbType.Int32; colvar2A4.MaxLength = 0; colvar2A4.AutoIncrement = false; colvar2A4.IsNullable = true; colvar2A4.IsPrimaryKey = false; colvar2A4.IsForeignKey = false; colvar2A4.IsReadOnly = false; schema.Columns.Add(colvar2A4); TableSchema.TableColumn colvar5A9 = new TableSchema.TableColumn(schema); colvar5A9.ColumnName = "5 a 9"; colvar5A9.DataType = DbType.Int32; colvar5A9.MaxLength = 0; colvar5A9.AutoIncrement = false; colvar5A9.IsNullable = true; colvar5A9.IsPrimaryKey = false; colvar5A9.IsForeignKey = false; colvar5A9.IsReadOnly = false; schema.Columns.Add(colvar5A9); TableSchema.TableColumn colvar10A14 = new TableSchema.TableColumn(schema); colvar10A14.ColumnName = "10 a 14"; colvar10A14.DataType = DbType.Int32; colvar10A14.MaxLength = 0; colvar10A14.AutoIncrement = false; colvar10A14.IsNullable = true; colvar10A14.IsPrimaryKey = false; colvar10A14.IsForeignKey = false; colvar10A14.IsReadOnly = false; schema.Columns.Add(colvar10A14); TableSchema.TableColumn colvar15A24 = new TableSchema.TableColumn(schema); colvar15A24.ColumnName = "15 a 24"; colvar15A24.DataType = DbType.Int32; colvar15A24.MaxLength = 0; colvar15A24.AutoIncrement = false; colvar15A24.IsNullable = true; colvar15A24.IsPrimaryKey = false; colvar15A24.IsForeignKey = false; colvar15A24.IsReadOnly = false; schema.Columns.Add(colvar15A24); TableSchema.TableColumn colvar25A34 = new TableSchema.TableColumn(schema); colvar25A34.ColumnName = "25 a 34"; colvar25A34.DataType = DbType.Int32; colvar25A34.MaxLength = 0; colvar25A34.AutoIncrement = false; colvar25A34.IsNullable = true; colvar25A34.IsPrimaryKey = false; colvar25A34.IsForeignKey = false; colvar25A34.IsReadOnly = false; schema.Columns.Add(colvar25A34); TableSchema.TableColumn colvar35A44 = new TableSchema.TableColumn(schema); colvar35A44.ColumnName = "35 a 44"; colvar35A44.DataType = DbType.Int32; colvar35A44.MaxLength = 0; colvar35A44.AutoIncrement = false; colvar35A44.IsNullable = true; colvar35A44.IsPrimaryKey = false; colvar35A44.IsForeignKey = false; colvar35A44.IsReadOnly = false; schema.Columns.Add(colvar35A44); TableSchema.TableColumn colvar45A64 = new TableSchema.TableColumn(schema); colvar45A64.ColumnName = "45 a 64"; colvar45A64.DataType = DbType.Int32; colvar45A64.MaxLength = 0; colvar45A64.AutoIncrement = false; colvar45A64.IsNullable = true; colvar45A64.IsPrimaryKey = false; colvar45A64.IsForeignKey = false; colvar45A64.IsReadOnly = false; schema.Columns.Add(colvar45A64); TableSchema.TableColumn colvar65Y = new TableSchema.TableColumn(schema); colvar65Y.ColumnName = "65 y +"; colvar65Y.DataType = DbType.Int32; colvar65Y.MaxLength = 0; colvar65Y.AutoIncrement = false; colvar65Y.IsNullable = true; colvar65Y.IsPrimaryKey = false; colvar65Y.IsForeignKey = false; colvar65Y.IsReadOnly = false; schema.Columns.Add(colvar65Y); TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema); colvarM.ColumnName = "M"; colvarM.DataType = DbType.Int32; colvarM.MaxLength = 0; colvarM.AutoIncrement = false; colvarM.IsNullable = true; colvarM.IsPrimaryKey = false; colvarM.IsForeignKey = false; colvarM.IsReadOnly = false; schema.Columns.Add(colvarM); TableSchema.TableColumn colvarF = new TableSchema.TableColumn(schema); colvarF.ColumnName = "F"; colvarF.DataType = DbType.Int32; colvarF.MaxLength = 0; colvarF.AutoIncrement = false; colvarF.IsNullable = true; colvarF.IsPrimaryKey = false; colvarF.IsForeignKey = false; colvarF.IsReadOnly = false; schema.Columns.Add(colvarF); TableSchema.TableColumn colvarI = new TableSchema.TableColumn(schema); colvarI.ColumnName = "I"; colvarI.DataType = DbType.Int32; colvarI.MaxLength = 0; colvarI.AutoIncrement = false; colvarI.IsNullable = true; colvarI.IsPrimaryKey = false; colvarI.IsForeignKey = false; colvarI.IsReadOnly = false; schema.Columns.Add(colvarI); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("GUARDIA_GrupoEtareoC2",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public GuardiaGrupoEtareoC2() { SetSQLProps(); SetDefaults(); MarkNew(); } public GuardiaGrupoEtareoC2(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public GuardiaGrupoEtareoC2(object keyID) { SetSQLProps(); LoadByKey(keyID); } public GuardiaGrupoEtareoC2(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("FechaIngreso")] [Bindable(true)] public string FechaIngreso { get { return GetColumnValue<string>("fechaIngreso"); } set { SetColumnValue("fechaIngreso", value); } } [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>("ID"); } set { SetColumnValue("ID", value); } } [XmlAttribute("1")] [Bindable(true)] public int? 1 { get { return GetColumnValue<int?>("<1"); } set { SetColumnValue("<1", value); } } [XmlAttribute("_1")] [Bindable(true)] public int? _1 { get { return GetColumnValue<int?>("1"); } set { SetColumnValue("1", value); } } [XmlAttribute("2A4")] [Bindable(true)] public int? 2A4 { get { return GetColumnValue<int?>("2 a 4"); } set { SetColumnValue("2 a 4", value); } } [XmlAttribute("5A9")] [Bindable(true)] public int? 5A9 { get { return GetColumnValue<int?>("5 a 9"); } set { SetColumnValue("5 a 9", value); } } [XmlAttribute("10A14")] [Bindable(true)] public int? 10A14 { get { return GetColumnValue<int?>("10 a 14"); } set { SetColumnValue("10 a 14", value); } } [XmlAttribute("15A24")] [Bindable(true)] public int? 15A24 { get { return GetColumnValue<int?>("15 a 24"); } set { SetColumnValue("15 a 24", value); } } [XmlAttribute("25A34")] [Bindable(true)] public int? 25A34 { get { return GetColumnValue<int?>("25 a 34"); } set { SetColumnValue("25 a 34", value); } } [XmlAttribute("35A44")] [Bindable(true)] public int? 35A44 { get { return GetColumnValue<int?>("35 a 44"); } set { SetColumnValue("35 a 44", value); } } [XmlAttribute("45A64")] [Bindable(true)] public int? 45A64 { get { return GetColumnValue<int?>("45 a 64"); } set { SetColumnValue("45 a 64", value); } } [XmlAttribute("65Y")] [Bindable(true)] public int? 65Y { get { return GetColumnValue<int?>("65 y +"); } set { SetColumnValue("65 y +", value); } } [XmlAttribute("M")] [Bindable(true)] public int? M { get { return GetColumnValue<int?>("M"); } set { SetColumnValue("M", value); } } [XmlAttribute("F")] [Bindable(true)] public int? F { get { return GetColumnValue<int?>("F"); } set { SetColumnValue("F", value); } } [XmlAttribute("I")] [Bindable(true)] public int? I { get { return GetColumnValue<int?>("I"); } set { SetColumnValue("I", value); } } #endregion #region Columns Struct public struct Columns { public static string FechaIngreso = @"fechaIngreso"; public static string Id = @"ID"; public static string 1 = @"<1"; public static string _1 = @"1"; public static string 2A4 = @"2 a 4"; public static string 5A9 = @"5 a 9"; public static string 10A14 = @"10 a 14"; public static string 15A24 = @"15 a 24"; public static string 25A34 = @"25 a 34"; public static string 35A44 = @"35 a 44"; public static string 45A64 = @"45 a 64"; public static string 65Y = @"65 y +"; public static string M = @"M"; public static string F = @"F"; public static string I = @"I"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL { // Known shortcomings: // - Escaping identifier names is missing (special characters and ILASM identifier names) // - Array bounds in signatures missing // - Custom modifiers and PINNED constraint not decoded in signatures // - Calling conventions in signatures not decoded // - Vararg signatures // - Floating point numbers are not represented in roundtrippable format /// <summary> /// Helper struct to disassemble IL instructions into a textual representation. /// </summary> public struct ILDisassembler { private byte[] _ilBytes; private MethodIL _methodIL; private ILTypeNameFormatter _typeNameFormatter; private int _currentOffset; public ILDisassembler(MethodIL methodIL) { _methodIL = methodIL; _ilBytes = methodIL.GetILBytes(); _currentOffset = 0; _typeNameFormatter = null; } #region Type/member/signature name formatting private ILTypeNameFormatter TypeNameFormatter { get { if (_typeNameFormatter == null) { // Find the owning module so that the type name formatter can remove // redundant assembly name qualifiers in type names. TypeDesc owningTypeDefinition = _methodIL.OwningMethod.OwningType; ModuleDesc owningModule = owningTypeDefinition is MetadataType ? ((MetadataType)owningTypeDefinition).Module : null; _typeNameFormatter = new ILTypeNameFormatter(owningModule); } return _typeNameFormatter; } } public void AppendType(StringBuilder sb, TypeDesc type, bool forceValueClassPrefix = true) { // Types referenced from the IL show as instantiated over generic parameter. // E.g. "initobj !0" becomes "initobj !T" TypeDesc typeInContext = type.InstantiateSignature( _methodIL.OwningMethod.OwningType.Instantiation, _methodIL.OwningMethod.Instantiation); if (typeInContext.HasInstantiation || forceValueClassPrefix) this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, typeInContext); else this.TypeNameFormatter.AppendName(sb, typeInContext); } private void AppendOwningType(StringBuilder sb, TypeDesc type) { // Special case primitive types: we don't want to use short names here if (type.IsPrimitive || type.IsString || type.IsObject) _typeNameFormatter.AppendNameForNamespaceTypeWithoutAliases(sb, (MetadataType)type); else AppendType(sb, type, false); } private void AppendMethodSignature(StringBuilder sb, MethodDesc method) { // If this is an instantiated generic method, the formatted signature should // be uninstantiated (e.g. "void Foo::Bar<int>(!!0 param)", not "void Foo::Bar<int>(int param)") MethodSignature signature = method.GetMethodDefinition().Signature; AppendSignaturePrefix(sb, signature); sb.Append(' '); AppendOwningType(sb, method.OwningType); sb.Append("::"); sb.Append(method.Name); if (method.HasInstantiation) { sb.Append('<'); for (int i = 0; i < method.Instantiation.Length; i++) { if (i != 0) sb.Append(", "); _typeNameFormatter.AppendNameWithValueClassPrefix(sb, method.Instantiation[i]); } sb.Append('>'); } sb.Append('('); AppendSignatureArgumentList(sb, signature); sb.Append(')'); } private void AppendMethodSignature(StringBuilder sb, MethodSignature signature) { AppendSignaturePrefix(sb, signature); sb.Append('('); AppendSignatureArgumentList(sb, signature); sb.Append(')'); } private void AppendSignaturePrefix(StringBuilder sb, MethodSignature signature) { if (!signature.IsStatic) sb.Append("instance "); this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, signature.ReturnType); } private void AppendSignatureArgumentList(StringBuilder sb, MethodSignature signature) { for (int i = 0; i < signature.Length; i++) { if (i != 0) sb.Append(", "); this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, signature[i]); } } private void AppendFieldSignature(StringBuilder sb, FieldDesc field) { this.TypeNameFormatter.AppendNameWithValueClassPrefix(sb, field.FieldType); sb.Append(' '); AppendOwningType(sb, field.OwningType); sb.Append("::"); sb.Append(field.Name); } private void AppendStringLiteral(StringBuilder sb, string s) { sb.Append('"'); for (int i = 0; i < s.Length; i++) { if (s[i] == '\\') sb.Append("\\\\"); else if (s[i] == '\t') sb.Append("\\t"); else if (s[i] == '"') sb.Append("\\\""); else if (s[i] == '\n') sb.Append("\\n"); else sb.Append(s[i]); } sb.Append('"'); } private void AppendToken(StringBuilder sb, int token) { object obj = _methodIL.GetObject(token); if (obj is MethodDesc) AppendMethodSignature(sb, (MethodDesc)obj); else if (obj is FieldDesc) AppendFieldSignature(sb, (FieldDesc)obj); else if (obj is MethodSignature) AppendMethodSignature(sb, (MethodSignature)obj); else if (obj is TypeDesc) AppendType(sb, (TypeDesc)obj, false); else { Debug.Assert(obj is string, "NYI: " + obj.GetType()); AppendStringLiteral(sb, (string)obj); } } #endregion #region Instruction decoding private byte ReadILByte() { return _ilBytes[_currentOffset++]; } private UInt16 ReadILUInt16() { UInt16 val = (UInt16)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8)); _currentOffset += 2; return val; } private UInt32 ReadILUInt32() { UInt32 val = (UInt32)(_ilBytes[_currentOffset] + (_ilBytes[_currentOffset + 1] << 8) + (_ilBytes[_currentOffset + 2] << 16) + (_ilBytes[_currentOffset + 3] << 24)); _currentOffset += 4; return val; } private int ReadILToken() { return (int)ReadILUInt32(); } private ulong ReadILUInt64() { ulong value = ReadILUInt32(); value |= (((ulong)ReadILUInt32()) << 32); return value; } private unsafe float ReadILFloat() { uint value = ReadILUInt32(); return *(float*)(&value); } private unsafe double ReadILDouble() { ulong value = ReadILUInt64(); return *(double*)(&value); } public static void AppendOffset(StringBuilder sb, int offset) { sb.Append("IL_"); sb.AppendFormat("{0:X4}", offset); } private static void PadForInstructionArgument(StringBuilder sb) { if (sb.Length < 22) sb.Append(' ', 22 - sb.Length); else sb.Append(' '); } public bool HasNextInstruction { get { return _currentOffset < _ilBytes.Length; } } public int Offset { get { return _currentOffset; } } public int CodeSize { get { return _ilBytes.Length; } } public string GetNextInstruction() { StringBuilder decodedInstruction = new StringBuilder(); AppendOffset(decodedInstruction, _currentOffset); decodedInstruction.Append(": "); again: ILOpcode opCode = (ILOpcode)ReadILByte(); if (opCode == ILOpcode.prefix1) { opCode = (ILOpcode)(0x100 + ReadILByte()); } // Quick and dirty way to get the opcode name is to convert the enum value to string. // We need some adjustments though. string opCodeString = opCode.ToString().Replace("_", "."); if (opCodeString.EndsWith(".")) opCodeString = opCodeString.Substring(0, opCodeString.Length - 1); decodedInstruction.Append(opCodeString); switch (opCode) { case ILOpcode.ldarg_s: case ILOpcode.ldarga_s: case ILOpcode.starg_s: case ILOpcode.ldloc_s: case ILOpcode.ldloca_s: case ILOpcode.stloc_s: case ILOpcode.ldc_i4_s: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILByte().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.unaligned: decodedInstruction.Append(' '); decodedInstruction.Append(ReadILByte().ToStringInvariant()); decodedInstruction.Append(' '); goto again; case ILOpcode.ldarg: case ILOpcode.ldarga: case ILOpcode.starg: case ILOpcode.ldloc: case ILOpcode.ldloca: case ILOpcode.stloc: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILUInt16().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_i4: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILUInt32().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_r4: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILFloat().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_i8: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILUInt64().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.ldc_r8: PadForInstructionArgument(decodedInstruction); decodedInstruction.Append(ReadILDouble().ToStringInvariant()); return decodedInstruction.ToString(); case ILOpcode.jmp: case ILOpcode.call: case ILOpcode.calli: case ILOpcode.callvirt: case ILOpcode.cpobj: case ILOpcode.ldobj: case ILOpcode.ldstr: case ILOpcode.newobj: case ILOpcode.castclass: case ILOpcode.isinst: case ILOpcode.unbox: case ILOpcode.ldfld: case ILOpcode.ldflda: case ILOpcode.stfld: case ILOpcode.ldsfld: case ILOpcode.ldsflda: case ILOpcode.stsfld: case ILOpcode.stobj: case ILOpcode.box: case ILOpcode.newarr: case ILOpcode.ldelema: case ILOpcode.ldelem: case ILOpcode.stelem: case ILOpcode.unbox_any: case ILOpcode.refanyval: case ILOpcode.mkrefany: case ILOpcode.ldtoken: case ILOpcode.ldftn: case ILOpcode.ldvirtftn: case ILOpcode.initobj: case ILOpcode.constrained: case ILOpcode.sizeof_: PadForInstructionArgument(decodedInstruction); AppendToken(decodedInstruction, ReadILToken()); return decodedInstruction.ToString(); case ILOpcode.br_s: case ILOpcode.leave_s: case ILOpcode.brfalse_s: case ILOpcode.brtrue_s: case ILOpcode.beq_s: case ILOpcode.bge_s: case ILOpcode.bgt_s: case ILOpcode.ble_s: case ILOpcode.blt_s: case ILOpcode.bne_un_s: case ILOpcode.bge_un_s: case ILOpcode.bgt_un_s: case ILOpcode.ble_un_s: case ILOpcode.blt_un_s: PadForInstructionArgument(decodedInstruction); AppendOffset(decodedInstruction, (sbyte)ReadILByte() + _currentOffset); return decodedInstruction.ToString(); case ILOpcode.br: case ILOpcode.leave: case ILOpcode.brfalse: case ILOpcode.brtrue: case ILOpcode.beq: case ILOpcode.bge: case ILOpcode.bgt: case ILOpcode.ble: case ILOpcode.blt: case ILOpcode.bne_un: case ILOpcode.bge_un: case ILOpcode.bgt_un: case ILOpcode.ble_un: case ILOpcode.blt_un: PadForInstructionArgument(decodedInstruction); AppendOffset(decodedInstruction, (int)ReadILUInt32() + _currentOffset); return decodedInstruction.ToString(); case ILOpcode.switch_: { decodedInstruction.Clear(); decodedInstruction.Append("switch ("); uint count = ReadILUInt32(); int jmpBase = _currentOffset + (int)(4 * count); for (uint i = 0; i < count; i++) { if (i != 0) decodedInstruction.Append(", "); int delta = (int)ReadILUInt32(); AppendOffset(decodedInstruction, jmpBase + delta); } decodedInstruction.Append(")"); return decodedInstruction.ToString(); } default: return decodedInstruction.ToString(); } } #endregion #region Helpers public class ILTypeNameFormatter : TypeNameFormatter { private ModuleDesc _thisModule; public ILTypeNameFormatter(ModuleDesc thisModule) { _thisModule = thisModule; } public void AppendNameWithValueClassPrefix(StringBuilder sb, TypeDesc type) { if (!type.IsSignatureVariable && type.IsDefType && !type.IsPrimitive && !type.IsObject && !type.IsString) { string prefix = type.IsValueType ? "valuetype " : "class "; sb.Append(prefix); AppendName(sb, type); } else { AppendName(sb, type); } } public override void AppendName(StringBuilder sb, PointerType type) { AppendNameWithValueClassPrefix(sb, type.ParameterType); sb.Append('*'); } public override void AppendName(StringBuilder sb, FunctionPointerType type) { MethodSignature signature = type.Signature; sb.Append("method "); if (!signature.IsStatic) sb.Append("instance "); // TODO: rest of calling conventions AppendName(sb, signature.ReturnType); sb.Append(" *("); for (int i = 0; i < signature.Length; i++) { if (i > 0) sb.Append(", "); AppendName(sb, signature[i]); } sb.Append(')'); } public override void AppendName(StringBuilder sb, SignatureMethodVariable type) { sb.Append("!!"); sb.Append(type.Index.ToStringInvariant()); } public override void AppendName(StringBuilder sb, SignatureTypeVariable type) { sb.Append("!"); sb.Append(type.Index.ToStringInvariant()); } public override void AppendName(StringBuilder sb, GenericParameterDesc type) { string prefix = type.Kind == GenericParameterKind.Type ? "!" : "!!"; sb.Append(prefix); sb.Append(type.Name); } protected override void AppendNameForInstantiatedType(StringBuilder sb, DefType type) { AppendName(sb, type.GetTypeDefinition()); sb.Append('<'); for (int i = 0; i < type.Instantiation.Length; i++) { if (i > 0) sb.Append(", "); AppendNameWithValueClassPrefix(sb, type.Instantiation[i]); } sb.Append('>'); } public override void AppendName(StringBuilder sb, ByRefType type) { AppendNameWithValueClassPrefix(sb, type.ParameterType); sb.Append('&'); } public override void AppendName(StringBuilder sb, ArrayType type) { AppendNameWithValueClassPrefix(sb, type.ElementType); sb.Append('['); sb.Append(',', type.Rank - 1); sb.Append(']'); } protected override void AppendNameForNamespaceType(StringBuilder sb, DefType type) { switch (type.Category) { case TypeFlags.Void: sb.Append("void"); return; case TypeFlags.Boolean: sb.Append("bool"); return; case TypeFlags.Char: sb.Append("char"); return; case TypeFlags.SByte: sb.Append("int8"); return; case TypeFlags.Byte: sb.Append("uint8"); return; case TypeFlags.Int16: sb.Append("int16"); return; case TypeFlags.UInt16: sb.Append("uint16"); return; case TypeFlags.Int32: sb.Append("int32"); return; case TypeFlags.UInt32: sb.Append("uint32"); return; case TypeFlags.Int64: sb.Append("int64"); return; case TypeFlags.UInt64: sb.Append("uint64"); return; case TypeFlags.IntPtr: sb.Append("native int"); return; case TypeFlags.UIntPtr: sb.Append("native uint"); return; case TypeFlags.Single: sb.Append("float32"); return; case TypeFlags.Double: sb.Append("float64"); return; } if (type.IsString) { sb.Append("string"); return; } if (type.IsObject) { sb.Append("object"); return; } AppendNameForNamespaceTypeWithoutAliases(sb, type); } public void AppendNameForNamespaceTypeWithoutAliases(StringBuilder sb, DefType type) { ModuleDesc owningModule = (type as MetadataType)?.Module; if (owningModule != null && owningModule != _thisModule) { Debug.Assert(owningModule is IAssemblyDesc); string owningModuleName = ((IAssemblyDesc)owningModule).GetName().Name; sb.Append('['); sb.Append(owningModuleName); sb.Append(']'); } string ns = type.Namespace; if (ns.Length > 0) { sb.Append(ns); sb.Append('.'); } sb.Append(type.Name); } protected override void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType) { AppendName(sb, containingType); sb.Append('/'); sb.Append(nestedType.Name); } } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Taskrouter.V1.Workspace { /// <summary> /// FetchWorkflowOptions /// </summary> public class FetchWorkflowOptions : IOptions<WorkflowResource> { /// <summary> /// The SID of the Workspace with the Workflow to fetch /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The SID of the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchWorkflowOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Workflow to fetch </param> /// <param name="pathSid"> The SID of the resource </param> public FetchWorkflowOptions(string pathWorkspaceSid, string pathSid) { PathWorkspaceSid = pathWorkspaceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// UpdateWorkflowOptions /// </summary> public class UpdateWorkflowOptions : IOptions<WorkflowResource> { /// <summary> /// The SID of the Workspace with the Workflow to update /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The SID of the resource /// </summary> public string PathSid { get; } /// <summary> /// descriptive string that you create to describe the Workflow resource /// </summary> public string FriendlyName { get; set; } /// <summary> /// The URL from your application that will process task assignment events /// </summary> public Uri AssignmentCallbackUrl { get; set; } /// <summary> /// The URL that we should call when a call to the `assignment_callback_url` fails /// </summary> public Uri FallbackAssignmentCallbackUrl { get; set; } /// <summary> /// A JSON string that contains the rules to apply to the Workflow /// </summary> public string Configuration { get; set; } /// <summary> /// How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker /// </summary> public int? TaskReservationTimeout { get; set; } /// <summary> /// Whether or not to re-evaluate Tasks /// </summary> public string ReEvaluateTasks { get; set; } /// <summary> /// Construct a new UpdateWorkflowOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Workflow to update </param> /// <param name="pathSid"> The SID of the resource </param> public UpdateWorkflowOptions(string pathWorkspaceSid, string pathSid) { PathWorkspaceSid = pathWorkspaceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (AssignmentCallbackUrl != null) { p.Add(new KeyValuePair<string, string>("AssignmentCallbackUrl", Serializers.Url(AssignmentCallbackUrl))); } if (FallbackAssignmentCallbackUrl != null) { p.Add(new KeyValuePair<string, string>("FallbackAssignmentCallbackUrl", Serializers.Url(FallbackAssignmentCallbackUrl))); } if (Configuration != null) { p.Add(new KeyValuePair<string, string>("Configuration", Configuration)); } if (TaskReservationTimeout != null) { p.Add(new KeyValuePair<string, string>("TaskReservationTimeout", TaskReservationTimeout.ToString())); } if (ReEvaluateTasks != null) { p.Add(new KeyValuePair<string, string>("ReEvaluateTasks", ReEvaluateTasks)); } return p; } } /// <summary> /// DeleteWorkflowOptions /// </summary> public class DeleteWorkflowOptions : IOptions<WorkflowResource> { /// <summary> /// The SID of the Workspace with the Workflow to delete /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The SID of the Workflow resource to delete /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteWorkflowOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Workflow to delete </param> /// <param name="pathSid"> The SID of the Workflow resource to delete </param> public DeleteWorkflowOptions(string pathWorkspaceSid, string pathSid) { PathWorkspaceSid = pathWorkspaceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// ReadWorkflowOptions /// </summary> public class ReadWorkflowOptions : ReadOptions<WorkflowResource> { /// <summary> /// The SID of the Workspace with the Workflow to read /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// The friendly_name of the Workflow resources to read /// </summary> public string FriendlyName { get; set; } /// <summary> /// Construct a new ReadWorkflowOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace with the Workflow to read </param> public ReadWorkflowOptions(string pathWorkspaceSid) { PathWorkspaceSid = pathWorkspaceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// CreateWorkflowOptions /// </summary> public class CreateWorkflowOptions : IOptions<WorkflowResource> { /// <summary> /// The SID of the Workspace that the new Workflow to create belongs to /// </summary> public string PathWorkspaceSid { get; } /// <summary> /// descriptive string that you create to describe the Workflow resource /// </summary> public string FriendlyName { get; } /// <summary> /// A JSON string that contains the rules to apply to the Workflow /// </summary> public string Configuration { get; } /// <summary> /// The URL from your application that will process task assignment events /// </summary> public Uri AssignmentCallbackUrl { get; set; } /// <summary> /// The URL that we should call when a call to the `assignment_callback_url` fails /// </summary> public Uri FallbackAssignmentCallbackUrl { get; set; } /// <summary> /// How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker /// </summary> public int? TaskReservationTimeout { get; set; } /// <summary> /// Construct a new CreateWorkflowOptions /// </summary> /// <param name="pathWorkspaceSid"> The SID of the Workspace that the new Workflow to create belongs to </param> /// <param name="friendlyName"> descriptive string that you create to describe the Workflow resource </param> /// <param name="configuration"> A JSON string that contains the rules to apply to the Workflow </param> public CreateWorkflowOptions(string pathWorkspaceSid, string friendlyName, string configuration) { PathWorkspaceSid = pathWorkspaceSid; FriendlyName = friendlyName; Configuration = configuration; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (FriendlyName != null) { p.Add(new KeyValuePair<string, string>("FriendlyName", FriendlyName)); } if (Configuration != null) { p.Add(new KeyValuePair<string, string>("Configuration", Configuration)); } if (AssignmentCallbackUrl != null) { p.Add(new KeyValuePair<string, string>("AssignmentCallbackUrl", Serializers.Url(AssignmentCallbackUrl))); } if (FallbackAssignmentCallbackUrl != null) { p.Add(new KeyValuePair<string, string>("FallbackAssignmentCallbackUrl", Serializers.Url(FallbackAssignmentCallbackUrl))); } if (TaskReservationTimeout != null) { p.Add(new KeyValuePair<string, string>("TaskReservationTimeout", TaskReservationTimeout.ToString())); } return p; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; // // Calendar ID Values. This is used to get data from calendar.nlp. // The order of calendar ID means the order of data items in the table. // internal const int CAL_GREGORIAN = 1 ; // Gregorian (localized) calendar internal const int CAL_GREGORIAN_US = 2 ; // Gregorian (U.S.) calendar internal const int CAL_JAPAN = 3 ; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4 ; // Taiwan Era calendar internal const int CAL_KOREA = 5 ; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6 ; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7 ; // Thai calendar internal const int CAL_HEBREW = 8 ; // Hebrew (Lunar) calendar internal const int CAL_GREGORIAN_ME_FRENCH = 9 ; // Gregorian Middle East French calendar internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar internal const int CAL_GREGORIAN_XLIT_FRENCH = 12; internal const int CAL_JULIAN = 13; internal const int CAL_JAPANESELUNISOLAR = 14; internal const int CAL_CHINESELUNISOLAR = 15; internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code internal const int CAL_KOREANLUNISOLAR = 20; internal const int CAL_TAIWANLUNISOLAR = 21; internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; internal int m_currentEraValue = -1; [System.Runtime.Serialization.OptionalField(VersionAdded = 2)] private bool m_isReadOnly = false; // The minimum supported DateTime range for the calendar. [System.Runtime.InteropServices.ComVisible(false)] public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. [System.Runtime.InteropServices.ComVisible(false)] public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual int ID { get { return (-1); } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual int BaseCalendarID { get { return ID; } } // Returns the type of the calendar. // [System.Runtime.InteropServices.ComVisible(false)] public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public bool IsReadOnly { get { return (m_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of ICloneable. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual Object Clone() { object o = MemberwiseClone(); ((Calendar) o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (m_isReadOnly) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); } } internal void SetReadOnlyState(bool readOnly) { m_isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (m_currentEraValue == -1) { Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (m_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Argument_ResultCalendarRange"), minValue, maxValue)); } Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue")); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day/7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( nameof(firstDayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( nameof(rule), Environment.GetResourceString("ArgumentOutOfRange_Range", CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month=1; month<=monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax/100 - ( year > TwoDigitYearMax % 100 ? 1 : 0))*100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue) { // Call nativeGetTwoDigitYearMax int twoDigitYearMax = CalendarData.nativeGetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // Copyright (C) 2006-2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; namespace Mono.Security.Protocol.Tls { public abstract class SslStreamBase: Stream, IDisposable { private delegate void AsyncHandshakeDelegate(InternalAsyncResult asyncResult, bool fromWrite); #region Fields static ManualResetEvent record_processing = new ManualResetEvent (true); internal Stream innerStream; internal MemoryStream inputBuffer; internal Context context; internal RecordProtocol protocol; internal bool ownsStream; private volatile bool disposed; private bool checkCertRevocationStatus; private object negotiate; private object read; private object write; private ManualResetEvent negotiationComplete; #endregion #region Constructors protected SslStreamBase( Stream stream, bool ownsStream) { if (stream == null) { throw new ArgumentNullException("stream is null."); } if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentNullException("stream is not both readable and writable."); } this.inputBuffer = new MemoryStream(); this.innerStream = stream; this.ownsStream = ownsStream; this.negotiate = new object(); this.read = new object(); this.write = new object(); this.negotiationComplete = new ManualResetEvent(false); } #endregion #region Handshakes private void AsyncHandshakeCallback(IAsyncResult asyncResult) { InternalAsyncResult internalResult = asyncResult.AsyncState as InternalAsyncResult; try { try { this.OnNegotiateHandshakeCallback(asyncResult); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); throw new IOException("The authentication or decryption has failed.", ex); } catch (Exception ex) { this.protocol.SendAlert(AlertDescription.InternalError); throw new IOException("The authentication or decryption has failed.", ex); } if (internalResult.ProceedAfterHandshake) { //kick off the read or write process (whichever called us) after the handshake is complete if (internalResult.FromWrite) { InternalBeginWrite(internalResult); } else { InternalBeginRead(internalResult); } negotiationComplete.Set(); } else { negotiationComplete.Set(); internalResult.SetComplete(); } } catch (Exception ex) { negotiationComplete.Set(); internalResult.SetComplete(ex); } } internal bool MightNeedHandshake { get { if (this.context.HandshakeState == HandshakeState.Finished) { return false; } else { lock (this.negotiate) { return (this.context.HandshakeState != HandshakeState.Finished); } } } } internal void NegotiateHandshake() { if (this.MightNeedHandshake) { InternalAsyncResult ar = new InternalAsyncResult(null, null, null, 0, 0, false, false); //if something already started negotiation, wait for it. //otherwise end it ourselves. if (!BeginNegotiateHandshake(ar)) { this.negotiationComplete.WaitOne(); } else { this.EndNegotiateHandshake(ar); } } } #endregion #region Abstracts/Virtuals internal abstract IAsyncResult OnBeginNegotiateHandshake(AsyncCallback callback, object state); internal abstract void OnNegotiateHandshakeCallback(IAsyncResult asyncResult); internal abstract X509Certificate OnLocalCertificateSelection(X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates); internal abstract bool OnRemoteCertificateValidation(X509Certificate certificate, int[] errors); internal abstract ValidationResult OnRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection); internal abstract bool HaveRemoteValidation2Callback { get; } internal abstract AsymmetricAlgorithm OnLocalPrivateKeySelection(X509Certificate certificate, string targetHost); #endregion #region Event Methods internal X509Certificate RaiseLocalCertificateSelection(X509CertificateCollection certificates, X509Certificate remoteCertificate, string targetHost, X509CertificateCollection requestedCertificates) { return OnLocalCertificateSelection(certificates, remoteCertificate, targetHost, requestedCertificates); } internal bool RaiseRemoteCertificateValidation(X509Certificate certificate, int[] errors) { return OnRemoteCertificateValidation(certificate, errors); } internal ValidationResult RaiseRemoteCertificateValidation2 (Mono.Security.X509.X509CertificateCollection collection) { return OnRemoteCertificateValidation2 (collection); } internal AsymmetricAlgorithm RaiseLocalPrivateKeySelection( X509Certificate certificate, string targetHost) { return OnLocalPrivateKeySelection(certificate, targetHost); } #endregion #region Security Properties public bool CheckCertRevocationStatus { get { return this.checkCertRevocationStatus; } set { this.checkCertRevocationStatus = value; } } public CipherAlgorithmType CipherAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Current.Cipher.CipherAlgorithmType; } return CipherAlgorithmType.None; } } public int CipherStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Current.Cipher.EffectiveKeyBits; } return 0; } } public HashAlgorithmType HashAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Current.Cipher.HashAlgorithmType; } return HashAlgorithmType.None; } } public int HashStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Current.Cipher.HashSize * 8; } return 0; } } public int KeyExchangeStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.ServerSettings.Certificates[0].RSA.KeySize; } return 0; } } public ExchangeAlgorithmType KeyExchangeAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Current.Cipher.ExchangeAlgorithmType; } return ExchangeAlgorithmType.None; } } public SecurityProtocolType SecurityProtocol { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.SecurityProtocol; } return 0; } } public X509Certificate ServerCertificate { get { if (this.context.HandshakeState == HandshakeState.Finished) { if (this.context.ServerSettings.Certificates != null && this.context.ServerSettings.Certificates.Count > 0) { return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData); } } return null; } } // this is used by Mono's certmgr tool to download certificates internal Mono.Security.X509.X509CertificateCollection ServerCertificates { get { return context.ServerSettings.Certificates; } } #endregion #region Internal Async Result/State Class private class InternalAsyncResult : IAsyncResult { private object locker = new object (); private AsyncCallback _userCallback; private object _userState; private Exception _asyncException; private ManualResetEvent handle; private bool completed; private int _bytesRead; private bool _fromWrite; private bool _proceedAfterHandshake; private byte[] _buffer; private int _offset; private int _count; public InternalAsyncResult(AsyncCallback userCallback, object userState, byte[] buffer, int offset, int count, bool fromWrite, bool proceedAfterHandshake) { _userCallback = userCallback; _userState = userState; _buffer = buffer; _offset = offset; _count = count; _fromWrite = fromWrite; _proceedAfterHandshake = proceedAfterHandshake; } public bool ProceedAfterHandshake { get { return _proceedAfterHandshake; } } public bool FromWrite { get { return _fromWrite; } } public byte[] Buffer { get { return _buffer; } } public int Offset { get { return _offset; } } public int Count { get { return _count; } } public int BytesRead { get { return _bytesRead; } } public object AsyncState { get { return _userState; } } public Exception AsyncException { get { return _asyncException; } } public bool CompletedWithError { get { if (IsCompleted == false) return false; return null != _asyncException; } } public WaitHandle AsyncWaitHandle { get { lock (locker) { if (handle == null) handle = new ManualResetEvent (completed); } return handle; } } public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get { lock (locker) return completed; } } private void SetComplete(Exception ex, int bytesRead) { lock (locker) { if (completed) return; completed = true; _asyncException = ex; _bytesRead = bytesRead; if (handle != null) handle.Set (); } if (_userCallback != null) _userCallback.BeginInvoke (this, null, null); } public void SetComplete(Exception ex) { SetComplete(ex, 0); } public void SetComplete(int bytesRead) { SetComplete(null, bytesRead); } public void SetComplete() { SetComplete(null, 0); } } #endregion #region Stream Overrides and Async Stream Operations private bool BeginNegotiateHandshake(InternalAsyncResult asyncResult) { try { lock (this.negotiate) { if (this.context.HandshakeState == HandshakeState.None) { this.OnBeginNegotiateHandshake(new AsyncCallback(AsyncHandshakeCallback), asyncResult); return true; } else { return false; } } } catch (TlsException ex) { this.negotiationComplete.Set(); this.protocol.SendAlert(ex.Alert); throw new IOException("The authentication or decryption has failed.", ex); } catch (Exception ex) { this.negotiationComplete.Set(); this.protocol.SendAlert(AlertDescription.InternalError); throw new IOException("The authentication or decryption has failed.", ex); } } private void EndNegotiateHandshake(InternalAsyncResult asyncResult) { if (asyncResult.IsCompleted == false) asyncResult.AsyncWaitHandle.WaitOne(); if (asyncResult.CompletedWithError) { throw asyncResult.AsyncException; } } public override IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, false, true); if (this.MightNeedHandshake) { if (! BeginNegotiateHandshake(asyncResult)) { //we made it down here so the handshake was not started. //another thread must have started it in the mean time. //wait for it to complete and then perform our original operation this.negotiationComplete.WaitOne(); InternalBeginRead(asyncResult); } } else { InternalBeginRead(asyncResult); } return asyncResult; } // bigger than max record length for SSL/TLS private byte[] recbuf = new byte[16384]; private void InternalBeginRead(InternalAsyncResult asyncResult) { try { int preReadSize = 0; lock (this.read) { // If actual buffer is fully read, reset it bool shouldReset = this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0; // If the buffer isn't fully read, but does have data, we need to immediately // read the info from the buffer and let the user know that they have more data. bool shouldReadImmediately = (this.inputBuffer.Length > 0) && (asyncResult.Count > 0); if (shouldReset) { this.resetBuffer(); } else if (shouldReadImmediately) { preReadSize = this.inputBuffer.Read(asyncResult.Buffer, asyncResult.Offset, asyncResult.Count); } } // This is explicitly done outside the synclock to avoid // any potential deadlocks in the delegate call. if (0 < preReadSize) { asyncResult.SetComplete(preReadSize); } else if (!this.context.ReceivedConnectionEnd) { // this will read data from the network until we have (at least) one // record to send back to the caller this.innerStream.BeginRead(recbuf, 0, recbuf.Length, new AsyncCallback(InternalReadCallback), new object[] { recbuf, asyncResult }); } else { // We're done with the connection so we need to let the caller know with 0 bytes read asyncResult.SetComplete(0); } } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); throw new IOException("The authentication or decryption has failed.", ex); } catch (Exception ex) { throw new IOException("IO exception during read.", ex); } } private MemoryStream recordStream = new MemoryStream(); // read encrypted data until we have enough to decrypt (at least) one // record and return are the records (may be more than one) we have private void InternalReadCallback(IAsyncResult result) { if (this.disposed) return; object[] state = (object[])result.AsyncState; byte[] recbuf = (byte[])state[0]; InternalAsyncResult internalResult = (InternalAsyncResult)state[1]; try { int n = innerStream.EndRead(result); if (n > 0) { // Add the just received data to the waiting data recordStream.Write(recbuf, 0, n); } else { // 0 length data means this read operation is done (lost connection in the case of a network stream). internalResult.SetComplete(0); return; } bool dataToReturn = false; long pos = recordStream.Position; recordStream.Position = 0; byte[] record = null; // don't try to decode record unless we have at least 5 bytes // i.e. type (1), protocol (2) and length (2) if (recordStream.Length >= 5) { record = this.protocol.ReceiveRecord(recordStream); } // a record of 0 length is valid (and there may be more record after it) while (record != null) { // we probably received more stuff after the record, and we must keep it! long remainder = recordStream.Length - recordStream.Position; byte[] outofrecord = null; if (remainder > 0) { outofrecord = new byte[remainder]; recordStream.Read(outofrecord, 0, outofrecord.Length); } lock (this.read) { long position = this.inputBuffer.Position; if (record.Length > 0) { // Write new data to the inputBuffer this.inputBuffer.Seek(0, SeekOrigin.End); this.inputBuffer.Write(record, 0, record.Length); // Restore buffer position this.inputBuffer.Seek(position, SeekOrigin.Begin); dataToReturn = true; } } recordStream.SetLength(0); record = null; if (remainder > 0) { recordStream.Write(outofrecord, 0, outofrecord.Length); // type (1), protocol (2) and length (2) if (recordStream.Length >= 5) { // try to see if another record is available recordStream.Position = 0; record = this.protocol.ReceiveRecord(recordStream); if (record == null) pos = recordStream.Length; } else pos = remainder; } else pos = 0; } if (!dataToReturn && (n > 0)) { if (context.ReceivedConnectionEnd) { internalResult.SetComplete (0); } else { // there is no record to return to caller and (possibly) more data waiting // so continue reading from network (and appending to stream) recordStream.Position = recordStream.Length; this.innerStream.BeginRead(recbuf, 0, recbuf.Length, new AsyncCallback(InternalReadCallback), state); } } else { // we have record(s) to return -or- no more available to read from network // reset position for further reading recordStream.Position = pos; int bytesRead = 0; lock (this.read) { bytesRead = this.inputBuffer.Read(internalResult.Buffer, internalResult.Offset, internalResult.Count); } internalResult.SetComplete(bytesRead); } } catch (Exception ex) { internalResult.SetComplete(ex); } } private void InternalBeginWrite(InternalAsyncResult asyncResult) { try { // Send the buffer as a TLS record lock (this.write) { byte[] record = this.protocol.EncodeRecord( ContentType.ApplicationData, asyncResult.Buffer, asyncResult.Offset, asyncResult.Count); this.innerStream.BeginWrite( record, 0, record.Length, new AsyncCallback(InternalWriteCallback), asyncResult); } } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed.", ex); } catch (Exception ex) { throw new IOException("IO exception during Write.", ex); } } private void InternalWriteCallback(IAsyncResult ar) { if (this.disposed) return; InternalAsyncResult internalResult = (InternalAsyncResult)ar.AsyncState; try { this.innerStream.EndWrite(ar); internalResult.SetComplete(); } catch (Exception ex) { internalResult.SetComplete(ex); } } public override IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } InternalAsyncResult asyncResult = new InternalAsyncResult(callback, state, buffer, offset, count, true, true); if (this.MightNeedHandshake) { if (! BeginNegotiateHandshake(asyncResult)) { //we made it down here so the handshake was not started. //another thread must have started it in the mean time. //wait for it to complete and then perform our original operation this.negotiationComplete.WaitOne(); InternalBeginWrite(asyncResult); } } else { InternalBeginWrite(asyncResult); } return asyncResult; } public override int EndRead(IAsyncResult asyncResult) { this.checkDisposed(); InternalAsyncResult internalResult = asyncResult as InternalAsyncResult; if (internalResult == null) { throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead."); } // Always wait until the read is complete if (!asyncResult.IsCompleted) { if (!asyncResult.AsyncWaitHandle.WaitOne ()) throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndRead"); } if (internalResult.CompletedWithError) { throw internalResult.AsyncException; } return internalResult.BytesRead; } public override void EndWrite(IAsyncResult asyncResult) { this.checkDisposed(); InternalAsyncResult internalResult = asyncResult as InternalAsyncResult; if (internalResult == null) { throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginWrite."); } if (!asyncResult.IsCompleted) { if (!internalResult.AsyncWaitHandle.WaitOne ()) throw new TlsException (AlertDescription.InternalError, "Couldn't complete EndWrite"); } if (internalResult.CompletedWithError) { throw internalResult.AsyncException; } } public override void Close() { base.Close (); } public override void Flush() { this.checkDisposed(); this.innerStream.Flush(); } public int Read(byte[] buffer) { return this.Read(buffer, 0, buffer.Length); } public override int Read(byte[] buffer, int offset, int count) { this.checkDisposed (); if (buffer == null) { throw new ArgumentNullException ("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } if (this.context.HandshakeState != HandshakeState.Finished) { this.NegotiateHandshake (); // Handshake negotiation } lock (this.read) { try { record_processing.Reset (); // do we already have some decrypted data ? if (this.inputBuffer.Position > 0) { // or maybe we used all the buffer before ? if (this.inputBuffer.Position == this.inputBuffer.Length) { this.inputBuffer.SetLength (0); } else { int n = this.inputBuffer.Read (buffer, offset, count); if (n > 0) { record_processing.Set (); return n; } } } bool needMoreData = false; while (true) { // we first try to process the read with the data we already have if ((recordStream.Position == 0) || needMoreData) { needMoreData = false; // if we loop, then it either means we need more data byte[] recbuf = new byte[16384]; int n = 0; if (count == 1) { int value = innerStream.ReadByte (); if (value >= 0) { recbuf[0] = (byte) value; n = 1; } } else { n = innerStream.Read (recbuf, 0, recbuf.Length); } if (n > 0) { // Add the new received data to the waiting data if ((recordStream.Length > 0) && (recordStream.Position != recordStream.Length)) recordStream.Seek (0, SeekOrigin.End); recordStream.Write (recbuf, 0, n); } else { // or that the read operation is done (lost connection in the case of a network stream). record_processing.Set (); return 0; } } bool dataToReturn = false; recordStream.Position = 0; byte[] record = null; // don't try to decode record unless we have at least 5 bytes // i.e. type (1), protocol (2) and length (2) if (recordStream.Length >= 5) { record = this.protocol.ReceiveRecord (recordStream); needMoreData = (record == null); } // a record of 0 length is valid (and there may be more record after it) while (record != null) { // we probably received more stuff after the record, and we must keep it! long remainder = recordStream.Length - recordStream.Position; byte[] outofrecord = null; if (remainder > 0) { outofrecord = new byte[remainder]; recordStream.Read (outofrecord, 0, outofrecord.Length); } long position = this.inputBuffer.Position; if (record.Length > 0) { // Write new data to the inputBuffer this.inputBuffer.Seek (0, SeekOrigin.End); this.inputBuffer.Write (record, 0, record.Length); // Restore buffer position this.inputBuffer.Seek (position, SeekOrigin.Begin); dataToReturn = true; } recordStream.SetLength (0); record = null; if (remainder > 0) { recordStream.Write (outofrecord, 0, outofrecord.Length); } if (dataToReturn) { // we have record(s) to return -or- no more available to read from network // reset position for further reading int i = inputBuffer.Read (buffer, offset, count); record_processing.Set (); return i; } } } } catch (TlsException ex) { throw new IOException("The authentication or decryption has failed.", ex); } catch (Exception ex) { throw new IOException("IO exception during read.", ex); } } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public void Write(byte[] buffer) { this.Write(buffer, 0, buffer.Length); } public override void Write(byte[] buffer, int offset, int count) { this.checkDisposed (); if (buffer == null) { throw new ArgumentNullException ("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } if (this.context.HandshakeState != HandshakeState.Finished) { this.NegotiateHandshake (); } lock (this.write) { try { // Send the buffer as a TLS record byte[] record = this.protocol.EncodeRecord (ContentType.ApplicationData, buffer, offset, count); this.innerStream.Write (record, 0, record.Length); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed.", ex); } catch (Exception ex) { throw new IOException("IO exception during Write.", ex); } } } public override bool CanRead { get { return this.innerStream.CanRead; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return this.innerStream.CanWrite; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion #region IDisposable Members and Finalizer ~SslStreamBase() { this.Dispose(false); } protected override void Dispose (bool disposing) { if (!this.disposed) { if (disposing) { if (this.innerStream != null) { if (this.context.HandshakeState == HandshakeState.Finished && !this.context.SentConnectionEnd) { // Write close notify try { this.protocol.SendAlert(AlertDescription.CloseNotify); } catch { } } if (this.ownsStream) { // Close inner stream this.innerStream.Close(); } } this.ownsStream = false; this.innerStream = null; } this.disposed = true; base.Dispose (disposing); } } #endregion #region Misc Methods private void resetBuffer() { this.inputBuffer.SetLength(0); this.inputBuffer.Position = 0; } internal void checkDisposed() { if (this.disposed) { throw new ObjectDisposedException("The Stream is closed."); } } #endregion } }
using System; using System.Globalization; using System.IO; using System.Text; using Verse.ParserDescriptors.Recurse; namespace Verse.Schemas.JSON { internal class Reader : IReader<ReaderContext, Value> { #region Constants private const ulong MANTISSA_MAX = long.MaxValue/10; #endregion #region Events public event ParserError Error; #endregion #region Attributes private readonly Encoding encoding; #endregion #region Constructors public Reader(Encoding encoding) { this.encoding = encoding; } #endregion #region Methods / Public public IBrowser<TEntity> ReadArray<TEntity>(Func<TEntity> constructor, Container<TEntity, ReaderContext, Value> container, ReaderContext context) { char ignore; BrowserMove<TEntity> move; switch (context.Current) { case (int)'[': context.Pull(); move = (int index, out TEntity current) => { current = constructor(); this.PullIgnored(context); if (context.Current == (int)']') { context.Pull(); return BrowserState.Success; } // Read comma separator if any if (index > 0) { if (!this.PullExpected(context, ',')) return BrowserState.Failure; this.PullIgnored(context); } // Read array value if (!this.ReadValue(ref current, container, context)) return BrowserState.Failure; return BrowserState.Continue; }; break; case (int)'{': context.Pull(); move = (int index, out TEntity current) => { current = constructor(); this.PullIgnored(context); if (context.Current == (int)'}') { context.Pull(); return BrowserState.Success; } // Read comma separator if any if (index > 0) { if (!this.PullExpected(context, ',')) return BrowserState.Failure; this.PullIgnored(context); } if (!this.PullExpected(context, '"')) return BrowserState.Failure; // Read and move to object key while (context.Current != (int)'"') { if (!this.PullCharacter(context, out ignore)) { this.OnError(context.Position, "invalid character in object key"); return BrowserState.Failure; } } context.Pull(); // Read object separator this.PullIgnored(context); if (!this.PullExpected(context, ':')) return BrowserState.Failure; // Read object value this.PullIgnored(context); // Read array value if (!this.ReadValue(ref current, container, context)) return BrowserState.Failure; return BrowserState.Continue; }; break; default: move = (int index, out TEntity current) => { current = default (TEntity); if (!this.ReadValue(ref current, container, context)) return BrowserState.Failure; return BrowserState.Success; }; break; } return new Browser<TEntity>(move); } public bool ReadValue<TEntity>(ref TEntity target, Container<TEntity, ReaderContext, Value> container, ReaderContext context) { StringBuilder buffer; char current; INode<TEntity, ReaderContext, Value> node; decimal number; uint numberExponent; uint numberExponentMask; uint numberExponentPlus; ulong numberMantissa; ulong numberMantissaMask; ulong numberMantissaPlus; int numberPower; if (container.items != null) return container.items(ref target, this, context); switch (context.Current) { case (int)'"': context.Pull(); // Read and store string in a buffer if its value is needed if (container.value != null) { buffer = new StringBuilder(32); while (context.Current != (int)'"') { if (!this.PullCharacter(context, out current)) { this.OnError(context.Position, "invalid character in string value"); return false; } buffer.Append(current); } container.value(ref target, Value.FromString(buffer.ToString())); } // Read and discard string otherwise else { while (context.Current != (int)'"') { if (!this.PullCharacter(context, out current)) { this.OnError(context.Position, "invalid character in string value"); return false; } } } context.Pull(); return true; case (int)'-': case (int)'.': case (int)'0': case (int)'1': case (int)'2': case (int)'3': case (int)'4': case (int)'5': case (int)'6': case (int)'7': case (int)'8': case (int)'9': unchecked { numberMantissa = 0; numberPower = 0; // Read number sign if (context.Current == (int)'-') { context.Pull(); numberMantissaMask = ~0UL; numberMantissaPlus = 1; } else { numberMantissaMask = 0; numberMantissaPlus = 0; } // Read integral part for (; context.Current >= (int)'0' && context.Current <= (int)'9'; context.Pull()) { if (numberMantissa > Reader.MANTISSA_MAX) { ++numberPower; continue; } numberMantissa = numberMantissa*10 + (ulong)(context.Current - (int)'0'); } // Read decimal part if any if (context.Current == (int)'.') { context.Pull(); for (; context.Current >= (int)'0' && context.Current <= (int)'9'; context.Pull()) { if (numberMantissa > Reader.MANTISSA_MAX) continue; numberMantissa = numberMantissa*10 + (ulong)(context.Current - (int)'0'); --numberPower; } } // Read exponent if any if (context.Current == (int)'E' || context.Current == (int)'e') { context.Pull(); switch (context.Current) { case (int)'+': context.Pull(); numberExponentMask = 0; numberExponentPlus = 0; break; case (int)'-': context.Pull(); numberExponentMask = ~0U; numberExponentPlus = 1; break; default: numberExponentMask = 0; numberExponentPlus = 0; break; } for (numberExponent = 0; context.Current >= (int)'0' && context.Current <= (int)'9'; context.Pull()) numberExponent = numberExponent*10 + (uint)(context.Current - (int)'0'); numberPower += (int)((numberExponent ^ numberExponentMask) + numberExponentPlus); } // Compute result number and assign if needed if (container.value != null) { number = (long)((numberMantissa ^ numberMantissaMask) + numberMantissaPlus) * (decimal)Math.Pow(10, numberPower); container.value(ref target, Value.FromNumber(number)); } } return true; case (int)'f': context.Pull(); if (!this.PullExpected(context, 'a') || !this.PullExpected(context, 'l') || !this.PullExpected(context, 's') || !this.PullExpected(context, 'e')) return false; if (container.value != null) container.value(ref target, Value.FromBoolean(false)); return true; case (int)'n': context.Pull(); if (!this.PullExpected(context, 'u') || !this.PullExpected(context, 'l') || !this.PullExpected(context, 'l')) return false; if (container.value != null) container.value(ref target, Value.Void); return true; case (int)'t': context.Pull(); if (!this.PullExpected(context, 'r') || !this.PullExpected(context, 'u') || !this.PullExpected(context, 'e')) return false; if (container.value != null) container.value(ref target, Value.FromBoolean(true)); return true; case (int)'[': context.Pull(); for (int index = 0; true; ++index) { this.PullIgnored(context); if (context.Current == (int)']') break; // Read comma separator if any if (index > 0) { if (!this.PullExpected(context, ',')) return false; this.PullIgnored(context); } // Build and move to array index node = container.fields; if (index > 9) { foreach (char digit in index.ToString(CultureInfo.InvariantCulture)) node = node.Follow(digit); } else node = node.Follow((char)('0' + index)); // Read array value if (!node.Enter(ref target, this, context)) return false; } context.Pull(); return true; case (int)'{': context.Pull(); for (int index = 0; true; ++index) { this.PullIgnored(context); if (context.Current == (int)'}') break; // Read comma separator if any if (index > 0) { if (!this.PullExpected(context, ',')) return false; this.PullIgnored(context); } if (!this.PullExpected(context, '"')) return false; // Read and move to object key node = container.fields; while (context.Current != (int)'"') { if (!this.PullCharacter(context, out current)) { this.OnError(context.Position, "invalid character in object key"); return false; } node = node.Follow(current); } context.Pull(); // Read object separator this.PullIgnored(context); if (!this.PullExpected(context, ':')) return false; // Read object value this.PullIgnored(context); if (!node.Enter(ref target, this, context)) return false; } context.Pull(); return true; default: this.OnError(context.Position, "expected array, object or value"); return false; } } public bool Start(Stream stream, out ReaderContext context) { context = new ReaderContext(stream, this.encoding); this.PullIgnored(context); if (context.Current < 0) { this.OnError(context.Position, "empty input stream"); return false; } return true; } public void Stop(ReaderContext context) { } #endregion #region Methods / Private private void OnError(int position, string message) { ParserError error; error = this.Error; if (error != null) error(position, message); } private bool PullCharacter(ReaderContext context, out char character) { int nibble; int previous; int value; previous = context.Current; context.Pull(); if (previous < 0) { character = default (char); return false; } if (previous != (int)'\\') { character = (char)previous; return true; } previous = context.Current; context.Pull(); switch (previous) { case -1: character = default (char); return false; case (int)'"': character = '"'; return true; case (int)'\\': character = '\\'; return true; case (int)'b': character = '\b'; return true; case (int)'f': character = '\f'; return true; case (int)'n': character = '\n'; return true; case (int)'r': character = '\r'; return true; case (int)'t': character = '\t'; return true; case (int)'u': value = 0; for (int i = 0; i < 4; ++i) { previous = context.Current; context.Pull(); if (previous >= (int)'0' && previous <= (int)'9') nibble = previous - (int)'0'; else if (previous >= (int)'A' && previous <= (int)'F') nibble = previous - (int)'A' + 10; else if (previous >= (int)'a' && previous <= (int)'f') nibble = previous - (int)'a' + 10; else { this.OnError(context.Position, "unknown character in unicode escape sequence"); character = default (char); return false; } value = (value << 4) + nibble; } character = (char)value; return true; default: character = (char)previous; return true; } } private bool PullExpected(ReaderContext context, char expected) { if (context.Current != (int)expected) { this.OnError(context.Position, string.Format(CultureInfo.InvariantCulture, "expected '{0}'", expected)); return false; } context.Pull(); return true; } private void PullIgnored(ReaderContext context) { int current; while (true) { current = context.Current; if (current < 0 || current > (int)' ') return; context.Pull(); } } #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.Win32; using VSRegistry = Microsoft.VisualStudio.Shell.VSRegistry; namespace Microsoft.VisualStudio.Project { /// <summary> /// Provides implementation IVsSingleFileGeneratorFactory for /// </summary> public class SingleFileGeneratorFactory : IVsSingleFileGeneratorFactory { #region nested types private class GeneratorMetaData { #region fields private Guid generatorClsid = Guid.Empty; private int generatesDesignTimeSource = -1; private int generatesSharedDesignTimeSource = -1; private int useDesignTimeCompilationFlag = -1; object generator; #endregion #region ctor /// <summary> /// Constructor /// </summary> public GeneratorMetaData() { } #endregion #region Public Properties /// <summary> /// Generator instance /// </summary> public Object Generator { get { return generator; } set { generator = value; } } /// <summary> /// GeneratesDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> public int GeneratesDesignTimeSource { get { return generatesDesignTimeSource; } set { generatesDesignTimeSource = value; } } /// <summary> /// GeneratesSharedDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> public int GeneratesSharedDesignTimeSource { get { return generatesSharedDesignTimeSource; } set { generatesSharedDesignTimeSource = value; } } /// <summary> /// UseDesignTimeCompilationFlag reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> public int UseDesignTimeCompilationFlag { get { return useDesignTimeCompilationFlag; } set { useDesignTimeCompilationFlag = value; } } /// <summary> /// Generator Class ID. /// </summary> public Guid GeneratorClsid { get { return generatorClsid; } set { generatorClsid = value; } } #endregion } #endregion #region fields /// <summary> /// Base generator registry key for MPF based project /// </summary> private RegistryKey baseGeneratorRegistryKey; /// <summary> /// CLSID reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string GeneratorClsid = "CLSID"; /// <summary> /// GeneratesDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string GeneratesDesignTimeSource = "GeneratesDesignTimeSource"; /// <summary> /// GeneratesSharedDesignTimeSource reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string GeneratesSharedDesignTimeSource = "GeneratesSharedDesignTimeSource"; /// <summary> /// UseDesignTimeCompilationFlag reg value name under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[VsVer]\Generators\[ProjFacGuid]\[GeneratorProgId] /// </summary> private string UseDesignTimeCompilationFlag = "UseDesignTimeCompilationFlag"; /// <summary> /// Caches all the generators registered for the project type. /// </summary> private Dictionary<string, GeneratorMetaData> generatorsMap = new Dictionary<string, GeneratorMetaData>(); /// <summary> /// The project type guid of the associated project. /// </summary> private Guid projectType; /// <summary> /// A service provider /// </summary> private System.IServiceProvider serviceProvider; #endregion #region ctors /// <summary> /// Constructor for SingleFileGeneratorFactory /// </summary> /// <param name="projectGuid">The project type guid of the associated project.</param> /// <param name="serviceProvider">A service provider.</param> public SingleFileGeneratorFactory(Guid projectType, System.IServiceProvider serviceProvider) { this.projectType = projectType; this.serviceProvider = serviceProvider; } #endregion #region properties /// <summary> /// Defines the project type guid of the associated project. /// </summary> public Guid ProjectGuid { get { return this.projectType; } set { this.projectType = value; } } /// <summary> /// Defines an associated service provider. /// </summary> public System.IServiceProvider ServiceProvider { get { return this.serviceProvider; } set { this.serviceProvider = value; } } #endregion #region IVsSingleFileGeneratorFactory Helpers /// <summary> /// Returns the project generator key under [VS-ConfigurationRoot]]\Generators /// </summary> private RegistryKey BaseGeneratorsKey { get { if(this.baseGeneratorRegistryKey == null) { using(RegistryKey root = VSRegistry.RegistryRoot(__VsLocalRegistryType.RegType_Configuration)) { if(null != root) { string regPath = "Generators\\" + this.ProjectGuid.ToString("B"); baseGeneratorRegistryKey = root.OpenSubKey(regPath); } } } return this.baseGeneratorRegistryKey; } } /// <summary> /// Returns the local registry instance /// </summary> private ILocalRegistry LocalRegistry { get { return this.serviceProvider.GetService(typeof(SLocalRegistry)) as ILocalRegistry; } } #endregion #region IVsSingleFileGeneratorFactory Members /// <summary> /// Creates an instance of the single file generator requested /// </summary> /// <param name="progId">prog id of the generator to be created. For e.g HKLM\SOFTWARE\Microsoft\VisualStudio\9.0Exp\Generators\[prjfacguid]\[wszProgId]</param> /// <param name="generatesDesignTimeSource">GeneratesDesignTimeSource key value</param> /// <param name="generatesSharedDesignTimeSource">GeneratesSharedDesignTimeSource key value</param> /// <param name="useTempPEFlag">UseDesignTimeCompilationFlag key value</param> /// <param name="generate">IVsSingleFileGenerator interface</param> /// <returns>S_OK if succesful</returns> public virtual int CreateGeneratorInstance(string progId, out int generatesDesignTimeSource, out int generatesSharedDesignTimeSource, out int useTempPEFlag, out IVsSingleFileGenerator generate) { Guid genGuid; ErrorHandler.ThrowOnFailure(this.GetGeneratorInformation(progId, out generatesDesignTimeSource, out generatesSharedDesignTimeSource, out useTempPEFlag, out genGuid)); //Create the single file generator and pass it out. Check to see if it is in the cache if(!this.generatorsMap.ContainsKey(progId) || ((this.generatorsMap[progId]).Generator == null)) { Guid riid = VSConstants.IID_IUnknown; uint dwClsCtx = (uint)CLSCTX.CLSCTX_INPROC_SERVER; IntPtr genIUnknown = IntPtr.Zero; //create a new one. ErrorHandler.ThrowOnFailure(this.LocalRegistry.CreateInstance(genGuid, null, ref riid, dwClsCtx, out genIUnknown)); if(genIUnknown != IntPtr.Zero) { try { object generator = Marshal.GetObjectForIUnknown(genIUnknown); //Build the generator meta data object and cache it. GeneratorMetaData genData = new GeneratorMetaData(); genData.GeneratesDesignTimeSource = generatesDesignTimeSource; genData.GeneratesSharedDesignTimeSource = generatesSharedDesignTimeSource; genData.UseDesignTimeCompilationFlag = useTempPEFlag; genData.GeneratorClsid = genGuid; genData.Generator = generator; this.generatorsMap[progId] = genData; } finally { Marshal.Release(genIUnknown); } } } generate = (this.generatorsMap[progId]).Generator as IVsSingleFileGenerator; return VSConstants.S_OK; } /// <summary> /// Gets the default generator based on the file extension. HKLM\Software\Microsoft\VS\9.0\Generators\[prjfacguid]\.extension /// </summary> /// <param name="filename">File name with extension</param> /// <param name="progID">The generator prog ID</param> /// <returns>S_OK if successful</returns> public virtual int GetDefaultGenerator(string filename, out string progID) { progID = ""; return VSConstants.E_NOTIMPL; } /// <summary> /// Gets the generator information. /// </summary> /// <param name="progId">prog id of the generator to be created. For e.g HKLM\SOFTWARE\Microsoft\VisualStudio\9.0Exp\Generators\[prjfacguid]\[wszProgId]</param> /// <param name="generatesDesignTimeSource">GeneratesDesignTimeSource key value</param> /// <param name="generatesSharedDesignTimeSource">GeneratesSharedDesignTimeSource key value</param> /// <param name="useTempPEFlag">UseDesignTimeCompilationFlag key value</param> /// <param name="guiddGenerator">CLSID key value</param> /// <returns>S_OK if succesful</returns> public virtual int GetGeneratorInformation(string progId, out int generatesDesignTimeSource, out int generatesSharedDesignTimeSource, out int useTempPEFlag, out Guid guidGenerator) { RegistryKey genKey; generatesDesignTimeSource = -1; generatesSharedDesignTimeSource = -1; useTempPEFlag = -1; guidGenerator = Guid.Empty; if(string.IsNullOrEmpty(progId)) return VSConstants.S_FALSE; //Create the single file generator and pass it out. if(!this.generatorsMap.ContainsKey(progId)) { // We have to check whether the BaseGeneratorkey returns null. RegistryKey tempBaseGeneratorKey = this.BaseGeneratorsKey; if(tempBaseGeneratorKey == null || (genKey = tempBaseGeneratorKey.OpenSubKey(progId)) == null) { return VSConstants.S_FALSE; } //Get the CLSID string guid = (string)genKey.GetValue(GeneratorClsid, ""); if(string.IsNullOrEmpty(guid)) return VSConstants.S_FALSE; GeneratorMetaData genData = new GeneratorMetaData(); genData.GeneratorClsid = guidGenerator = new Guid(guid); //Get the GeneratesDesignTimeSource flag. Assume 0 if not present. genData.GeneratesDesignTimeSource = generatesDesignTimeSource = (int)genKey.GetValue(this.GeneratesDesignTimeSource, 0); //Get the GeneratesSharedDesignTimeSource flag. Assume 0 if not present. genData.GeneratesSharedDesignTimeSource = generatesSharedDesignTimeSource = (int)genKey.GetValue(GeneratesSharedDesignTimeSource, 0); //Get the UseDesignTimeCompilationFlag flag. Assume 0 if not present. genData.UseDesignTimeCompilationFlag = useTempPEFlag = (int)genKey.GetValue(UseDesignTimeCompilationFlag, 0); this.generatorsMap.Add(progId, genData); } else { GeneratorMetaData genData = this.generatorsMap[progId]; generatesDesignTimeSource = genData.GeneratesDesignTimeSource; //Get the GeneratesSharedDesignTimeSource flag. Assume 0 if not present. generatesSharedDesignTimeSource = genData.GeneratesSharedDesignTimeSource; //Get the UseDesignTimeCompilationFlag flag. Assume 0 if not present. useTempPEFlag = genData.UseDesignTimeCompilationFlag; //Get the CLSID guidGenerator = genData.GeneratorClsid; } return VSConstants.S_OK; } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>DomainCategory</c> resource.</summary> public sealed partial class DomainCategoryName : gax::IResourceName, sys::IEquatable<DomainCategoryName> { /// <summary>The possible contents of <see cref="DomainCategoryName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> CustomerCampaignBase64CategoryLanguageCode = 1, } private static gax::PathTemplate s_customerCampaignBase64CategoryLanguageCode = new gax::PathTemplate("customers/{customer_id}/domainCategories/{campaign_id_base64_category_language_code}"); /// <summary>Creates a <see cref="DomainCategoryName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="DomainCategoryName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static DomainCategoryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DomainCategoryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DomainCategoryName"/> with the pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DomainCategoryName"/> constructed from the provided ids.</returns> public static DomainCategoryName FromCustomerCampaignBase64CategoryLanguageCode(string customerId, string campaignId, string base64CategoryId, string languageCodeId) => new DomainCategoryName(ResourceNameType.CustomerCampaignBase64CategoryLanguageCode, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), base64CategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)), languageCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </returns> public static string Format(string customerId, string campaignId, string base64CategoryId, string languageCodeId) => FormatCustomerCampaignBase64CategoryLanguageCode(customerId, campaignId, base64CategoryId, languageCodeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </returns> public static string FormatCustomerCampaignBase64CategoryLanguageCode(string customerId, string campaignId, string base64CategoryId, string languageCodeId) => s_customerCampaignBase64CategoryLanguageCode.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="DomainCategoryName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DomainCategoryName"/> if successful.</returns> public static DomainCategoryName Parse(string domainCategoryName) => Parse(domainCategoryName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DomainCategoryName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="DomainCategoryName"/> if successful.</returns> public static DomainCategoryName Parse(string domainCategoryName, bool allowUnparsed) => TryParse(domainCategoryName, allowUnparsed, out DomainCategoryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DomainCategoryName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DomainCategoryName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string domainCategoryName, out DomainCategoryName result) => TryParse(domainCategoryName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DomainCategoryName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="DomainCategoryName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string domainCategoryName, bool allowUnparsed, out DomainCategoryName result) { gax::GaxPreconditions.CheckNotNull(domainCategoryName, nameof(domainCategoryName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignBase64CategoryLanguageCode.TryParseName(domainCategoryName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCampaignBase64CategoryLanguageCode(resourceName[0], split1[0], split1[1], split1[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(domainCategoryName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private DomainCategoryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string base64CategoryId = null, string campaignId = null, string customerId = null, string languageCodeId = null) { Type = type; UnparsedResource = unparsedResourceName; Base64CategoryId = base64CategoryId; CampaignId = campaignId; CustomerId = customerId; LanguageCodeId = languageCodeId; } /// <summary> /// Constructs a new instance of a <see cref="DomainCategoryName"/> class from the component parts of pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> public DomainCategoryName(string customerId, string campaignId, string base64CategoryId, string languageCodeId) : this(ResourceNameType.CustomerCampaignBase64CategoryLanguageCode, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), base64CategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)), languageCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Base64Category</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string Base64CategoryId { get; } /// <summary> /// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>LanguageCode</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string LanguageCodeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCampaignBase64CategoryLanguageCode: return s_customerCampaignBase64CategoryLanguageCode.Expand(CustomerId, $"{CampaignId}~{Base64CategoryId}~{LanguageCodeId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DomainCategoryName); /// <inheritdoc/> public bool Equals(DomainCategoryName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DomainCategoryName a, DomainCategoryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DomainCategoryName a, DomainCategoryName b) => !(a == b); } public partial class DomainCategory { /// <summary> /// <see cref="DomainCategoryName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal DomainCategoryName ResourceNameAsDomainCategoryName { get => string.IsNullOrEmpty(ResourceName) ? null : DomainCategoryName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Diagnostics; namespace System.Threading.Tasks.Tests { public class TaskContinueWhenAnyTests { #region TaskFactory.ContinueWhenAny tests [Fact] public static void RunContinueWhenAnyTests() { TaskCompletionSource<int> tcs = null; ManualResetEvent mre1 = null; ManualResetEvent mre2 = null; Task[] antecedents; Task continuation = null; for (int i = 0; i < 2; i++) { bool antecedentsAreFutures = (i == 0); for (int j = 0; j < 2; j++) { bool continuationIsFuture = (j == 0); for (int k = 0; k < 2; k++) { bool preCanceledToken = (k == 0); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; if (preCanceledToken) cts.Cancel(); for (int x = 0; x < 2; x++) { bool longRunning = (x == 0); TaskContinuationOptions tco = longRunning ? TaskContinuationOptions.LongRunning : TaskContinuationOptions.None; for (int y = 0; y < 2; y++) { bool preCompletedTask = (y == 0); for (int z = 0; z < 2; z++) { bool useFutureFactory = (z == 0); // This would be a nonsensical combination if (useFutureFactory && !continuationIsFuture) continue; //Assert.True(false, string.Format(" - Test Task{5}.Factory.ContinueWhenAny(Task{0}[]({1} completed), {2}, ct({3}), {4}, ts.Default)", // antecedentsAreFutures ? "<int>" : "", // preCompletedTask ? 1 : 0, // continuationIsFuture ? "func" : "action", // preCanceledToken ? "signaled" : "unsignaled", // tco, // useFutureFactory ? "<int>" : "")); TaskScheduler ts = TaskScheduler.Default; if (antecedentsAreFutures) antecedents = new Task<int>[3]; else antecedents = new Task[3]; tcs = new TaskCompletionSource<int>(); mre1 = new ManualResetEvent(false); mre2 = new ManualResetEvent(false); continuation = null; if (antecedentsAreFutures) { antecedents[0] = new Task<int>(() => { mre2.WaitOne(); return 0; }); antecedents[1] = new Task<int>(() => { mre1.WaitOne(); return 1; }); antecedents[2] = new Task<int>(() => { mre2.WaitOne(); return 2; }); } else { antecedents[0] = new Task(() => { mre2.WaitOne(); tcs.TrySetResult(0); }); antecedents[1] = new Task(() => { mre1.WaitOne(); tcs.TrySetResult(1); }); antecedents[2] = new Task(() => { mre2.WaitOne(); tcs.TrySetResult(2); }); } if (preCompletedTask) { mre1.Set(); antecedents[1].Start(); antecedents[1].Wait(); } if (continuationIsFuture) { if (antecedentsAreFutures) { if (useFutureFactory) { continuation = Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { tcs.TrySetResult(t.Result); return 10; }, ct, tco, ts); } else { continuation = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => { tcs.TrySetResult(t.Result); return 10; }, ct, tco, ts); } } else // antecedents are tasks { if (useFutureFactory) { continuation = Task<int>.Factory.ContinueWhenAny(antecedents, _ => 10, ct, tco, ts); } else { continuation = Task.Factory.ContinueWhenAny<int>(antecedents, _ => 10, ct, tco, ts); } } } else // continuation is task { if (antecedentsAreFutures) { continuation = Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => tcs.TrySetResult(t.Result), ct, tco, ts); } else { continuation = Task.Factory.ContinueWhenAny(antecedents, _ => { }, ct, tco, ts); } } // If we have a pre-canceled token, the continuation should have completed by now Assert.False(preCanceledToken && !continuation.IsCompleted, " > FAILED. Continuation should complete early on pre-canceled ct"); // Slightly different than the previous assert: // We should only have completed by now if we have a preCanceledToken or a preCompletedTask Assert.True(!continuation.IsCompleted || preCompletedTask || preCanceledToken, " > FAILED! Continuation should fire early only if (preCanceledToken or preCompletedTask)(1)."); // Kick off our antecedents array startTaskArray(antecedents); //Thread.Sleep(50); // re-assert that the only way that the continuation should have completed by now is preCompletedTask or preCanceledToken Assert.True(!continuation.IsCompleted || preCompletedTask || preCanceledToken, " > FAILED! Continuation should fire early only if (preCanceledToken or preCompletedTask)(2)."); // signal mre1 if we have not done so already if (!preCompletedTask) mre1.Set(); Exception ex = null; int result = 0; try { if (continuationIsFuture) result = ((Task<int>)continuation).Result; else continuation.Wait(); } catch (Exception e) { ex = e; } Assert.True((ex == null) == !preCanceledToken, "RunContinueWhenAnyTests: > FAILED! continuation.Wait() should throw exception iff preCanceledToken"); if (preCanceledToken) { if (ex == null) { Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (no exception thrown)")); ; } else if (ex.GetType() != typeof(AggregateException)) { Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (didn't throw aggregate exception)")); } else if (((AggregateException)ex).InnerException.GetType() != typeof(TaskCanceledException)) { ex = ((AggregateException)ex).InnerException; Assert.True(false, string.Format("RunContinueWhenAnyTests: > FAILED! Expected AE<TCE> from continuation.Wait() (threw " + ex.GetType().Name + " instead of TaskCanceledException)")); } } Assert.True(preCanceledToken || (tcs.Task.Result == 1), "RunContinueWhenAnyTests: > FAILED! Wrong task was recorded as completed."); Assert.True((result == 10) || !continuationIsFuture || preCanceledToken, "RunContinueWhenAnyTests:> FAILED! continuation yielded wrong result"); Assert.Equal((continuation.CreationOptions & TaskCreationOptions.LongRunning) != 0, longRunning); Assert.True((continuation.CreationOptions == TaskCreationOptions.None) || longRunning, "continuation CreationOptions should be None unless longRunning is true"); // Allow remaining antecedents to finish mre2.Set(); // Make sure that you wait for the antecedents to complete. // When this line wasn't here, antecedent completion could sneak into // the next loop iteration, causing tcs to be set to 0 or 2 instead of 1, // resulting in intermittent test failures. Task.WaitAll(antecedents); // We don't need to call this for every combination of i/j/k/x/y/z. So only // call under these conditions. if (preCanceledToken && longRunning && preCompletedTask) { TestContinueWhenAnyException(antecedents, useFutureFactory, continuationIsFuture); } } //end z-loop (useFutureFactory) } // end y-loop (preCompletedTask) } // end x-loop (longRunning) } // end k-loop (preCanceledToken) } // end j-loop (continuationIsFuture) } // end i-loop (antecedentsAreFutures) } private static void TestContinueWhenAnyException(Task[] antecedents, bool FutureFactory, bool continuationIsFuture) { bool antecedentsAreFutures = (antecedents as Task<int>[]) != null; Debug.WriteLine(" * Test Exceptions in TaskFactory{0}.ContinueWhenAny(Task{1}[],Task{2})", FutureFactory ? "<TResult>" : "", antecedentsAreFutures ? "<TResult>" : "", continuationIsFuture ? "<TResult>" : ""); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken ct = cts.Token; cts.Cancel(); Task t1 = Task.Factory.StartNew(() => { }); Task<int> f1 = Task<int>.Factory.StartNew(() => 10); Task[] dummyTasks = new Task[] { t1 }; Task<int>[] dummyFutures = new Task<int>[] { f1 }; if (FutureFactory) //TaskFactory<TResult> methods { if (antecedentsAreFutures) { Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny<int>(null, t => 0); }); var cFuture = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, ct); CheckForCorrectCT(cFuture, ct); antecedents[0] = null; Assert.Throws<ArgumentException>( () => { Task<int>.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => 0); }); AssertExtensions.Throws<ArgumentException>("tasks", () => Task<int>.Factory.ContinueWhenAny(new Task<int>[0], t => 0)); // // Test for exception on null continuation function // Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, TaskContinuationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny<int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); }); } else //antecedents are tasks { var dummy = Task.Factory.StartNew(delegate { }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task<int>.Factory.ContinueWhenAny(new Task[] { dummy }, t => 0, TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously); }); dummy.Wait(); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny(antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task<int>.Factory.ContinueWhenAny(antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny(null, t => 0); }); var cTask = Task.Factory.ContinueWhenAny(antecedents, t => 0, ct); CheckForCorrectCT(cTask, ct); antecedents[0] = null; Assert.Throws<ArgumentException>( () => { Task<int>.Factory.ContinueWhenAny(antecedents, (t) => 0); }); AssertExtensions.Throws<ArgumentException>("tasks", () => Task<int>.Factory.ContinueWhenAny(new Task[0], t => 0)); // // Test for exception on null continuation function // Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, TaskContinuationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { Task<int>.Factory.ContinueWhenAny(dummyTasks, (Func<Task, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); }); } } else //TaskFactory methods { //test exceptions if (continuationIsFuture) { if (antecedentsAreFutures) { Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int, int>(null, t => 0); }); var cTask = Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0, ct); CheckForCorrectCT(cTask, ct); antecedents[0] = null; Assert.Throws<ArgumentException>( () => { Task.Factory.ContinueWhenAny<int, int>((Task<int>[])antecedents, t => 0); }); AssertExtensions.Throws<ArgumentException>("tasks", () => Task.Factory.ContinueWhenAny(new Task<int>[0], t => 0)); // // Test for exception on null continuation function // Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, TaskContinuationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int, int>(dummyFutures, (Func<Task<int>, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); }); } else // antecedents are tasks { Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(antecedents, t => 0, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Factory.ContinueWhenAny<int>(antecedents, t => 0, TaskContinuationOptions.NotOnFaulted); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(null, t => 0); }); var cTask = Task.Factory.ContinueWhenAny(antecedents, delegate (Task t) { }, ct); CheckForCorrectCT(cTask, ct); antecedents[0] = null; Assert.Throws<ArgumentException>( () => { Task.Factory.ContinueWhenAny<int>(antecedents, t => 0); }); AssertExtensions.Throws<ArgumentException>("tasks", () => Task.Factory.ContinueWhenAny(new Task[0], t => 0)); // // Test for exception on null continuation function // Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, TaskContinuationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyTasks, (Func<Task, int>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); }); } } else //Continuation is task { if (antecedentsAreFutures) { Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, TaskContinuationOptions.NotOnFaulted); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(null, t => { }); }); var cTask = Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }, ct); CheckForCorrectCT(cTask, ct); antecedents[0] = null; Assert.Throws<ArgumentException>( () => { Task.Factory.ContinueWhenAny<int>((Task<int>[])antecedents, t => { }); }); AssertExtensions.Throws<ArgumentException>("tasks", () => Task.Factory.ContinueWhenAny(new Task<int>[] { }, t => { })); // // Test for exception on null continuation action // Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, TaskContinuationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny<int>(dummyFutures, (Action<Task<int>>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); }); } else // antecedents are tasks { Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny(antecedents, t => { }, CancellationToken.None, TaskContinuationOptions.None, (TaskScheduler)null); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Factory.ContinueWhenAny(antecedents, t => { }, TaskContinuationOptions.NotOnFaulted); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny(null, t => { }); }); var task = Task.Factory.ContinueWhenAny(antecedents, t => { }, ct); CheckForCorrectCT(task, ct); antecedents[0] = null; Assert.Throws<ArgumentException>( () => { Task.Factory.ContinueWhenAny(antecedents, t => { }); }); AssertExtensions.Throws<ArgumentException>("tasks",() => Task.Factory.ContinueWhenAny(new Task[0], t => { })); // // Test for exception on null continuation action // Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, CancellationToken.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, TaskContinuationOptions.None); }); Assert.Throws<ArgumentNullException>( () => { Task.Factory.ContinueWhenAny(dummyTasks, (Action<Task>)null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default); }); } } } } #endregion #region Helper Methods // used in ContinueWhenAll/ContinueWhenAny tests private static void startTaskArray(Task[] tasks) { for (int i = 0; i < tasks.Length; i++) { if (tasks[i].Status == TaskStatus.Created) tasks[i].Start(); } } private static void CheckForCorrectCT(Task canceledTask, CancellationToken correctToken) { try { canceledTask.Wait(); Assert.True(false, string.Format(" > FAILED! Pre-canceled result did not throw from Wait()")); } catch (AggregateException ae) { ae.Flatten().Handle(e => { var tce = e as TaskCanceledException; if (tce == null) { Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw non-TCE from Wait()")); } else if (tce.CancellationToken != correctToken) { Assert.True(false, string.Format(" > FAILED! Pre-canceled result threw TCE w/ wrong token")); } return true; }); } } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace DennyTalk { public partial class DialogForm : Form { public event EventHandler<MessageSendEventArgs> MessageSend; public event EventHandler<FilesSendEventArgs> FilesSend; private Bitmap accountAvatar; private string accountNick; private Address accountAddress; public DialogForm() { InitializeComponent(); } public DialogUserControl GetDialog(Address address) { foreach (DialogTabPage page in tabControl1.TabPages) { if (page.UserInfo.Address.Equals(address)) { return page.Dialog; } } return null; } public DialogUserControl AddDialog(ContactEx contactInfo, IEnumerable<Message> messages) { DialogTabPage page = new DialogTabPage(); page.UserInfo = contactInfo; tabControl1.TabPages.Add(page); tabControl1.SelectedTab = page; SetText(contactInfo); if (!Visible) { page.ImageIndex = 14; } page.Dialog.AccountAddress = AccountAddress; page.Dialog.AccountNick = AccountNick; page.Dialog.AccountAvatar = AccountAvatar; page.Dialog.GotFocus += new EventHandler(Dialog_GotFocus); return page.Dialog; } void Dialog_GotFocus(object sender, EventArgs e) { ResetPageImage(); } public bool HasDialog(Address address) { foreach (DialogTabPage page in tabControl1.TabPages) { if (page.UserInfo.Address.Equals(address)) { return true; } } return false; } public bool HasDialog(ContactEx contactInfo) { foreach (DialogTabPage page in tabControl1.TabPages) { if (page.UserInfo.Equals(contactInfo)) { return true; } } return false; } public DialogUserControl SelectDialog(Address address) { foreach (DialogTabPage page in tabControl1.TabPages) { if (page.UserInfo.Address.Equals(address)) { tabControl1.SelectedTab = page; return page.Dialog; } } if (!Visible) Show(); return null; } public DialogUserControl SelectDialog(ContactEx contactInfo) { foreach (DialogTabPage page in tabControl1.TabPages) { if (page.UserInfo.Equals(contactInfo)) { tabControl1.SelectedTab = page; page.ImageIndex = (int)page.Dialog.UserInfo.Status; return page.Dialog; } } return null; } void SetText(ContactEx user) { if (string.IsNullOrEmpty(user.Nick)) Text = user.Address.Host; else Text = user.Nick; } private void DialogForm_Load(object sender, EventArgs e) { } private void btnSend_Click(object sender, EventArgs e) { SendMessage(); textBox1.Focus(); } private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { textBox1.Focus(); if (tabControl1.SelectedTab != null) { ContactEx user = ((DialogTabPage)tabControl1.SelectedTab).UserInfo; SetText(user); if (ContactSelected != null) { ContactSelected(this, new ContactInfoEventArgs(user)); } } } public DialogUserControl SelectedDialog { get { DialogTabPage page = (DialogTabPage)tabControl1.SelectedTab; if (page == null) { return null; } return page.Dialog; } } public void ResetPageImage(Address address) { Control dialog = GetDialog(address); if (dialog != null) { DialogTabPage page = (DialogTabPage)dialog.Parent; ResetPageImage(page); } } public void ResetPageImage() { if (tabControl1.SelectedTab != null) { ResetPageImage(tabControl1.SelectedTab); } } public void ResetPageImage(TabPage page) { if (page != null) page.ImageIndex = (int)((DialogTabPage)page).Dialog.UserInfo.Status; } private void SendFiles() { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (FilesSend != null) FilesSend(this, new FilesSendEventArgs(openFileDialog1.FileNames, ((DialogTabPage)tabControl1.SelectedTab).UserInfo)); } } private void SendMessage() { if (MessageSend != null) { if (textBox1.Text == "") return; MessageSendEventArgs e = new MessageSendEventArgs(textBox1.Text, ((DialogTabPage)tabControl1.SelectedTab).UserInfo.Address); MessageSend(this, e); if (e.ID > 0) textBox1.Text = ""; } } private void textBox1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: if (!e.Control) { SendMessage(); e.SuppressKeyPress = true; } break; } } private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { } private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { } public void CloseAllDialogs() { foreach (DialogTabPage page in this.tabControl1.TabPages) { page.Controls.Remove(page); page.Dialog.Dispose(); } this.tabControl1.TabPages.Clear(); } public Address AccountAddress { get { return accountAddress; } set { accountAddress = value; } } public string AccountNick { get { return accountNick; } set { accountNick = value; } } public Bitmap AccountAvatar { get { return accountAvatar; } set { accountAvatar = value; } } private void addToContactListToolStripMenuItem_Click(object sender, EventArgs e) { DialogTabPage tab = (DialogTabPage)tabControl1.SelectedTab; ContactAdd(this, new ContactInfoEventArgs(tab.Dialog.UserInfo)); } protected virtual void OnContactAdd(ContactEx user) { if (ContactAdd != null) { ContactAdd(this, new ContactInfoEventArgs(user)); } } private void tabControl1_MouseDown(object sender, MouseEventArgs e) { DialogTabPage page = null; for (int i = 0; i < tabControl1.TabPages.Count;i++) { Rectangle rect = tabControl1.GetTabRect(i); if (rect.Contains(e.Location)) { page = (DialogTabPage)tabControl1.TabPages[i]; break; } } if (page != null) { OnTabMouseDown(e, page); } } protected virtual void OnTabMouseDown(MouseEventArgs e, DialogTabPage tabPage) { tabControl1.SelectedTab = tabPage; if (e.Button == MouseButtons.Right) { this.contextMenuStrip1.Show(Cursor.Position); } } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { DialogTabPage page = (DialogTabPage)tabControl1.SelectedTab; if (page == null) return; DialogUserControl dialog = page.Dialog; page.Controls.Remove(dialog); page.Dialog.Dispose(); tabControl1.TabPages.Remove(page); if (tabControl1.TabPages.Count == 0) Close(); } public void Initialize() { IntPtr formHandle = this.Handle; foreach (Control control in this.Controls) { IntPtr handle = control.Handle; InitControls(control); } } private void InitControls(Control control) { foreach (Control x in control.Controls) { IntPtr handle = x.Handle; InitControls(x); } } public void ShowTopMost() { //this.TopMost = true; this.Focus(); //this.Select(); //this.TopMost = false; } public void SetDialogImageAsNewMessage(Address address) { if (!WinFormsHelper.IsFocused(this)) { WinFormsHelper.StartBlinking(this); } DialogUserControl dialog = GetDialog(address); if (dialog != null) { DialogTabPage page = (DialogTabPage)dialog.Parent; //if (page != tabControl1.SelectedTab && !WinFormsHelper.IsFocused(page)) page.ImageIndex = 14; } } private void DialogForm_Activated(object sender, EventArgs e) { WinFormsHelper.StopBlinking(this); ResetPageImage(); } private void btnSendFile_Click(object sender, EventArgs e) { SendFiles(); } public event EventHandler<ContactInfoEventArgs> ContactAdd; public event EventHandler<ContactInfoEventArgs> ContactSelected; } }
// 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\Arm\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void LoadVector128_Double() { var test = new LoadUnaryOpTest__LoadVector128_Double(); if (test.IsSupported) { // Validates basic functionality works test.RunBasicScenario_Load(); // Validates calling via reflection works test.RunReflectionScenario_Load(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class LoadUnaryOpTest__LoadVector128_Double { private struct DataTable { private byte[] inArray1; private byte[] outArray; private GCHandle inHandle1; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private DataTable _dataTable; public LoadUnaryOpTest__LoadVector128_Double() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.LoadVector128( (Double*)(_dataTable.inArray1Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.LoadVector128), new Type[] { typeof(Double*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArray1Ptr, typeof(Double*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); Succeeded = false; try { RunBasicScenario_Load(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(firstOp[0]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(firstOp[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.LoadVector128)}<Double>(Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = 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.Diagnostics; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; namespace System.Reflection.Metadata { partial class MetadataReader { internal const string ClrPrefix = "<CLR>"; internal static readonly byte[] WinRTPrefix = new[] { (byte)'<', (byte)'W', (byte)'i', (byte)'n', (byte)'R', (byte)'T', (byte)'>' }; #region Projection Tables // Maps names of projected types to projection information for each type. // Both arrays are of the same length and sorted by the type name. private static string[] s_projectedTypeNames; private static ProjectionInfo[] s_projectionInfos; private readonly struct ProjectionInfo { public readonly string WinRTNamespace; public readonly StringHandle.VirtualIndex ClrNamespace; public readonly StringHandle.VirtualIndex ClrName; public readonly AssemblyReferenceHandle.VirtualIndex AssemblyRef; public readonly TypeDefTreatment Treatment; public readonly TypeRefSignatureTreatment SignatureTreatment; public readonly bool IsIDisposable; public ProjectionInfo( string winRtNamespace, StringHandle.VirtualIndex clrNamespace, StringHandle.VirtualIndex clrName, AssemblyReferenceHandle.VirtualIndex clrAssembly, TypeDefTreatment treatment = TypeDefTreatment.RedirectedToClrType, TypeRefSignatureTreatment signatureTreatment = TypeRefSignatureTreatment.None, bool isIDisposable = false) { this.WinRTNamespace = winRtNamespace; this.ClrNamespace = clrNamespace; this.ClrName = clrName; this.AssemblyRef = clrAssembly; this.Treatment = treatment; this.SignatureTreatment = signatureTreatment; this.IsIDisposable = isIDisposable; } } private TypeDefTreatment GetWellKnownTypeDefinitionTreatment(TypeDefinitionHandle typeDef) { InitializeProjectedTypes(); StringHandle name = TypeDefTable.GetName(typeDef); int index = StringHeap.BinarySearchRaw(s_projectedTypeNames, name); if (index < 0) { return TypeDefTreatment.None; } StringHandle namespaceName = TypeDefTable.GetNamespace(typeDef); if (StringHeap.EqualsRaw(namespaceName, StringHeap.GetVirtualString(s_projectionInfos[index].ClrNamespace))) { return s_projectionInfos[index].Treatment; } // TODO: we can avoid this comparison if info.DotNetNamespace == info.WinRtNamespace if (StringHeap.EqualsRaw(namespaceName, s_projectionInfos[index].WinRTNamespace)) { return s_projectionInfos[index].Treatment | TypeDefTreatment.MarkInternalFlag; } return TypeDefTreatment.None; } private int GetProjectionIndexForTypeReference(TypeReferenceHandle typeRef, out bool isIDisposable) { InitializeProjectedTypes(); int index = StringHeap.BinarySearchRaw(s_projectedTypeNames, TypeRefTable.GetName(typeRef)); if (index >= 0 && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), s_projectionInfos[index].WinRTNamespace)) { isIDisposable = s_projectionInfos[index].IsIDisposable; return index; } isIDisposable = false; return -1; } internal static AssemblyReferenceHandle GetProjectedAssemblyRef(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return AssemblyReferenceHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].AssemblyRef); } internal static StringHandle GetProjectedName(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrName); } internal static StringHandle GetProjectedNamespace(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return StringHandle.FromVirtualIndex(s_projectionInfos[projectionIndex].ClrNamespace); } internal static TypeRefSignatureTreatment GetProjectedSignatureTreatment(int projectionIndex) { Debug.Assert(s_projectionInfos != null && projectionIndex >= 0 && projectionIndex < s_projectionInfos.Length); return s_projectionInfos[projectionIndex].SignatureTreatment; } private static void InitializeProjectedTypes() { if (s_projectedTypeNames == null || s_projectionInfos == null) { var systemRuntimeWindowsRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime; var systemRuntime = AssemblyReferenceHandle.VirtualIndex.System_Runtime; var systemObjectModel = AssemblyReferenceHandle.VirtualIndex.System_ObjectModel; var systemRuntimeWindowsUiXaml = AssemblyReferenceHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml; var systemRuntimeInterop = AssemblyReferenceHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime; var systemNumericsVectors = AssemblyReferenceHandle.VirtualIndex.System_Numerics_Vectors; // sorted by name var keys = new string[50]; var values = new ProjectionInfo[50]; int k = 0, v = 0; // WARNING: Keys must be sorted by name and must only contain ASCII characters. WinRTNamespace must also be ASCII only. keys[k++] = "AttributeTargets"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeTargets, systemRuntime); keys[k++] = "AttributeUsageAttribute"; values[v++] = new ProjectionInfo("Windows.Foundation.Metadata", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.AttributeUsageAttribute, systemRuntime, treatment: TypeDefTreatment.RedirectedToClrAttribute); keys[k++] = "Color"; values[v++] = new ProjectionInfo("Windows.UI", StringHandle.VirtualIndex.Windows_UI, StringHandle.VirtualIndex.Color, systemRuntimeWindowsRuntime); keys[k++] = "CornerRadius"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.CornerRadius, systemRuntimeWindowsUiXaml); keys[k++] = "DateTime"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.DateTimeOffset, systemRuntime); keys[k++] = "Duration"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Duration, systemRuntimeWindowsUiXaml); keys[k++] = "DurationType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.DurationType, systemRuntimeWindowsUiXaml); keys[k++] = "EventHandler`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.EventHandler1, systemRuntime); keys[k++] = "EventRegistrationToken"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime, StringHandle.VirtualIndex.EventRegistrationToken, systemRuntimeInterop); keys[k++] = "GeneratorPosition"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Controls.Primitives", StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives, StringHandle.VirtualIndex.GeneratorPosition, systemRuntimeWindowsUiXaml); keys[k++] = "GridLength"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridLength, systemRuntimeWindowsUiXaml); keys[k++] = "GridUnitType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.GridUnitType, systemRuntimeWindowsUiXaml); keys[k++] = "HResult"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Exception, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass); keys[k++] = "IBindableIterable"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IEnumerable, systemRuntime); keys[k++] = "IBindableVector"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections, StringHandle.VirtualIndex.IList, systemRuntime); keys[k++] = "IClosable"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.IDisposable, systemRuntime, isIDisposable: true); keys[k++] = "ICommand"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Input", StringHandle.VirtualIndex.System_Windows_Input, StringHandle.VirtualIndex.ICommand, systemObjectModel); keys[k++] = "IIterable`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IEnumerable1, systemRuntime); keys[k++] = "IKeyValuePair`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.KeyValuePair2, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType); keys[k++] = "IMapView`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyDictionary2, systemRuntime); keys[k++] = "IMap`2"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IDictionary2, systemRuntime); keys[k++] = "INotifyCollectionChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.INotifyCollectionChanged, systemObjectModel); keys[k++] = "INotifyPropertyChanged"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.INotifyPropertyChanged, systemObjectModel); keys[k++] = "IReference`1"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Nullable1, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToValueType); keys[k++] = "IVectorView`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IReadOnlyList1, systemRuntime); keys[k++] = "IVector`1"; values[v++] = new ProjectionInfo("Windows.Foundation.Collections", StringHandle.VirtualIndex.System_Collections_Generic, StringHandle.VirtualIndex.IList1, systemRuntime); keys[k++] = "KeyTime"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.KeyTime, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media", StringHandle.VirtualIndex.Windows_UI_Xaml_Media, StringHandle.VirtualIndex.Matrix, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3D"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Media3D", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D, StringHandle.VirtualIndex.Matrix3D, systemRuntimeWindowsUiXaml); keys[k++] = "Matrix3x2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix3x2, systemNumericsVectors); keys[k++] = "Matrix4x4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Matrix4x4, systemNumericsVectors); keys[k++] = "NotifyCollectionChangedAction"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedAction, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs, systemObjectModel); keys[k++] = "NotifyCollectionChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System_Collections_Specialized, StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler, systemObjectModel); keys[k++] = "Plane"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Plane, systemNumericsVectors); keys[k++] = "Point"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Point, systemRuntimeWindowsRuntime); keys[k++] = "PropertyChangedEventArgs"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventArgs, systemObjectModel); keys[k++] = "PropertyChangedEventHandler"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Data", StringHandle.VirtualIndex.System_ComponentModel, StringHandle.VirtualIndex.PropertyChangedEventHandler, systemObjectModel); keys[k++] = "Quaternion"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Quaternion, systemNumericsVectors); keys[k++] = "Rect"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Rect, systemRuntimeWindowsRuntime); keys[k++] = "RepeatBehavior"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehavior, systemRuntimeWindowsUiXaml); keys[k++] = "RepeatBehaviorType"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Media.Animation", StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation, StringHandle.VirtualIndex.RepeatBehaviorType, systemRuntimeWindowsUiXaml); keys[k++] = "Size"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.Windows_Foundation, StringHandle.VirtualIndex.Size, systemRuntimeWindowsRuntime); keys[k++] = "Thickness"; values[v++] = new ProjectionInfo("Windows.UI.Xaml", StringHandle.VirtualIndex.Windows_UI_Xaml, StringHandle.VirtualIndex.Thickness, systemRuntimeWindowsUiXaml); keys[k++] = "TimeSpan"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.TimeSpan, systemRuntime); keys[k++] = "TypeName"; values[v++] = new ProjectionInfo("Windows.UI.Xaml.Interop", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Type, systemRuntime, signatureTreatment: TypeRefSignatureTreatment.ProjectedToClass); keys[k++] = "Uri"; values[v++] = new ProjectionInfo("Windows.Foundation", StringHandle.VirtualIndex.System, StringHandle.VirtualIndex.Uri, systemRuntime); keys[k++] = "Vector2"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector2, systemNumericsVectors); keys[k++] = "Vector3"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector3, systemNumericsVectors); keys[k++] = "Vector4"; values[v++] = new ProjectionInfo("Windows.Foundation.Numerics", StringHandle.VirtualIndex.System_Numerics, StringHandle.VirtualIndex.Vector4, systemNumericsVectors); Debug.Assert(k == keys.Length && v == keys.Length && k == v); AssertSorted(keys); s_projectedTypeNames = keys; s_projectionInfos = values; } } [Conditional("DEBUG")] private static void AssertSorted(string[] keys) { for (int i = 0; i < keys.Length - 1; i++) { Debug.Assert(String.CompareOrdinal(keys[i], keys[i + 1]) < 0); } } // test only internal static string[] GetProjectedTypeNames() { InitializeProjectedTypes(); return s_projectedTypeNames; } #endregion private static uint TreatmentAndRowId(byte treatment, int rowId) { return ((uint)treatment << TokenTypeIds.RowIdBitCount) | (uint)rowId; } #region TypeDef [MethodImpl(MethodImplOptions.NoInlining)] internal uint CalculateTypeDefTreatmentAndRowId(TypeDefinitionHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); TypeDefTreatment treatment; TypeAttributes flags = TypeDefTable.GetFlags(handle); EntityHandle extends = TypeDefTable.GetExtends(handle); if ((flags & TypeAttributes.WindowsRuntime) != 0) { if (_metadataKind == MetadataKind.WindowsMetadata) { treatment = GetWellKnownTypeDefinitionTreatment(handle); if (treatment != TypeDefTreatment.None) { return TreatmentAndRowId((byte)treatment, handle.RowId); } // Is this an attribute? if (extends.Kind == HandleKind.TypeReference && IsSystemAttribute((TypeReferenceHandle)extends)) { treatment = TypeDefTreatment.NormalAttribute; } else { treatment = TypeDefTreatment.NormalNonAttribute; } } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && NeedsWinRTPrefix(flags, extends)) { // WinMDExp emits two versions of RuntimeClasses and Enums: // // public class Foo {} // the WinRT reference class // internal class <CLR>Foo {} // the implementation class that we want WinRT consumers to ignore // // The adapter's job is to undo WinMDExp's transformations. I.e. turn the above into: // // internal class <WinRT>Foo {} // the WinRT reference class that we want CLR consumers to ignore // public class Foo {} // the implementation class // // We only add the <WinRT> prefix here since the WinRT view is the only view that is marked WindowsRuntime // De-mangling the CLR name is done below. // tomat: The CLR adapter implements a back-compat quirk: Enums exported with an older WinMDExp have only one version // not marked with tdSpecialName. These enums should *not* be mangled and flipped to private. // We don't implement this flag since the WinMDs produced by the older WinMDExp are not used in the wild. treatment = TypeDefTreatment.PrefixWinRTName; } else { treatment = TypeDefTreatment.None; } // Scan through Custom Attributes on type, looking for interesting bits. We only // need to do this for RuntimeClasses if ((treatment == TypeDefTreatment.PrefixWinRTName || treatment == TypeDefTreatment.NormalNonAttribute)) { if ((flags & TypeAttributes.Interface) == 0 && HasAttribute(handle, "Windows.UI.Xaml", "TreatAsAbstractComposableClassAttribute")) { treatment |= TypeDefTreatment.MarkAbstractFlag; } } } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && IsClrImplementationType(handle)) { // <CLR> implementation classes are not marked WindowsRuntime, but still need to be modified // by the adapter. treatment = TypeDefTreatment.UnmangleWinRTName; } else { treatment = TypeDefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } private bool IsClrImplementationType(TypeDefinitionHandle typeDef) { var attrs = TypeDefTable.GetFlags(typeDef); if ((attrs & (TypeAttributes.VisibilityMask | TypeAttributes.SpecialName)) != TypeAttributes.SpecialName) { return false; } return StringHeap.StartsWithRaw(TypeDefTable.GetName(typeDef), ClrPrefix); } #endregion #region TypeRef internal uint CalculateTypeRefTreatmentAndRowId(TypeReferenceHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); bool isIDisposable; int projectionIndex = GetProjectionIndexForTypeReference(handle, out isIDisposable); if (projectionIndex >= 0) { return TreatmentAndRowId((byte)TypeRefTreatment.UseProjectionInfo, projectionIndex); } else { return TreatmentAndRowId((byte)GetSpecialTypeRefTreatment(handle), handle.RowId); } } private TypeRefTreatment GetSpecialTypeRefTreatment(TypeReferenceHandle handle) { if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System")) { StringHandle name = TypeRefTable.GetName(handle); if (StringHeap.EqualsRaw(name, "MulticastDelegate")) { return TypeRefTreatment.SystemDelegate; } if (StringHeap.EqualsRaw(name, "Attribute")) { return TypeRefTreatment.SystemAttribute; } } return TypeRefTreatment.None; } private bool IsSystemAttribute(TypeReferenceHandle handle) { return StringHeap.EqualsRaw(TypeRefTable.GetNamespace(handle), "System") && StringHeap.EqualsRaw(TypeRefTable.GetName(handle), "Attribute"); } private bool NeedsWinRTPrefix(TypeAttributes flags, EntityHandle extends) { if ((flags & (TypeAttributes.VisibilityMask | TypeAttributes.Interface)) != TypeAttributes.Public) { return false; } if (extends.Kind != HandleKind.TypeReference) { return false; } // Check if the type is a delegate, struct, or attribute TypeReferenceHandle extendsRefHandle = (TypeReferenceHandle)extends; if (StringHeap.EqualsRaw(TypeRefTable.GetNamespace(extendsRefHandle), "System")) { StringHandle nameHandle = TypeRefTable.GetName(extendsRefHandle); if (StringHeap.EqualsRaw(nameHandle, "MulticastDelegate") || StringHeap.EqualsRaw(nameHandle, "ValueType") || StringHeap.EqualsRaw(nameHandle, "Attribute")) { return false; } } return true; } #endregion #region MethodDef private uint CalculateMethodDefTreatmentAndRowId(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = MethodDefTreatment.Implementation; TypeDefinitionHandle parentTypeDef = GetDeclaringType(methodDef); TypeAttributes parentFlags = TypeDefTable.GetFlags(parentTypeDef); if ((parentFlags & TypeAttributes.WindowsRuntime) != 0) { if (IsClrImplementationType(parentTypeDef)) { treatment = MethodDefTreatment.Implementation; } else if (parentFlags.IsNested()) { treatment = MethodDefTreatment.Implementation; } else if ((parentFlags & TypeAttributes.Interface) != 0) { treatment = MethodDefTreatment.InterfaceMethod; } else if (_metadataKind == MetadataKind.ManagedWindowsMetadata && (parentFlags & TypeAttributes.Public) == 0) { treatment = MethodDefTreatment.Implementation; } else { treatment = MethodDefTreatment.Other; var parentBaseType = TypeDefTable.GetExtends(parentTypeDef); if (parentBaseType.Kind == HandleKind.TypeReference) { switch (GetSpecialTypeRefTreatment((TypeReferenceHandle)parentBaseType)) { case TypeRefTreatment.SystemAttribute: treatment = MethodDefTreatment.AttributeMethod; break; case TypeRefTreatment.SystemDelegate: treatment = MethodDefTreatment.DelegateMethod | MethodDefTreatment.MarkPublicFlag; break; } } } } if (treatment == MethodDefTreatment.Other) { // we want to hide the method if it implements // only redirected interfaces // We also want to check if the methodImpl is IClosable.Close, // so we can change the name bool seenRedirectedInterfaces = false; bool seenNonRedirectedInterfaces = false; bool isIClosableClose = false; foreach (var methodImplHandle in new MethodImplementationHandleCollection(this, parentTypeDef)) { MethodImplementation methodImpl = GetMethodImplementation(methodImplHandle); if (methodImpl.MethodBody == methodDef) { EntityHandle declaration = methodImpl.MethodDeclaration; // See if this MethodImpl implements a redirected interface // In WinMD, MethodImpl will always use MemberRef and TypeRefs to refer to redirected interfaces, // even if they are in the same module. if (declaration.Kind == HandleKind.MemberReference && ImplementsRedirectedInterface((MemberReferenceHandle)declaration, out isIClosableClose)) { seenRedirectedInterfaces = true; if (isIClosableClose) { // This method implements IClosable.Close // Let's rename to IDisposable later // Once we know this implements IClosable.Close, we are done // looking break; } } else { // Now we know this implements a non-redirected interface // But we need to keep looking, just in case we got a methodimpl that // implements the IClosable.Close method and needs to be renamed seenNonRedirectedInterfaces = true; } } } if (isIClosableClose) { treatment = MethodDefTreatment.DisposeMethod; } else if (seenRedirectedInterfaces && !seenNonRedirectedInterfaces) { // Only hide if all the interfaces implemented are redirected treatment = MethodDefTreatment.HiddenInterfaceImplementation; } } // If treatment is other, then this is a non-managed WinRT runtime class definition // Find out about various bits that we apply via attributes and name parsing if (treatment == MethodDefTreatment.Other) { treatment |= GetMethodTreatmentFromCustomAttributes(methodDef); } return TreatmentAndRowId((byte)treatment, methodDef.RowId); } private MethodDefTreatment GetMethodTreatmentFromCustomAttributes(MethodDefinitionHandle methodDef) { MethodDefTreatment treatment = 0; foreach (var caHandle in GetCustomAttributes(methodDef)) { StringHandle namespaceHandle, nameHandle; if (!GetAttributeTypeNameRaw(caHandle, out namespaceHandle, out nameHandle)) { continue; } Debug.Assert(!namespaceHandle.IsVirtual && !nameHandle.IsVirtual); if (StringHeap.EqualsRaw(namespaceHandle, "Windows.UI.Xaml")) { if (StringHeap.EqualsRaw(nameHandle, "TreatAsPublicMethodAttribute")) { treatment |= MethodDefTreatment.MarkPublicFlag; } if (StringHeap.EqualsRaw(nameHandle, "TreatAsAbstractMethodAttribute")) { treatment |= MethodDefTreatment.MarkAbstractFlag; } } } return treatment; } #endregion #region FieldDef /// <summary> /// The backing field of a WinRT enumeration type is not public although the backing fields /// of managed enumerations are. To allow managed languages to directly access this field, /// it is made public by the metadata adapter. /// </summary> private uint CalculateFieldDefTreatmentAndRowId(FieldDefinitionHandle handle) { var flags = FieldTable.GetFlags(handle); FieldDefTreatment treatment = FieldDefTreatment.None; if ((flags & FieldAttributes.RTSpecialName) != 0 && StringHeap.EqualsRaw(FieldTable.GetName(handle), "value__")) { TypeDefinitionHandle typeDef = GetDeclaringType(handle); EntityHandle baseTypeHandle = TypeDefTable.GetExtends(typeDef); if (baseTypeHandle.Kind == HandleKind.TypeReference) { var typeRef = (TypeReferenceHandle)baseTypeHandle; if (StringHeap.EqualsRaw(TypeRefTable.GetName(typeRef), "Enum") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(typeRef), "System")) { treatment = FieldDefTreatment.EnumValue; } } } return TreatmentAndRowId((byte)treatment, handle.RowId); } #endregion #region MemberRef private uint CalculateMemberRefTreatmentAndRowId(MemberReferenceHandle handle) { MemberRefTreatment treatment; // We need to rename the MemberRef for IClosable.Close as well // so that the MethodImpl for the Dispose method can be correctly shown // as IDisposable.Dispose instead of IDisposable.Close bool isIDisposable; if (ImplementsRedirectedInterface(handle, out isIDisposable) && isIDisposable) { treatment = MemberRefTreatment.Dispose; } else { treatment = MemberRefTreatment.None; } return TreatmentAndRowId((byte)treatment, handle.RowId); } /// <summary> /// We want to know if a given method implements a redirected interface. /// For example, if we are given the method RemoveAt on a class "A" /// which implements the IVector interface (which is redirected /// to IList in .NET) then this method would return true. The most /// likely reason why we would want to know this is that we wish to hide /// (mark private) all methods which implement methods on a redirected /// interface. /// </summary> /// <param name="memberRef">The declaration token for the method</param> /// <param name="isIDisposable"> /// Returns true if the redirected interface is <see cref="IDisposable"/>. /// </param> /// <returns>True if the method implements a method on a redirected interface. /// False otherwise.</returns> private bool ImplementsRedirectedInterface(MemberReferenceHandle memberRef, out bool isIDisposable) { isIDisposable = false; EntityHandle parent = MemberRefTable.GetClass(memberRef); TypeReferenceHandle typeRef; if (parent.Kind == HandleKind.TypeReference) { typeRef = (TypeReferenceHandle)parent; } else if (parent.Kind == HandleKind.TypeSpecification) { BlobHandle blob = TypeSpecTable.GetSignature((TypeSpecificationHandle)parent); BlobReader sig = new BlobReader(BlobHeap.GetMemoryBlock(blob)); if (sig.Length < 2 || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_GENERICINST || sig.ReadByte() != (byte)CorElementType.ELEMENT_TYPE_CLASS) { return false; } EntityHandle token = sig.ReadTypeHandle(); if (token.Kind != HandleKind.TypeReference) { return false; } typeRef = (TypeReferenceHandle)token; } else { return false; } return GetProjectionIndexForTypeReference(typeRef, out isIDisposable) >= 0; } #endregion #region AssemblyRef private int FindMscorlibAssemblyRefNoProjection() { for (int i = 1; i <= AssemblyRefTable.NumberOfNonVirtualRows; i++) { if (StringHeap.EqualsRaw(AssemblyRefTable.GetName(i), "mscorlib")) { return i; } } throw new BadImageFormatException(SR.WinMDMissingMscorlibRef); } #endregion #region CustomAttribute internal CustomAttributeValueTreatment CalculateCustomAttributeValueTreatment(CustomAttributeHandle handle) { Debug.Assert(_metadataKind != MetadataKind.Ecma335); var parent = CustomAttributeTable.GetParent(handle); // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (!IsWindowsAttributeUsageAttribute(parent, handle)) { return CustomAttributeValueTreatment.None; } var targetTypeDef = (TypeDefinitionHandle)parent; if (StringHeap.EqualsRaw(TypeDefTable.GetNamespace(targetTypeDef), "Windows.Foundation.Metadata")) { if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "VersionAttribute")) { return CustomAttributeValueTreatment.AttributeUsageVersionAttribute; } if (StringHeap.EqualsRaw(TypeDefTable.GetName(targetTypeDef), "DeprecatedAttribute")) { return CustomAttributeValueTreatment.AttributeUsageDeprecatedAttribute; } } bool allowMultiple = HasAttribute(targetTypeDef, "Windows.Foundation.Metadata", "AllowMultipleAttribute"); return allowMultiple ? CustomAttributeValueTreatment.AttributeUsageAllowMultiple : CustomAttributeValueTreatment.AttributeUsageAllowSingle; } private bool IsWindowsAttributeUsageAttribute(EntityHandle targetType, CustomAttributeHandle attributeHandle) { // Check for Windows.Foundation.Metadata.AttributeUsageAttribute. // WinMD rules: // - The attribute is only applicable on TypeDefs. // - Constructor must be a MemberRef with TypeRef. if (targetType.Kind != HandleKind.TypeDefinition) { return false; } var attributeCtor = CustomAttributeTable.GetConstructor(attributeHandle); if (attributeCtor.Kind != HandleKind.MemberReference) { return false; } var attributeType = MemberRefTable.GetClass((MemberReferenceHandle)attributeCtor); if (attributeType.Kind != HandleKind.TypeReference) { return false; } var attributeTypeRef = (TypeReferenceHandle)attributeType; return StringHeap.EqualsRaw(TypeRefTable.GetName(attributeTypeRef), "AttributeUsageAttribute") && StringHeap.EqualsRaw(TypeRefTable.GetNamespace(attributeTypeRef), "Windows.Foundation.Metadata"); } private bool HasAttribute(EntityHandle token, string asciiNamespaceName, string asciiTypeName) { foreach (var caHandle in GetCustomAttributes(token)) { StringHandle namespaceName, typeName; if (GetAttributeTypeNameRaw(caHandle, out namespaceName, out typeName) && StringHeap.EqualsRaw(typeName, asciiTypeName) && StringHeap.EqualsRaw(namespaceName, asciiNamespaceName)) { return true; } } return false; } private bool GetAttributeTypeNameRaw(CustomAttributeHandle caHandle, out StringHandle namespaceName, out StringHandle typeName) { namespaceName = typeName = default(StringHandle); EntityHandle typeDefOrRef = GetAttributeTypeRaw(caHandle); if (typeDefOrRef.IsNil) { return false; } if (typeDefOrRef.Kind == HandleKind.TypeReference) { TypeReferenceHandle typeRef = (TypeReferenceHandle)typeDefOrRef; var resolutionScope = TypeRefTable.GetResolutionScope(typeRef); if (!resolutionScope.IsNil && resolutionScope.Kind == HandleKind.TypeReference) { // we don't need to handle nested types return false; } // other resolution scopes don't affect full name typeName = TypeRefTable.GetName(typeRef); namespaceName = TypeRefTable.GetNamespace(typeRef); } else if (typeDefOrRef.Kind == HandleKind.TypeDefinition) { TypeDefinitionHandle typeDef = (TypeDefinitionHandle)typeDefOrRef; if (TypeDefTable.GetFlags(typeDef).IsNested()) { // we don't need to handle nested types return false; } typeName = TypeDefTable.GetName(typeDef); namespaceName = TypeDefTable.GetNamespace(typeDef); } else { // invalid metadata return false; } return true; } /// <summary> /// Returns the type definition or reference handle of the attribute type. /// </summary> /// <returns><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/> or nil token if the metadata is invalid and the type can't be determined.</returns> private EntityHandle GetAttributeTypeRaw(CustomAttributeHandle handle) { var ctor = CustomAttributeTable.GetConstructor(handle); if (ctor.Kind == HandleKind.MethodDefinition) { return GetDeclaringType((MethodDefinitionHandle)ctor); } if (ctor.Kind == HandleKind.MemberReference) { // In general the parent can be MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec. // For attributes only TypeDef and TypeRef are applicable. EntityHandle typeDefOrRef = MemberRefTable.GetClass((MemberReferenceHandle)ctor); HandleKind handleType = typeDefOrRef.Kind; if (handleType == HandleKind.TypeReference || handleType == HandleKind.TypeDefinition) { return typeDefOrRef; } } return default(EntityHandle); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="RuleSettings.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System; using System.Xml; using System.Configuration; using System.Collections.Specialized; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.ComponentModel; using System.Web.Hosting; using System.Web.Util; using System.Web.Configuration; using System.Web.Management; using System.Web.Compilation; using System.Security.Permissions; public sealed class RuleSettings : ConfigurationElement { internal static int DEFAULT_MIN_INSTANCES = 1; internal static int DEFAULT_MAX_LIMIT = int.MaxValue; internal static TimeSpan DEFAULT_MIN_INTERVAL = TimeSpan.Zero; internal static string DEFAULT_CUSTOM_EVAL = null; private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propName = new ConfigurationProperty("name", typeof(string), null, null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired | ConfigurationPropertyOptions.IsKey); private static readonly ConfigurationProperty _propEventName = new ConfigurationProperty("eventName", typeof(string), String.Empty, ConfigurationPropertyOptions.IsRequired); private static readonly ConfigurationProperty _propProvider = new ConfigurationProperty("provider", typeof(string), String.Empty, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propProfile = new ConfigurationProperty("profile", typeof(string), String.Empty, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMinInstances = new ConfigurationProperty("minInstances", typeof(int), DEFAULT_MIN_INSTANCES, null, StdValidatorsAndConverters.NonZeroPositiveIntegerValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMaxLimit = new ConfigurationProperty("maxLimit", typeof(int), DEFAULT_MAX_LIMIT, new InfiniteIntConverter(), StdValidatorsAndConverters.PositiveIntegerValidator, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propMinInterval = new ConfigurationProperty("minInterval", typeof(TimeSpan), DEFAULT_MIN_INTERVAL, StdValidatorsAndConverters.InfiniteTimeSpanConverter, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propCustom = new ConfigurationProperty("custom", typeof(string), String.Empty, ConfigurationPropertyOptions.None); static RuleSettings() { // Property initialization _properties = new ConfigurationPropertyCollection(); _properties.Add(_propName); _properties.Add(_propEventName); _properties.Add(_propProvider); _properties.Add(_propProfile); _properties.Add(_propMinInstances); _properties.Add(_propMaxLimit); _properties.Add(_propMinInterval); _properties.Add(_propCustom); } internal RuleSettings() { } public RuleSettings(String name, String eventName, String provider) : this() { Name = name; EventName = eventName; Provider = provider; } public RuleSettings(String name, String eventName, String provider, String profile, int minInstances, int maxLimit, TimeSpan minInterval) : this(name, eventName, provider) { Profile = profile; MinInstances = minInstances; MaxLimit = maxLimit; MinInterval = minInterval; } public RuleSettings(String name, String eventName, String provider, String profile, int minInstances, int maxLimit, TimeSpan minInterval, string custom) : this(name, eventName, provider) { Profile = profile; MinInstances = minInstances; MaxLimit = maxLimit; MinInterval = minInterval; Custom = custom; } protected override ConfigurationPropertyCollection Properties { get { return _properties; } } [ConfigurationProperty("name", IsRequired = true, IsKey = true, DefaultValue = "")] [StringValidator(MinLength = 1)] public String Name { get { return (string)base[_propName]; } set { base[_propName] = value; } } [ConfigurationProperty("eventName", IsRequired = true, DefaultValue = "")] public String EventName { get { return (string)base[_propEventName]; } set { base[_propEventName] = value; } } [ConfigurationProperty("custom", DefaultValue = "")] public String Custom { get { return (string)base[_propCustom]; } set { base[_propCustom] = value; } } [ConfigurationProperty("profile", DefaultValue = "")] public String Profile { get { return (string)base[_propProfile]; } set { base[_propProfile] = value; } } [ConfigurationProperty("provider", DefaultValue = "")] public String Provider { get { return (string)base[_propProvider]; } set { base[_propProvider] = value; } } [ConfigurationProperty("minInstances", DefaultValue = 1)] [IntegerValidator(MinValue = 1)] public int MinInstances { get { return (int)base[_propMinInstances]; } set { base[_propMinInstances] = value; } } [ConfigurationProperty("maxLimit", DefaultValue = int.MaxValue)] [TypeConverter(typeof(InfiniteIntConverter))] [IntegerValidator(MinValue = 0)] public int MaxLimit { get { return (int)base[_propMaxLimit]; } set { base[_propMaxLimit] = value; } } [ConfigurationProperty("minInterval", DefaultValue = "00:00:00")] [TypeConverter(typeof(InfiniteTimeSpanConverter))] public TimeSpan MinInterval { get { return (TimeSpan)base[_propMinInterval]; } set { base[_propMinInterval] = value; } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using NBitcoin; using WalletWasabi.Blockchain.Blocks; using Xunit; namespace WalletWasabi.Tests.UnitTests { /// <seealso cref="XunitConfiguration.SerialCollectionDefinition"/> [Collection("Serial unit tests collection")] public class BlockNotifierTests { [Fact] public async Task GenesisBlockOnlyAsync() { var chain = new ConcurrentChain(Network.RegTest); using var notifier = CreateNotifier(chain); var blockAwaiter = new EventAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h); var reorgAwaiter = new EventAwaiter<uint256>( h => notifier.OnReorg += h, h => notifier.OnReorg -= h); await notifier.StartAsync(CancellationToken.None); // No block notifications nor reorg notifications await Assert.ThrowsAsync<OperationCanceledException>(() => blockAwaiter.WaitAsync(TimeSpan.FromSeconds(1))); await Assert.ThrowsAsync<OperationCanceledException>(() => reorgAwaiter.WaitAsync(TimeSpan.FromSeconds(1))); Assert.Equal(Network.RegTest.GenesisHash, notifier.BestBlockHash); await notifier.StopAsync(CancellationToken.None); } [Fact] public async Task HitGenesisBlockDuringInitializationAsync() { var chain = new ConcurrentChain(Network.RegTest); foreach (var n in Enumerable.Range(0, 3)) { await AddBlockAsync(chain); } using var notifier = CreateNotifier(chain); var blockAwaiter = new EventAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h); var reorgAwaiter = new EventAwaiter<uint256>( h => notifier.OnReorg += h, h => notifier.OnReorg -= h); await notifier.StartAsync(CancellationToken.None); // No block notifications nor reorg notifications await Assert.ThrowsAsync<OperationCanceledException>(() => blockAwaiter.WaitAsync(TimeSpan.FromSeconds(1))); await Assert.ThrowsAsync<OperationCanceledException>(() => reorgAwaiter.WaitAsync(TimeSpan.FromSeconds(1))); Assert.Equal(chain.Tip.HashBlock, notifier.BestBlockHash); await notifier.StopAsync(CancellationToken.None); } [Fact] public async Task NotifyBlocksAsync() { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1.5)); const int BlockCount = 3; var chain = new ConcurrentChain(Network.RegTest); using var notifier = CreateNotifier(chain); var reorgAwaiter = new EventAwaiter<uint256>( h => notifier.OnReorg += h, h => notifier.OnReorg -= h); await notifier.StartAsync(CancellationToken.None); // Assert that the blocks come in the right order var height = 0; string message = string.Empty; void OnBlockInv(object? blockNotifier, Block b) { uint256 h1 = b.GetHash(); uint256 h2 = chain.GetBlock(height + 1).HashBlock; if (h1 != h2) { message = string.Format("height={0}, [h1] {1} != [h2] {2}", height, h1, h2); cts.Cancel(); return; } height++; if (height == BlockCount) { cts.Cancel(); } } notifier.OnBlock += OnBlockInv; foreach (var n in Enumerable.Range(0, BlockCount)) { await AddBlockAsync(chain); } notifier.TriggerRound(); // Waits at most 1.5s given CancellationTokenSource definition await Task.WhenAny(Task.Delay(Timeout.InfiniteTimeSpan, cts.Token)); Assert.True(string.IsNullOrEmpty(message), message); // Three blocks notifications Assert.Equal(chain.Height, height); // No reorg notifications await Assert.ThrowsAsync<OperationCanceledException>(() => reorgAwaiter.WaitAsync(TimeSpan.FromSeconds(1))); Assert.Equal(chain.Tip.HashBlock, notifier.BestBlockHash); notifier.OnBlock -= OnBlockInv; await notifier.StopAsync(CancellationToken.None); } [Fact] public async Task SimpleReorgAsync() { var chain = new ConcurrentChain(Network.RegTest); using var notifier = CreateNotifier(chain); var blockAwaiter = new EventsAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h, 5); var reorgAwaiter = new EventAwaiter<uint256>( h => notifier.OnReorg += h, h => notifier.OnReorg -= h); await notifier.StartAsync(CancellationToken.None); await AddBlockAsync(chain); var forkPoint = chain.Tip; var blockToBeReorged = await AddBlockAsync(chain); chain.SetTip(forkPoint); await AddBlockAsync(chain, wait: false); await AddBlockAsync(chain, wait: false); await AddBlockAsync(chain); notifier.TriggerRound(); // Three blocks notifications await blockAwaiter.WaitAsync(TimeSpan.FromSeconds(2)); // No reorg notifications var reorgedkBlock = await reorgAwaiter.WaitAsync(TimeSpan.FromSeconds(1)); Assert.Equal(blockToBeReorged.HashBlock, reorgedkBlock); Assert.Equal(chain.Tip.HashBlock, notifier.BestBlockHash); await notifier.StopAsync(CancellationToken.None); } [Fact] public async Task LongChainReorgAsync() { var chain = new ConcurrentChain(Network.RegTest); using var notifier = CreateNotifier(chain); var blockAwaiter = new EventsAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h, 11); var reorgAwaiter = new EventsAwaiter<uint256>( h => notifier.OnReorg += h, h => notifier.OnReorg -= h, 3); await notifier.StartAsync(CancellationToken.None); await AddBlockAsync(chain); var forkPoint = chain.Tip; var firstReorgedChain = new[] { await AddBlockAsync(chain, wait: false), await AddBlockAsync(chain) }; chain.SetTip(forkPoint); var secondReorgedChain = new[] { await AddBlockAsync(chain, wait: false), await AddBlockAsync(chain, wait: false), await AddBlockAsync(chain) }; chain.SetTip(secondReorgedChain[1]); await AddBlockAsync(chain, wait: false); await AddBlockAsync(chain, wait: false); await AddBlockAsync(chain, wait: false); await AddBlockAsync(chain, wait: false); await AddBlockAsync(chain); // Three blocks notifications await blockAwaiter.WaitAsync(TimeSpan.FromSeconds(2)); // No reorg notifications var reorgedkBlock = await reorgAwaiter.WaitAsync(TimeSpan.FromSeconds(1)); var expectedReorgedBlocks = firstReorgedChain.ToList().Concat(new[] { secondReorgedChain[2] }); Assert.Subset(reorgedkBlock.ToHashSet(), expectedReorgedBlocks.Select(x => x.Header.GetHash()).ToHashSet()); Assert.Equal(chain.Tip.HashBlock, notifier.BestBlockHash); await notifier.StopAsync(CancellationToken.None); } [Fact] public async Task SuperFastNodeValidationAsync() { var chain = new ConcurrentChain(Network.RegTest); using var notifier = CreateNotifier(chain); var blockAwaiter = new EventsAwaiter<Block>( h => notifier.OnBlock += h, h => notifier.OnBlock -= h, 144); await notifier.StartAsync(CancellationToken.None); var lastKnownBlock = await AddBlockAsync(chain); foreach (var i in Enumerable.Range(0, 200)) { await AddBlockAsync(chain, wait: false); } await AddBlockAsync(chain, wait: true); notifier.TriggerRound(); Assert.Equal(chain.Tip.HashBlock, notifier.BestBlockHash); var nofifiedBlocks = (await blockAwaiter.WaitAsync(TimeSpan.FromSeconds(1))).ToArray(); var tip = chain.Tip; var pos = nofifiedBlocks.Length - 1; while (tip.HashBlock != nofifiedBlocks[pos].GetHash()) { tip = tip.Previous; } while (pos >= 0) { Assert.Equal(tip.HashBlock, nofifiedBlocks[pos].GetHash()); tip = tip.Previous; pos--; } await notifier.StopAsync(CancellationToken.None); } private BlockNotifier CreateNotifier(ConcurrentChain chain) { var rpc = new MockRpcClient(); rpc.OnGetBestBlockHashAsync = () => Task.FromResult(chain.Tip.HashBlock); rpc.OnGetBlockAsync = (blockHash) => Task.FromResult(Block.CreateBlock(chain.GetBlock(blockHash).Header, rpc.Network)); rpc.OnGetBlockHeaderAsync = (blockHash) => Task.FromResult(chain.GetBlock(blockHash).Header); var notifier = new BlockNotifier(TimeSpan.FromMilliseconds(100), rpc); return notifier; } private async Task<ChainedBlock> AddBlockAsync(ConcurrentChain chain, bool wait = true) { BlockHeader header = Network.RegTest.Consensus.ConsensusFactory.CreateBlockHeader(); header.Nonce = RandomUtils.GetUInt32(); header.HashPrevBlock = chain.Tip.HashBlock; chain.SetTip(header); var block = chain.GetBlock(header.GetHash()); if (wait) { await Task.Delay(TimeSpan.FromSeconds(1)); } return block; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: MemoryErrorLog.cs 776 2011-01-12 21:09:24Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using Mannex; using IDictionary = System.Collections.IDictionary; using CultureInfo = System.Globalization.CultureInfo; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses memory as its /// backing store. /// </summary> /// <remarks> /// All <see cref="MemoryErrorLog"/> instances will share the same memory /// store that is bound to the application (not an instance of this class). /// </remarks> public sealed class MemoryErrorLog : ErrorLog { // // The collection that provides the actual storage for this log // implementation and a lock to guarantee concurrency correctness. // private static EntryCollection _entries; private readonly static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); // // IMPORTANT! The size must be the same for all instances // for the entires collection to be intialized correctly. // private readonly int _size; /// <summary> /// The maximum number of errors that will ever be allowed to be stored /// in memory. /// </summary> public static readonly int MaximumSize = 500; /// <summary> /// The maximum number of errors that will be held in memory by default /// if no size is specified. /// </summary> public static readonly int DefaultSize = 15; /// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// with a default size for maximum recordable entries. /// </summary> public MemoryErrorLog() : this(DefaultSize) {} /// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// with a specific size for maximum recordable entries. /// </summary> public MemoryErrorLog(int size) { if (size < 0 || size > MaximumSize) throw new ArgumentOutOfRangeException("size", size, string.Format("Size must be between 0 and {0}.", MaximumSize)); _size = size; } /// <summary> /// Initializes a new instance of the <see cref="MemoryErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public MemoryErrorLog(IDictionary config) { if (config == null) { _size = DefaultSize; } else { var sizeString = config.Find("size", string.Empty); if (sizeString.Length == 0) { _size = DefaultSize; } else { _size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture); _size = Math.Max(0, Math.Min(MaximumSize, _size)); } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "In-Memory Error Log"; } } /// <summary> /// Logs an error to the application memory. /// </summary> /// <remarks> /// If the log is full then the oldest error entry is removed. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); // // Make a copy of the error to log since the source is mutable. // Assign a new GUID and create an entry for the error. // error = error.CloneObject(); error.ApplicationName = ApplicationName; var newId = Guid.NewGuid(); var entry = new ErrorLogEntry(this, newId.ToString(), error); _lock.EnterWriteLock(); try { var entries = _entries ?? (_entries = new EntryCollection(_size)); entries.Add(entry); } finally { _lock.ExitWriteLock(); } return newId.ToString(); } /// <summary> /// Returns the specified error from application memory, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { _lock.EnterReadLock(); ErrorLogEntry entry; try { if (_entries == null) return null; entry = _entries[id]; } finally { _lock.ExitReadLock(); } if (entry == null) return null; // // Return a copy that the caller can party on. // var error = entry.Error.CloneObject(); return new ErrorLogEntry(this, entry.Id, error); } /// <summary> /// Returns a page of errors from the application memory in /// descending order of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); // // To minimize the time for which we hold the lock, we'll first // grab just references to the entries we need to return. Later, // we'll make copies and return those to the caller. Since Error // is mutable, we don't want to return direct references to our // internal versions since someone could change their state. // ErrorLogEntry[] selectedEntries = null; int totalCount; _lock.EnterReadLock(); try { if (_entries == null) return 0; totalCount = _entries.Count; var startIndex = pageIndex * pageSize; var endIndex = Math.Min(startIndex + pageSize, totalCount); var count = Math.Max(0, endIndex - startIndex); if (count > 0) { selectedEntries = new ErrorLogEntry[count]; var sourceIndex = endIndex; var targetIndex = 0; while (sourceIndex > startIndex) selectedEntries[targetIndex++] = _entries[--sourceIndex]; } } finally { _lock.ExitReadLock(); } if (errorEntryList != null && selectedEntries != null) { // // Return copies of fetched entries. If the Error class would // be immutable then this step wouldn't be necessary. // foreach (var entry in selectedEntries) { var error = entry.Error.CloneObject(); errorEntryList.Add(new ErrorLogEntry(this, entry.Id, error)); } } return totalCount; } sealed class EntryCollection : KeyedCollection<string, ErrorLogEntry> { private readonly int _size; public EntryCollection(int size) { _size = size; } protected override string GetKeyForItem(ErrorLogEntry item) { return item.Id; } protected override void InsertItem(int index, ErrorLogEntry item) { if (Count == _size) RemoveAt(0); base.InsertItem(index, item); } } } }
/* Distributed as part of TiledSharp, Copyright 2012 Marshall Ward * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Xml.Linq; namespace TiledSharp { // TODO: The design here is all wrong. A Tileset should be a list of tiles, // it shouldn't force the user to do so much tile ID management public class TmxTileset : TmxDocument, ITmxElement { public int FirstGid {get; private set;} public string Name {get; private set;} public int TileWidth {get; private set;} public int TileHeight {get; private set;} public int Spacing {get; private set;} public int Margin {get; private set;} public int? Columns {get; private set;} public int? TileCount {get; private set;} public Dictionary<int, TmxTilesetTile> Tiles {get; private set;} public TmxTileOffset TileOffset {get; private set;} public PropertyDict Properties {get; private set;} public TmxImage Image {get; private set;} public TmxList<TmxTerrain> Terrains {get; private set;} // TSX file constructor public TmxTileset(XContainer xDoc, string tmxDir, ICustomLoader customLoader = null) : this(xDoc.Element("tileset"), tmxDir, customLoader) { } // TMX tileset element constructor public TmxTileset(XElement xTileset, string tmxDir = "", ICustomLoader customLoader = null) : base(customLoader) { var xFirstGid = xTileset.Attribute("firstgid"); var source = (string) xTileset.Attribute("source"); if (source != null) { // Prepend the parent TMX directory if necessary source = Path.Combine(tmxDir, source); // source is always preceded by firstgid FirstGid = (int) xFirstGid; // Everything else is in the TSX file var xDocTileset = ReadXml(source); var ts = new TmxTileset(xDocTileset, TmxDirectory, CustomLoader); Name = ts.Name; TileWidth = ts.TileWidth; TileHeight = ts.TileHeight; Spacing = ts.Spacing; Margin = ts.Margin; Columns = ts.Columns; TileCount = ts.TileCount; TileOffset = ts.TileOffset; Image = ts.Image; Terrains = ts.Terrains; Tiles = ts.Tiles; Properties = ts.Properties; } else { // firstgid is always in TMX, but not TSX if (xFirstGid != null) FirstGid = (int) xFirstGid; Name = (string) xTileset.Attribute("name"); TileWidth = (int) xTileset.Attribute("tilewidth"); TileHeight = (int) xTileset.Attribute("tileheight"); Spacing = (int?) xTileset.Attribute("spacing") ?? 0; Margin = (int?) xTileset.Attribute("margin") ?? 0; Columns = (int?) xTileset.Attribute("columns"); TileCount = (int?) xTileset.Attribute("tilecount"); TileOffset = new TmxTileOffset(xTileset.Element("tileoffset")); Image = new TmxImage(xTileset.Element("image"), tmxDir); Terrains = new TmxList<TmxTerrain>(); var xTerrainType = xTileset.Element("terraintypes"); if (xTerrainType != null) { foreach (var e in xTerrainType.Elements("terrain")) Terrains.Add(new TmxTerrain(e)); } Tiles = new Dictionary<int, TmxTilesetTile>(); foreach (var xTile in xTileset.Elements("tile")) { var tile = new TmxTilesetTile(xTile, Terrains, tmxDir); Tiles[tile.Id] = tile; } Properties = new PropertyDict(xTileset.Element("properties")); } } } public class TmxTileOffset { public int X {get; private set;} public int Y {get; private set;} public TmxTileOffset(XElement xTileOffset) { if (xTileOffset == null) { X = 0; Y = 0; } else { X = (int)xTileOffset.Attribute("x"); Y = (int)xTileOffset.Attribute("y"); } } } public class TmxTerrain : ITmxElement { public string Name {get; private set;} public int Tile {get; private set;} public PropertyDict Properties {get; private set;} public TmxTerrain(XElement xTerrain) { Name = (string)xTerrain.Attribute("name"); Tile = (int)xTerrain.Attribute("tile"); Properties = new PropertyDict(xTerrain.Element("properties")); } } public class TmxTilesetTile { public int Id {get; private set;} public Collection<TmxTerrain> TerrainEdges {get; private set;} public double Probability {get; private set;} public string Type { get; private set; } public PropertyDict Properties {get; private set;} public TmxImage Image {get; private set;} public TmxList<TmxObjectGroup> ObjectGroups {get; private set;} public Collection<TmxAnimationFrame> AnimationFrames {get; private set;} // Human-readable aliases to the Terrain markers public TmxTerrain TopLeft { get { return TerrainEdges[0]; } } public TmxTerrain TopRight { get { return TerrainEdges[1]; } } public TmxTerrain BottomLeft { get { return TerrainEdges[2]; } } public TmxTerrain BottomRight { get { return TerrainEdges[3]; } } public TmxTilesetTile(XElement xTile, TmxList<TmxTerrain> Terrains, string tmxDir = "") { Id = (int)xTile.Attribute("id"); TerrainEdges = new Collection<TmxTerrain>(); int result; TmxTerrain edge; var strTerrain = (string)xTile.Attribute("terrain") ?? ",,,"; foreach (var v in strTerrain.Split(',')) { var success = int.TryParse(v, out result); if (success) edge = Terrains[result]; else edge = null; TerrainEdges.Add(edge); // TODO: Assert that TerrainEdges length is 4 } Probability = (double?)xTile.Attribute("probability") ?? 1.0; Type = (string)xTile.Attribute("type"); Image = new TmxImage(xTile.Element("image"), tmxDir); ObjectGroups = new TmxList<TmxObjectGroup>(); foreach (var e in xTile.Elements("objectgroup")) ObjectGroups.Add(new TmxObjectGroup(e)); AnimationFrames = new Collection<TmxAnimationFrame>(); if (xTile.Element("animation") != null) { foreach (var e in xTile.Element("animation").Elements("frame")) AnimationFrames.Add(new TmxAnimationFrame(e)); } Properties = new PropertyDict(xTile.Element("properties")); } } public class TmxAnimationFrame { public int Id {get; private set;} public int Duration {get; private set;} public TmxAnimationFrame(XElement xFrame) { Id = (int)xFrame.Attribute("tileid"); Duration = (int)xFrame.Attribute("duration"); } } }
// 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.Globalization; using System.Reflection; using NUnit.Framework; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine; namespace Microsoft.Build.UnitTests { [TestFixture] public class ScannerTest { /// <summary> /// Tests that we give a useful error position (not 0 for example) /// </summary> /// <owner>danmose</owner> [Test] public void ErrorPosition() { string[,] tests = { { "1==1.1.", "7", "AllowAll"}, // Position of second '.' { "1==0xFG", "7", "AllowAll"}, // Position of G { "1==-0xF", "6", "AllowAll"}, // Position of x { "1234=5678", "6", "AllowAll"}, // Position of '5' { " ", "2", "AllowAll"}, // Position of End of Input { " (", "3", "AllowAll"}, // Position of End of Input { " false or ", "12", "AllowAll"}, // Position of End of Input { " \"foo", "2", "AllowAll"}, // Position of open quote { " @(foo", "2", "AllowAll"}, // Position of @ { " @(", "2", "AllowAll"}, // Position of @ { " $", "2", "AllowAll"}, // Position of $ { " $(foo", "2", "AllowAll"}, // Position of $ { " $(", "2", "AllowAll"}, // Position of $ { " $", "2", "AllowAll"}, // Position of $ { " @(foo)", "2", "AllowProperties"}, // Position of @ { " '@(foo)'", "3", "AllowProperties"}, // Position of @ /* test escaped chars: message shows them escaped so count should include them */ { "'%24%28x' == '%24(x''", "21", "AllowAll"} // Position of extra quote }; // Some errors are caught by the Parser, not merely by the Lexer/Scanner. So we have to do a full Parse, // rather than just calling AdvanceToScannerError(). (The error location is still supplied by the Scanner.) for (int i = 0; i < tests.GetLength(0); i++) { Parser parser = null; try { parser = new Parser(); ParserOptions options = (ParserOptions)Enum.Parse(typeof(ParserOptions), tests[i, 2], true /* case-insensitive */); GenericExpressionNode parsedExpression = parser.Parse(tests[i, 0], null, options); } catch (InvalidProjectFileException ex) { Console.WriteLine(ex.Message); Assertion.Assert("Expression '" + tests[i, 0] + "' should have an error at " + tests[i, 1] + " but it was at " + parser.errorPosition, Convert.ToInt32(tests[i, 1]) == parser.errorPosition); } } } /// <summary> /// Advance to the point of the lexer error. If the error is only caught by the parser, this isn't useful. /// </summary> /// <param name="lexer"></param> private void AdvanceToScannerError(Scanner lexer) { while (true) { if (!lexer.Advance()) break; if (lexer.IsNext(Token.TokenType.EndOfInput)) break; } } /// <summary> /// Tests the special error for "=". /// </summary> /// <owner>danmose</owner> [Test] public void SingleEquals() { Scanner lexer; lexer = new Scanner("a=b", ParserOptions.AllowProperties); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedEqualsInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == "b"); } /// <summary> /// Tests the special errors for "$(" and "$x" and similar cases /// </summary> /// <owner>danmose</owner> [Test] public void IllFormedProperty() { Scanner lexer; lexer = new Scanner("$(", ParserOptions.AllowProperties); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedPropertyCloseParenthesisInCondition"); lexer = new Scanner("$x", ParserOptions.AllowProperties); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedPropertyOpenParenthesisInCondition"); } /// <summary> /// Tests the special errors for "@(" and "@x" and similar cases. /// </summary> /// <owner>danmose</owner> [Test] public void IllFormedItemList() { Scanner lexer; lexer = new Scanner("@(", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedItemListCloseParenthesisInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); lexer = new Scanner("@x", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedItemListOpenParenthesisInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); lexer = new Scanner("@(x", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedItemListCloseParenthesisInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); lexer = new Scanner("@(x->'%(y)", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedItemListQuoteInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); lexer = new Scanner("@(x->'%(y)', 'x", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedItemListQuoteInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); lexer = new Scanner("@(x->'%(y)', 'x'", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedItemListCloseParenthesisInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); } /// <summary> /// Tests the special error for unterminated quotes. /// Note, scanner only understands single quotes. /// </summary> /// <owner>danmose</owner> [Test] public void IllFormedQuotedString() { Scanner lexer; lexer = new Scanner("false or 'abc", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedQuotedStringInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); lexer = new Scanner("\'", ParserOptions.AllowAll); AdvanceToScannerError(lexer); Assertion.Assert(lexer.GetErrorResource() == "IllFormedQuotedStringInCondition"); Assertion.Assert(lexer.UnexpectedlyFound == null); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void NumericSingleTokenTests() { Scanner lexer; lexer = new Scanner("1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("1234", lexer.IsNextString()), 0); lexer = new Scanner("-1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("-1234", lexer.IsNextString()), 0); lexer = new Scanner("+1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("+1234", lexer.IsNextString()), 0); lexer = new Scanner("1234.1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("1234.1234", lexer.IsNextString()), 0); lexer = new Scanner(".1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare(".1234", lexer.IsNextString()), 0); lexer = new Scanner("1234.", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("1234.", lexer.IsNextString()), 0); lexer = new Scanner("0x1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("0x1234", lexer.IsNextString()), 0); lexer = new Scanner("0X1234abcd", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("0X1234abcd", lexer.IsNextString()), 0); lexer = new Scanner("0x1234ABCD", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); Assertion.AssertEquals(String.Compare("0x1234ABCD", lexer.IsNextString()), 0); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void PropsStringsAndBooleanSingleTokenTests() { Scanner lexer = new Scanner("$(foo)", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Property), true); lexer = new Scanner("@(foo)", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.ItemList), true); lexer = new Scanner("abcde", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.String), true); Assertion.AssertEquals(String.Compare("abcde", lexer.IsNextString()), 0); lexer = new Scanner("'abc-efg'", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.String), true); Assertion.AssertEquals(String.Compare("abc-efg", lexer.IsNextString()), 0); lexer = new Scanner("and", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.And), true); Assertion.AssertEquals(String.Compare("and", lexer.IsNextString()), 0); lexer = new Scanner("or", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Or), true); Assertion.AssertEquals(String.Compare("or", lexer.IsNextString()), 0); lexer = new Scanner("AnD", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.And), true); Assertion.AssertEquals(String.Compare("AnD", lexer.IsNextString()), 0); lexer = new Scanner("Or", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Or), true); Assertion.AssertEquals(String.Compare("Or", lexer.IsNextString()), 0); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void SimpleSingleTokenTests () { Scanner lexer = new Scanner("(", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.LeftParenthesis), true); lexer = new Scanner(")", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.RightParenthesis), true); lexer = new Scanner(",", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Comma), true); lexer = new Scanner("==", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.EqualTo), true); lexer = new Scanner("!=", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.NotEqualTo), true); lexer = new Scanner("<", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.LessThan), true); lexer = new Scanner(">", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.GreaterThan), true); lexer = new Scanner("<=", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.LessThanOrEqualTo), true); lexer = new Scanner(">=", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo), true); lexer = new Scanner("!", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Not), true); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void StringEdgeTests() { Scanner lexer; lexer = new Scanner("@(Foo, ' ')", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("'@(Foo, ' ')'", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("'%40(( '", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner("'@(Complex_ItemType-123, ';')' == ''", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void FunctionTests() { Scanner lexer; lexer = new Scanner("Foobar()", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( 1 )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( $(Property) )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( @(ItemList) )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( simplestring )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( 'Not a Simple String' )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( 'Not a Simple String', 1234 )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( $(Property), 'Not a Simple String', 1234 )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); lexer = new Scanner("Foobar( @(ItemList), $(Property), simplestring, 'Not a Simple String', 1234 )", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Function)); Assertion.AssertEquals(String.Compare("Foobar", lexer.IsNextString()), 0); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LeftParenthesis)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Comma)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.RightParenthesis)); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void ComplexTests1 () { Scanner lexer; lexer = new Scanner("'String with a $(Property) inside'", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.AssertEquals(String.Compare("String with a $(Property) inside", lexer.IsNextString()), 0); lexer = new Scanner("'String with an embedded \\' in it'", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); // Assertion.AssertEquals(String.Compare("String with an embedded ' in it", lexer.IsNextString()), 0); lexer = new Scanner("'String with a $(Property) inside'", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.AssertEquals(String.Compare("String with a $(Property) inside", lexer.IsNextString()), 0); lexer = new Scanner("@(list, ' ')", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.AssertEquals(String.Compare("@(list, ' ')", lexer.IsNextString()), 0); lexer = new Scanner("@(files->'%(Filename)')", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.AssertEquals(String.Compare("@(files->'%(Filename)')", lexer.IsNextString()), 0); } /// <summary> /// </summary> /// <owner>DavidLe</owner> [Test] public void ComplexTests2() { Scanner lexer = new Scanner("1234", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); lexer = new Scanner("'abc-efg'==$(foo)", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.String), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.EqualTo), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Property), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.EndOfInput), true); lexer = new Scanner("$(debug)!=true", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Property), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.NotEqualTo), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.String), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.EndOfInput), true); lexer = new Scanner("$(VERSION)<5", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance()); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Property), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.LessThan), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.Numeric), true); lexer.Advance(); Assertion.AssertEquals(lexer.IsNext(Token.TokenType.EndOfInput), true); } /// <summary> /// Tests all tokens with no whitespace and whitespace. /// </summary> /// <owner>DavidLe</owner> [Test] public void WhitespaceTests() { Scanner lexer; Console.WriteLine("here"); lexer = new Scanner("$(DEBUG) and $(FOO)", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.And)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); lexer = new Scanner("1234$(DEBUG)0xabcd@(foo)asdf<>'foobar'<=false>=true==1234!=", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThan)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThan)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThanOrEqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.NotEqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); lexer = new Scanner(" 1234 $(DEBUG) 0xabcd \n@(foo) \nasdf \n< \n> \n'foobar' \n<= \nfalse \n>= \ntrue \n== \n 1234 \n!= ", ParserOptions.AllowAll); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Property)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.ItemList)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThan)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThan)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.LessThanOrEqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.GreaterThanOrEqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.String)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.Numeric)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.NotEqualTo)); Assertion.Assert(lexer.Advance() && lexer.IsNext(Token.TokenType.EndOfInput)); } /// <summary> /// Tests the parsing of item lists. /// </summary> /// <owner>DavidLe</owner> [Test] public void ItemListTests() { Scanner lexer; lexer = new Scanner("@(foo)", ParserOptions.AllowProperties); Assertion.Assert(!lexer.Advance()); Assertion.Assert(String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional") == 0); lexer = new Scanner("1234 '@(foo)'", ParserOptions.AllowProperties); Assertion.Assert(lexer.Advance()); Assertion.Assert(!lexer.Advance()); Assertion.Assert(String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional") == 0); lexer = new Scanner("'1234 @(foo)'", ParserOptions.AllowProperties); Assertion.Assert(!lexer.Advance()); Assertion.Assert(String.Compare(lexer.GetErrorResource(), "ItemListNotAllowedInThisConditional") == 0); } /// <summary> /// Tests that shouldn't work. /// </summary> /// <owner>DavidLe</owner> [Test] public void NegativeTests() { Scanner lexer; lexer = new Scanner("'$(DEBUG) == true", ParserOptions.AllowAll); Assertion.Assert(!lexer.Advance()); } } }
// This code is part of the Fungus library (https://github.com/snozbot/fungus) // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using System.Collections.Generic; namespace Fungus { /// <summary> /// Display story text in a visual novel style dialog box. /// </summary> public class SayDialog : MonoBehaviour { [Tooltip("Duration to fade dialogue in/out")] [SerializeField] protected float fadeDuration = 0.25f; [Tooltip("The continue button UI object")] [SerializeField] protected Button continueButton; [Tooltip("The canvas UI object")] [SerializeField] protected Canvas dialogCanvas; [Tooltip("The name text UI object")] [SerializeField] protected Text nameText; [Tooltip("TextAdapter will search for appropriate output on this GameObject if nameText is null")] [SerializeField] protected GameObject nameTextGO; protected TextAdapter nameTextAdapter = new TextAdapter(); public virtual string NameText { get { return nameTextAdapter.Text; } set { nameTextAdapter.Text = value; } } [Tooltip("The story text UI object")] [SerializeField] protected Text storyText; [Tooltip("TextAdapter will search for appropriate output on this GameObject if storyText is null")] [SerializeField] protected GameObject storyTextGO; protected TextAdapter storyTextAdapter = new TextAdapter(); public virtual string StoryText { get { return storyTextAdapter.Text; } set { storyTextAdapter.Text = value; } } public virtual RectTransform StoryTextRectTrans { get { return storyText != null ? storyText.rectTransform : storyTextGO.GetComponent<RectTransform>(); } } [Tooltip("The character UI object")] [SerializeField] protected Image characterImage; public virtual Image CharacterImage { get { return characterImage; } } [Tooltip("Adjust width of story text when Character Image is displayed (to avoid overlapping)")] [SerializeField] protected bool fitTextWithImage = true; [Tooltip("Close any other open Say Dialogs when this one is active")] [SerializeField] protected bool closeOtherDialogs; protected float startStoryTextWidth; protected float startStoryTextInset; protected WriterAudio writerAudio; protected Writer writer; protected CanvasGroup canvasGroup; protected bool fadeWhenDone = true; protected float targetAlpha = 0f; protected float fadeCoolDownTimer = 0f; protected Sprite currentCharacterImage; // Most recent speaking character protected static Character speakingCharacter; protected StringSubstituter stringSubstituter = new StringSubstituter(); // Cache active Say Dialogs to avoid expensive scene search protected static List<SayDialog> activeSayDialogs = new List<SayDialog>(); protected virtual void Awake() { if (!activeSayDialogs.Contains(this)) { activeSayDialogs.Add(this); } nameTextAdapter.InitFromGameObject(nameText != null ? nameText.gameObject : nameTextGO); storyTextAdapter.InitFromGameObject(storyText != null ? storyText.gameObject : storyTextGO); } protected virtual void OnDestroy() { activeSayDialogs.Remove(this); } protected virtual Writer GetWriter() { if (writer != null) { return writer; } writer = GetComponent<Writer>(); if (writer == null) { writer = gameObject.AddComponent<Writer>(); } return writer; } protected virtual CanvasGroup GetCanvasGroup() { if (canvasGroup != null) { return canvasGroup; } canvasGroup = GetComponent<CanvasGroup>(); if (canvasGroup == null) { canvasGroup = gameObject.AddComponent<CanvasGroup>(); } return canvasGroup; } protected virtual WriterAudio GetWriterAudio() { if (writerAudio != null) { return writerAudio; } writerAudio = GetComponent<WriterAudio>(); if (writerAudio == null) { writerAudio = gameObject.AddComponent<WriterAudio>(); } return writerAudio; } protected virtual void Start() { // Dialog always starts invisible, will be faded in when writing starts GetCanvasGroup().alpha = 0f; // Add a raycaster if none already exists so we can handle dialog input GraphicRaycaster raycaster = GetComponent<GraphicRaycaster>(); if (raycaster == null) { gameObject.AddComponent<GraphicRaycaster>(); } // It's possible that SetCharacterImage() has already been called from the // Start method of another component, so check that no image has been set yet. // Same for nameText. if (NameText == "") { SetCharacterName("", Color.white); } if (currentCharacterImage == null) { // Character image is hidden by default. SetCharacterImage(null); } } protected virtual void LateUpdate() { UpdateAlpha(); if (continueButton != null) { continueButton.gameObject.SetActive( GetWriter().IsWaitingForInput ); } } protected virtual void UpdateAlpha() { if (GetWriter().IsWriting) { targetAlpha = 1f; fadeCoolDownTimer = 0.1f; } else if (fadeWhenDone && Mathf.Approximately(fadeCoolDownTimer, 0f)) { targetAlpha = 0f; } else { // Add a short delay before we start fading in case there's another Say command in the next frame or two. // This avoids a noticeable flicker between consecutive Say commands. fadeCoolDownTimer = Mathf.Max(0f, fadeCoolDownTimer - Time.deltaTime); } CanvasGroup canvasGroup = GetCanvasGroup(); if (fadeDuration <= 0f) { canvasGroup.alpha = targetAlpha; } else { float delta = (1f / fadeDuration) * Time.deltaTime; float alpha = Mathf.MoveTowards(canvasGroup.alpha, targetAlpha, delta); canvasGroup.alpha = alpha; if (alpha <= 0f) { // Deactivate dialog object once invisible gameObject.SetActive(false); } } } protected virtual void ClearStoryText() { StoryText = ""; } #region Public members public Character SpeakingCharacter { get { return speakingCharacter; } } /// <summary> /// Currently active Say Dialog used to display Say text /// </summary> public static SayDialog ActiveSayDialog { get; set; } /// <summary> /// Returns a SayDialog by searching for one in the scene or creating one if none exists. /// </summary> public static SayDialog GetSayDialog() { if (ActiveSayDialog == null) { SayDialog sd = null; // Use first active Say Dialog in the scene (if any) if (activeSayDialogs.Count > 0) { sd = activeSayDialogs[0]; } if (sd != null) { ActiveSayDialog = sd; } if (ActiveSayDialog == null) { // Auto spawn a say dialog object from the prefab GameObject prefab = Resources.Load<GameObject>("Prefabs/SayDialog"); if (prefab != null) { GameObject go = Instantiate(prefab) as GameObject; go.SetActive(false); go.name = "SayDialog"; ActiveSayDialog = go.GetComponent<SayDialog>(); } } } return ActiveSayDialog; } /// <summary> /// Stops all active portrait tweens. /// </summary> public static void StopPortraitTweens() { // Stop all tweening portraits var activeCharacters = Character.ActiveCharacters; for (int i = 0; i < activeCharacters.Count; i++) { var c = activeCharacters[i]; if (c.State.portraitImage != null) { if (LeanTween.isTweening(c.State.portraitImage.gameObject)) { LeanTween.cancel(c.State.portraitImage.gameObject, true); PortraitController.SetRectTransform(c.State.portraitImage.rectTransform, c.State.position); if (c.State.dimmed == true) { c.State.portraitImage.color = new Color(0.5f, 0.5f, 0.5f, 1f); } else { c.State.portraitImage.color = Color.white; } } } } } /// <summary> /// Sets the active state of the Say Dialog gameobject. /// </summary> public virtual void SetActive(bool state) { gameObject.SetActive(state); } /// <summary> /// Sets the active speaking character. /// </summary> /// <param name="character">The active speaking character.</param> public virtual void SetCharacter(Character character) { if (character == null) { if (characterImage != null) { characterImage.gameObject.SetActive(false); } if (NameText != null) { NameText = ""; } speakingCharacter = null; } else { var prevSpeakingCharacter = speakingCharacter; speakingCharacter = character; // Dim portraits of non-speaking characters var activeStages = Stage.ActiveStages; for (int i = 0; i < activeStages.Count; i++) { var stage = activeStages[i]; if (stage.DimPortraits) { var charactersOnStage = stage.CharactersOnStage; for (int j = 0; j < charactersOnStage.Count; j++) { var c = charactersOnStage[j]; if (prevSpeakingCharacter != speakingCharacter) { if (c != null && !c.Equals(speakingCharacter)) { stage.SetDimmed(c, true); } else { stage.SetDimmed(c, false); } } } } } string characterName = character.NameText; if (characterName == "") { // Use game object name as default characterName = character.GetObjectName(); } SetCharacterName(characterName, character.NameColor); } } /// <summary> /// Sets the character image to display on the Say Dialog. /// </summary> public virtual void SetCharacterImage(Sprite image) { if (characterImage == null) { return; } if (image != null) { characterImage.overrideSprite = image; characterImage.gameObject.SetActive(true); currentCharacterImage = image; } else { characterImage.gameObject.SetActive(false); if (startStoryTextWidth != 0) { StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, startStoryTextInset, startStoryTextWidth); } } // Adjust story text box to not overlap image rect if (fitTextWithImage && StoryText != null && characterImage.gameObject.activeSelf) { if (Mathf.Approximately(startStoryTextWidth, 0f)) { startStoryTextWidth = StoryTextRectTrans.rect.width; startStoryTextInset = StoryTextRectTrans.offsetMin.x; } // Clamp story text to left or right depending on relative position of the character image if (StoryTextRectTrans.position.x < characterImage.rectTransform.position.x) { StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, startStoryTextInset, startStoryTextWidth - characterImage.rectTransform.rect.width); } else { StoryTextRectTrans.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Right, startStoryTextInset, startStoryTextWidth - characterImage.rectTransform.rect.width); } } } /// <summary> /// Sets the character name to display on the Say Dialog. /// Supports variable substitution e.g. John {$surname} /// </summary> public virtual void SetCharacterName(string name, Color color) { if (NameText != null) { var subbedName = stringSubstituter.SubstituteStrings(name); NameText = subbedName; nameTextAdapter.SetTextColor(color); } } /// <summary> /// Write a line of story text to the Say Dialog. Starts coroutine automatically. /// </summary> /// <param name="text">The text to display.</param> /// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param> /// <param name="waitForInput">Wait for player input before continuing once text is written.</param> /// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param> /// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param> /// <param name="voiceOverClip">Voice over audio clip to play.</param> /// <param name="onComplete">Callback to execute when writing and player input have finished.</param> public virtual void Say(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, bool waitForVO, AudioClip voiceOverClip, Action onComplete) { StartCoroutine(DoSay(text, clearPrevious, waitForInput, fadeWhenDone, stopVoiceover, waitForVO, voiceOverClip, onComplete)); } /// <summary> /// Write a line of story text to the Say Dialog. Must be started as a coroutine. /// </summary> /// <param name="text">The text to display.</param> /// <param name="clearPrevious">Clear any previous text in the Say Dialog.</param> /// <param name="waitForInput">Wait for player input before continuing once text is written.</param> /// <param name="fadeWhenDone">Fade out the Say Dialog when writing and player input has finished.</param> /// <param name="stopVoiceover">Stop any existing voiceover audio before writing starts.</param> /// <param name="voiceOverClip">Voice over audio clip to play.</param> /// <param name="onComplete">Callback to execute when writing and player input have finished.</param> public virtual IEnumerator DoSay(string text, bool clearPrevious, bool waitForInput, bool fadeWhenDone, bool stopVoiceover, bool waitForVO, AudioClip voiceOverClip, Action onComplete) { var writer = GetWriter(); if (writer.IsWriting || writer.IsWaitingForInput) { writer.Stop(); while (writer.IsWriting || writer.IsWaitingForInput) { yield return null; } } if (closeOtherDialogs) { for (int i = 0; i < activeSayDialogs.Count; i++) { var sd = activeSayDialogs[i]; if (sd.gameObject != gameObject) { sd.SetActive(false); } } } gameObject.SetActive(true); this.fadeWhenDone = fadeWhenDone; // Voice over clip takes precedence over a character sound effect if provided AudioClip soundEffectClip = null; if (voiceOverClip != null) { WriterAudio writerAudio = GetWriterAudio(); writerAudio.OnVoiceover(voiceOverClip); } else if (speakingCharacter != null) { soundEffectClip = speakingCharacter.SoundEffect; } writer.AttachedWriterAudio = writerAudio; yield return StartCoroutine(writer.Write(text, clearPrevious, waitForInput, stopVoiceover, waitForVO, soundEffectClip, onComplete)); } /// <summary> /// Tell the Say Dialog to fade out once writing and player input have finished. /// </summary> public virtual bool FadeWhenDone { get {return fadeWhenDone; } set { fadeWhenDone = value; } } /// <summary> /// Stop the Say Dialog while its writing text. /// </summary> public virtual void Stop() { fadeWhenDone = true; GetWriter().Stop(); } /// <summary> /// Stops writing text and clears the Say Dialog. /// </summary> public virtual void Clear() { ClearStoryText(); // Kill any active write coroutine StopAllCoroutines(); } #endregion } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.OpenGL; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.IO.Stores; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using JetBrains.Annotations; using osu.Framework.Logging; using osuTK.Graphics.ES30; namespace osu.Framework.Graphics.Textures { public class TextureStore : ResourceStore<TextureUpload> { private readonly Dictionary<string, Texture> textureCache = new Dictionary<string, Texture>(); private readonly All filteringMode; private readonly bool manualMipmaps; protected TextureAtlas Atlas; private const int max_atlas_size = 1024; /// <summary> /// Decides at what resolution multiple this <see cref="TextureStore"/> is providing sprites at. /// ie. if we are providing high resolution (at 2x the resolution of standard 1366x768) sprites this should be 2. /// </summary> public readonly float ScaleAdjust; public TextureStore(IResourceStore<TextureUpload> store = null, bool useAtlas = true, All filteringMode = All.Linear, bool manualMipmaps = false, float scaleAdjust = 2) : base(store) { this.filteringMode = filteringMode; this.manualMipmaps = manualMipmaps; ScaleAdjust = scaleAdjust; AddExtension(@"png"); AddExtension(@"jpg"); if (useAtlas) { int size = Math.Min(max_atlas_size, GLWrapper.MaxTextureSize); Atlas = new TextureAtlas(size, size, filteringMode: filteringMode); } } private async Task<Texture> getTextureAsync(string name, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None) => loadRaw(await base.GetAsync(name).ConfigureAwait(false), wrapModeS, wrapModeT); private Texture getTexture(string name, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None) => loadRaw(base.Get(name), wrapModeS, wrapModeT); private Texture loadRaw(TextureUpload upload, WrapMode wrapModeS = WrapMode.None, WrapMode wrapModeT = WrapMode.None) { if (upload == null) return null; TextureGL glTexture = null; if (Atlas != null) { if ((glTexture = Atlas.Add(upload.Width, upload.Height, wrapModeS, wrapModeT)) == null) { Logger.Log( $"Texture requested ({upload.Width}x{upload.Height}) which exceeds {nameof(TextureStore)}'s atlas size ({max_atlas_size}x{max_atlas_size}) - bypassing atlasing. Consider using {nameof(LargeTextureStore)}.", LoggingTarget.Performance); } } glTexture ??= new TextureGLSingle(upload.Width, upload.Height, manualMipmaps, filteringMode, wrapModeS, wrapModeT); Texture tex = new Texture(glTexture) { ScaleAdjust = ScaleAdjust }; tex.SetData(upload); return tex; } /// <summary> /// Retrieves a texture from the store and adds it to the atlas. /// </summary> /// <param name="name">The name of the texture.</param> /// <returns>The texture.</returns> public new Task<Texture> GetAsync(string name) => GetAsync(name, default, default); /// <summary> /// Retrieves a texture from the store and adds it to the atlas. /// </summary> /// <param name="name">The name of the texture.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <returns>The texture.</returns> public Task<Texture> GetAsync(string name, WrapMode wrapModeT, WrapMode wrapModeS) => Task.Run(() => Get(name, wrapModeS, wrapModeT)); // TODO: best effort. need to re-think textureCache data structure to fix this. /// <summary> /// Retrieves a texture from the store and adds it to the atlas. /// </summary> /// <param name="name">The name of the texture.</param> /// <returns>The texture.</returns> public new Texture Get(string name) => Get(name, default, default); private readonly Dictionary<string, Task> retrievalCompletionSources = new Dictionary<string, Task>(); /// <summary> /// Retrieves a texture from the store and adds it to the atlas. /// </summary> /// <param name="name">The name of the texture.</param> /// <param name="wrapModeS">The texture wrap mode in horizontal direction.</param> /// <param name="wrapModeT">The texture wrap mode in vertical direction.</param> /// <returns>The texture.</returns> public virtual Texture Get(string name, WrapMode wrapModeS, WrapMode wrapModeT) { if (string.IsNullOrEmpty(name)) return null; string key = $"{name}:wrap-{(int)wrapModeS}-{(int)wrapModeT}"; TaskCompletionSource<Texture> tcs = null; Task task; lock (retrievalCompletionSources) { // Check if the texture exists in the cache. if (TryGetCached(key, out var cached)) return cached; // check if an existing lookup was already started for this key. if (!retrievalCompletionSources.TryGetValue(key, out task)) // if not, take responsibility for the lookup. retrievalCompletionSources[key] = (tcs = new TaskCompletionSource<Texture>()).Task; } // handle the case where a lookup is already in progress. if (task != null) { task.Wait(); // always perform re-lookups through TryGetCached (see LargeTextureStore which has a custom implementation of this where it matters). if (TryGetCached(key, out var cached)) return cached; return null; } this.LogIfNonBackgroundThread(key); Texture tex = null; try { tex = getTexture(name, wrapModeS, wrapModeT); if (tex != null) tex.LookupKey = key; return CacheAndReturnTexture(key, tex); } catch (TextureTooLargeForGLException) { Logger.Log($"Texture \"{name}\" exceeds the maximum size supported by this device ({GLWrapper.MaxTextureSize}px).", level: LogLevel.Error); } finally { // notify other lookups waiting on the same name lookup. lock (retrievalCompletionSources) { Debug.Assert(tcs != null); tcs.SetResult(tex); retrievalCompletionSources.Remove(key); } } return null; } /// <summary> /// Attempts to retrieve an existing cached texture. /// </summary> /// <param name="lookupKey">The lookup key that uniquely identifies textures in the cache.</param> /// <param name="texture">The returned texture. Null if the texture did not exist in the cache.</param> /// <returns>Whether a cached texture was retrieved.</returns> protected virtual bool TryGetCached([NotNull] string lookupKey, [CanBeNull] out Texture texture) { lock (textureCache) return textureCache.TryGetValue(lookupKey, out texture); } /// <summary> /// Caches and returns the given texture. /// </summary> /// <param name="lookupKey">The lookup key that uniquely identifies textures in the cache.</param> /// <param name="texture">The texture to be cached and returned.</param> /// <returns>The texture to be returned.</returns> [CanBeNull] protected virtual Texture CacheAndReturnTexture([NotNull] string lookupKey, [CanBeNull] Texture texture) { lock (textureCache) return textureCache[lookupKey] = texture; } /// <summary> /// Disposes and removes a texture from the cache. /// </summary> /// <param name="texture">The texture to purge from the cache.</param> protected void Purge(Texture texture) { lock (textureCache) { if (textureCache.TryGetValue(texture.LookupKey, out var tex)) { // we are doing this locally as right now, Textures don't dispose the underlying texture (leaving it to GC finalizers). // in the case of a purge operation we are pretty sure this is the intended behaviour. tex?.TextureGL?.Dispose(); tex?.Dispose(); } textureCache.Remove(texture.LookupKey); } } } }