context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//Copyright (c) ServiceStack, Inc. All Rights Reserved. //License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt using System; namespace ServiceStack { [Flags] public enum RequestAttributes : long { None = 0, Any = AnyNetworkAccessType | AnySecurityMode | AnyHttpMethod | AnyCallStyle | AnyFormat | AnyEndpoint, AnyNetworkAccessType = External | LocalSubnet | Localhost | InProcess, AnySecurityMode = Secure | InSecure, AnyHttpMethod = HttpHead | HttpGet | HttpPost | HttpPut | HttpDelete | HttpPatch | HttpOptions | HttpOther, AnyCallStyle = OneWay | Reply, AnyFormat = Soap11 | Soap12 | Xml | Json | Jsv | Html | ProtoBuf | Csv | MsgPack | Wire | FormatOther, AnyEndpoint = Http | MessageQueue | Tcp | Grpc | EndpointOther, InternalNetworkAccess = InProcess | Localhost | LocalSubnet, //Whether it came from an Internal or External address Localhost = 1 << 0, LocalSubnet = 1 << 1, External = 1 << 2, //Called over a secure or insecure channel Secure = 1 << 3, InSecure = 1 << 4, //HTTP request type HttpHead = 1 << 5, HttpGet = 1 << 6, HttpPost = 1 << 7, HttpPut = 1 << 8, HttpDelete = 1 << 9, HttpPatch = 1 << 10, HttpOptions = 1 << 11, HttpOther = 1 << 12, //Call Styles OneWay = 1 << 13, Reply = 1 << 14, //Different formats Soap11 = 1 << 15, Soap12 = 1 << 16, //POX Xml = 1 << 17, //Javascript Json = 1 << 18, //Jsv i.e. TypeSerializer Jsv = 1 << 19, //e.g. protobuf-net ProtoBuf = 1 << 20, //e.g. text/csv Csv = 1 << 21, Html = 1 << 22, Wire = 1 << 23, MsgPack = 1 << 24, FormatOther = 1 << 25, //Different endpoints Http = 1 << 26, MessageQueue = 1 << 27, Tcp = 1 << 28, Grpc = 1 << 29, EndpointOther = 1 << 30, InProcess = 1 << 31, //Service was executed within code (e.g. ResolveService<T>) } public enum Network : long { Localhost = 1 << 0, LocalSubnet = 1 << 1, External = 1 << 2, } public enum Security : long { Secure = 1 << 3, InSecure = 1 << 4, } public enum Http : long { Head = 1 << 5, Get = 1 << 6, Post = 1 << 7, Put = 1 << 8, Delete = 1 << 9, Patch = 1 << 10, Options = 1 << 11, Other = 1 << 12, } public enum CallStyle : long { OneWay = 1 << 13, Reply = 1 << 14, } public enum Format : long { Soap11 = 1 << 15, Soap12 = 1 << 16, Xml = 1 << 17, Json = 1 << 18, Jsv = 1 << 19, ProtoBuf = 1 << 20, Csv = 1 << 21, Html = 1 << 22, Wire = 1 << 23, MsgPack = 1 << 24, Other = 1 << 25, } public enum Endpoint : long { Http = 1 << 26, Mq = 1 << 27, Tcp = 1 << 28, Other = 1 << 29, } public static class RequestAttributesExtensions { public static bool IsLocalhost(this RequestAttributes attrs) { return (RequestAttributes.Localhost & attrs) == RequestAttributes.Localhost; } public static bool IsLocalSubnet(this RequestAttributes attrs) { return (RequestAttributes.LocalSubnet & attrs) == RequestAttributes.LocalSubnet; } public static bool IsExternal(this RequestAttributes attrs) { return (RequestAttributes.External & attrs) == RequestAttributes.External; } public static Format ToFormat(this string format) { try { return (Format)Enum.Parse(typeof(Format), format.ToUpper().Replace("X-", ""), true); } catch (Exception) { return Format.Other; } } public static string FromFormat(this Format format) { var formatStr = format.ToString().ToLowerInvariant(); if (format == Format.ProtoBuf || format == Format.MsgPack) return "x-" + formatStr; return formatStr; } public static Format ToFormat(this Feature feature) { switch (feature) { case Feature.Xml: return Format.Xml; case Feature.Json: return Format.Json; case Feature.Jsv: return Format.Jsv; case Feature.Csv: return Format.Csv; case Feature.Html: return Format.Html; case Feature.MsgPack: return Format.MsgPack; case Feature.ProtoBuf: return Format.ProtoBuf; case Feature.Soap11: return Format.Soap11; case Feature.Soap12: return Format.Soap12; } return Format.Other; } public static Feature ToFeature(this Format format) { switch (format) { case Format.Xml: return Feature.Xml; case Format.Json: return Feature.Json; case Format.Jsv: return Feature.Jsv; case Format.Csv: return Feature.Csv; case Format.Html: return Feature.Html; case Format.MsgPack: return Feature.MsgPack; case Format.ProtoBuf: return Feature.ProtoBuf; case Format.Soap11: return Feature.Soap11; case Format.Soap12: return Feature.Soap12; } return Feature.CustomFormat; } public static Feature ToSoapFeature(this RequestAttributes attributes) { if ((RequestAttributes.Soap11 & attributes) == RequestAttributes.Soap11) return Feature.Soap11; if ((RequestAttributes.Soap12 & attributes) == RequestAttributes.Soap12) return Feature.Soap12; return Feature.None; } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Xunit; namespace System.Runtime.CompilerServices.Tests { public class ConfiguredCancelableAsyncEnumerableTests { [Fact] public void Default_GetAsyncEnumerator_Throws() { ConfiguredCancelableAsyncEnumerable<int> e = default; Assert.Throws<NullReferenceException>(() => e.GetAsyncEnumerator()); e = ((IAsyncEnumerable<int>)null).ConfigureAwait(false); Assert.Throws<NullReferenceException>(() => e.GetAsyncEnumerator()); } [Fact] public void Default_EnumeratorMembers_Throws() { ConfiguredCancelableAsyncEnumerable<int>.Enumerator e = default; Assert.Throws<NullReferenceException>(() => e.MoveNextAsync()); Assert.Throws<NullReferenceException>(() => e.Current); Assert.Throws<NullReferenceException>(() => e.DisposeAsync()); } [Fact] public void Default_WithCancellation_ConfigureAwait_NoThrow() { ConfiguredCancelableAsyncEnumerable<int> e = ((IAsyncEnumerable<int>)null).WithCancellation(default); e = e.ConfigureAwait(false); e = e.WithCancellation(default); Assert.Throws<NullReferenceException>(() => e.GetAsyncEnumerator()); } [Fact] public void Default_ConfigureAwait_WithCancellation_NoThrow() { ConfiguredCancelableAsyncEnumerable<int> e = ((IAsyncEnumerable<int>)null).ConfigureAwait(false); e = e.WithCancellation(default); e = e.ConfigureAwait(false); Assert.Throws<NullReferenceException>(() => e.GetAsyncEnumerator()); } [Theory] [InlineData(false)] [InlineData(true)] public void ConfigureAwait_AwaitMoveNextAsync_FlagsSetAppropriately(bool continueOnCapturedContext) { TrackFlagsAsyncEnumerable enumerable; CancellationToken token = new CancellationTokenSource().Token; // Single ConfigureAwait call enumerable = new TrackFlagsAsyncEnumerable() { Flags = 0 }; enumerable.ConfigureAwait(continueOnCapturedContext).GetAsyncEnumerator().MoveNextAsync().GetAwaiter().UnsafeOnCompleted(() => { }); Assert.Equal( continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None, enumerable.Flags); // Unnecessary multiple calls; only last one is used enumerable = new TrackFlagsAsyncEnumerable() { Flags = 0 }; enumerable.ConfigureAwait(!continueOnCapturedContext).ConfigureAwait(continueOnCapturedContext).GetAsyncEnumerator().MoveNextAsync().GetAwaiter().UnsafeOnCompleted(() => { }); Assert.Equal( continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None, enumerable.Flags); // After WithCancellation enumerable = new TrackFlagsAsyncEnumerable() { Flags = 0 }; enumerable.WithCancellation(token).ConfigureAwait(continueOnCapturedContext).GetAsyncEnumerator().MoveNextAsync().GetAwaiter().UnsafeOnCompleted(() => { }); Assert.Equal( continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None, enumerable.Flags); // Before WithCancellation enumerable = new TrackFlagsAsyncEnumerable() { Flags = 0 }; enumerable.ConfigureAwait(continueOnCapturedContext).WithCancellation(token).GetAsyncEnumerator().MoveNextAsync().GetAwaiter().UnsafeOnCompleted(() => { }); Assert.Equal( continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None, enumerable.Flags); } [Theory] [InlineData(false)] [InlineData(true)] public void ConfigureAwait_AwaitDisposeAsync_FlagsSetAppropriately(bool continueOnCapturedContext) { var enumerable = new TrackFlagsAsyncEnumerable() { Flags = 0 }; enumerable.ConfigureAwait(continueOnCapturedContext).GetAsyncEnumerator().DisposeAsync().GetAwaiter().UnsafeOnCompleted(() => { }); Assert.Equal( continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None, enumerable.Flags); } [Fact] public async Task CanBeEnumeratedWithStandardPattern() { IAsyncEnumerable<int> asyncEnumerable = new EnumerableWithDelayToAsyncEnumerable<int>(Enumerable.Range(1, 10), 1); int sum = 0; ConfiguredCancelableAsyncEnumerable<int>.Enumerator e = asyncEnumerable.ConfigureAwait(false).WithCancellation(new CancellationTokenSource().Token).GetAsyncEnumerator(); try { while (await e.MoveNextAsync()) { sum += e.Current; } } finally { await e.DisposeAsync(); } Assert.Equal(55, sum); } [Fact] public void WithCancellation_TokenPassedThrough() { TrackFlagsAsyncEnumerable enumerable; CancellationToken token1 = new CancellationTokenSource().Token; CancellationToken token2 = new CancellationTokenSource().Token; // No WithCancellation call enumerable = new TrackFlagsAsyncEnumerable(); enumerable.GetAsyncEnumerator(); Assert.Equal(CancellationToken.None, enumerable.CancellationToken); // Only ConfigureAwait call enumerable = new TrackFlagsAsyncEnumerable(); enumerable.ConfigureAwait(false).GetAsyncEnumerator(); Assert.Equal(CancellationToken.None, enumerable.CancellationToken); // Single WithCancellation call enumerable = new TrackFlagsAsyncEnumerable(); enumerable.WithCancellation(token1).GetAsyncEnumerator(); Assert.Equal(token1, enumerable.CancellationToken); // Unnecessary multiple calls; only last one is used enumerable = new TrackFlagsAsyncEnumerable(); enumerable.WithCancellation(token1).WithCancellation(token2).GetAsyncEnumerator(); Assert.Equal(token2, enumerable.CancellationToken); // Before ConfigureAwait enumerable = new TrackFlagsAsyncEnumerable(); enumerable.WithCancellation(token1).ConfigureAwait(false).GetAsyncEnumerator(); Assert.Equal(token1, enumerable.CancellationToken); // After ConfigureAwait enumerable = new TrackFlagsAsyncEnumerable(); enumerable.ConfigureAwait(false).WithCancellation(token1).GetAsyncEnumerator(); Assert.Equal(token1, enumerable.CancellationToken); } private sealed class TrackFlagsAsyncEnumerable : IAsyncEnumerable<int> { public ValueTaskSourceOnCompletedFlags Flags; public CancellationToken CancellationToken; public IAsyncEnumerator<int> GetAsyncEnumerator(CancellationToken cancellationToken = default) { CancellationToken = cancellationToken; return new Enumerator(this); } private sealed class Enumerator : IAsyncEnumerator<int>, IValueTaskSource<bool>, IValueTaskSource { private readonly TrackFlagsAsyncEnumerable _enumerable; public Enumerator(TrackFlagsAsyncEnumerable enumerable) => _enumerable = enumerable; public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(this, 0); public int Current => throw new NotImplementedException(); public ValueTask DisposeAsync() => new ValueTask(this, 0); public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) => _enumerable.Flags = flags; public ValueTaskSourceStatus GetStatus(short token) => ValueTaskSourceStatus.Pending; public bool GetResult(short token) => throw new NotImplementedException(); void IValueTaskSource.GetResult(short token) => throw new NotImplementedException(); } } private sealed class EnumerableWithDelayToAsyncEnumerable<T> : IAsyncEnumerable<T>, IAsyncEnumerator<T> { private readonly int _delayMs; private readonly IEnumerable<T> _enumerable; private IEnumerator<T> _enumerator; public EnumerableWithDelayToAsyncEnumerable(IEnumerable<T> enumerable, int delayMs) { _enumerable = enumerable; _delayMs = delayMs; } public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) { _enumerator = _enumerable.GetEnumerator(); return this; } public async ValueTask<bool> MoveNextAsync() { await Task.Delay(_delayMs); return _enumerator.MoveNext(); } public T Current => _enumerator.Current; public async ValueTask DisposeAsync() { await Task.Delay(_delayMs); _enumerator.Dispose(); } } } }
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace Bam.Core.Test { sealed class TokenizedStringTestModule : Bam.Core.Module { protected override void Init() { base.Init(); // this is quite ugly, but you can only use // Bam.Core.Graph.FindReferencedModule while modules are being // created, and the tests need a handle to the module TokenizedStringTest.testModule = this; } protected override void EvaluateInternal() => throw new System.NotImplementedException(); protected override void ExecuteInternal(ExecutionContext context) => throw new System.NotImplementedException(); } [NUnit.Framework.TestFixture(Author="Mark Final")] [NUnit.Framework.TestOf(typeof(Bam.Core.TokenizedString))] public sealed class TokenizedStringTest { private Bam.Core.Graph graph; public static Bam.Core.Module testModule = null; // workaround for not being able to use Graph.FindReferencedModule [NUnit.Framework.SetUp] public void Setup() { // because there is no BAM package, this can be set up incorrectly // see // - BamState.ExecutableDirectory (will be null) // - BamState.WorkingDirectory (will be null) // - Graph.PackageRepositories (will be empty) this.graph = Bam.Core.Graph.Instance; Bam.Core.TokenizedString.Reset(); Bam.Core.Module.Reset(); } [NUnit.Framework.TearDown] public void Teardown() { this.graph = null; TokenizedStringTest.testModule = null; } [NUnit.Framework.Test] public void VerbatimStringIsAlreadyParsed() { var verbatim = Bam.Core.TokenizedString.CreateVerbatim("Hello World"); NUnit.Framework.Assert.IsTrue(verbatim.IsParsed); NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(1)); } [NUnit.Framework.Test] public void ParsingAParsedStringThrows() { var verbatim = Bam.Core.TokenizedString.CreateVerbatim("Hello World"); // verbatim strings do not require parsing NUnit.Framework.Assert.That(() => verbatim.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.Exception>().And. Message.Contains("is already parsed")); var str = Bam.Core.TokenizedString.Create("Hello World", null, null); NUnit.Framework.Assert.That(str, NUnit.Framework.Is.Not.SameAs(verbatim)); // first parse str.Parse(); // second parse NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.Exception>().And. Message.Contains("is already parsed")); NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(2)); } [NUnit.Framework.Test] public void ReferencedButNullPositionalArgumentList() { var str = Bam.Core.TokenizedString.Create("$(0)", null, null); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.Exception>().And. InnerException.TypeOf<System.ArgumentOutOfRangeException>()); NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(1)); } [NUnit.Framework.Test] public void ReferencedButMissingPositionalArgumentList() { var hello = Bam.Core.TokenizedString.CreateVerbatim("Hello"); var str = Bam.Core.TokenizedString.Create("$(0) $(1)", null, new TokenizedStringArray{hello}); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.Exception>().And. InnerException.TypeOf<System.ArgumentOutOfRangeException>()); NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(2)); } [NUnit.Framework.Test] public void UnknownPostFunction() { var str = Bam.Core.TokenizedString.Create("@failunittest()", null, null); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.Exception>().And. Message.Contains("Unknown post-function 'failunittest'")); NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(1)); } [NUnit.Framework.Test] public void UnknownPreFunction() { var str = Bam.Core.TokenizedString.Create("#failunittest()", null, null); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.Exception>().And. Message.Contains("Unknown pre-function 'failunittest'")); NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(1)); } [NUnit.Framework.Test] public void EmptyTokenStringThrows() { var str = Bam.Core.TokenizedString.Create("$()", null, null); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.TokenizedString.EmptyStringException>() ); } [NUnit.Framework.Test] public void MissingOpenParenthesisThrows() { var str = Bam.Core.TokenizedString.Create("$packagedir)", null, null); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.TokenizedString.BadTokenFormatException>() ); } [NUnit.Framework.Test] public void MissingCloseParenthesisThrows() { var str = Bam.Core.TokenizedString.Create("$(packagedir", null, null); NUnit.Framework.Assert.That(() => str.Parse(), NUnit.Framework.Throws.Exception.TypeOf<Bam.Core.TokenizedString.BadTokenFormatException>() ); } [NUnit.Framework.Test] public void MissingBothParenthesisDoesNotThrow() { var str = Bam.Core.TokenizedString.Create("$ORIGIN", null, null); str.Parse(); NUnit.Framework.StringAssert.AreEqualIgnoringCase(str.ToString(), "$ORIGIN"); } #if false [NUnit.Framework.Test] public void UseBuiltInModuleMacros() { var env = new Bam.Core.Environment(); env.Configuration = Bam.Core.EConfiguration.Debug; this.graph.CreateTopLevelModuleFromTypes(new[] { typeof(TokenizedStringTestModule) }, env); NUnit.Framework.Assert.That(Bam.Core.Module.Count, NUnit.Framework.Is.EqualTo(1)); // macros created by a new Module (in unittest mode anyway) // modulename // OutputName (same object as modulename) // config NUnit.Framework.Assert.That(Bam.Core.TokenizedString.Count, NUnit.Framework.Is.EqualTo(2)); var module = TokenizedStringTest.testModule; var str = module.CreateTokenizedString("'$(modulename)' in '$(config)'"); str.Parse(); NUnit.Framework.Assert.That(str.ToString(), NUnit.Framework.Is.EqualTo("'TokenizedStringTestModule' in 'Debug'")); } [NUnit.Framework.Test] public void CanAddVerbatimMacro() { var env = new Bam.Core.Environment(); env.Configuration = Bam.Core.EConfiguration.Debug; this.graph.SetPackageDefinitions(new Array<PackageDefinition>()); this.graph.CreateTopLevelModuleFromTypes(new [] {typeof(TokenizedStringTestModule)}, env); NUnit.Framework.Assert.That(Bam.Core.Module.Count, NUnit.Framework.Is.EqualTo(1)); var module = TokenizedStringTest.testModule; module.Macros.AddVerbatim("Macro1", "Hello World"); var str = module.CreateTokenizedString("$(Macro1)"); str.Parse(); NUnit.Framework.Assert.That(str.ToString(), NUnit.Framework.Is.EqualTo("Hello World")); } #endif } }
namespace DrinkAndRate.Data.Migrations { using DrinkAndRate.Models; using FakeData; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data.Entity.Migrations; using System.IO; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<DrinkAndRateDbContext> { public Configuration() { AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; } protected override void Seed(DrinkAndRateDbContext context) { // Check if database is already seeded if (context.Users.Any()) { return; } var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); // Roles var roles = Settings.Default.Roles.Split(','); var adminRole = roles[0]; var userRole = roles[1]; foreach (var role in roles) { roleManager.Create(new IdentityRole { Name = role }); } var userStore = new UserStore<AppUser>(context); var userManager = new UserManager<AppUser>(userStore); // Images var defaultImage = new Image { Path = "~/Images/default.png" }; var adminImage = new Image { Path = "~/Images/admin.jpg" }; context.Images.AddOrUpdate( defaultImage, adminImage ); context.SaveChanges(); // Countries var json = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + @"\App_Data\countries.json"); var countries = JsonConvert.DeserializeObject<IEnumerable<Country>>(json); foreach (var country in countries) { context.Countries.Add(country); } // Users var countryBulgaria = context.Countries.Local.Single(item => item.Name == "Bulgaria"); var userAdmin = new AppUser { UserName = "admin@admin", Email = "admin@admin", FirstName = NameData.GetFirstName(), LastName = NameData.GetSurname(), Country = countryBulgaria, Image = adminImage }; userManager.Create(userAdmin, userAdmin.UserName); userManager.AddToRole(userAdmin.Id, adminRole); for (int userIndex = 0; userIndex < 100; userIndex++) { bool isSuccess = false; while (!isSuccess) { var firstName = NameData.GetFirstName(); var lastName = NameData.GetSurname(); var userName = firstName + "@" + lastName; Country country = null; while (country == null) { var countryName = PlaceData.GetCountry(); country = context.Countries.Local.SingleOrDefault(item => item.Name == countryName); } var user = new AppUser { UserName = userName, Email = userName, FirstName = firstName, LastName = lastName, Country = country, Image = new Image() { Path = string.Format("~/Images/Users/{0}.jpg", userIndex + 1) } }; isSuccess = userManager.Create(user, userName).Succeeded; if (isSuccess) { userManager.AddToRole(user.Id, userRole); } } } // Beer Categories var categoryDark = new Category { Name = "Dark" }; var categoryLight = new Category { Name = "Light" }; var categoryFruit = new Category { Name = "Fruit" }; var categoryReserve = new Category { Name = "Reserve" }; var categoryPremium = new Category { Name = "Premium" }; var categoryOther = new Category { Name = "Other" }; context.Categories.AddOrUpdate(categoryDark, categoryLight, categoryFruit, categoryReserve, categoryPremium, categoryOther); // Beer Brands var brandKamenitza = new Brand { Name = "Kamenitza", Country = countryBulgaria, Established = new DateTime(1876, 1, 1) }; var brandZagorka = new Brand { Name = "Zagorka", Country = countryBulgaria, Established = new DateTime(1902, 1, 1) }; var brandShumensko = new Brand { Name = "Shumensko", Country = countryBulgaria, Established = new DateTime(1882, 1, 1) }; var brandStaropramen = new Brand { Name = "Staropramen", Country = context.Countries.Local.Single(item => item.Name == "Czech Republic"), Established = new DateTime(1869, 1, 1) }; var brandCarlsberg = new Brand { Name = "Carlsberg", Country = context.Countries.Local.Single(item => item.Name == "Denmark"), Established = new DateTime(1847, 1, 1) }; var brandTuborg = new Brand { Name = "Tuborg Brewery", Country = context.Countries.Local.Single(item => item.Name == "Denmark"), Established = new DateTime(1873, 1, 1) }; context.Brands.AddOrUpdate(brandKamenitza, brandZagorka, brandShumensko, brandStaropramen, brandCarlsberg, brandTuborg); // Beers context.Beers.AddOrUpdate( new Beer { Name = categoryDark.Name, Brand = brandShumensko, AlchoholPercentage = 5.5f, Category = categoryDark, Creator = userAdmin, CreatedOn = DateTime.Now, Images = new[] { new Image() { Path = "~/Images/Beers/Shumensko_Dark.jpg" } } }, new Beer { Name = categoryLight.Name, Brand = brandShumensko, AlchoholPercentage = 4.3f, Category = categoryLight, Creator = userAdmin, CreatedOn = DateTime.Now, Images = new[] { new Image() { Path = "~/Images/Beers/Shumensko_Light.jpg" } } }, new Beer { Name = categoryPremium.Name, Brand = brandShumensko, AlchoholPercentage = 4.6f, Category = categoryPremium, Creator = userAdmin, CreatedOn = DateTime.Now, Images = new[] { new Image() { Path = "~/Images/Beers/Shumensko_Premium.jpg" } } }, new Beer { Name = "Twist", Brand = brandShumensko, AlchoholPercentage = 2f, Category = categoryFruit, Creator = userAdmin, CreatedOn = DateTime.Now, Images = new[] { new Image() { Path = "~/Images/Beers/Shumensko_Twist.jpg" } } } ); // Events var eventDenver = new Event() { Title = "Denver Beerfest", Creator = userAdmin, Date = DateTime.Now.AddDays(10), Image = new Image() { Path = "~/Images/Events/Denver.jpg" }, Location = "Denver" }; eventDenver.UsersEvents = context.Users.Local.Take(30).Select(user => new UsersEvents() { Event = eventDenver, User = user }).ToArray(); var eventBelgrade = new Event() { Title = "Belgrade Beerfest", Creator = context.Users.Local.Skip(10).First(), Date = DateTime.Now.AddDays(15), Image = new Image() { Path = "~/Images/Events/Belgrade.jpg" }, Location = "Belgrade" }; eventBelgrade.UsersEvents = context.Users.Local.Skip(30).Take(30).Select(user => new UsersEvents() { Event = eventBelgrade, User = user }).ToArray(); var eventPalmBeachNewTimes = new Event() { Title = "Palm Beach New Times Beerfest", Creator = context.Users.Local.Skip(60).First(), Date = DateTime.Now.AddDays(15), Image = new Image() { Path = "~/Images/Events/PalmBeachNewTimes.jpg" }, Location = "Palm Beach" }; eventPalmBeachNewTimes.UsersEvents = context.Users.Local.Skip(60).Take(30).Select(user => new UsersEvents() { Event = eventPalmBeachNewTimes, User = user }).ToArray(); var eventTheAustralian = new Event() { Title = "The Australian Beerfest", Creator = context.Users.Local.Skip(13).First(), Date = DateTime.Now.AddDays(15), Image = new Image() { Path = "~/Images/Events/TheAustralian.jpg" }, Location = "Sydney" }; eventTheAustralian.UsersEvents = context.Users.Local.Skip(90).Select(user => new UsersEvents() { Event = eventTheAustralian, User = user }).ToArray(); context.Events.AddOrUpdate(eventDenver, eventBelgrade, eventPalmBeachNewTimes, eventTheAustralian); context.SaveChanges(); } } }
// // codegen.cs: The code generator // // Authors: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Copyright 2001, 2002, 2003 Ximian, Inc. // Copyright 2004 Novell, Inc. // Copyright 2011 Xamarin Inc // using System; using System.Collections.Generic; using Mono.CompilerServices.SymbolWriter; #if STATIC using MetaType = IKVM.Reflection.Type; using IKVM.Reflection; using IKVM.Reflection.Emit; #else using MetaType = System.Type; using System.Reflection; using System.Reflection.Emit; #endif namespace Mono.CSharp { /// <summary> /// An Emit Context is created for each body of code (from methods, /// properties bodies, indexer bodies or constructor bodies) /// </summary> public class EmitContext : BuilderContext { // TODO: Has to be private public readonly ILGenerator ig; /// <summary> /// The value that is allowed to be returned or NULL if there is no /// return type. /// </summary> readonly TypeSpec return_type; /// <summary> /// Keeps track of the Type to LocalBuilder temporary storage created /// to store structures (used to compute the address of the structure /// value on structure method invocations) /// </summary> Dictionary<TypeSpec, object> temporary_storage; /// <summary> /// The location where we store the return value. /// </summary> public LocalBuilder return_value; /// <summary> /// Current loop begin and end labels. /// </summary> public Label LoopBegin, LoopEnd; /// <summary> /// Default target in a switch statement. Only valid if /// InSwitch is true /// </summary> public Label DefaultTarget; /// <summary> /// If this is non-null, points to the current switch statement /// </summary> public Switch Switch; /// <summary> /// Whether we are inside an anonymous method. /// </summary> public AnonymousExpression CurrentAnonymousMethod; readonly IMemberContext member_context; readonly SourceMethodBuilder methodSymbols; DynamicSiteClass dynamic_site_container; Label? return_label; List<IExpressionCleanup> epilogue_expressions; public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type, SourceMethodBuilder methodSymbols) { this.member_context = rc; this.ig = ig; this.return_type = return_type; if (rc.Module.Compiler.Settings.Checked) flags |= Options.CheckedScope; if (methodSymbols != null) { this.methodSymbols = methodSymbols; if (!rc.Module.Compiler.Settings.Optimize) flags |= Options.AccurateDebugInfo; } else { flags |= Options.OmitDebugInfo; } #if STATIC ig.__CleverExceptionBlockAssistance (); #endif } #region Properties internal AsyncTaskStorey AsyncTaskStorey { get { return CurrentAnonymousMethod.Storey as AsyncTaskStorey; } } public BuiltinTypes BuiltinTypes { get { return MemberContext.Module.Compiler.BuiltinTypes; } } public ConditionalAccessContext ConditionalAccess { get; set; } public TypeSpec CurrentType { get { return member_context.CurrentType; } } public TypeParameters CurrentTypeParameters { get { return member_context.CurrentTypeParameters; } } public MemberCore CurrentTypeDefinition { get { return member_context.CurrentMemberDefinition; } } public bool EmitAccurateDebugInfo { get { return (flags & Options.AccurateDebugInfo) != 0; } } public bool HasMethodSymbolBuilder { get { return methodSymbols != null; } } public bool HasReturnLabel { get { return return_label.HasValue; } } public bool IsStatic { get { return member_context.IsStatic; } } public bool IsStaticConstructor { get { return member_context.IsStatic && (flags & Options.ConstructorScope) != 0; } } public bool IsAnonymousStoreyMutateRequired { get { return CurrentAnonymousMethod != null && CurrentAnonymousMethod.Storey != null && CurrentAnonymousMethod.Storey.Mutator != null; } } public IMemberContext MemberContext { get { return member_context; } } public ModuleContainer Module { get { return member_context.Module; } } public bool NotifyEvaluatorOnStore { get { return Module.Evaluator != null && Module.Evaluator.ModificationListener != null; } } // Has to be used for specific emitter errors only any // possible resolver errors have to be reported during Resolve public Report Report { get { return member_context.Module.Compiler.Report; } } public TypeSpec ReturnType { get { return return_type; } } // // The label where we have to jump before leaving the context // public Label ReturnLabel { get { return return_label.Value; } } public List<IExpressionCleanup> StatementEpilogue { get { return epilogue_expressions; } } public LocalVariable AsyncThrowVariable { get; set; } public List<TryFinally> TryFinallyUnwind { get; set; } public Label RecursivePatternLabel { get; set; } #endregion public void AddStatementEpilog (IExpressionCleanup cleanupExpression) { if (epilogue_expressions == null) { epilogue_expressions = new List<IExpressionCleanup> (); } else if (epilogue_expressions.Contains (cleanupExpression)) { return; } epilogue_expressions.Add (cleanupExpression); } public void AssertEmptyStack () { #if STATIC if (ig.__StackHeight != 0) throw new InternalErrorException ("Await yields with non-empty stack in `{0}", member_context.GetSignatureForError ()); #endif } /// <summary> /// This is called immediately before emitting an IL opcode to tell the symbol /// writer to which source line this opcode belongs. /// </summary> public bool Mark (Location loc) { if ((flags & Options.OmitDebugInfo) != 0) return false; if (loc.IsNull || methodSymbols == null) return false; var sf = loc.SourceFile; if (sf.IsHiddenLocation (loc)) return false; methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false); return true; } public void MarkCallEntry (Location loc) { if (!EmitAccurateDebugInfo) return; // // TODO: This should emit different kind of sequence point to make // step-over work for statement over multiple lines // // Debugging experience for Foo (A () + B ()) where A and B are // on separate lines is not great // Mark (loc); } public void DefineLocalVariable (string name, LocalBuilder builder) { if ((flags & Options.OmitDebugInfo) != 0) return; methodSymbols.AddLocal (builder.LocalIndex, name); } public void BeginCatchBlock (TypeSpec type) { if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); ig.BeginCatchBlock (type.GetMetaInfo ()); } public void BeginFilterHandler () { ig.BeginCatchBlock (null); } public void BeginExceptionBlock () { ig.BeginExceptionBlock (); } public void BeginExceptionFilterBlock () { ig.BeginExceptFilterBlock (); } public void BeginFinallyBlock () { ig.BeginFinallyBlock (); } public void BeginScope (int scopeIndex) { if ((flags & Options.OmitDebugInfo) != 0) return; methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset, scopeIndex); } public void BeginCompilerScope (int scopeIndex) { if ((flags & Options.OmitDebugInfo) != 0) return; methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset, scopeIndex); } public void EndExceptionBlock () { ig.EndExceptionBlock (); } public void EndScope () { if ((flags & Options.OmitDebugInfo) != 0) return; methodSymbols.EndBlock (ig.ILOffset); } public void CloseConditionalAccess (TypeSpec type) { if (type != null) Emit (OpCodes.Newobj, Nullable.NullableInfo.GetConstructor (type)); MarkLabel (ConditionalAccess.EndLabel); ConditionalAccess = null; } // // Creates a nested container in this context for all dynamic compiler generated stuff // internal DynamicSiteClass CreateDynamicSite () { if (dynamic_site_container == null) { var mc = member_context.CurrentMemberDefinition as MemberBase; dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters); CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container); dynamic_site_container.CreateContainer (); dynamic_site_container.DefineContainer (); dynamic_site_container.Define (); var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes); var inflated = dynamic_site_container.CurrentType.InflateMember (inflator); CurrentType.MemberCache.AddMember (inflated); } return dynamic_site_container; } public Label CreateReturnLabel () { if (!return_label.HasValue) return_label = DefineLabel (); return return_label.Value; } public LocalBuilder DeclareLocal (TypeSpec type, bool pinned) { if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); if (pinned) { // // This is for .net compatibility. I am not sure why pinned // pointer temps are converted to & even if they are pointers to // pointers. // var pt = type as PointerContainer; if (pt != null) { type = pt.Element; if (type.Kind == MemberKind.Void) type = Module.Compiler.BuiltinTypes.IntPtr; return ig.DeclareLocal (type.GetMetaInfo ().MakeByRefType (), true); } } return ig.DeclareLocal (type.GetMetaInfo (), pinned); } public Label DefineLabel () { return ig.DefineLabel (); } // // Creates temporary field in current async storey // public StackFieldExpr GetTemporaryField (TypeSpec type, bool initializedFieldRequired = false) { var f = AsyncTaskStorey.AddCapturedLocalVariable (type, initializedFieldRequired); var fexpr = new StackFieldExpr (f); fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null); return fexpr; } public void MarkLabel (Label label) { ig.MarkLabel (label); } public void Emit (OpCode opcode) { ig.Emit (opcode); } public void Emit (OpCode opcode, LocalBuilder local) { ig.Emit (opcode, local); } public void Emit (OpCode opcode, string arg) { ig.Emit (opcode, arg); } public void Emit (OpCode opcode, double arg) { ig.Emit (opcode, arg); } public void Emit (OpCode opcode, float arg) { ig.Emit (opcode, arg); } public void Emit (OpCode opcode, Label label) { ig.Emit (opcode, label); } public void Emit (OpCode opcode, Label[] labels) { ig.Emit (opcode, labels); } public void Emit (OpCode opcode, TypeSpec type) { if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); ig.Emit (opcode, type.GetMetaInfo ()); } public void Emit (OpCode opcode, FieldSpec field) { if (IsAnonymousStoreyMutateRequired) field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator); ig.Emit (opcode, field.GetMetaInfo ()); } public void Emit (OpCode opcode, MethodSpec method) { if (IsAnonymousStoreyMutateRequired) method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator); if (method.IsConstructor) ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ()); else ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ()); } // TODO: REMOVE breaks mutator public void Emit (OpCode opcode, MethodInfo method) { ig.Emit (opcode, method); } public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs) { // TODO MemberCache: This should mutate too ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs); } public void EmitArrayNew (ArrayContainer ac) { if (ac.Rank == 1) { var type = IsAnonymousStoreyMutateRequired ? CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) : ac.Element; ig.Emit (OpCodes.Newarr, type.GetMetaInfo ()); } else { if (IsAnonymousStoreyMutateRequired) ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator); ig.Emit (OpCodes.Newobj, ac.GetConstructor ()); } } public void EmitArrayAddress (ArrayContainer ac) { if (ac.Rank > 1) { if (IsAnonymousStoreyMutateRequired) ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator); ig.Emit (OpCodes.Call, ac.GetAddressMethod ()); } else { var type = IsAnonymousStoreyMutateRequired ? CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) : ac.Element; ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ()); } } // // Emits the right opcode to load from an array // public void EmitArrayLoad (ArrayContainer ac) { if (ac.Rank > 1) { if (IsAnonymousStoreyMutateRequired) ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator); ig.Emit (OpCodes.Call, ac.GetGetMethod ()); return; } var type = ac.Element; if (type.Kind == MemberKind.Enum) type = EnumSpec.GetUnderlyingType (type); switch (type.BuiltinType) { case BuiltinTypeSpec.Type.Bool: // // bool array can actually store any byte value in underlying byte slot // and C# spec does not specify any normalization rule, except the result // is undefined // case BuiltinTypeSpec.Type.Byte: ig.Emit (OpCodes.Ldelem_U1); break; case BuiltinTypeSpec.Type.SByte: ig.Emit (OpCodes.Ldelem_I1); break; case BuiltinTypeSpec.Type.Short: ig.Emit (OpCodes.Ldelem_I2); break; case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.Char: ig.Emit (OpCodes.Ldelem_U2); break; case BuiltinTypeSpec.Type.Int: ig.Emit (OpCodes.Ldelem_I4); break; case BuiltinTypeSpec.Type.UInt: ig.Emit (OpCodes.Ldelem_U4); break; case BuiltinTypeSpec.Type.ULong: case BuiltinTypeSpec.Type.Long: ig.Emit (OpCodes.Ldelem_I8); break; case BuiltinTypeSpec.Type.Float: ig.Emit (OpCodes.Ldelem_R4); break; case BuiltinTypeSpec.Type.Double: ig.Emit (OpCodes.Ldelem_R8); break; case BuiltinTypeSpec.Type.IntPtr: ig.Emit (OpCodes.Ldelem_I); break; default: switch (type.Kind) { case MemberKind.Struct: if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ()); ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ()); break; case MemberKind.TypeParameter: if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ()); break; case MemberKind.PointerType: ig.Emit (OpCodes.Ldelem_I); break; default: ig.Emit (OpCodes.Ldelem_Ref); break; } break; } } // // Emits the right opcode to store to an array // public void EmitArrayStore (ArrayContainer ac) { if (ac.Rank > 1) { if (IsAnonymousStoreyMutateRequired) ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator); ig.Emit (OpCodes.Call, ac.GetSetMethod ()); return; } var type = ac.Element; if (type.Kind == MemberKind.Enum) type = EnumSpec.GetUnderlyingType (type); switch (type.BuiltinType) { case BuiltinTypeSpec.Type.Byte: case BuiltinTypeSpec.Type.SByte: case BuiltinTypeSpec.Type.Bool: Emit (OpCodes.Stelem_I1); return; case BuiltinTypeSpec.Type.Short: case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.Char: Emit (OpCodes.Stelem_I2); return; case BuiltinTypeSpec.Type.Int: case BuiltinTypeSpec.Type.UInt: Emit (OpCodes.Stelem_I4); return; case BuiltinTypeSpec.Type.Long: case BuiltinTypeSpec.Type.ULong: Emit (OpCodes.Stelem_I8); return; case BuiltinTypeSpec.Type.Float: Emit (OpCodes.Stelem_R4); return; case BuiltinTypeSpec.Type.Double: Emit (OpCodes.Stelem_R8); return; } switch (type.Kind) { case MemberKind.Struct: Emit (OpCodes.Stobj, type); break; case MemberKind.TypeParameter: Emit (OpCodes.Stelem, type); break; case MemberKind.PointerType: Emit (OpCodes.Stelem_I); break; default: Emit (OpCodes.Stelem_Ref); break; } } public void EmitInt (int i) { EmitIntConstant (i); } void EmitIntConstant (int i) { switch (i) { case -1: ig.Emit (OpCodes.Ldc_I4_M1); break; case 0: ig.Emit (OpCodes.Ldc_I4_0); break; case 1: ig.Emit (OpCodes.Ldc_I4_1); break; case 2: ig.Emit (OpCodes.Ldc_I4_2); break; case 3: ig.Emit (OpCodes.Ldc_I4_3); break; case 4: ig.Emit (OpCodes.Ldc_I4_4); break; case 5: ig.Emit (OpCodes.Ldc_I4_5); break; case 6: ig.Emit (OpCodes.Ldc_I4_6); break; case 7: ig.Emit (OpCodes.Ldc_I4_7); break; case 8: ig.Emit (OpCodes.Ldc_I4_8); break; default: if (i >= -128 && i <= 127) { ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i); } else ig.Emit (OpCodes.Ldc_I4, i); break; } } public void EmitLong (long l) { if (l >= int.MinValue && l <= int.MaxValue) { EmitIntConstant (unchecked ((int) l)); ig.Emit (OpCodes.Conv_I8); } else if (l >= 0 && l <= uint.MaxValue) { EmitIntConstant (unchecked ((int) l)); ig.Emit (OpCodes.Conv_U8); } else { ig.Emit (OpCodes.Ldc_I8, l); } } // // Load the object from the pointer. // public void EmitLoadFromPtr (TypeSpec type) { if (type.Kind == MemberKind.Enum) type = EnumSpec.GetUnderlyingType (type); switch (type.BuiltinType) { case BuiltinTypeSpec.Type.Int: ig.Emit (OpCodes.Ldind_I4); break; case BuiltinTypeSpec.Type.UInt: ig.Emit (OpCodes.Ldind_U4); break; case BuiltinTypeSpec.Type.Short: ig.Emit (OpCodes.Ldind_I2); break; case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.Char: ig.Emit (OpCodes.Ldind_U2); break; case BuiltinTypeSpec.Type.Byte: ig.Emit (OpCodes.Ldind_U1); break; case BuiltinTypeSpec.Type.SByte: case BuiltinTypeSpec.Type.Bool: ig.Emit (OpCodes.Ldind_I1); break; case BuiltinTypeSpec.Type.ULong: case BuiltinTypeSpec.Type.Long: ig.Emit (OpCodes.Ldind_I8); break; case BuiltinTypeSpec.Type.Float: ig.Emit (OpCodes.Ldind_R4); break; case BuiltinTypeSpec.Type.Double: ig.Emit (OpCodes.Ldind_R8); break; case BuiltinTypeSpec.Type.IntPtr: ig.Emit (OpCodes.Ldind_I); break; default: switch (type.Kind) { case MemberKind.Struct: case MemberKind.TypeParameter: if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ()); break; case MemberKind.PointerType: ig.Emit (OpCodes.Ldind_I); break; default: ig.Emit (OpCodes.Ldind_Ref); break; } break; } } public void EmitNull () { ig.Emit (OpCodes.Ldnull); } public void EmitArgumentAddress (int pos) { if (!IsStatic) ++pos; if (pos > byte.MaxValue) ig.Emit (OpCodes.Ldarga, pos); else ig.Emit (OpCodes.Ldarga_S, (byte) pos); } public void EmitArgumentLoad (int pos) { if (!IsStatic) ++pos; switch (pos) { case 0: ig.Emit (OpCodes.Ldarg_0); break; case 1: ig.Emit (OpCodes.Ldarg_1); break; case 2: ig.Emit (OpCodes.Ldarg_2); break; case 3: ig.Emit (OpCodes.Ldarg_3); break; default: if (pos > byte.MaxValue) ig.Emit (OpCodes.Ldarg, pos); else ig.Emit (OpCodes.Ldarg_S, (byte) pos); break; } } public void EmitArgumentStore (int pos) { if (!IsStatic) ++pos; if (pos > byte.MaxValue) ig.Emit (OpCodes.Starg, pos); else ig.Emit (OpCodes.Starg_S, (byte) pos); } // // The stack contains the pointer and the value of type `type' // public void EmitStoreFromPtr (TypeSpec type) { if (type.IsEnum) type = EnumSpec.GetUnderlyingType (type); switch (type.BuiltinType) { case BuiltinTypeSpec.Type.Int: case BuiltinTypeSpec.Type.UInt: ig.Emit (OpCodes.Stind_I4); return; case BuiltinTypeSpec.Type.Long: case BuiltinTypeSpec.Type.ULong: ig.Emit (OpCodes.Stind_I8); return; case BuiltinTypeSpec.Type.Char: case BuiltinTypeSpec.Type.Short: case BuiltinTypeSpec.Type.UShort: ig.Emit (OpCodes.Stind_I2); return; case BuiltinTypeSpec.Type.Float: ig.Emit (OpCodes.Stind_R4); return; case BuiltinTypeSpec.Type.Double: ig.Emit (OpCodes.Stind_R8); return; case BuiltinTypeSpec.Type.Byte: case BuiltinTypeSpec.Type.SByte: case BuiltinTypeSpec.Type.Bool: ig.Emit (OpCodes.Stind_I1); return; case BuiltinTypeSpec.Type.IntPtr: ig.Emit (OpCodes.Stind_I); return; } switch (type.Kind) { case MemberKind.Struct: case MemberKind.TypeParameter: if (IsAnonymousStoreyMutateRequired) type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type); ig.Emit (OpCodes.Stobj, type.GetMetaInfo ()); break; case MemberKind.PointerType: ig.Emit (OpCodes.Stind_I); break; default: ig.Emit (OpCodes.Stind_Ref); break; } } public void EmitThis () { ig.Emit (OpCodes.Ldarg_0); } public void EmitEpilogue () { if (epilogue_expressions == null) return; foreach (var e in epilogue_expressions) e.EmitCleanup (this); epilogue_expressions = null; } /// <summary> /// Returns a temporary storage for a variable of type t as /// a local variable in the current body. /// </summary> public LocalBuilder GetTemporaryLocal (TypeSpec t) { if (temporary_storage != null) { object o; if (temporary_storage.TryGetValue (t, out o)) { if (o is Stack<LocalBuilder>) { var s = (Stack<LocalBuilder>) o; o = s.Count == 0 ? null : s.Pop (); } else { temporary_storage.Remove (t); } } if (o != null) return (LocalBuilder) o; } return DeclareLocal (t, false); } public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t) { if (temporary_storage == null) { temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default); temporary_storage.Add (t, b); return; } object o; if (!temporary_storage.TryGetValue (t, out o)) { temporary_storage.Add (t, b); return; } var s = o as Stack<LocalBuilder>; if (s == null) { s = new Stack<LocalBuilder> (); s.Push ((LocalBuilder)o); temporary_storage [t] = s; } s.Push (b); } /// <summary> /// ReturnValue creates on demand the LocalBuilder for the /// return value from the function. By default this is not /// used. This is only required when returns are found inside /// Try or Catch statements. /// /// This method is typically invoked from the Emit phase, so /// we allow the creation of a return label if it was not /// requested during the resolution phase. Could be cleaned /// up, but it would replicate a lot of logic in the Emit phase /// of the code that uses it. /// </summary> public LocalBuilder TemporaryReturn () { if (return_value == null){ return_value = DeclareLocal (return_type, false); } return return_value; } } public class ConditionalAccessContext { public ConditionalAccessContext (TypeSpec type, Label endLabel) { Type = type; EndLabel = endLabel; } public bool Statement { get; set; } public Label EndLabel { get; private set; } public TypeSpec Type { get; private set; } } struct CallEmitter { public Expression InstanceExpression; // // When call has to leave an extra copy of all arguments on the stack // public bool DuplicateArguments; // // Does not emit InstanceExpression load when InstanceExpressionOnStack // is set. Used by compound assignments. // public bool InstanceExpressionOnStack; // // Any of arguments contains await expression // public bool HasAwaitArguments; public bool ConditionalAccess; // // When dealing with await arguments the original arguments are converted // into a new set with hoisted stack results // public Arguments EmittedArguments; public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc) { EmitPredefined (ec, method, Arguments, false, loc); } public void EmitStatement (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc) { EmitPredefined (ec, method, Arguments, true, loc); } public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, bool statement = false, Location? loc = null) { Expression instance_copy = null; if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) { HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait (); if (HasAwaitArguments && InstanceExpressionOnStack) { throw new NotSupportedException (); } } OpCode call_op; LocalTemporary lt = null; if (method.IsStatic) { call_op = OpCodes.Call; } else { call_op = IsVirtualCallRequired (InstanceExpression, method) ? OpCodes.Callvirt : OpCodes.Call; if (HasAwaitArguments) { instance_copy = InstanceExpression.EmitToField (ec); var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType)); if (Arguments == null) { if (ConditionalAccess) ie.Emit (ec, true); else ie.EmitLoad (ec, true); } } else if (!InstanceExpressionOnStack) { var ie = new InstanceEmitter (InstanceExpression, IsAddressCall (InstanceExpression, call_op, method.DeclaringType)); ie.Emit (ec, ConditionalAccess); if (DuplicateArguments) { ec.Emit (OpCodes.Dup); if (Arguments != null && Arguments.Count != 0) { lt = new LocalTemporary (ie.GetStackType (ec)); lt.Store (ec); instance_copy = lt; } } } } if (Arguments != null && !InstanceExpressionOnStack) { EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments); if (EmittedArguments != null) { if (instance_copy != null) { var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType)); ie.Emit (ec, ConditionalAccess); if (lt != null) lt.Release (ec); } EmittedArguments.Emit (ec); } } if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) { ec.Emit (OpCodes.Constrained, InstanceExpression.Type); } if (loc != null) { // // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to // break at right place when LHS expression can be stepped-into // ec.MarkCallEntry (loc.Value); } // // Set instance expression to actual result expression. When it contains await it can be // picked up by caller // InstanceExpression = instance_copy; if (method.Parameters.HasArglist) { var varargs_types = GetVarargsTypes (method, Arguments); ec.Emit (call_op, method, varargs_types); } else { // // If you have: // this.DoFoo (); // and DoFoo is not virtual, you can omit the callvirt, // because you don't need the null checking behavior. // ec.Emit (call_op, method); } // // Pop the return value if there is one and stack should be empty // if (statement && method.ReturnType.Kind != MemberKind.Void) ec.Emit (OpCodes.Pop); } static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments) { AParametersCollection pd = method.Parameters; Argument a = arguments[pd.Count - 1]; Arglist list = (Arglist) a.Expr; return list.ArgumentTypes; } // // Used to decide whether call or callvirt is needed // static bool IsVirtualCallRequired (Expression instance, MethodSpec method) { // // There are 2 scenarious where we emit callvirt // // Case 1: A method is virtual and it's not used to call base // Case 2: A method instance expression can be null. In this casen callvirt ensures // correct NRE exception when the method is called // var decl_type = method.DeclaringType; if (decl_type.IsStruct || decl_type.IsEnum) return false; if (instance is BaseThis) return false; // // It's non-virtual and will never be null and it can be determined // whether it's known value or reference type by verifier // if (!method.IsVirtual && Expression.IsNeverNull (instance) && !instance.Type.IsGenericParameter) return false; return true; } static bool IsAddressCall (Expression instance, OpCode callOpcode, TypeSpec declaringType) { var instance_type = instance.Type; return (instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) || instance_type.IsGenericParameter || declaringType.IsNullableType; } } public struct InstanceEmitter { readonly Expression instance; readonly bool addressRequired; public InstanceEmitter (Expression instance, bool addressLoad) { this.instance = instance; this.addressRequired = addressLoad; } public void Emit (EmitContext ec, bool conditionalAccess) { Label NullOperatorLabel; Nullable.Unwrap unwrap; if (conditionalAccess && Expression.IsNeverNull (instance)) conditionalAccess = false; if (conditionalAccess) { NullOperatorLabel = ec.DefineLabel (); unwrap = instance as Nullable.Unwrap; } else { NullOperatorLabel = new Label (); unwrap = null; } IMemoryLocation instance_address = null; bool conditional_access_dup = false; if (unwrap != null) { unwrap.Store (ec); unwrap.EmitCheck (ec); ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel); } else { if (conditionalAccess && addressRequired) { // // Don't allocate temp variable when instance load is cheap and load and load-address // operate on same memory // instance_address = instance as VariableReference; if (instance_address == null) instance_address = instance as LocalTemporary; if (instance_address == null) { EmitLoad (ec, false); ec.Emit (OpCodes.Dup); ec.EmitLoadFromPtr (instance.Type); conditional_access_dup = true; } else { instance.Emit (ec); } } else { EmitLoad (ec, !conditionalAccess); if (conditionalAccess) { conditional_access_dup = !ExpressionAnalyzer.IsInexpensiveLoad (instance); if (conditional_access_dup) ec.Emit (OpCodes.Dup); } } if (conditionalAccess) { if (instance.Type.Kind == MemberKind.TypeParameter) ec.Emit (OpCodes.Box, instance.Type); ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel); if (conditional_access_dup) ec.Emit (OpCodes.Pop); } } if (conditionalAccess) { if (!ec.ConditionalAccess.Statement) { var t = ec.ConditionalAccess.Type; if (t.IsNullableType) Nullable.LiftedNull.Create (t, Location.Null).Emit (ec); else { ec.EmitNull (); if (t.IsGenericParameter) ec.Emit (OpCodes.Unbox_Any, t); } } ec.Emit (OpCodes.Br, ec.ConditionalAccess.EndLabel); ec.MarkLabel (NullOperatorLabel); if (instance_address != null) { instance_address.AddressOf (ec, AddressOp.Load); } else if (unwrap != null) { unwrap.Emit (ec); if (addressRequired) { var tmp = ec.GetTemporaryLocal (unwrap.Type); ec.Emit (OpCodes.Stloc, tmp); ec.Emit (OpCodes.Ldloca, tmp); ec.FreeTemporaryLocal (tmp, unwrap.Type); } } else if (!conditional_access_dup) { instance.Emit (ec); } } } public void EmitLoad (EmitContext ec, bool boxInstance) { var instance_type = instance.Type; // // Push the instance expression // if (addressRequired) { // // If the expression implements IMemoryLocation, then // we can optimize and use AddressOf on the // return. // // If not we have to use some temporary storage for // it. var iml = instance as IMemoryLocation; if (iml != null) { iml.AddressOf (ec, AddressOp.Load); } else { LocalTemporary temp = new LocalTemporary (instance_type); instance.Emit (ec); temp.Store (ec); temp.AddressOf (ec, AddressOp.Load); } return; } instance.Emit (ec); // Only to make verifier happy if (boxInstance && ExpressionAnalyzer.RequiresBoxing (instance)) { ec.Emit (OpCodes.Box, instance_type); } } public TypeSpec GetStackType (EmitContext ec) { var instance_type = instance.Type; if (addressRequired) return ReferenceContainer.MakeType (ec.Module, instance_type); if (instance_type.IsStructOrEnum) return ec.Module.Compiler.BuiltinTypes.Object; return instance_type; } } static class ExpressionAnalyzer { public static bool RequiresBoxing (Expression instance) { var instance_type = instance.Type; if (instance_type.IsGenericParameter && !(instance is This) && TypeSpec.IsReferenceType (instance_type)) return true; if (instance_type.IsStructOrEnum) return true; return false; } // // Returns true for cheap race-free load, where we can avoid using dup // public static bool IsInexpensiveLoad (Expression instance) { if (instance is Constant) return instance.IsSideEffectFree; if (RequiresBoxing (instance)) return false; var vr = instance as VariableReference; if (vr != null) { // Load from captured local would be racy without dup return !vr.IsRef && !vr.IsHoisted; } if (instance is LocalTemporary) return true; var fe = instance as FieldExpr; if (fe != null) return fe.IsStatic || fe.InstanceExpression is This; return false; } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Verify.V2.Service { /// <summary> /// Create a new Rate Limit for a Service /// </summary> public class CreateRateLimitOptions : IOptions<RateLimitResource> { /// <summary> /// The SID of the Service that the resource is associated with /// </summary> public string PathServiceSid { get; } /// <summary> /// A unique, developer assigned name of this Rate Limit. /// </summary> public string UniqueName { get; } /// <summary> /// Description of this Rate Limit /// </summary> public string Description { get; set; } /// <summary> /// Construct a new CreateRateLimitOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service that the resource is associated with </param> /// <param name="uniqueName"> A unique, developer assigned name of this Rate Limit. </param> public CreateRateLimitOptions(string pathServiceSid, string uniqueName) { PathServiceSid = pathServiceSid; UniqueName = uniqueName; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } if (Description != null) { p.Add(new KeyValuePair<string, string>("Description", Description)); } return p; } } /// <summary> /// Update a specific Rate Limit. /// </summary> public class UpdateRateLimitOptions : IOptions<RateLimitResource> { /// <summary> /// The SID of the Service that the resource is associated with /// </summary> public string PathServiceSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Description of this Rate Limit /// </summary> public string Description { get; set; } /// <summary> /// Construct a new UpdateRateLimitOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service that the resource is associated with </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public UpdateRateLimitOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Description != null) { p.Add(new KeyValuePair<string, string>("Description", Description)); } return p; } } /// <summary> /// Fetch a specific Rate Limit. /// </summary> public class FetchRateLimitOptions : IOptions<RateLimitResource> { /// <summary> /// The SID of the Service that the resource is associated with /// </summary> public string PathServiceSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchRateLimitOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service that the resource is associated with </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public FetchRateLimitOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Retrieve a list of all Rate Limits for a service. /// </summary> public class ReadRateLimitOptions : ReadOptions<RateLimitResource> { /// <summary> /// The SID of the Service that the resource is associated with /// </summary> public string PathServiceSid { get; } /// <summary> /// Construct a new ReadRateLimitOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service that the resource is associated with </param> public ReadRateLimitOptions(string pathServiceSid) { PathServiceSid = pathServiceSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// Delete a specific Rate Limit. /// </summary> public class DeleteRateLimitOptions : IOptions<RateLimitResource> { /// <summary> /// The SID of the Service that the resource is associated with /// </summary> public string PathServiceSid { get; } /// <summary> /// The unique string that identifies the resource /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteRateLimitOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Service that the resource is associated with </param> /// <param name="pathSid"> The unique string that identifies the resource </param> public DeleteRateLimitOptions(string pathServiceSid, string pathSid) { PathServiceSid = pathServiceSid; PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex001.complex001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex001.complex001; // <Title>Derived generic types</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass<T> where T : List<object> { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<List<object>> mc = new MyClass<List<dynamic>>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex002.complex002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex002.complex002; // <Title>Derived generic types</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class MyClass<T> where T : List<object> { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<List<dynamic>> mc = new MyClass<List<dynamic>>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex008.complex008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex008.complex008; // <Title>Generic constraints</Title> // <Description> Trying to pass in int and dynamic as type parameters used to give an error saying that there is no boxing conversion from int to dynamic // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class M { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int rez = M1<int, dynamic>(); rez += M2<int, dynamic>(); int i = 4; dynamic d = 4; // Simple call let Runtime decide d's type which is 'int' instead of 'object' rez += M3(i, d); return rez > 0 ? 1 : 0; } public static int M3<T, S>(T t, S s) where T : S { // if (typeof(T) != typeof(int) || typeof(S) != typeof(object)) return 1; if (typeof(T) != typeof(int) || typeof(S) != typeof(int)) return 1; return 0; } public static int M2<T, S>() where T : struct, S { if (typeof(T) != typeof(int) || typeof(S) != typeof(object)) return 1; return 0; } public static int M1<T, S>() where T : S { if (typeof(T) != typeof(int) || typeof(S) != typeof(object)) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex009.complex009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex009.complex009; // <Title>Derived generic types</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic c = new C(); c.NakedGen1<GenDerClass<int>, GenBaseClass<int>>(); c.NakedGen1<GenDerClass<Struct>, GenBaseClass<Struct>>(); return 0; } } public class C { public void NakedGen1<T, U>() where T : U { } } public struct Struct { } public class GenBaseClass<T> { } public class GenDerClass<T> : GenBaseClass<T> { } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex010.complex010 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex010.complex010; // <Title>Derived generic types</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Base<T> { public virtual void Foo<G>() where G : T, new() { } } public class DerivedNullableOfInt : Base<int?> { public override void Foo<G>() { dynamic d = new G(); d = 4; d.ToString(); Program.Status = 1; } } public class Program { public static int Status = 0; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new DerivedNullableOfInt(); d.Foo<int?>(); if (Program.Status == 1) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex011.complex011 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex011.complex011; // <Title>Derived generic types</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Base<T> { public virtual IEnumerable<G> Foo<G>() where G : T, new() { return null; } } public class DerivedNullableOfInt : Base<int?> { public override IEnumerable<G> Foo<G>() { yield return new G(); } } public class Program { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new DerivedNullableOfInt(); var x = d.Foo<int?>(); return x != null ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex012.complex012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.complex012.complex012; // <Title>Derived generic types</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class Base<T> { public virtual int Foo<G>() where G : T, new() { return -1; } } public class DerivedNullableOfInt : Base<int?> { public override int Foo<G>() { int i = 3; Func<G, int> f = x => i; return f(new G()); } } public class Program { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new DerivedNullableOfInt(); var x = d.Foo<int?>(); if (x != null) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple001.simple001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple001.simple001; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T> where T : class { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<object> mc = new MyClass<dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple002.simple002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple002.simple002; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T> where T : class { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<dynamic> mc = new MyClass<object>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple006.simple006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple006.simple006; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class MyClass<T> { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<object> mc = new MyClass<dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple008.simple008 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple008.simple008; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T, U> where T : U { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<dynamic, object> mc = new MyClass<dynamic, object>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple009.simple009 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple009.simple009; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T> where T : class { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<dynamic> mc = new MyClass<dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple012.simple012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple012.simple012; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class MyClass<T, U> where T : U { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<object, object> mc = new MyClass<dynamic, dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple013.simple013 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple013.simple013; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T, U> where T : U { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<dynamic, object> mc = new MyClass<object, dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple015.simple015 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple015.simple015; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T> where T : new() { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<dynamic> mc = new MyClass<dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple016.simple016 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple016.simple016; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class MyClass<T> where T : new() { public void Foo() { Test.Status = 1; } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<object> mc = new MyClass<dynamic>(); mc.Foo(); if (Test.Status != 1) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple018.simple018 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple018.simple018; // <Title>Generic constraints</Title> // <Description></Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = new Test(); x.Bar<string, dynamic>(); var y = new Test(); y.Bar<string, dynamic>(); // used to be error CS0311: // The type 'string' cannot be used as type parameter 'T' in the generic type or method 'A.Foo<T,S>()'. // There is no implicit reference conversion from 'string' to '::dynamic'. return 0; } public void Bar<T, S>() where T : S { } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple019.simple019 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple019.simple019; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class B { public static int Status = 1; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = new B(); x.Foo<int>(); return B.Status; } public void Foo<T, S>() where T : S { B.Status = 1; } public void Foo<T>() { B.Status = 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple020.simple020 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple020.simple020; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class B { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = new B(); try { x.Foo(); // Unexpected NullReferenceException } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "B.Foo<T>()")) return 0; } return 1; } public void Foo<T>() { } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple021.simple021 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple021.simple021; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class B { public static int Status = 1; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = new B(); x.Foo<int, int>(); return B.Status; } public void Foo<T, S>() where T : S // The constraint is important part { B.Status = 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple022.simple022 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.simple022.simple022; // <Title>Generic constraints</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class B { public static int Status = 1; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic x = new B(); try { x.Foo<int>(); // Unexpected NullReferenceException } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArity, e.Message, "B.Foo<T,S>()", ErrorVerifier.GetErrorElement(ErrorElementId.SK_METHOD), "2")) B.Status = 0; } return B.Status; } public void Foo<T, S>() where T : S { B.Status = 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference001.typeinference001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference001.typeinference001; // <Title>Generic Type Inference</Title> // <Description> Runtime type inference succeeds in cases where it should fail // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class C { public static void M<T>(T x, T y) { } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { string x = "string"; dynamic y = 7; try { C.M(x, y); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "C.M<T>(T, T)")) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference002.typeinference002 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference002.typeinference002; // <Title>Generic Type Inference</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class A { public void M<T>(T x, T y) { } } public class TestClass { [Fact] public void RunTest() { Test.DynamicCSharpRunTest(); } } public struct Test { public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var vv = new A(); dynamic vd = new A(); int ret = 0; // dyn (null) & string -> string dynamic dynPara = null; string str = "QC"; try { vv.M(dynPara, str); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("1)" + ex); ret++; // Fail } try { vd.M(dynPara, str); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("2)" + ex); ret++; // Fail } // dyn (null) & class dynPara = null; var a = new A(); try { vv.M(dynPara, a); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("3)" + ex); ret++; // Fail } try { vd.M(a, dynPara); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("4)" + ex); ret++; // Fail } // dyn (class), dyn (null) dynPara = new A(); dynamic dynP2 = null; try { vv.M(dynPara, dynP2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("5)" + ex); ret++; // Fail } try { vd.M(dynP2, dynPara); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("6)" + ex); ret++; // Fail } return 0 == ret ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference003.typeinference003 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference003.typeinference003; // <Title>Generic Type Inference</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public struct S { public void M<T>(T x, T y) { } } public struct Test { [Fact(Skip = "870811")] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var vv = new S(); dynamic vd = new S(); int ret = 6; // dyn (int), string (null) dynamic dynPara = 100; string str = null; try { vv.M(str, dynPara); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "S.M<T>(T, T)")) ret--; // Pass } try { vd.M(dynPara, str); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "S.M<T>(T, T)")) ret--; // Pass } // dyn (null), int -\-> int? dynPara = null; int n = 0; try { vv.M(dynPara, n); System.Console.WriteLine("3) no ex"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<int>(int, int)")) ret--; // Pass } try { vd.M(n, dynPara); System.Console.WriteLine("4) no ex"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<int>(int, int)")) ret--; // Pass } // dyn->struct, dyn->null dynPara = new Test(); dynamic dynP2 = null; try { vv.M(dynPara, dynP2); System.Console.WriteLine("5) no ex"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<Test>(Test, Test)")) ret--; // Pass } try { vd.M(dynPara, dynP2); System.Console.WriteLine("6) no ex"); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "S.M<Test>(Test, Test)")) ret--; // Pass } return 0 == ret ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference004.typeinference004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference004.typeinference004; // <Title>Generic Type Inference</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { public void M<T>(T x, T y, T z) { } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var obj = new Test(); dynamic dobj = new Test(); int ret = 0; // -> object dynamic d = 11; string str = "string"; object o = null; try { obj.M(d, str, o); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("1)" + ex); ret++; // Fail } try { dobj.M(o, d, str); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("2)" + ex); ret++; // Fail } // -> int? d = null; int n1 = 111111; int? n2 = 11; try { obj.M(n1, d, n2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("3)" + ex); ret++; // Fail } try { dobj.M(n1, n2, d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("4)" + ex); ret++; // Fail } // -> long d = 0; var v = -50000000000; // long byte b = 1; try { obj.M(d, v, b); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("5)" + ex); ret++; // Fail } try { dobj.M(b, d, v); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("6)" + ex); ret++; // Fail } // -> d = null; dynamic d2 = 0; long? sb = null; // failed for (s)byte, (u)short, etc. try { obj.M<long?>(d, sb, d2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("7)" + ex); ret++; // Fail } try { dobj.M<long?>(sb, d2, d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException ex) // Should Not Ex { System.Console.WriteLine("8)" + ex); ret++; // Fail } return 0 == ret ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference005.typeinference005 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference005.typeinference005; // <Title>Generic Type Inference</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public struct Test { public void M<T>(T x, T y, T z) { } [Fact(Skip = "870811")] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var vv = new Test(); dynamic vd = new Test(); int ret = 6; string x = "string"; int? y = null; dynamic z = 7; try { vv.M(x, y, z); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)")) ret--; // Pass } try { vd.M(x, z, y); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)")) ret--; // Pass } Test? o1 = null; char ch = '\0'; z = ""; try { vv.M(z, o1, ch); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)")) ret--; // Pass } try { vd.M(ch, z, o1); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.CantInferMethTypeArgs, e.Message, "Test.M<T>(T, T, T)")) ret--; // Pass } dynamic z2 = 100; z = null; try { vv.M(z2, ch, z); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Test.M<int>(int, int, int)")) ret--; // Pass } try { vd.M(z, z2, ch); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Test.M<int>(int, int, int)")) ret--; // Pass } return 0 == ret ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference006.typeinference006 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.generics.cnstraintegeregers.typeinference006.typeinference006; // <Title>Generic Type Inference</Title> // <Description> We used to give compiler errors in these cases // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections.Generic; public class A { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { int rez = 0; dynamic x = 1; rez += Bar1(1, x); rez += Bar1((dynamic)1, x); dynamic d = new List<List<int>>(); rez += Bar2(d, 1); rez += Bar2(d, (dynamic)1); var l = new List<List<int>>(); rez += Bar2(l, x); rez += Bar3(1, x, x); rez += Bar3(1, 1, x); var cls = new C<int>(); rez += cls.Foo(1, x); rez += cls.Foo(x, 1); rez += Bar4(x, 1); rez += Bar4(1, x); return rez; } public static int Bar1<T, S>(T x, S y) where T : IComparable<S> { return 0; } public static int Bar2<T, S>(T t, S s) where T : IList<List<S>> { return 0; } public static int Bar3<T, U, V>(T t, U u, V v) where T : U where U : IComparable<V> { return 0; } public static int Bar4<T, U>(T t, IComparable<U> u) where T : IComparable<U> { return 0; } } public class C<T> { public int Foo<U>(T t, U u) where U : IComparable<T> { return 0; } } // </Code> }
//----------------------------------------------------------------------- // <copyright file="AppNexusThrottleFixture.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Threading; using AppNexusClient; using ConfigManager; using Microsoft.Http; using Microsoft.VisualStudio.TestTools.UnitTesting; using Rhino.Mocks; using Rhino.Mocks.Constraints; using Utilities.Net; using Utilities.Net.Http; using Utilities.Storage; using Utilities.Storage.Testing; namespace AppNexusClientUnitTests { /// <summary>Test the AppNexus throttle</summary> [TestClass] public class AppNexusThrottleFixture { /// <summary>Success AppNexus response</summary> private const string SuccessResponse = @" { ""response"": { ""status"":""OK"", ""id"":152492, ""dbg_info"": { ""instance"":""02.hbapi.sand-08.nym2"", ""slave_hit"":false, ""db"":""master"", ""reads"":2, ""read_limit"":100, ""read_limit_seconds"":60, ""writes"":4, ""write_limit"":60, ""write_limit_seconds"":60, ""parent_dbg_info"": { ""instance"":""04.hbapi.sand-08.lax1"", ""slave_hit"":false, ""db"":""master"", ""reads"":0, ""read_limit"":100, ""read_limit_seconds"":60, ""writes"":4, ""write_limit"":60, ""write_limit_seconds"":60, ""awesomesauce_cache_used"":false, ""time"":398.32520484924, ""start_microtime"":1337390247.1187, ""version"":""1.12.4.0"" }, ""awesomesauce_cache_used"":false, ""time"":607.74183273315, ""start_microtime"":1337390246.9503, ""version"":""1.12.4.0"", ""master_instance"":""04.hbapi.sand-08.lax1"", ""proxy"":true, ""master_time"":398.32520484924 } } }"; /// <summary>NOAUTH response</summary> private const string NoAuthResponse = @" { ""response"": { ""error_id"":""NOAUTH"", ""error"":""Authentication failed - not logged in"", ""error_description"":null, ""service"":null, ""method"":null, ""error_code"":null, ""dbg_info"": { ""instance"":""02.hbapi.sand-08.nym2"", ""slave_hit"":false, ""db"":""master"", ""awesomesauce_cache_used"":false, ""time"":57.261943817139, ""start_microtime"":1337400522.6696, ""version"":""1.12.4.0"" } } }"; /// <summary>Response for auth requests</summary> private static readonly string AuthResponse = @" {{ ""response"": {{ ""status"": ""OK"", ""token"": ""{0}"" }} }}" .FormatInvariant(authToken = Guid.NewGuid().ToString("N")); /// <summary>Token from the auth response</summary> private static string authToken; /// <summary>Mock http client used for tests</summary> private IHttpClient mockHttpClient; /// <summary>Test configuration</summary> private IConfig testConfig; /// <summary> /// Initialize the mock entity repository before each test /// </summary> [TestInitialize] public void TestInitialize() { SimulatedPersistentDictionaryFactory.Initialize(); this.testConfig = new CustomConfig(new Dictionary<string, string> { { "AppNexus.Endpoint", "http://localhost/api" }, { "AppNexus.Timeout", "00:00:05" }, { "AppNexus.Retries", "5" }, { "AppNexus.RetryWait", "00:00:00.500" }, { "AppNexus.Username", "username" }, { "AppNexus.Password", "password" }, }); this.mockHttpClient = MockRepository.GenerateMock<IHttpClient>(); this.mockHttpClient.Stub(f => f.BaseAddress).Return(new Uri("http://example.com/")); this.mockHttpClient.Stub(f => f.TransportSettings).Return(new HttpWebRequestTransportSettings()); } /// <summary>Test authentication</summary> [TestMethod] public void UpdateThrottleAfterNoAuth() { // Simulate the request immediately after auth token expires var authorized = false; this.mockHttpClient.Stub(f => f.Send(Arg<HttpRequestMessage>.Is.Anything)) .Return(null) .WhenCalled(call => { var request = call.Arguments[0] as HttpRequestMessage; if (request.Uri.OriginalString.Contains("auth")) { authorized = true; call.ReturnValue = BuildResponseMessage(AuthResponse); } else { call.ReturnValue = BuildResponseMessage( authorized ? SuccessResponse : NoAuthResponse); } Thread.Sleep(50); }); var preRequestNextPeriodStart = AppNexusThrottle.NextPeriodStart; var client = new AppNexusRestClient(this.mockHttpClient, this.testConfig); AppNexusRestClient.AuthTokens[client.Id] = Guid.NewGuid().ToString("N"); var result = client.Get("/path/to/object"); Assert.IsNotNull(result); Assert.AreEqual(SuccessResponse, result); Assert.IsTrue(AppNexusThrottle.NextPeriodStart > preRequestNextPeriodStart); } /// <summary> /// Builds an HttpResponseMessage with the specified content /// </summary> /// <param name="content">Content to include in the response</param> /// <returns>The built response</returns> private static HttpResponseMessage BuildResponseMessage(string content) { return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = HttpContent.Create(content) }; } } }
#pragma warning disable 1587 #region Header /// /// JsonData.cs /// Generic type to hold JSON data (objects, arrays, and so on). This is /// the default type returned by JsonMapper.ToObject(). /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; namespace ThirdParty.Json.LitJson { internal class JsonData : IJsonWrapper, IEquatable<JsonData> { #region Fields private IList<JsonData> inst_array; private bool inst_boolean; private double inst_double; // number datatype that holds int, uint, long, and ulong values. // type field keeps track of the actual type of the value // and casted before returning the value to the client code. private ulong inst_number; private IDictionary<string, JsonData> inst_object; private string inst_string; private string json; private JsonType type; // Used to implement the IOrderedDictionary interface private IList<KeyValuePair<string, JsonData>> object_list; #endregion #region Properties public int Count { get { return EnsureCollection ().Count; } } public bool IsArray { get { return type == JsonType.Array; } } public bool IsBoolean { get { return type == JsonType.Boolean; } } public bool IsDouble { get { return type == JsonType.Double; } } public bool IsInt { get { return type == JsonType.Int; } } public bool IsUInt { get { return type == JsonType.UInt; } } public bool IsLong { get { return type == JsonType.Long; } } public bool IsULong { get { return type == JsonType.ULong; } } public bool IsObject { get { return type == JsonType.Object; } } public bool IsString { get { return type == JsonType.String; } } #endregion #region ICollection Properties int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return EnsureCollection ().IsSynchronized; } } object ICollection.SyncRoot { get { return EnsureCollection ().SyncRoot; } } #endregion #region IDictionary Properties bool IDictionary.IsFixedSize { get { return EnsureDictionary ().IsFixedSize; } } bool IDictionary.IsReadOnly { get { return EnsureDictionary ().IsReadOnly; } } ICollection IDictionary.Keys { get { EnsureDictionary (); IList<string> keys = new List<string> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { keys.Add (entry.Key); } return (ICollection) keys; } } ICollection IDictionary.Values { get { EnsureDictionary (); IList<JsonData> values = new List<JsonData> (); foreach (KeyValuePair<string, JsonData> entry in object_list) { values.Add (entry.Value); } return (ICollection) values; } } #endregion #region IJsonWrapper Properties bool IJsonWrapper.IsArray { get { return IsArray; } } bool IJsonWrapper.IsBoolean { get { return IsBoolean; } } bool IJsonWrapper.IsDouble { get { return IsDouble; } } bool IJsonWrapper.IsInt { get { return IsInt; } } bool IJsonWrapper.IsLong { get { return IsLong; } } bool IJsonWrapper.IsObject { get { return IsObject; } } bool IJsonWrapper.IsString { get { return IsString; } } #endregion #region IList Properties bool IList.IsFixedSize { get { return EnsureList ().IsFixedSize; } } bool IList.IsReadOnly { get { return EnsureList ().IsReadOnly; } } #endregion #region IDictionary Indexer object IDictionary.this[object key] { get { return EnsureDictionary ()[key]; } set { if (! (key is String)) throw new ArgumentException ( "The key has to be a string"); JsonData data = ToJsonData (value); this[(string) key] = data; } } #endregion #region IOrderedDictionary Indexer object IOrderedDictionary.this[int idx] { get { EnsureDictionary (); return object_list[idx].Value; } set { EnsureDictionary (); JsonData data = ToJsonData (value); KeyValuePair<string, JsonData> old_entry = object_list[idx]; inst_object[old_entry.Key] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (old_entry.Key, data); object_list[idx] = entry; } } #endregion #region IList Indexer object IList.this[int index] { get { return EnsureList ()[index]; } set { EnsureList (); JsonData data = ToJsonData (value); this[index] = data; } } #endregion #region Public Indexers public IEnumerable<string> PropertyNames { get { EnsureDictionary(); return inst_object.Keys; } } public JsonData this[string prop_name] { get { EnsureDictionary (); JsonData data = null; inst_object.TryGetValue(prop_name, out data); return data; } set { EnsureDictionary (); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (prop_name, value); if (inst_object.ContainsKey (prop_name)) { for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == prop_name) { object_list[i] = entry; break; } } } else object_list.Add (entry); inst_object[prop_name] = value; json = null; } } public JsonData this[int index] { get { EnsureCollection (); if (type == JsonType.Array) return inst_array[index]; return object_list[index].Value; } set { EnsureCollection (); if (type == JsonType.Array) inst_array[index] = value; else { KeyValuePair<string, JsonData> entry = object_list[index]; KeyValuePair<string, JsonData> new_entry = new KeyValuePair<string, JsonData> (entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; } json = null; } } #endregion #region Constructors public JsonData () { } public JsonData (bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } public JsonData (double number) { type = JsonType.Double; inst_double = number; } public JsonData (int number) { type = JsonType.Int; inst_number = (ulong)number; } public JsonData(uint number) { type = JsonType.UInt; inst_number = (ulong)number; } public JsonData (long number) { type = JsonType.Long; inst_number = (ulong)number; } public JsonData(ulong number) { type = JsonType.ULong; inst_number = number; } public JsonData (object obj) { if (obj is Boolean) { type = JsonType.Boolean; inst_boolean = (bool) obj; return; } if (obj is Double) { type = JsonType.Double; inst_double = (double) obj; return; } if (obj is Int32) { type = JsonType.Int; inst_number = (ulong)obj; return; } if (obj is UInt32) { type = JsonType.UInt; inst_number = (ulong)obj; return; } if (obj is Int64) { type = JsonType.Long; inst_number = (ulong)obj; return; } if (obj is UInt64) { type = JsonType.ULong; inst_number = (ulong)obj; return; } if (obj is String) { type = JsonType.String; inst_string = (string) obj; return; } throw new ArgumentException ( "Unable to wrap the given object with JsonData"); } public JsonData (string str) { type = JsonType.String; inst_string = str; } #endregion #region Implicit Conversions public static implicit operator JsonData (Boolean data) { return new JsonData (data); } public static implicit operator JsonData (Double data) { return new JsonData (data); } public static implicit operator JsonData (Int32 data) { return new JsonData (data); } public static implicit operator JsonData (Int64 data) { return new JsonData (data); } public static implicit operator JsonData (String data) { return new JsonData (data); } #endregion #region Explicit Conversions public static explicit operator Boolean (JsonData data) { if (data.type != JsonType.Boolean) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } public static explicit operator Double (JsonData data) { if (data.type != JsonType.Double) throw new InvalidCastException ( "Instance of JsonData doesn't hold a double"); return data.inst_double; } public static explicit operator Int32 (JsonData data) { if (data.type != JsonType.Int) { throw new InvalidCastException ( "Instance of JsonData doesn't hold an int"); } return unchecked((int)data.inst_number); } public static explicit operator UInt32(JsonData data) { if (data.type != JsonType.UInt) { throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); } return unchecked((uint)data.inst_number); } public static explicit operator Int64 (JsonData data) { if (data.type != JsonType.Int && data.type != JsonType.Long) { throw new InvalidCastException ( "Instance of JsonData doesn't hold an long"); } return unchecked((long)data.inst_number); } public static explicit operator UInt64(JsonData data) { if (data.type != JsonType.UInt && data.type != JsonType.ULong) { throw new InvalidCastException( "Instance of JsonData doesn't hold an long"); } return (ulong)data.inst_number; } public static explicit operator String (JsonData data) { if (data.type != JsonType.String) throw new InvalidCastException ( "Instance of JsonData doesn't hold a string"); return data.inst_string; } #endregion #region ICollection Methods void ICollection.CopyTo (Array array, int index) { EnsureCollection ().CopyTo (array, index); } #endregion #region IDictionary Methods void IDictionary.Add (object key, object value) { JsonData data = ToJsonData (value); EnsureDictionary ().Add (key, data); KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> ((string) key, data); object_list.Add (entry); json = null; } void IDictionary.Clear () { EnsureDictionary ().Clear (); object_list.Clear (); json = null; } bool IDictionary.Contains (object key) { return EnsureDictionary ().Contains (key); } IDictionaryEnumerator IDictionary.GetEnumerator () { return ((IOrderedDictionary) this).GetEnumerator (); } void IDictionary.Remove (object key) { EnsureDictionary ().Remove (key); for (int i = 0; i < object_list.Count; i++) { if (object_list[i].Key == (string) key) { object_list.RemoveAt (i); break; } } json = null; } #endregion #region IEnumerable Methods IEnumerator IEnumerable.GetEnumerator () { return EnsureCollection ().GetEnumerator (); } #endregion #region IJsonWrapper Methods bool IJsonWrapper.GetBoolean () { if (type != JsonType.Boolean) throw new InvalidOperationException ( "JsonData instance doesn't hold a boolean"); return inst_boolean; } double IJsonWrapper.GetDouble () { if (type != JsonType.Double) throw new InvalidOperationException ( "JsonData instance doesn't hold a double"); return inst_double; } int IJsonWrapper.GetInt () { if (type != JsonType.Int) throw new InvalidOperationException ( "JsonData instance doesn't hold an int"); return unchecked((int)inst_number); } uint IJsonWrapper.GetUInt() { if (type != JsonType.UInt) throw new InvalidOperationException( "JsonData instance doesn't hold an int"); return unchecked((uint)inst_number); } long IJsonWrapper.GetLong () { if (type != JsonType.Long) throw new InvalidOperationException ( "JsonData instance doesn't hold a long"); return unchecked((long)inst_number); } ulong IJsonWrapper.GetULong() { if (type != JsonType.ULong) throw new InvalidOperationException( "JsonData instance doesn't hold a long"); return inst_number; } string IJsonWrapper.GetString () { if (type != JsonType.String) throw new InvalidOperationException ( "JsonData instance doesn't hold a string"); return inst_string; } void IJsonWrapper.SetBoolean (bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } void IJsonWrapper.SetDouble (double val) { type = JsonType.Double; inst_double = val; json = null; } void IJsonWrapper.SetInt (int val) { type = JsonType.Int; inst_number = unchecked((ulong)val); json = null; } void IJsonWrapper.SetUInt(uint val) { type = JsonType.UInt; inst_number = unchecked((ulong)val); json = null; } void IJsonWrapper.SetLong (long val) { type = JsonType.Long; inst_number = unchecked((ulong)val); json = null; } void IJsonWrapper.SetULong(ulong val) { type = JsonType.ULong; inst_number = val; json = null; } void IJsonWrapper.SetString (string val) { type = JsonType.String; inst_string = val; json = null; } string IJsonWrapper.ToJson () { return ToJson (); } void IJsonWrapper.ToJson (JsonWriter writer) { ToJson (writer); } #endregion #region IList Methods int IList.Add (object value) { return Add (value); } void IList.Clear () { EnsureList ().Clear (); json = null; } bool IList.Contains (object value) { return EnsureList ().Contains (value); } int IList.IndexOf (object value) { return EnsureList ().IndexOf (value); } void IList.Insert (int index, object value) { EnsureList ().Insert (index, value); json = null; } void IList.Remove (object value) { EnsureList ().Remove (value); json = null; } void IList.RemoveAt (int index) { EnsureList ().RemoveAt (index); json = null; } #endregion #region IOrderedDictionary Methods IDictionaryEnumerator IOrderedDictionary.GetEnumerator () { EnsureDictionary (); return new OrderedDictionaryEnumerator ( object_list.GetEnumerator ()); } void IOrderedDictionary.Insert (int idx, object key, object value) { string property = (string) key; JsonData data = ToJsonData (value); this[property] = data; KeyValuePair<string, JsonData> entry = new KeyValuePair<string, JsonData> (property, data); object_list.Insert (idx, entry); } void IOrderedDictionary.RemoveAt (int idx) { EnsureDictionary (); inst_object.Remove (object_list[idx].Key); object_list.RemoveAt (idx); } #endregion #region Private Methods private ICollection EnsureCollection () { if (type == JsonType.Array) return (ICollection) inst_array; if (type == JsonType.Object) return (ICollection) inst_object; throw new InvalidOperationException ( "The JsonData instance has to be initialized first"); } private IDictionary EnsureDictionary () { if (type == JsonType.Object) return (IDictionary) inst_object; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a dictionary"); type = JsonType.Object; inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); return (IDictionary) inst_object; } private IList EnsureList () { if (type == JsonType.Array) return (IList) inst_array; if (type != JsonType.None) throw new InvalidOperationException ( "Instance of JsonData is not a list"); type = JsonType.Array; inst_array = new List<JsonData> (); return (IList) inst_array; } private JsonData ToJsonData (object obj) { if (obj == null) return null; if (obj is JsonData) return (JsonData) obj; return new JsonData (obj); } private static void WriteJson (IJsonWrapper obj, JsonWriter writer) { if (obj == null) { writer.Write(null); return; } if (obj.IsString) { writer.Write (obj.GetString ()); return; } if (obj.IsBoolean) { writer.Write (obj.GetBoolean ()); return; } if (obj.IsDouble) { writer.Write (obj.GetDouble ()); return; } if (obj.IsInt) { writer.Write (obj.GetInt ()); return; } if (obj.IsUInt) { writer.Write(obj.GetUInt()); return; } if (obj.IsLong) { writer.Write (obj.GetLong ()); return; } if (obj.IsULong) { writer.Write(obj.GetULong()); return; } if (obj.IsArray) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteJson ((JsonData) elem, writer); writer.WriteArrayEnd (); return; } if (obj.IsObject) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in ((IDictionary) obj)) { writer.WritePropertyName ((string) entry.Key); WriteJson ((JsonData) entry.Value, writer); } writer.WriteObjectEnd (); return; } } #endregion public int Add (object value) { JsonData data = ToJsonData (value); json = null; return EnsureList ().Add (data); } public void Clear () { if (IsObject) { ((IDictionary) this).Clear (); return; } if (IsArray) { ((IList) this).Clear (); return; } } public bool Equals (JsonData x) { if (x == null) return false; if (x.type != this.type) { bool thisIsSigned = (this.type == JsonType.Int || this.type == JsonType.Long); bool thisIsUnsigned = (this.type == JsonType.UInt || this.type == JsonType.ULong); bool xIsSigned = (x.type == JsonType.Int || x.type == JsonType.Long); bool xIsUnsigned = (x.type == JsonType.UInt || x.type == JsonType.ULong); if (thisIsSigned == xIsSigned || thisIsUnsigned == xIsUnsigned) { // only allow types between signed numbers and between unsigned numbers to be actually compared } else { return false; } } switch (this.type) { case JsonType.None: return true; case JsonType.Object: return this.inst_object.Equals (x.inst_object); case JsonType.Array: return this.inst_array.Equals (x.inst_array); case JsonType.String: return this.inst_string.Equals (x.inst_string); case JsonType.Int: case JsonType.UInt: case JsonType.Long: case JsonType.ULong: return this.inst_number.Equals (x.inst_number); case JsonType.Double: return this.inst_double.Equals (x.inst_double); case JsonType.Boolean: return this.inst_boolean.Equals (x.inst_boolean); } return false; } public JsonType GetJsonType () { return type; } public void SetJsonType (JsonType type) { if (this.type == type) return; switch (type) { case JsonType.None: break; case JsonType.Object: inst_object = new Dictionary<string, JsonData> (); object_list = new List<KeyValuePair<string, JsonData>> (); break; case JsonType.Array: inst_array = new List<JsonData> (); break; case JsonType.String: inst_string = default (String); break; case JsonType.Int: inst_number = default (Int32); break; case JsonType.UInt: inst_number = default(UInt32); break; case JsonType.Long: inst_number = default (Int64); break; case JsonType.ULong: inst_number = default(UInt64); break; case JsonType.Double: inst_double = default (Double); break; case JsonType.Boolean: inst_boolean = default (Boolean); break; } this.type = type; } public string ToJson () { if (json != null) return json; StringWriter sw = new StringWriter (); JsonWriter writer = new JsonWriter (sw); writer.Validate = false; WriteJson (this, writer); json = sw.ToString (); return json; } public void ToJson (JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; WriteJson (this, writer); writer.Validate = old_validate; } public override string ToString () { switch (type) { case JsonType.Array: return "JsonData array"; case JsonType.Boolean: return inst_boolean.ToString (); case JsonType.Double: return inst_double.ToString (); case JsonType.Int: return unchecked((int)inst_number).ToString(); case JsonType.UInt: return unchecked((uint)inst_number).ToString(); case JsonType.Long: return unchecked((long)inst_number).ToString(); case JsonType.ULong: return inst_number.ToString (); case JsonType.Object: return "JsonData object"; case JsonType.String: return inst_string; } return "Uninitialized JsonData"; } } internal class OrderedDictionaryEnumerator : IDictionaryEnumerator { IEnumerator<KeyValuePair<string, JsonData>> list_enumerator; public object Current { get { return Entry; } } public DictionaryEntry Entry { get { KeyValuePair<string, JsonData> curr = list_enumerator.Current; return new DictionaryEntry (curr.Key, curr.Value); } } public object Key { get { return list_enumerator.Current.Key; } } public object Value { get { return list_enumerator.Current.Value; } } public OrderedDictionaryEnumerator ( IEnumerator<KeyValuePair<string, JsonData>> enumerator) { list_enumerator = enumerator; } public bool MoveNext () { return list_enumerator.MoveNext (); } public void Reset () { list_enumerator.Reset (); } } }
// 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.Search { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for ServicesOperations. /// </summary> public static partial class ServicesOperationsExtensions { /// <summary> /// Creates or updates a Search service in the given resource group. If the /// Search service already exists, all properties will be updated with the /// given values. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service to create or update. Search service /// names must only contain lowercase letters, digits or dashes, cannot use /// dash as the first two or last one characters, cannot contain consecutive /// dashes, and must be between 2 and 60 characters in length. Search service /// names must be globally unique since they are part of the service URI /// (https://&lt;name&gt;.search.windows.net). You cannot change the service /// name after the service is created. /// </param> /// <param name='service'> /// The definition of the Search service to create or update. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> public static SearchService CreateOrUpdate(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchService service, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IServicesOperations)s).CreateOrUpdateAsync(resourceGroupName, searchServiceName, service, searchManagementRequestOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a Search service in the given resource group. If the /// Search service already exists, all properties will be updated with the /// given values. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service to create or update. Search service /// names must only contain lowercase letters, digits or dashes, cannot use /// dash as the first two or last one characters, cannot contain consecutive /// dashes, and must be between 2 and 60 characters in length. Search service /// names must be globally unique since they are part of the service URI /// (https://&lt;name&gt;.search.windows.net). You cannot change the service /// name after the service is created. /// </param> /// <param name='service'> /// The definition of the Search service to create or update. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SearchService> CreateOrUpdateAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchService service, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, searchServiceName, service, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the Search service with the given name in the given resource group. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service associated with the specified /// resource group. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> public static SearchService Get(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IServicesOperations)s).GetAsync(resourceGroupName, searchServiceName, searchManagementRequestOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the Search service with the given name in the given resource group. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service associated with the specified /// resource group. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SearchService> GetAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, searchServiceName, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a Search service in the given resource group, along with its /// associated resources. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service associated with the specified /// resource group. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> public static void Delete(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions)) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IServicesOperations)s).DeleteAsync(resourceGroupName, searchServiceName, searchManagementRequestOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a Search service in the given resource group, along with its /// associated resources. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchServiceName'> /// The name of the Azure Search service associated with the specified /// resource group. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this IServicesOperations operations, string resourceGroupName, string searchServiceName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, searchServiceName, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a list of all Search services in the given resource group. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> public static System.Collections.Generic.IEnumerable<SearchService> ListByResourceGroup(this IServicesOperations operations, string resourceGroupName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IServicesOperations)s).ListByResourceGroupAsync(resourceGroupName, searchManagementRequestOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of all Search services in the given resource group. /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. You can /// obtain this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<System.Collections.Generic.IEnumerable<SearchService>> ListByResourceGroupAsync(this IServicesOperations operations, string resourceGroupName, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Checks whether or not the given Search service name is available for use. /// Search service names must be globally unique since they are part of the /// service URI (https://&lt;name&gt;.search.windows.net). /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// The Search service name to validate. Search service names must only /// contain lowercase letters, digits or dashes, cannot use dash as the first /// two or last one characters, cannot contain consecutive dashes, and must /// be between 2 and 60 characters in length. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> public static CheckNameAvailabilityOutput CheckNameAvailability(this IServicesOperations operations, string name, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IServicesOperations)s).CheckNameAvailabilityAsync(name, searchManagementRequestOptions), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether or not the given Search service name is available for use. /// Search service names must be globally unique since they are part of the /// service URI (https://&lt;name&gt;.search.windows.net). /// <see href="https://aka.ms/search-manage" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='name'> /// The Search service name to validate. Search service names must only /// contain lowercase letters, digits or dashes, cannot use dash as the first /// two or last one characters, cannot contain consecutive dashes, and must /// be between 2 and 60 characters in length. /// </param> /// <param name='searchManagementRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<CheckNameAvailabilityOutput> CheckNameAvailabilityAsync(this IServicesOperations operations, string name, SearchManagementRequestOptions searchManagementRequestOptions = default(SearchManagementRequestOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityWithHttpMessagesAsync(name, searchManagementRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories.Models; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.DataFactories { /// <summary> /// Operations for managing pipelines. /// </summary> public partial interface IPipelineOperations { /// <summary> /// Create or update a pipeline instance. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='parameters'> /// The parameters required to create or update a pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update pipeline operation response. /// </returns> Task<PipelineCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, PipelineCreateOrUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Create a new pipeline instance with raw json content. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// A unique pipeline instance name. /// </param> /// <param name='parameters'> /// The parameters required to create a pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update pipeline operation response. /// </returns> Task<PipelineCreateOrUpdateResponse> BeginCreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, PipelineCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken); /// <summary> /// Delete a pipeline instance. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// Name of the data pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> BeginDeleteAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, CancellationToken cancellationToken); /// <summary> /// Create or update a pipeline instance. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='parameters'> /// The parameters required to create or update a pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update pipeline operation response. /// </returns> Task<PipelineCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, PipelineCreateOrUpdateParameters parameters, CancellationToken cancellationToken); /// <summary> /// Create a new pipeline instance with raw json content. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// A unique pipeline instance name. /// </param> /// <param name='parameters'> /// The parameters required to create or update a pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update pipeline operation response. /// </returns> Task<PipelineCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, PipelineCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken); /// <summary> /// Delete a pipeline instance. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// Name of the data pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> Task<LongRunningOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, CancellationToken cancellationToken); /// <summary> /// Gets a pipeline instance. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// Name of the data pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get pipeline operation response. /// </returns> Task<PipelineGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, CancellationToken cancellationToken); /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update pipeline operation response. /// </returns> Task<PipelineCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Gets the first page of pipeline instances with the link to the next /// page. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List pipeline operation response. /// </returns> Task<PipelineListResponse> ListAsync(string resourceGroupName, string dataFactoryName, CancellationToken cancellationToken); /// <summary> /// Gets the next page of pipeline instances with the link to the next /// page. /// </summary> /// <param name='nextLink'> /// The url to the next pipelines page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List pipeline operation response. /// </returns> Task<PipelineListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken); /// <summary> /// Resume a suspended pipeline. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// Name of the data pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> ResumeAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, CancellationToken cancellationToken); /// <summary> /// Sets the active period of a pipeline. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// Name of the data pipeline. /// </param> /// <param name='parameters'> /// Parameters required to set the active period of a pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> SetActivePeriodAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, PipelineSetActivePeriodParameters parameters, CancellationToken cancellationToken); /// <summary> /// Suspend a running pipeline. /// </summary> /// <param name='resourceGroupName'> /// The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// A unique data factory instance name. /// </param> /// <param name='dataPipelineName'> /// Name of the data pipeline. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> Task<OperationResponse> SuspendAsync(string resourceGroupName, string dataFactoryName, string dataPipelineName, CancellationToken cancellationToken); } }
using System; using System.Threading; using System.Threading.Tasks; namespace GitHub.Unity { public interface ITask : IAsyncResult { T Then<T>(T continuation, bool always = false) where T : ITask; ITask Catch(Action<Exception> handler); ITask Catch(Func<Exception, bool> handler); ITask Finally(Action handler); ITask Finally(Action<bool, Exception> actionToContinueWith, TaskAffinity affinity = TaskAffinity.Concurrent); ITask Defer<T>(Func<T, Task> continueWith, TaskAffinity affinity = TaskAffinity.Concurrent, bool always = false); ITask Start(); ITask Start(TaskScheduler scheduler); void Wait(); bool Wait(int milliseconds); bool Successful { get; } string Errors { get; } Task Task { get; } string Name { get; } TaskAffinity Affinity { get; set; } CancellationToken Token { get; } TaskBase DependsOn { get; } event Action<ITask> OnStart; event Action<ITask> OnEnd; } public interface ITask<TResult> : ITask { new ITask<TResult> Catch(Action<Exception> handler); new ITask<TResult> Catch(Func<Exception, bool> handler); ITask<TResult> Finally(Action<TResult> handler); ITask<TResult> Finally(Func<bool, Exception, TResult, TResult> continuation, TaskAffinity affinity = TaskAffinity.Concurrent); ITask Finally(Action<bool, Exception, TResult> continuation, TaskAffinity affinity = TaskAffinity.Concurrent); new ITask<TResult> Start(); new ITask<TResult> Start(TaskScheduler scheduler); TResult Result { get; } new Task<TResult> Task { get; } new event Action<ITask<TResult>> OnStart; new event Action<ITask<TResult>, TResult> OnEnd; ITask<T> Defer<T>(Func<TResult, Task<T>> continueWith, TaskAffinity affinity = TaskAffinity.Concurrent, bool always = false); } interface ITask<TData, T> : ITask<T> { event Action<TData> OnData; } interface IStubTask { } public abstract class TaskBase : ITask { protected const TaskContinuationOptions runAlwaysOptions = TaskContinuationOptions.None; protected const TaskContinuationOptions runOnSuccessOptions = TaskContinuationOptions.OnlyOnRanToCompletion; protected const TaskContinuationOptions runOnFaultOptions = TaskContinuationOptions.OnlyOnFaulted; public event Action<ITask> OnStart; public event Action<ITask> OnEnd; protected bool previousSuccess = true; protected Exception previousException; protected object previousResult; protected TaskBase continuation; protected bool continuationAlways; protected event Func<Exception, bool> faultHandler; private event Action finallyHandler; public TaskBase(CancellationToken token) { Guard.ArgumentNotNull(token, "token"); Token = token; Task = new Task(() => Run(DependsOn?.Successful ?? previousSuccess), Token, TaskCreationOptions.None); } public TaskBase(Task task) { Task = new Task(t => { var scheduler = TaskManager.GetScheduler(Affinity); RaiseOnStart(); var tk = ((Task)t); try { if (tk.Status == TaskStatus.Created && !tk.IsCompleted && ((tk.CreationOptions & (TaskCreationOptions)512) == TaskCreationOptions.None)) { tk.RunSynchronously(scheduler); } } catch (Exception ex) { Errors = ex.Message; if (!RaiseFaultHandlers(ex)) throw; } finally { RaiseOnEnd(); } }, task, Token, TaskCreationOptions.None); } protected TaskBase() {} public virtual T Then<T>(T cont, bool always = false) where T : ITask { Guard.ArgumentNotNull(cont, nameof(cont)); var taskBase = ((TaskBase)(object)cont); var firstTaskBase = taskBase.GetTopMostTask() ?? taskBase; firstTaskBase.SetDependsOn(this); this.continuation = firstTaskBase; this.continuationAlways = always; return cont; } /// <summary> /// Catch runs right when the exception happens (on the same thread) /// Chain will be cancelled /// </summary> public ITask Catch(Action<Exception> handler) { Guard.ArgumentNotNull(handler, "handler"); faultHandler += e => { handler(e); return false; }; DependsOn?.Catch(handler); return this; } /// <summary> /// Catch runs right when the exception happens (on the same threaD) /// Return true if you want the task to completely successfully /// </summary> public ITask Catch(Func<Exception, bool> handler) { Guard.ArgumentNotNull(handler, "handler"); faultHandler += handler; DependsOn?.Catch(handler); return this; } /// <summary> /// This finally will always run on the same thread as the last task that runs /// </summary> public ITask Finally(Action handler) { Guard.ArgumentNotNull(handler, "handler"); finallyHandler += handler; DependsOn?.Finally(handler); return this; } public ITask Finally(Action<bool, Exception> actionToContinueWith, TaskAffinity affinity = TaskAffinity.Concurrent) { Guard.ArgumentNotNull(actionToContinueWith, nameof(actionToContinueWith)); var ret = Then(new ActionTask(Token, actionToContinueWith) { Affinity = affinity, Name = "Finally" }, true); DependsOn?.SetFaultHandler(ret); ret.ContinuationIsFinally = true; return ret; } internal virtual ITask Finally<T>(T taskToContinueWith) where T : TaskBase { Guard.ArgumentNotNull(taskToContinueWith, nameof(taskToContinueWith)); continuation = (TaskBase)(object)taskToContinueWith; continuationAlways = true; continuation.SetDependsOn(this); DependsOn?.SetFaultHandler((TaskBase)(object)continuation); return continuation; } public ITask Defer<T>(Func<T, Task> continueWith, TaskAffinity affinity = TaskAffinity.Concurrent, bool always = false) { Guard.ArgumentNotNull(continueWith, "continueWith"); var ret = Then(new StubTask<T>(Token, (s, d) => {}) { Affinity = affinity }); SetDeferred(new DeferredContinuation { Always = always, GetContinueWith = d => new ActionTask<T>(continueWith((T)d)) { Affinity = affinity, Name = "Deferred" } }); return ret; } internal void SetFaultHandler(TaskBase handler) { Task.ContinueWith(t => handler.Start(t), Token, TaskContinuationOptions.OnlyOnFaulted, TaskManager.GetScheduler(handler.Affinity)); DependsOn?.SetFaultHandler(handler); } public virtual ITask Start() { var depends = GetTopMostTaskInCreatedState(); if (depends != null) { depends.Run(); return this; } else { return TaskManager.Instance.Schedule(this); } } protected void Run() { if (Task.Status == TaskStatus.Created) { TaskManager.Instance.Schedule(this); } else { RunContinuation(); } } protected void Start(Task task) { previousSuccess = task.Status == TaskStatus.RanToCompletion && task.Status != TaskStatus.Faulted; previousException = task.Exception; Task.Start(TaskManager.GetScheduler(Affinity)); RunContinuation(); } public virtual ITask Start(TaskScheduler scheduler) { if (Task.Status == TaskStatus.Created) { //Logger.Trace($"Starting {Affinity} {ToString()}"); Task.Start(scheduler); } RunContinuation(); return this; } protected virtual void RunContinuation() { if (continuation != null) { //Logger.Trace($"Setting ContinueWith {Affinity} {continuation}"); Task.ContinueWith(_ => ((TaskBase)(object)continuation).Run(), Token, continuationAlways ? runAlwaysOptions : runOnSuccessOptions, TaskManager.GetScheduler(continuation.Affinity)); } } protected ITask SetDependsOn(ITask dependsOn) { DependsOn = (TaskBase)dependsOn; return this; } protected TaskBase GetTopMostTaskInCreatedState() { var depends = DependsOn; if (depends == null) return null; return depends.GetTopMostTask(null, true); } protected TaskBase GetTopMostTask() { var depends = DependsOn; if (depends == null) return null; return depends.GetTopMostTask(null, false); } protected TaskBase GetTopMostTask(TaskBase ret, bool onlyCreatedState) { ret = (!onlyCreatedState || Task.Status == TaskStatus.Created ? this : ret); var depends = DependsOn; if (depends == null) return ret; return depends.GetTopMostTask(ret, onlyCreatedState); } public virtual void Wait() { Task.Wait(Token); } public virtual bool Wait(int milliseconds) { return Task.Wait(milliseconds, Token); } protected virtual void Run(bool success) { } protected virtual void RaiseOnStart() { //Logger.Trace($"Executing {ToString()}"); OnStart?.Invoke(this); } protected virtual void RaiseOnEnd() { OnEnd?.Invoke(this); if (Task.Status != TaskStatus.Faulted && continuation == null) finallyHandler?.Invoke(); //Logger.Trace($"Finished {ToString()}"); } protected virtual bool RaiseFaultHandlers(Exception ex) { if (faultHandler == null) return false; bool handled = false; foreach (var handler in faultHandler.GetInvocationList()) { handled |= (bool)handler.DynamicInvoke(new object[] { ex }); if (handled) break; } if (!handled) finallyHandler?.Invoke(); return handled; } protected Exception GetThrownException() { if (DependsOn == null) return null; if (DependsOn.Task.Status == TaskStatus.Faulted) { var exception = DependsOn.Task.Exception; return exception?.InnerException ?? exception; } return DependsOn.GetThrownException(); } protected class DeferredContinuation { public bool Always; public Func<object, ITask> GetContinueWith; } private DeferredContinuation deferred; internal object GetDeferred() { return deferred; } internal void SetDeferred(object def) { deferred = (DeferredContinuation)def; } internal void ClearDeferred() { deferred = null; } public override string ToString() { return $"{Task?.Id ?? -1} {Name} {GetType()}"; } public virtual bool Successful { get { return Task.Status == TaskStatus.RanToCompletion && Task.Status != TaskStatus.Faulted; } } public string Errors { get; protected set; } public Task Task { get; protected set; } public bool IsCompleted { get { return (Task as IAsyncResult).IsCompleted; } } public WaitHandle AsyncWaitHandle { get { return (Task as IAsyncResult).AsyncWaitHandle; } } public object AsyncState { get { return (Task as IAsyncResult).AsyncState; } } public bool CompletedSynchronously { get { return (Task as IAsyncResult).CompletedSynchronously; } } public string Name { get; set; } public virtual TaskAffinity Affinity { get; set; } private ILogging logger; protected ILogging Logger { get { return logger = logger ?? Logging.GetLogger(GetType()); } } public TaskBase DependsOn { get; private set; } public CancellationToken Token { get; } internal TaskBase Continuation => continuation; internal bool ContinuationAlways => continuationAlways; internal bool ContinuationIsFinally { get; set; } class StubTask<T> : ActionTask<T>, IStubTask { public StubTask(CancellationToken token, Action<bool, T> func) : base(token, func) { Name = "Stub"; } } } abstract class TaskBase<TResult> : TaskBase, ITask<TResult> { protected TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); private event Action<TResult> finallyHandler; public new event Action<ITask<TResult>> OnStart; public new event Action<ITask<TResult>, TResult> OnEnd; public TaskBase(CancellationToken token) : base(token) { Task = new Task<TResult>(() => { var ret = RunWithReturn(DependsOn?.Successful ?? previousSuccess); tcs.SetResult(ret); AdjustNextTask(ret); return ret; }, Token, TaskCreationOptions.None); } public TaskBase(Task<TResult> task) : base() { Task = new Task<TResult>(t => { TResult ret = default(TResult); RaiseOnStart(); var tk = ((Task<TResult>)t); try { if (tk.Status == TaskStatus.Created && !tk.IsCompleted && ((tk.CreationOptions & (TaskCreationOptions)512) == TaskCreationOptions.None)) { tk.RunSynchronously(); } ret = tk.Result; } catch (Exception ex) { Errors = ex.Message; if (!RaiseFaultHandlers(ex)) throw; } finally { RaiseOnEnd(); } return ret; }, task, Token, TaskCreationOptions.None); } protected void AdjustNextTask(TResult ret) { var def = GetDeferred(); if (def != null) { var next = (def as DeferredContinuation)?.GetContinueWith(ret); var cont = continuation.Continuation; var nextDefer = continuation.GetDeferred(); if (continuation is IStubTask) { ((TaskBase)next).SetDeferred(nextDefer); ((TaskBase)continuation).ClearDeferred(); } if (cont != null) { if (cont.ContinuationIsFinally) { ((TaskBase)next).Finally(cont); } else { next.Then(cont, cont.ContinuationAlways); } } continuation.Then(next, continuationAlways); ClearDeferred(); } } public override T Then<T>(T continuation, bool always = false) { return base.Then<T>(continuation, always); } /// <summary> /// Catch runs right when the exception happens (on the same threaD) /// Marks the catch as handled so other Catch statements down the chain /// won't be called for this exception (but the chain will be cancelled) /// </summary> public new ITask<TResult> Catch(Action<Exception> handler) { Guard.ArgumentNotNull(handler, "handler"); faultHandler += e => { handler(e); return false; }; DependsOn?.Catch(handler); return this; } /// <summary> /// Catch runs right when the exception happens (on the same threaD) /// Return false if you want other Catch statements on the chain to also /// get called for this exception /// </summary> public new ITask<TResult> Catch(Func<Exception, bool> handler) { Guard.ArgumentNotNull(handler, "handler"); faultHandler += handler; DependsOn?.Catch(handler); return this; } public ITask<T> Defer<T>(Func<TResult, Task<T>> continueWith, TaskAffinity affinity = TaskAffinity.Concurrent, bool always = false) { Guard.ArgumentNotNull(continueWith, "continueWith"); var ret = Then(new StubTask<T>(Token, (s, d) => default(T)) { Affinity = affinity }, always); SetDeferred(new DeferredContinuation { Always = always, GetContinueWith = d => new FuncTask<T>(continueWith((TResult)d)) { Affinity = affinity, Name = "Deferred" } }); return ret; } class StubTask<T> : FuncTask<TResult, T>, IStubTask { public StubTask(CancellationToken token, Func<bool, TResult, T> func) : base(token, func) { Name = "Stub"; } } /// <summary> /// This finally will always run on the same thread as the last task that runs /// </summary> public ITask<TResult> Finally(Action<TResult> handler) { Guard.ArgumentNotNull(handler, "handler"); finallyHandler += handler; DependsOn?.Finally(() => handler(default(TResult))); return this; } public ITask<TResult> Finally(Func<bool, Exception, TResult, TResult> continuation, TaskAffinity affinity = TaskAffinity.Concurrent) { Guard.ArgumentNotNull(continuation, "continuation"); var ret = Then(new FuncTask<TResult, TResult>(Token, continuation) { Affinity = affinity, Name = "Finally" }, true); ret.ContinuationIsFinally = true; DependsOn?.SetFaultHandler(ret); return ret; } public ITask Finally(Action<bool, Exception, TResult> continuation, TaskAffinity affinity = TaskAffinity.Concurrent) { Guard.ArgumentNotNull(continuation, "continuation"); var ret = Then(new ActionTask<TResult>(Token, continuation) { Affinity = affinity, Name = "Finally" }, true); ret.ContinuationIsFinally = true; DependsOn?.SetFaultHandler(ret); return ret; } public new ITask<TResult> Start() { base.Start(); return this; } public new ITask<TResult> Start(TaskScheduler scheduler) { base.Start(scheduler); return this; } protected virtual TResult RunWithReturn(bool success) { base.Run(success); return default(TResult); } protected override void RaiseOnStart() { //Logger.Trace($"Executing {ToString()}"); OnStart?.Invoke(this); base.RaiseOnStart(); } protected virtual void RaiseOnEnd(TResult result) { OnEnd?.Invoke(this, result); if (Task.Status == TaskStatus.Faulted || continuation == null) finallyHandler?.Invoke(result); RaiseOnEnd(); //Logger.Trace($"Finished {ToString()} {result}"); } public new Task<TResult> Task { get { return base.Task as Task<TResult>; } set { base.Task = value; } } public TResult Result { get { return Task.Result; } } } abstract class TaskBase<T, TResult> : TaskBase<TResult> { public TaskBase(CancellationToken token) : base(token) { Task = new Task<TResult>(() => { var ret = RunWithData(DependsOn?.Successful ?? previousSuccess, DependsOn.Successful ? ((ITask<T>)DependsOn).Result : default(T)); tcs.SetResult(ret); AdjustNextTask(ret); return ret; }, Token, TaskCreationOptions.None); } public TaskBase(Task<TResult> task) : base(task) { } protected virtual TResult RunWithData(bool success, T previousResult) { base.Run(success); return default(TResult); } } abstract class DataTaskBase<TData, TResult> : TaskBase<TResult>, ITask<TData, TResult> { public DataTaskBase(CancellationToken token) : base(token) {} public DataTaskBase(Task<TResult> task) : base(task) {} public event Action<TData> OnData; protected void RaiseOnData(TData data) { OnData?.Invoke(data); } } abstract class DataTaskBase<T, TData, TResult> : TaskBase<T, TResult>, ITask<TData, TResult> { public DataTaskBase(CancellationToken token) : base(token) {} public DataTaskBase(Task<TResult> task) : base(task) {} public event Action<TData> OnData; protected void RaiseOnData(TData data) { OnData?.Invoke(data); } } static class TaskBaseExtensions { public static T Schedule<T>(this T task, ITaskManager taskManager) where T : ITask { return taskManager.Schedule(task); } public static T ScheduleUI<T>(this T task, ITaskManager taskManager) where T : ITask { return taskManager.ScheduleUI(task); } public static T ScheduleExclusive<T>(this T task, ITaskManager taskManager) where T : ITask { return taskManager.ScheduleExclusive(task); } public static T ScheduleConcurrent<T>(this T task, ITaskManager taskManager) where T : ITask { return taskManager.ScheduleConcurrent(task); } } public enum TaskAffinity { Concurrent, Exclusive, UI } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Xunit; namespace System.Collections.ObjectModel.Tests { /// <summary> /// Tests the public properties and constructor in ObservableCollection<T>. /// </summary> public class ReadOnlyObservableCollectionTests { [Fact] public static void Ctor_Tests() { string[] anArray = new string[] { "one", "two", "three", "four", "five" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray); helper.InitialItems_Tests(); IList<string> readOnlyColAsIList = readOnlyCol; Assert.True(readOnlyColAsIList.IsReadOnly, "ReadOnlyObservableCollection should be readOnly."); } [Fact] public static void Ctor_Tests_Negative() { ReadOnlyObservableCollection<string> collection; Assert.Throws<ArgumentNullException>(() => collection = new ReadOnlyObservableCollection<string>(null)); } [Fact] public static void GetItemTests() { string[] anArray = new string[] { "one", "two", "three", "four", "five" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray); helper.Item_get_Tests(); } [Fact] public static void GetItemTests_Negative() { string[] anArray = new string[] { "one", "two", "three", "four", "five" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(readOnlyCol, anArray); helper.Item_get_Tests_Negative(); } /// <summary> /// Tests that contains returns true when the item is in the collection /// and false otherwise. /// </summary> [Fact] public static void ContainsTests() { string[] anArray = new string[] { "one", "two", "three", "four", "five" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); for (int i = 0; i < anArray.Length; i++) { string item = anArray[i]; Assert.True(readOnlyCol.Contains(item), "ReadOnlyCol did not contain item: " + anArray[i] + " at index: " + i); } Assert.False(readOnlyCol.Contains("randomItem"), "ReadOnlyCol should not have contained non-existent item"); Assert.False(readOnlyCol.Contains(null), "ReadOnlyCol should not have contained null"); } /// <summary> /// Tests that the collection can be copied into a destination array. /// </summary> [Fact] public static void CopyToTest() { string[] anArray = new string[] { "one", "two", "three", "four" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); string[] aCopy = new string[anArray.Length]; readOnlyCol.CopyTo(aCopy, 0); for (int i = 0; i < anArray.Length; ++i) Assert.Equal(anArray[i], aCopy[i]); // copy observable collection starting in middle, where array is larger than source. aCopy = new string[anArray.Length + 2]; int offsetIndex = 1; readOnlyCol.CopyTo(aCopy, offsetIndex); for (int i = 0; i < aCopy.Length; i++) { string value = aCopy[i]; if (i == 0) Assert.True(null == value, "Should not have a value since we did not start copying there."); else if (i == (aCopy.Length - 1)) Assert.True(null == value, "Should not have a value since the collection is shorter than the copy array.."); else { int indexInCollection = i - offsetIndex; Assert.Equal(readOnlyCol[indexInCollection], aCopy[i]); } } } /// <summary> /// Tests that: /// ArgumentOutOfRangeException is thrown when the Index is >= collection.Count /// or Index < 0. /// ArgumentException when the destination array does not have enough space to /// contain the source Collection. /// ArgumentNullException when the destination array is null. /// </summary> [Fact] public static void CopyToTest_Negative() { string[] anArray = new string[] { "one", "two", "three", "four" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue }; foreach (var index in iArrInvalidValues) { string[] aCopy = new string[anArray.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => readOnlyCol.CopyTo(aCopy, index)); } int[] iArrLargeValues = new Int32[] { anArray.Length, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 }; foreach (var index in iArrLargeValues) { string[] aCopy = new string[anArray.Length]; Assert.Throws<ArgumentException>(() => readOnlyCol.CopyTo(aCopy, index)); } Assert.Throws<ArgumentNullException>(() => readOnlyCol.CopyTo(null, 1)); string[] copy = new string[anArray.Length - 1]; Assert.Throws<ArgumentException>(() => readOnlyCol.CopyTo(copy, 0)); copy = new string[0]; Assert.Throws<ArgumentException>(() => readOnlyCol.CopyTo(copy, 0)); } /// <summary> /// Tests that the index of an item can be retrieved when the item is /// in the collection and -1 otherwise. /// </summary> [Fact] public static void IndexOfTest() { string[] anArray = new string[] { "one", "two", "three", "four" }; ReadOnlyObservableCollection<string> readOnlyCollection = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); for (int i = 0; i < anArray.Length; ++i) Assert.Equal(i, readOnlyCollection.IndexOf(anArray[i])); Assert.Equal(-1, readOnlyCollection.IndexOf("seven")); Assert.Equal(-1, readOnlyCollection.IndexOf(null)); // testing that the first occurrence is the index returned. ObservableCollection<int> intCol = new ObservableCollection<int>(); for (int i = 0; i < 4; ++i) intCol.Add(i % 2); ReadOnlyObservableCollection<int> intReadOnlyCol = new ReadOnlyObservableCollection<int>(intCol); Assert.Equal(0, intReadOnlyCol.IndexOf(0)); Assert.Equal(1, intReadOnlyCol.IndexOf(1)); IList colAsIList = (IList)intReadOnlyCol; var index = colAsIList.IndexOf("stringObj"); Assert.Equal(-1, index); } /// <summary> /// Tests that a ReadOnlyDictionary cannot be modified. That is, that /// Add, Remove, Clear does not work. /// </summary> [Fact] public static void CannotModifyDictionaryTests_Negative() { string[] anArray = new string[] { "one", "two", "three", "four", "five" }; ReadOnlyObservableCollection<string> readOnlyCol = new ReadOnlyObservableCollection<string>(new ObservableCollection<string>(anArray)); IReadOnlyList_T_Test<string> helper = new IReadOnlyList_T_Test<string>(); IList<string> readOnlyColAsIList = readOnlyCol; Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Add("seven")); Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Insert(0, "nine")); Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Remove("one")); Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.RemoveAt(0)); Assert.Throws<NotSupportedException>(() => readOnlyColAsIList.Clear()); helper.VerifyReadOnlyCollection(readOnlyCol, anArray); } [Fact] public static void DebuggerAttribute_Tests() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new ReadOnlyObservableCollection<int>(new ObservableCollection<int>())); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new ReadOnlyObservableCollection<int>(new ObservableCollection<int>())); } } internal class IReadOnlyList_T_Test<T> { private readonly IReadOnlyList<T> _collection; private readonly T[] _expectedItems; /// <summary> /// Initializes a new instance of the IReadOnlyList_T_Test. /// </summary> /// <param name="collection">The collection to run the tests on.</param> /// <param name="expectedItems">The items expected to be in the collection.</param> public IReadOnlyList_T_Test(IReadOnlyList<T> collection, T[] expectedItems) { _collection = collection; _expectedItems = expectedItems; } public IReadOnlyList_T_Test() { } /// <summary> /// This verifies that the collection contains the expected items. /// </summary> public void InitialItems_Tests() { // Verify Count returns the expected value Assert.Equal(_expectedItems.Length, _collection.Count); // Verify the initial items in the collection VerifyReadOnlyCollection(_collection, _expectedItems); } /// <summary> /// Runs all of the valid tests on get Item. /// </summary> public void Item_get_Tests() { // Verify get_Item with valid item on Collection Verify_get(_collection, _expectedItems); } /// <summary> /// Runs all of the argument checking(invalid) tests on get Item. /// </summary> public void Item_get_Tests_Negative() { // Verify get_Item with index=Int32.MinValue Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[Int32.MinValue]; }); // Verify that the collection was not mutated VerifyReadOnlyCollection(_collection, _expectedItems); // Verify get_Item with index=-1 Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[-1]; }); // Verify that the collection was not mutated VerifyReadOnlyCollection(_collection, _expectedItems); if (_expectedItems.Length == 0) { // Verify get_Item with index=0 on Empty collection Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[0]; }); // Verify that the collection was not mutated VerifyReadOnlyCollection(_collection, _expectedItems); } else { // Verify get_Item with index=Count on Empty collection Assert.Throws<ArgumentOutOfRangeException>(() => { T item = _collection[_expectedItems.Length]; }); // Verify that the collection was not mutated VerifyReadOnlyCollection(_collection, _expectedItems); } } #region Helper Methods /// <summary> /// Verifies that the items in the collection match the expected items. /// </summary> internal void VerifyReadOnlyCollection(IReadOnlyList<T> collection, T[] items) { Verify_get(collection, items); VerifyGenericEnumerator(collection, items); VerifyEnumerator(collection, items); } /// <summary> /// Verifies that you can get all items that should be in the collection. /// </summary> private void Verify_get(IReadOnlyList<T> collection, T[] items) { Assert.Equal(items.Length, collection.Count); for (int i = 0; i < items.Length; i++) { int itemsIndex = i; Assert.Equal(items[itemsIndex], collection[i]); } } /// <summary> /// Verifies that the generic enumerator retrieves the correct items. /// </summary> private void VerifyGenericEnumerator(IReadOnlyList<T> collection, T[] expectedItems) { IEnumerator<T> enumerator = collection.GetEnumerator(); int iterations = 0; int expectedCount = expectedItems.Length; // There is a sequential order to the collection, so we're testing for that. while ((iterations < expectedCount) && enumerator.MoveNext()) { T currentItem = enumerator.Current; T tempItem; // Verify we have not gotten more items then we expected Assert.True(iterations < expectedCount, "Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) than are in the expectedElements(" + expectedCount + " items)"); // Verify Current returned the correct value Assert.Equal(currentItem, expectedItems[iterations]); // Verify Current always returns the same value every time it is called for (int i = 0; i < 3; i++) { tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } iterations++; } Assert.Equal(expectedCount, iterations); for (int i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"); } enumerator.Dispose(); } /// <summary> /// Verifies that the non-generic enumerator retrieves the correct items. /// </summary> private void VerifyEnumerator(IReadOnlyList<T> collection, T[] expectedItems) { IEnumerator enumerator = collection.GetEnumerator(); int iterations = 0; int expectedCount = expectedItems.Length; // There is no sequential order to the collection, so we're testing that all the items // in the readonlydictionary exist in the array. bool[] itemsVisited = new bool[expectedCount]; bool itemFound; while ((iterations < expectedCount) && enumerator.MoveNext()) { object currentItem = enumerator.Current; object tempItem; // Verify we have not gotten more items then we expected Assert.True(iterations < expectedCount, "Err_9844awpa More items have been returned from the enumerator(" + iterations + " items) then are in the expectedElements(" + expectedCount + " items)"); // Verify Current returned the correct value itemFound = false; for (int i = 0; i < itemsVisited.Length; ++i) { if (!itemsVisited[i] && expectedItems[i].Equals(currentItem)) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "Err_1432pauy Current returned unexpected value=" + currentItem); // Verify Current always returns the same value every time it is called for (int i = 0; i < 3; i++) { tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } iterations++; } for (int i = 0; i < expectedCount; ++i) { Assert.True(itemsVisited[i], "Err_052848ahiedoi Expected Current to return true for item: " + expectedItems[i] + "index: " + i); } Assert.Equal(expectedCount, iterations); for (int i = 0; i < 3; i++) { Assert.False(enumerator.MoveNext(), "Err_2929ahiea Expected MoveNext to return false after" + iterations + " iterations"); } } #endregion } }
/**************************************************************************** Copyright (c) 2010-2011 cocos2d-x.org http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ // root name of xml using System; using CocosSharp; using System.IO; #if !WINDOWS && !MACOS && !LINUX && !NETFX_CORE using System.IO.IsolatedStorage; #endif #if NETFX_CORE using Microsoft.Xna.Framework.Storage; #endif using System.Collections.Generic; using System.Text; using System.Xml; // Note: Something to use here http://msdn.microsoft.com/en-us/library/hh582102.aspx namespace CocosSharp { public class CCUserDefault { static CCUserDefault UserDefault = null; static string USERDEFAULT_ROOT_NAME = "userDefaultRoot"; static string XML_FILE_NAME = "UserDefault.xml"; #if !WINDOWS && !MACOS && !LINUX && !NETFX_CORE IsolatedStorageFile myIsolatedStorage; #elif NETFX_CORE StorageContainer myIsolatedStorage; StorageDevice myDevice; #endif Dictionary<string, string> values = new Dictionary<string, string>(); #region Properties public static CCUserDefault SharedUserDefault { get { if (UserDefault == null) { UserDefault = new CCUserDefault(); } return UserDefault; } } #endregion Properties #if NETFX_CORE private StorageDevice CheckStorageDevice() { if(myDevice != null) { return(myDevice); } var result = StorageDevice.BeginShowSelector(null, null); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); myDevice = StorageDevice.EndShowSelector(result); if(myDevice != null) { result = myDevice.BeginOpenContainer(XML_FILE_NAME, null, null); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); myIsolatedStorage = myDevice.EndOpenContainer(result); // Close the wait handle. result.AsyncWaitHandle.Dispose(); } return(myDevice); } #endif #region Constructors CCUserDefault() { #if NETFX_CORE if(myIsolatedStorage == null) { CheckStorageDevice(); } if(myIsolatedStorage != null) { // only create xml file once if it doesnt exist if ((!IsXMLFileExist())) { CreateXMLFile(); } using (Stream s = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate)) { ParseXMLFile(s); } } #elif WINDOWS || MACOS || LINUX || WINDOWSGL // only create xml file once if it doesnt exist if ((!IsXMLFileExist())) { CreateXMLFile(); } using (FileStream fileStream = new FileInfo(XML_FILE_NAME).OpenRead()){ ParseXMLFile(fileStream); } #else myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); // only create xml file once if it doesnt exist if ((!IsXMLFileExist())) { CreateXMLFile(); } using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Open, FileAccess.Read)) { ParseXMLFile(fileStream); } #endif } #endregion Constructors public void PurgeSharedUserDefault() { UserDefault = null; } bool ParseXMLFile(Stream xmlFile) { values.Clear(); string key = ""; // Create an XmlReader using (XmlReader reader = XmlReader.Create(xmlFile)) { // Parse the file and display each of the nodes. while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: key = reader.Name; break; case XmlNodeType.Text: values.Add(key, reader.Value); break; case XmlNodeType.XmlDeclaration: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Comment: break; case XmlNodeType.EndElement: break; } } } return true; } string GetValueForKey(string key) { string value = null; if (! values.TryGetValue(key, out value)) { value = null; } return value; } void SetValueForKey(string key, string value) { values[key] = value; } public bool GetBoolForKey(string key, bool defaultValue=false) { string value = GetValueForKey(key); bool ret = defaultValue; if (value != null) { ret = bool.Parse(value); } return ret; } public int GetIntegerForKey(string key, int defaultValue=0) { string value = GetValueForKey(key); int ret = defaultValue; if (value != null) { ret = CCUtils.CCParseInt(value); } return ret; } public float GetFloatForKey(string key, float defaultValue) { float ret = (float)GetDoubleForKey(key, (double)defaultValue); return ret; } public double GetDoubleForKey(string key, double defaultValue) { string value = GetValueForKey(key); double ret = defaultValue; if (value != null) { ret = double.Parse(value); } return ret; } public string GetStringForKey(string key, string defaultValue) { string value = GetValueForKey(key); string ret = defaultValue; if (value != null) { ret = value; } return ret; } public void SetBoolForKey(string key, bool value) { // check key if (key == null) { return; } // save bool value as string SetStringForKey(key, value.ToString()); } public void SetIntegerForKey(string key, int value) { // check key if (key == null) { return; } // convert to string SetValueForKey(key, value.ToString()); } public void SetFloatForKey(string key, float value) { SetDoubleForKey(key, value); } public void SetDoubleForKey(string key, double value) { // check key if (key == null) { return; } // convert to string SetValueForKey(key, value.ToString()); } public void SetStringForKey(string key, string value) { // check key if (key == null) { return; } // convert to string SetValueForKey(key, value.ToString()); } bool IsXMLFileExist() { bool bRet = false; #if NETFX_CORE // use the StorageContainer to determine if the file exists. if (myIsolatedStorage.FileExists(XML_FILE_NAME)) { bRet = true; } #elif WINDOWS || LINUX || MACOS || WINDOWSGL if (new FileInfo(XML_FILE_NAME).Exists) { bRet = true; } #else if (myIsolatedStorage.FileExists(XML_FILE_NAME)) { bRet = true; } #endif return bRet; } bool CreateXMLFile() { bool bRet = false; #if NETFX_CORE using (StreamWriter writeFile = new StreamWriter(myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate))) #elif WINDOWS || LINUX || MACOS || WINDOWSGL using (StreamWriter writeFile = new StreamWriter(XML_FILE_NAME)) #else using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(XML_FILE_NAME, FileMode.Create, FileAccess.Write, myIsolatedStorage))) #endif { string someTextData = "<?xml version=\"1.0\" encoding=\"utf-8\"?><userDefaultRoot>"; writeFile.WriteLine(someTextData); // Do not write anything here. This just creates the temporary xml save file. writeFile.WriteLine("</userDefaultRoot>"); } return bRet; } public void Flush() { #if NETFX_CORE using (Stream stream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate)) #elif WINDOWS || LINUX || MACOS || WINDOWSGL using (StreamWriter stream = new StreamWriter(XML_FILE_NAME)) #else using (StreamWriter stream = new StreamWriter(new IsolatedStorageFileStream(XML_FILE_NAME, FileMode.Create, FileAccess.Write, myIsolatedStorage))) #endif { //create xml doc XmlWriterSettings ws = new XmlWriterSettings(); ws.Encoding = Encoding.UTF8; ws.Indent = true; using (XmlWriter writer = XmlWriter.Create(stream, ws)) { writer.WriteStartDocument(); writer.WriteStartElement(USERDEFAULT_ROOT_NAME); foreach (KeyValuePair<string, string> pair in values) { writer.WriteStartElement(pair.Key); writer.WriteString(pair.Value); writer.WriteEndElement(); } writer.WriteEndElement(); writer.WriteEndDocument(); } } } } }
/* * Copyright 2017 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 System; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Firebase.Platform { // The FirebaseHandler class is used to interact with Unity specific behavior, // and is included in the Firebase.Platform.dll. Note that while it does not // implement an interface, it effectively needs to, as it's methods are called // from other Firebase libraries, and non-Unity specific versions of this class // do exist. // // During runtime outside of the Editor (or when in play mode in the Editor), // a MonoBehaviour is spun up to handle the necessary calls, such as invoking // things on the main Unity thread, update ticks, etc. // // This implementation has Unity Editor functionality as well, handled through // FirebaseEditorDispatcher, which uses reflection. Reflection is necessary as this // class is also used in builds, which do not include the UnityEngine.dll, and as // such we need to assume that UnityEngine will not necessarily be available. internal sealed class FirebaseHandler { // The MonoBehaviour that is added to the Unity game, used to receive Update ticks, etc. private static Firebase.Platform.FirebaseMonoBehaviour firebaseMonoBehaviour = null; // Utility class that provides functions to interact with the FirebaseApp dll, // since the Platform cannot directly depend on it because of circular dependencies. public static Firebase.Platform.IFirebaseAppUtils AppUtils { get; private set; } private static int tickCount = 0; // Gets the number of times Update has been called since the construction of this class. public static int TickCount { get { return tickCount; } } // Dispatcher used to preserve calls that need to be done on the main Unity thread. private static Dispatcher ThreadDispatcher { get; set; } // Tracks if the FirebaseHandler is configured for Play mode (using the MonoBehaviour), // or edit mode, using UnityEditor's update call. public bool IsPlayMode { get; set; } static FirebaseHandler() { AppUtils = Firebase.Platform.FirebaseAppUtilsStub.Instance; } private FirebaseHandler() { // If we are in the Unity editor, we need to check if we are actually in play // mode or not. We also need to listen to the play mode state, so that if it // changes we can tear down and initialize the proper support. if (UnityEngine.Application.isEditor) { IsPlayMode = FirebaseEditorDispatcher.EditorIsPlaying; FirebaseEditorDispatcher.ListenToPlayState(); } else { // If we aren't in the editor, we can assume that we are in play mode, and // that is not going to change. IsPlayMode = true; } if (IsPlayMode) { StartMonoBehaviour(); } else { FirebaseEditorDispatcher.StartEditorUpdate(); } } internal void StartMonoBehaviour() { // If the default instance isn't initialized, set it up now so that the behavior does not // stop itself on creation. if (firebaseHandler == null) firebaseHandler = this; // Create the Unity object. UnityEngine.GameObject firebaseHandlerGameObject = new UnityEngine.GameObject("Firebase Services"); firebaseMonoBehaviour = firebaseHandlerGameObject.AddComponent<Firebase.Platform.FirebaseMonoBehaviour>(); Firebase.Unity.UnitySynchronizationContext.Create(firebaseHandlerGameObject); UnityEngine.Object.DontDestroyOnLoad(firebaseHandlerGameObject); } internal void StopMonoBehaviour() { // Check the condition before potentially waiting on another thread. if (firebaseMonoBehaviour != null) { RunOnMainThread(() => { if (firebaseMonoBehaviour != null) { Firebase.Unity.UnitySynchronizationContext.Destroy(); UnityEngine.Object.Destroy(firebaseMonoBehaviour.gameObject); } // Needs to return something. return true; }); } } // Blocks and waits for the function provided to execute on the same thread // as this instance of FirebaseHandler, and returns the result. // NOTE: This only works once a FirebaseHandler instance constructed // with CreatePartialOnMainThread. Otherwise, it will run the given function // on the calling thread. public static TResult RunOnMainThread<TResult>(System.Func<TResult> f) { if (ThreadDispatcher != null) { TResult r = ThreadDispatcher.Run(f); return r; } else { return f(); } } // Queue the function provided and execute on the same thread as this instance of // FirebaseHandler asynchronously. Returns a Task which is complete once the // function is executed. // NOTE: This only works once a FirebaseHandler instance constructed // with CreatePartialOnMainThread. Otherwise, it will run the given function // on the calling thread. public static Task<TResult> RunOnMainThreadAsync<TResult>(System.Func<TResult> f) { if (ThreadDispatcher != null) { return ThreadDispatcher.RunAsync(f); } else { return Dispatcher.RunAsyncNow(f); } } // Returns whether the current thread is the main thread. // NOTE: This only works once a FirebaseHandler instance constructed // with CreatePartialOnMainThread. internal bool IsMainThread() { if (ThreadDispatcher != null) { return ThreadDispatcher.ManagesThisThread(); } else { return false; } } private static FirebaseHandler firebaseHandler = null; // Passed to the ApplicationFocusChanged event. internal class ApplicationFocusChangedEventArgs : System.EventArgs { public bool HasFocus { get; set; } }; // Called each time this behavior is updated by Unity. internal event System.EventHandler<System.EventArgs> Updated; // Wrapper action used to capture exceptions while calling Updated. internal Action UpdatedEventWrapper = null; // Called when the application focus changes. internal event System.EventHandler<ApplicationFocusChangedEventArgs> ApplicationFocusChanged; // Get the singleton. internal static FirebaseHandler DefaultInstance { get { return firebaseHandler; } } // This is an optional "Pre" Create() call, that handles all main-thread // work. It contains the bulk of the Create logic that has to be done on the // main thread, however it does not completely setup all of the Platform // Services. // To finish creation you must still call Create() after calling this, // however that can safely be done on another thread. If this is not used, // you can still call Create() as usual from the main thread. internal static void CreatePartialOnMainThread(Platform.IFirebaseAppUtils appUtils) { appUtils.TranslateDllNotFoundException(() => { lock (typeof(FirebaseHandler)) { if (firebaseHandler != null) return; AppUtils = appUtils; if (ThreadDispatcher == null) { ThreadDispatcher = new Dispatcher(); } firebaseHandler = new FirebaseHandler(); } }); } // Create the FirebaseHandler if it hasn't been created and configure // logging. // // This can throw Firebase.InitializationException if the C/C++ dependencies // are not included in the application. internal static void Create(Platform.IFirebaseAppUtils appUtils) { CreatePartialOnMainThread(appUtils); // The first hit to the Services static object is slow, but it's // fast (cached) afterwards, so we'll always do it in a full creation. Firebase.Unity.UnityPlatformServices.SetupServices(); } internal void Update() { ThreadDispatcher.PollJobs(); AppUtils.PollCallbacks(); if (Updated != null) { if (UpdatedEventWrapper == null) { UpdatedEventWrapper = () => { Updated(this, null); }; } ExceptionAggregator.Wrap(UpdatedEventWrapper); } ExceptionAggregator.ThrowAndClearPendingExceptions(); tickCount++; } internal void OnApplicationFocus(bool hasFocus) { if (ApplicationFocusChanged != null) { ApplicationFocusChanged(null, new ApplicationFocusChangedEventArgs { HasFocus = hasFocus }); } } internal static void Terminate() { if (firebaseHandler != null) { // The FirebaseEditorDispatcher handles if the current platform is not the Editor. FirebaseEditorDispatcher.Terminate(firebaseHandler.IsPlayMode); // Stop the MonoBehaviour, since it depends on the FirebaseHandler. // Note, this can potentially block for the main Unity thread. firebaseHandler.StopMonoBehaviour(); } firebaseHandler = null; // TODO(amaurice): Need to fix the creation / destruction of ThreadDispatcher. If // any C# calls need to use it to run items on the main thread. // ThreadDispatcher = null; } // Invalid the behaviour referenced by this class if it matches the specified beaviour instance. internal static void OnMonoBehaviourDestroyed(Firebase.Platform.FirebaseMonoBehaviour behaviour) { if (behaviour == firebaseMonoBehaviour) firebaseMonoBehaviour = null; } } } // namespace Firebase
using System; namespace NTumbleBit.BouncyCastle.Crypto { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion. The BufferedBlockCipher outputs a block only when the * buffer is full and more data is being added, or on a doFinal. * <p> * Note: in the case where the underlying cipher is either a CFB cipher or an * OFB one the last block may not be a multiple of the block size. * </p> */ internal class BufferedBlockCipher : BufferedCipherBase { internal byte[] buf; internal int bufOff; internal bool forEncryption; internal IBlockCipher cipher; /** * constructor for subclasses */ protected BufferedBlockCipher() { } /** * Create a buffered block cipher without padding. * * @param cipher the underlying block cipher this buffering object wraps. * false otherwise. */ public BufferedBlockCipher( IBlockCipher cipher) { if(cipher == null) throw new ArgumentNullException(nameof(cipher)); this.cipher = cipher; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } public override string AlgorithmName { get { return cipher.AlgorithmName; } } /** * initialise the cipher. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ // Note: This doubles as the Init in the event that this cipher is being used as an IWrapper public override void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; Reset(); cipher.Init(forEncryption, parameters); } /** * return the blocksize for the underlying cipher. * * @return the blocksize for the underlying cipher. */ public override int GetBlockSize() { return cipher.GetBlockSize(); } /** * return the size of the output buffer required for an update * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update * with len bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; return total - leftOver; } /** * return the size of the output buffer required for an update plus a * doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ public override int GetOutputSize( int length) { // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation return length + bufOff; } /** * process a single byte, producing an output block if necessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { buf[bufOff++] = input; if(bufOff == buf.Length) { if((outOff + buf.Length) > output.Length) throw new DataLengthException("output buffer too short"); bufOff = 0; return cipher.ProcessBlock(buf, 0, output, outOff); } return 0; } public override byte[] ProcessByte( byte input) { int outLength = GetUpdateOutputSize(1); byte[] outBytes = outLength > 0 ? new byte[outLength] : null; int pos = ProcessByte(input, outBytes, 0); if(outLength > 0 && pos < outLength) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } public override byte[] ProcessBytes( byte[] input, int inOff, int length) { if(input == null) throw new ArgumentNullException(nameof(input)); if(length < 1) return null; int outLength = GetUpdateOutputSize(length); byte[] outBytes = outLength > 0 ? new byte[outLength] : null; int pos = ProcessBytes(input, inOff, length, outBytes, 0); if(outLength > 0 && pos < outLength) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param len the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if(length < 1) { if(length < 0) throw new ArgumentException("Can't have a negative input length!"); return 0; } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if(outLength > 0) { Check.OutputLength(output, outOff, outLength, "output buffer too short"); } int resultLen = 0; int gapLen = buf.Length - bufOff; if(length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; while(length > buf.Length) { resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; if(bufOff == buf.Length) { resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); bufOff = 0; } return resultLen; } public override byte[] DoFinal() { byte[] outBytes = EmptyBuffer; int length = GetOutputSize(0); if(length > 0) { outBytes = new byte[length]; int pos = DoFinal(outBytes, 0); if(pos < outBytes.Length) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } public override byte[] DoFinal( byte[] input, int inOff, int inLen) { if(input == null) throw new ArgumentNullException(nameof(input)); int length = GetOutputSize(inLen); byte[] outBytes = EmptyBuffer; if(length > 0) { outBytes = new byte[length]; int pos = (inLen > 0) ? ProcessBytes(input, inOff, inLen, outBytes, 0) : 0; pos += DoFinal(outBytes, pos); if(pos < outBytes.Length) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } /** * Process the last block in the buffer. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output, or the input is not block size aligned and should be. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. * @exception DataLengthException if the input is not block size * aligned. */ public override int DoFinal( byte[] output, int outOff) { try { if(bufOff != 0) { Check.DataLength(!cipher.IsPartialBlockOkay, "data not block size aligned"); Check.OutputLength(output, outOff, bufOff, "output buffer too short for DoFinal()"); // NB: Can't copy directly, or we may write too much output cipher.ProcessBlock(buf, 0, buf, 0); Array.Copy(buf, 0, output, outOff, bufOff); } return bufOff; } finally { Reset(); } } /** * Reset the buffer and cipher. After resetting the object is in the same * state as it was after the last init (if there was one). */ public override void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; cipher.Reset(); } } }
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using ConvNetSharp.Volume.Single; namespace ConvNetSharp.Volume.Tests { [TestClass] public class SingleVolumeTests { [TestMethod] public void Add1D() { var left = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(3)); var right = new Single.Volume(new[] { 0.1f, 0.2f, 0.3f }, new Shape(3)); var result = left + right; Assert.AreEqual(1.1, result.Get(0), 0.0001f); Assert.AreEqual(2.2, result.Get(1), 0.0001f); Assert.AreEqual(3.3, result.Get(2), 0.0001f); } [TestMethod] public void Add2D() { var left = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f, 4.0f }, new Shape(2, -1)); var right = new Single.Volume(new[] { 0.1f, 0.2f, 0.3f, 0.4f }, new Shape(2, -1)); var result = left + right; Assert.AreEqual(1.1, result.Get(0, 0), 0.0001f); Assert.AreEqual(2.2f, result.Get(1, 0), 0.0001f); Assert.AreEqual(3.3f, result.Get(0, 1), 0.0001f); Assert.AreEqual(4.4f, result.Get(1, 1), 0.0001f); } [TestMethod] public void DoAddToSame() { var left = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f, 4.0f }, new Shape(2, -1)); var right = new Single.Volume(new[] { 0.1f, 0.2f, 0.3f, 0.4f }, new Shape(2, -1)); right.DoAdd(left, right); Assert.AreEqual(1.1, right.Get(0, 0), 0.0001f); Assert.AreEqual(2.2f, right.Get(1, 0), 0.0001f); Assert.AreEqual(3.3f, right.Get(0, 1), 0.0001f); Assert.AreEqual(4.4f, right.Get(1, 1), 0.0001f); } [TestMethod] public void AddBroadcast() { var volume = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f, 1.0f, 2.0f, 3.0f, 4.0f }, new Shape(2, 2, 3)); var bias = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(1, 1, 3)); var result = volume + bias; Assert.AreEqual(2.0f, result.Get(0, 0, 0)); Assert.AreEqual(3.0f, result.Get(0, 0, 1)); Assert.AreEqual(4.0f, result.Get(0, 0, 2)); } [TestMethod] public void BiasBackward() { var outputGradient = new Single.Volume( new[] { 1.0f, 2.0f, 3.0f, 1.0f, 2.0f, 3.0f }, new Shape(2, 1, 3, 1)); var biasGradient = BuilderInstance<float>.Volume.SameAs(new Shape(1, 1, 3, 1)); outputGradient.BiasGradient(biasGradient); Assert.AreEqual(3.0f, biasGradient.Get(0, 0, 0, 0)); Assert.AreEqual(4.0f, biasGradient.Get(0, 0, 1, 0)); Assert.AreEqual(5.0f, biasGradient.Get(0, 0, 2, 0)); } [TestMethod] public void BiasBackwardBatch() { var outputGradient = new Single.Volume( new[] { 1.0f, 2.0f, 3.0f, 1.0f, 2.0f, 3.0f, 1.0f, 2.0f, 3.0f, 1.0f, 2.0f, 3.0f }, new Shape(2, 1, 3, 2)); var biasGradient = BuilderInstance<float>.Volume.SameAs(new Shape(1, 1, 3, 1)); outputGradient.BiasGradient(biasGradient); Assert.AreEqual(6.0f, biasGradient.Get(0, 0, 0, 0)); Assert.AreEqual(8.0f, biasGradient.Get(0, 0, 1, 0)); Assert.AreEqual(10.0f, biasGradient.Get(0, 0, 2, 0)); } [TestMethod] public void Builder() { var example = new Single.Volume(new[] { 1.0f }, new Shape(1)); var volume = BuilderInstance<float>.Volume.SameAs(example.Storage, 1.0f, new Shape(10)); // SameAs creates an instance that // - has the same type of storage as example Assert.AreEqual(example.Storage.GetType(), volume.Storage.GetType()); // - is filled with provided value Assert.AreEqual(10, volume.Shape.GetDimension(0)); for (var i = 0; i < 10; i++) { Assert.AreEqual(1.0f, volume.Get(i)); } } [TestMethod] public void BuilderArray() { var array = new[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f }; var volume = BuilderInstance<float>.Volume.SameAs(array, new Shape(5)); Assert.AreEqual(5, volume.Shape.GetDimension(0)); for (var i = 0; i < 5; i++) { Assert.AreEqual(array[i], volume.Get(i)); } } [TestMethod] public void BuilderEmpty() { var example = new Single.Volume(new[] { 1.0f }, new Shape(1)); var volume = BuilderInstance<float>.Volume.SameAs(example.Storage, new Shape(10)); // SameAs creates an instance that // - has the same type of storage as example Assert.AreEqual(example.Storage.GetType(), volume.Storage.GetType()); // - is empty Assert.AreEqual(10, volume.Shape.GetDimension(0)); for (var i = 0; i < 10; i++) { Assert.AreEqual(0.0f, volume.Get(i)); } } [ClassInitialize] public static void ClassInit(TestContext context) { BuilderInstance<float>.Volume = new VolumeBuilder(); } [TestMethod] public void Convolve() { // 3x3x3x1 var input = new Single.Volume(new float[27].Populate(1.0f), new Shape(3, 3, 3, 1)); // 2x2x3x2 var filter = new Single.Volume( new float[12].Populate(1.0f).Concat(new float[12].Populate(2.0f)).ToArray(), new Shape(2, 2, 3, 2)); var result = input.Convolve(filter, 0, 2); // 1x1x2x1 Assert.AreEqual(1, result.Shape.GetDimension(0)); Assert.AreEqual(1, result.Shape.GetDimension(1)); Assert.AreEqual(2, result.Shape.GetDimension(2)); Assert.AreEqual(1, result.Shape.GetDimension(3)); Assert.AreEqual(12.0f, result.Storage.Get(0, 0, 0)); Assert.AreEqual(24.0f, result.Storage.Get(0, 0, 1)); } [TestMethod] public void ConvolveBatch() { // 3x3x3x2 var input = new Single.Volume(new float[27 * 2].Populate(1.0f), new Shape(3, 3, 3, 2)); // 2x2x3x2 var filter = new Single.Volume( new float[12].Populate(1.0f).Concat(new float[12].Populate(2.0f)).ToArray(), new Shape(2, 2, 3, 2)); var result = input.Convolve(filter, 0, 2); // 1x1x2x2 Assert.AreEqual(1, result.Shape.GetDimension(0)); Assert.AreEqual(1, result.Shape.GetDimension(1)); Assert.AreEqual(2, result.Shape.GetDimension(2)); Assert.AreEqual(2, result.Shape.GetDimension(3)); Assert.AreEqual(12.0f, result.Storage.Get(0, 0, 0, 0)); Assert.AreEqual(24.0f, result.Storage.Get(0, 0, 1, 0)); Assert.AreEqual(12.0f, result.Storage.Get(0, 0, 0, 1)); Assert.AreEqual(24.0f, result.Storage.Get(0, 0, 1, 1)); } [TestMethod] public void ConvolveGradient() { // 3x3x3x1 var input = new Single.Volume(new float[27].Populate(1.0f), new Shape(3, 3, 3, 1)); // 2x2x3x2 var filter = new Single.Volume( new float[12].Populate(1.0f).Concat(new float[12].Populate(2.0f)).ToArray(), new Shape(2, 2, 3, 2)); var outputGradient = new Single.Volume(new[] { 2.0f, 3.0f }, new Shape(1, 1, 2, 1)); var inputGradient = BuilderInstance<float>.Volume.SameAs(input.Storage, input.Shape); var filterGradient = BuilderInstance<float>.Volume.SameAs(filter.Storage, filter.Shape); input.ConvolveGradient(filter, outputGradient, inputGradient, filterGradient, 0, 2); Assert.AreEqual(8, inputGradient.Get(0, 0, 0, 0)); Assert.AreEqual(0, inputGradient.Get(2, 2, 2, 0)); Assert.AreEqual(0, inputGradient.Get(2, 2, 1, 0)); } [TestMethod] public void ConvolveGradientBatch() { // 3x3x3x2 var input = new Single.Volume(new float[27 * 2].Populate(1.0f), new Shape(3, 3, 3, 2)); // 2x2x3x2 var filter = new Single.Volume( new float[12].Populate(1.0f).Concat(new float[12].Populate(2.0f)).ToArray(), new Shape(2, 2, 3, 2)); var outputGradient = new Single.Volume(new[] { 2.0f, 3.0f, 4.0f, 5.0f }, new Shape(1, 1, 2, 2)); var inputGradient = BuilderInstance<float>.Volume.SameAs(input.Storage, input.Shape); var filterGradient = BuilderInstance<float>.Volume.SameAs(filter.Storage, filter.Shape); input.ConvolveGradient(filter, outputGradient, inputGradient, filterGradient, 0, 2); // input gradient Assert.AreEqual(8.0f, inputGradient.Get(0, 0, 0, 0)); Assert.AreEqual(0.0f, inputGradient.Get(2, 2, 2, 0)); Assert.AreEqual(0.0f, inputGradient.Get(2, 2, 1, 0)); Assert.AreEqual(14.0f, inputGradient.Get(0, 0, 0, 1)); Assert.AreEqual(0.0f, inputGradient.Get(2, 2, 2, 1)); Assert.AreEqual(0.0f, inputGradient.Get(2, 2, 1, 1)); // filter gradient Assert.AreEqual(1.0f, filter.Get(0, 0, 0, 0)); Assert.AreEqual(1.0f, filter.Get(0, 0, 1, 0)); Assert.AreEqual(1.0f, filter.Get(0, 0, 2, 0)); Assert.AreEqual(2.0f, filter.Get(0, 0, 0, 1)); Assert.AreEqual(2.0f, filter.Get(0, 0, 1, 1)); Assert.AreEqual(2.0f, filter.Get(0, 0, 2, 1)); } /// <summary> /// Fully connection can be expressed as a convolution with 1x1 filters /// </summary> [TestMethod] public void FullyCon() { // 1x3x1x1 var input = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(1, 1, 3, 1)); // 1x1x3x2 var filter = new Single.Volume( new[] { 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f }, new Shape(1, 1, 3, 2)); var result = input.Convolve(filter, 0, 1); // 1x1x2x1 Assert.AreEqual(1, result.Shape.GetDimension(0)); Assert.AreEqual(1, result.Shape.GetDimension(1)); Assert.AreEqual(2, result.Shape.GetDimension(2)); Assert.AreEqual(1, result.Shape.GetDimension(3)); Assert.AreEqual(6.0f, result.Storage.Get(0, 0, 0)); Assert.AreEqual(12.0f, result.Storage.Get(0, 0, 1)); } [TestMethod] public void Negate() { var volume = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(3)); var result = -volume; Assert.AreEqual(-1.0f, result.Get(0)); Assert.AreEqual(-2.0f, result.Get(1)); Assert.AreEqual(-3.0f, result.Get(2)); } [TestMethod] public void Pool2D() { var volume = new Single.Volume(new[] { 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 7.0f, 2.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 4.0f, 1.0f }, new Shape(4, 4)); var result = volume.Pool(2, 2, 0, 2); Assert.AreEqual(2, result.Shape.GetDimension(0)); Assert.AreEqual(2, result.Shape.GetDimension(0)); Assert.AreEqual(1.0f, result.Get(0, 0)); Assert.AreEqual(7.0f, result.Get(1, 0)); Assert.AreEqual(2.0f, result.Get(0, 1)); Assert.AreEqual(4.0f, result.Get(1, 1)); } [TestMethod] public void Pool2DBatch() { var volume = new Single.Volume(new[] { 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 7.0f, 2.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 4.0f, 1.0f, 2.0f, 0.0f, 2.0f, 2.0f, 2.0f, 0.0f, 2.0f, 14.0f, 4.0f, 0.0f, 2.0f, 2.0f, 2.0f, 0.0f, 8.0f, 2.0f }, new Shape(4, 4, 1, 2)); var result = volume.Pool(2, 2, 0, 2); Assert.AreEqual(2, result.Shape.GetDimension(0)); Assert.AreEqual(2, result.Shape.GetDimension(1)); Assert.AreEqual(1, result.Shape.GetDimension(2)); Assert.AreEqual(2, result.Shape.GetDimension(3)); Assert.AreEqual(1.0f, result.Get(0, 0, 0, 0)); Assert.AreEqual(7.0f, result.Get(1, 0, 0, 0)); Assert.AreEqual(2.0f, result.Get(0, 1, 0, 0)); Assert.AreEqual(4.0f, result.Get(1, 1, 0, 0)); Assert.AreEqual(2.0f, result.Get(0, 0, 0, 1)); Assert.AreEqual(14.0f, result.Get(1, 0, 0, 1)); Assert.AreEqual(4.0f, result.Get(0, 1, 0, 1)); Assert.AreEqual(8.0f, result.Get(1, 1, 0, 1)); } [TestMethod] public void Pool2DGradient() { var inputActivation = new Single.Volume(new[] { 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 7.0f, 2.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 4.0f, 1.0f }, new Shape(4, 4)); var outputActivation = inputActivation.Pool(2, 2, 0, 2); var outputActivationGradient = new Single.Volume(new[] { 1.0f, 1.0f, 1.0f, 1.0f }, new Shape(2, 2)); var result = outputActivation.PoolGradient(inputActivation, outputActivationGradient, 2, 2, 0, 2); Assert.AreEqual(1.0f, result.Get(0, 0)); Assert.AreEqual(1.0f, result.Get(3, 1)); Assert.AreEqual(1.0f, result.Get(0, 2)); Assert.AreEqual(1.0f, result.Get(2, 3)); } [TestMethod] public void Pool2DGradientBatch() { var inputActivation = new Single.Volume(new[] { 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 7.0f, 2.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 4.0f, 1.0f, 2.0f, 0.0f, 2.0f, 2.0f, 2.0f, 0.0f, 2.0f, 14.0f, 4.0f, 0.0f, 2.0f, 2.0f, 2.0f, 0.0f, 8.0f, 2.0f }, new Shape(4, 4, 1, 2)); var outputActivation = inputActivation.Pool(2, 2, 0, 2); var outputActivationGradient = new Single.Volume(new[] { 1.0f, 1.0f, 1.0f, 1.0f, 2.0f, 2.0f, 2.0f, 2.0f, }, new Shape(2, 2, 1, 2)); var result = outputActivation.PoolGradient(inputActivation, outputActivationGradient, 2, 2, 0, 2); Assert.AreEqual(1.0f, result.Get(0, 0, 0, 0)); Assert.AreEqual(1.0f, result.Get(3, 1, 0, 0)); Assert.AreEqual(1.0f, result.Get(0, 2, 0, 0)); Assert.AreEqual(1.0f, result.Get(2, 3, 0, 0)); Assert.AreEqual(2.0f, result.Get(0, 0, 0, 1)); Assert.AreEqual(2.0f, result.Get(3, 1, 0, 1)); Assert.AreEqual(2.0f, result.Get(0, 2, 0, 1)); Assert.AreEqual(2.0f, result.Get(2, 3, 0, 1)); } [TestMethod] public void Relu() { var volume = new Single.Volume(new[] { -1.0f, 0.0f, 3.0f, 5.0f }, new Shape(4)); var result = volume.Relu(); Assert.AreEqual(0.0f, result.Get(0)); Assert.AreEqual(0.0f, result.Get(1)); Assert.AreEqual(3.0f, result.Get(2)); Assert.AreEqual(5.0f, result.Get(3)); } [TestMethod] public void ReluGradient() { var inputActivation = new Single.Volume(new[] { -1.0f, 0.0f, 3.0f, 5.0f }, new Shape(4)); var outputActivation = inputActivation.Relu(); var outputActivationGradient = new Single.Volume(new[] { 1.0f, 1.0f, 1.0f, 1.0f }, new Shape(4)); var result = outputActivation.ReluGradient(inputActivation, outputActivationGradient); Assert.AreEqual(0.0f, result.Get(0)); Assert.AreEqual(0.0f, result.Get(1)); Assert.AreEqual(1.0f, result.Get(2)); Assert.AreEqual(1.0f, result.Get(3)); } [TestMethod] public void Shape2D() { var volume = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f, 4.0f }, new Shape(2, -1)); Assert.AreEqual(2, volume.Shape.GetDimension(0)); Assert.AreEqual(2, volume.Shape.GetDimension(1)); } [TestMethod] public void Sigmoid() { var volume = new Single.Volume(new[] { -1.0f, 0.0f, 3.0f, 5.0f }, new Shape(4)); var eps = 0.00001f; var result = volume.Sigmoid(); Assert.AreEqual(1.0f / (1.0f + Math.Exp(1.0f)), result.Get(0), eps); Assert.AreEqual(1.0f / (1.0f + Math.Exp(0.0f)), result.Get(1), eps); Assert.AreEqual(1.0f / (1.0f + Math.Exp(-3.0)), result.Get(2), eps); Assert.AreEqual(1.0f / (1.0f + Math.Exp(-5.0)), result.Get(3), eps); } [TestMethod] public void SigmoidGradient() { var inputActivation = new Single.Volume(new[] { -1.0f, 0.0f, 3.0f, 5.0f }, new Shape(4)); var outputActivation = inputActivation.Relu(); var outputActivationGradient = new Single.Volume(new[] { 1.0f, 1.0f, 1.0f, 1.0f }, new Shape(4)); var result = outputActivation.SigmoidGradient(inputActivation, outputActivationGradient); Assert.AreEqual(0.0f, result.Get(0)); Assert.AreEqual(0.0f, result.Get(1)); Assert.AreEqual(-6.0f, result.Get(2)); Assert.AreEqual(-20.0f, result.Get(3)); } [TestMethod] public void SoftMax() { var input1 = new Single.Volume(new[] { 0.0f, 0.0f, 0.0f, 10000.0f }, new Shape(1, 1, -1, 1)); var softmax1 = input1.SoftMax(); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 0, 0)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 1, 0)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 2, 0)); Assert.AreEqual(1.0f, softmax1.Get(0, 0, 3, 0)); var input2 = new Single.Volume(new[] { 10000.0f, 0.0f, 0.0f, 10000.0f }, new Shape(1, 1, -1, 1)); var softmax2 = input2.SoftMax(); Assert.AreEqual(0.5, softmax2.Get(0, 0, 0, 0)); Assert.AreEqual(0.5, softmax2.Get(0, 0, 3, 0)); } [TestMethod] public void SoftMaxBatch() { var volume1 = new Single.Volume(new[] { 0.0f, 0.0f, 0.0f, 10000.0f, 0.0f, 0.0f, 10000.0f, 0.0f }, new Shape(1, 1, -1, 2)); var softmax1 = volume1.SoftMax(); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 0, 0)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 1, 0)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 2, 0)); Assert.AreEqual(1.0f, softmax1.Get(0, 0, 3, 0)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 0, 1)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 1, 1)); Assert.AreEqual(1.0f, softmax1.Get(0, 0, 2, 1)); Assert.AreEqual(0.0f, softmax1.Get(0, 0, 3, 1)); } [TestMethod] public void SoftMaxGradient() { // input = [1, 0.1f, 0.1f, 0.1f] var input = new Single.Volume(new[] { 1.0f, 0.1f, 0.1f, 0.1f }, new Shape(1, 1, -1, 1)); // output = softmax(input) var output = input.SoftMax(); // groundTruth = [0, 1, 0 , 0] var groundTruth = new Single.Volume(new[] { 0.0f, 1.0f, 0.0f, 0.0f }, new Shape(1, 1, -1, 1)); // output gradient = 1 - groundTruth ./ output var outputGradient = new Single.Volume(new float[4], new Shape(1, 1, -1, 1)); groundTruth.Storage.Map((p, q) => 1 - p / q, output.Storage, outputGradient.Storage); // inputGradient = softmax_gradient(output, outputGradient) var inputGradient = output.SoftMaxGradient(outputGradient); // theorical result = output-groundTruth var result = output - groundTruth; Assert.AreEqual(result.Get(0, 0, 0, 0), inputGradient.Get(0, 0, 0, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 1, 0), inputGradient.Get(0, 0, 1, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 2, 0), inputGradient.Get(0, 0, 2, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 3, 0), inputGradient.Get(0, 0, 3, 0), 1e-4); } [TestMethod] public void SoftMaxGradientBatch() { // input = [1, 0.1f, 0.1f, 0.1f] var input = new Single.Volume(new[] { 1.0f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 1.0f, 0.1f }, new Shape(1, 1, -1, 2)); // output = softmax(input) var output = input.SoftMax(); // groundTruth = [0, 1, 0 , 0] var groundTruth = new Single.Volume(new[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }, new Shape(1, 1, -1, 2)); // output gradient = 1 - groundTruth ./ output var outputGradient = new Single.Volume(new float[8], new Shape(1, 1, -1, 2)); groundTruth.Storage.Map((p, q) => 1 - p / q, output.Storage, outputGradient.Storage); // inputGradient = softmax_gradient(output, outputGradient) var inputGradient = output.SoftMaxGradient(outputGradient); // theorical result = output-groundTruth var result = output - groundTruth; Assert.AreEqual(result.Get(0, 0, 0, 0), inputGradient.Get(0, 0, 0, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 1, 0), inputGradient.Get(0, 0, 1, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 2, 0), inputGradient.Get(0, 0, 2, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 3, 0), inputGradient.Get(0, 0, 3, 0), 1e-4); Assert.AreEqual(result.Get(0, 0, 0, 1), inputGradient.Get(0, 0, 0, 1), 1e-4); Assert.AreEqual(result.Get(0, 0, 1, 1), inputGradient.Get(0, 0, 1, 1), 1e-4); Assert.AreEqual(result.Get(0, 0, 2, 1), inputGradient.Get(0, 0, 2, 1), 1e-4); Assert.AreEqual(result.Get(0, 0, 3, 1), inputGradient.Get(0, 0, 3, 1), 1e-4); } [TestMethod] public void SubstractFrom() { var left = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(3)); var right = new Single.Volume(new[] { 2.0f, 0.0f, 1.0f }, new Shape(3)); var result = left - right; Assert.AreEqual(-1.0f, result.Get(0)); Assert.AreEqual(2.0f, result.Get(1)); Assert.AreEqual(2.0f, result.Get(2)); } [TestMethod] public void DoSubstractFrom() { var left = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(3)); var right = new Single.Volume(new[] { 2.0f, 0.0f, 1.0f }, new Shape(3)); var result = BuilderInstance<float>.Volume.SameAs(left.Shape); right.DoSubtractFrom(left, result); Assert.AreEqual(-1.0f, result.Get(0)); Assert.AreEqual(2.0f, result.Get(1)); Assert.AreEqual(2.0f, result.Get(2)); } [TestMethod] public void DoSubstractFromInPlace() { var left = new Single.Volume(new[] { 1.0f, 2.0f, 3.0f }, new Shape(3)); var right = new Single.Volume(new[] { 2.0f, 0.0f, 1.0f }, new Shape(3)); right.DoSubtractFrom(left, left); Assert.AreEqual(-1.0f, left.Get(0)); Assert.AreEqual(2.0f, left.Get(1)); Assert.AreEqual(2.0f, left.Get(2)); } [TestMethod] public void Tanh() { var volume = new Single.Volume(new[] { -1.0f, 0.0f, 3.0f, 5.0f }, new Shape(4)); var result = volume.Tanh(); var eps = 0.00001f; Assert.AreEqual(Math.Tanh(-1.0f), result.Get(0), eps); Assert.AreEqual(Math.Tanh(0.0f), result.Get(1), eps); Assert.AreEqual(Math.Tanh(3.0f), result.Get(2), eps); Assert.AreEqual(Math.Tanh(5.0f), result.Get(3), eps); } [TestMethod] public void TanhGradient() { var inputActivation = new Single.Volume(new[] { -1.0f, 0.0f, 3.0f, 5.0f }, new Shape(4)); var outputActivation = inputActivation.Relu(); var outputActivationGradient = new Single.Volume(new[] { 1.0f, 1.0f, 1.0f, 1.0f }, new Shape(4)); var result = outputActivation.TanhGradient(inputActivation, outputActivationGradient); Assert.AreEqual(1.0f, result.Get(0)); Assert.AreEqual(1.0f, result.Get(1)); Assert.AreEqual(-8.0f, result.Get(2)); Assert.AreEqual(-24.0f, result.Get(3)); } [TestMethod] public void Multiply() { var matrix = new[] { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f }; var a = new Single.Volume(matrix, Shape.From(2, 2, 2)); var b = a.Clone(); const double eps = 0.0001f; var result = b.Multiply(0.1f); Assert.AreNotSame(b, result); Assert.AreNotSame(b.Storage, result.Storage); for (var i = 0; i < matrix.Length; i++) { Assert.AreEqual(matrix[i], a.Get(i), eps); Assert.AreEqual(matrix[i], b.Get(i), eps); Assert.AreEqual(matrix[i] * 0.1f, result.Get(i), eps); } b = result; result = a.Clone(); a.DoMultiply(b, result); for (var i = 0; i < matrix.Length; i++) { Assert.AreEqual(matrix[i], a.Get(i), eps); Assert.AreEqual(matrix[i] * 0.1f, b.Get(i), eps); Assert.AreEqual(matrix[i] * matrix[i] * 0.1f, result.Get(i), eps); } } [TestMethod] public void ToArray() { var floats = new[] { 1.0f, 2.0f, 3.0f }; var v = new Single.Volume(floats, new Shape(3)); var array = v.ToArray(); Assert.IsTrue(floats.SequenceEqual(array)); } } }
/* * TypedObjectListView - A wrapper around an ObjectListView that provides type-safe delegates. * * Author: Phillip Piper * Date: 27/09/2008 9:15 AM * * Change log: * v2.3 * 2009-03-31 JPP - Added Objects property * 2008-11-26 JPP - Added tool tip getting methods * 2008-11-05 JPP - Added CheckState handling methods * 2008-10-24 JPP - Generate dynamic methods MkII. This one handles value types * 2008-10-21 JPP - Generate dynamic methods * 2008-09-27 JPP - Separated from ObjectListView.cs * * Copyright (C) 2006-2012 Phillip Piper * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you wish to use this code in a closed source application, please contact phillip_piper@bigfoot.com. */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Reflection.Emit; namespace BrightIdeasSoftware { /// <summary> /// A TypedObjectListView is a type-safe wrapper around an ObjectListView. /// </summary> /// <remarks> /// <para>VCS does not support generics on controls. It can be faked to some degree, but it /// cannot be completely overcome. In our case in particular, there is no way to create /// the custom OLVColumn's that we need to truly be generic. So this wrapper is an /// experiment in providing some type-safe access in a way that is useful and available today.</para> /// <para>A TypedObjectListView is not more efficient than a normal ObjectListView. /// Underneath, the same name of casts are performed. But it is easier to use since you /// do not have to write the casts yourself. /// </para> /// </remarks> /// <typeparam name="T">The class of model object that the list will manage</typeparam> /// <example> /// To use a TypedObjectListView, you write code like this: /// <code> /// TypedObjectListView&lt;Person> tlist = new TypedObjectListView&lt;Person>(this.listView1); /// tlist.CheckStateGetter = delegate(Person x) { return x.IsActive; }; /// tlist.GetColumn(0).AspectGetter = delegate(Person x) { return x.Name; }; /// ... /// </code> /// To iterate over the selected objects, you can write something elegant like this: /// <code> /// foreach (Person x in tlist.SelectedObjects) { /// x.GrantSalaryIncrease(); /// } /// </code> /// </example> public class TypedObjectListView<T> where T : class { /// <summary> /// Create a typed wrapper around the given list. /// </summary> /// <param name="olv">The listview to be wrapped</param> public TypedObjectListView(ObjectListView olv) { this.olv = olv; } //-------------------------------------------------------------------------------------- // Properties /// <summary> /// Return the model object that is checked, if only one row is checked. /// If zero rows are checked, or more than one row, null is returned. /// </summary> public virtual T CheckedObject { get { return (T)this.olv.CheckedObject; } } /// <summary> /// Return the list of all the checked model objects /// </summary> public virtual IList<T> CheckedObjects { get { IList checkedObjects = this.olv.CheckedObjects; List<T> objects = new List<T>(checkedObjects.Count); foreach (object x in checkedObjects) objects.Add((T)x); return objects; } set { this.olv.CheckedObjects = (IList)value; } } /// <summary> /// The ObjectListView that is being wrapped /// </summary> public virtual ObjectListView ListView { get { return olv; } set { olv = value; } } private ObjectListView olv; /// <summary> /// Get or set the list of all model objects /// </summary> public virtual IList<T> Objects { get { List<T> objects = new List<T>(this.olv.GetItemCount()); for (int i = 0; i < this.olv.GetItemCount(); i++) objects.Add(this.GetModelObject(i)); return objects; } set { this.olv.SetObjects(value); } } /// <summary> /// Return the model object that is selected, if only one row is selected. /// If zero rows are selected, or more than one row, null is returned. /// </summary> public virtual T SelectedObject { get { return (T)this.olv.SelectedObject; } set { this.olv.SelectedObject = value; } } /// <summary> /// The list of model objects that are selected. /// </summary> public virtual IList<T> SelectedObjects { get { List<T> objects = new List<T>(this.olv.SelectedIndices.Count); foreach (int index in this.olv.SelectedIndices) objects.Add((T)this.olv.GetModelObject(index)); return objects; } set { this.olv.SelectedObjects = (IList)value; } } //-------------------------------------------------------------------------------------- // Accessors /// <summary> /// Return a typed wrapper around the column at the given index /// </summary> /// <param name="i">The index of the column</param> /// <returns>A typed column or null</returns> public virtual TypedColumn<T> GetColumn(int i) { return new TypedColumn<T>(this.olv.GetColumn(i)); } /// <summary> /// Return a typed wrapper around the column with the given name /// </summary> /// <param name="name">The name of the column</param> /// <returns>A typed column or null</returns> public virtual TypedColumn<T> GetColumn(string name) { return new TypedColumn<T>(this.olv.GetColumn(name)); } /// <summary> /// Return the model object at the given index /// </summary> /// <param name="index">The index of the model object</param> /// <returns>The model object or null</returns> public virtual T GetModelObject(int index) { return (T)this.olv.GetModelObject(index); } //-------------------------------------------------------------------------------------- // Delegates /// <summary> /// CheckStateGetter /// </summary> /// <param name="rowObject"></param> /// <returns></returns> public delegate CheckState TypedCheckStateGetterDelegate(T rowObject); /// <summary> /// Gets or sets the check state getter /// </summary> public virtual TypedCheckStateGetterDelegate CheckStateGetter { get { return checkStateGetter; } set { this.checkStateGetter = value; if (value == null) this.olv.CheckStateGetter = null; else this.olv.CheckStateGetter = delegate(object x) { return this.checkStateGetter((T)x); }; } } private TypedCheckStateGetterDelegate checkStateGetter; /// <summary> /// BooleanCheckStateGetter /// </summary> /// <param name="rowObject"></param> /// <returns></returns> public delegate bool TypedBooleanCheckStateGetterDelegate(T rowObject); /// <summary> /// Gets or sets the boolean check state getter /// </summary> public virtual TypedBooleanCheckStateGetterDelegate BooleanCheckStateGetter { set { if (value == null) this.olv.BooleanCheckStateGetter = null; else this.olv.BooleanCheckStateGetter = delegate(object x) { return value((T)x); }; } } /// <summary> /// CheckStatePutter /// </summary> /// <param name="rowObject"></param> /// <param name="newValue"></param> /// <returns></returns> public delegate CheckState TypedCheckStatePutterDelegate(T rowObject, CheckState newValue); /// <summary> /// Gets or sets the check state putter delegate /// </summary> public virtual TypedCheckStatePutterDelegate CheckStatePutter { get { return checkStatePutter; } set { this.checkStatePutter = value; if (value == null) this.olv.CheckStatePutter = null; else this.olv.CheckStatePutter = delegate(object x, CheckState newValue) { return this.checkStatePutter((T)x, newValue); }; } } private TypedCheckStatePutterDelegate checkStatePutter; /// <summary> /// BooleanCheckStatePutter /// </summary> /// <param name="rowObject"></param> /// <param name="newValue"></param> /// <returns></returns> public delegate bool TypedBooleanCheckStatePutterDelegate(T rowObject, bool newValue); /// <summary> /// Gets or sets the boolean check state putter /// </summary> public virtual TypedBooleanCheckStatePutterDelegate BooleanCheckStatePutter { set { if (value == null) this.olv.BooleanCheckStatePutter = null; else this.olv.BooleanCheckStatePutter = delegate(object x, bool newValue) { return value((T)x, newValue); }; } } /// <summary> /// ToolTipGetter /// </summary> /// <param name="column"></param> /// <param name="modelObject"></param> /// <returns></returns> public delegate String TypedCellToolTipGetterDelegate(OLVColumn column, T modelObject); /// <summary> /// Gets or sets the cell tooltip getter /// </summary> public virtual TypedCellToolTipGetterDelegate CellToolTipGetter { set { if (value == null) this.olv.CellToolTipGetter = null; else this.olv.CellToolTipGetter = delegate(OLVColumn col, Object x) { return value(col, (T)x); }; } } /// <summary> /// Gets or sets the header tool tip getter /// </summary> public virtual HeaderToolTipGetterDelegate HeaderToolTipGetter { get { return this.olv.HeaderToolTipGetter; } set { this.olv.HeaderToolTipGetter = value; } } //-------------------------------------------------------------------------------------- // Commands /// <summary> /// This method will generate AspectGetters for any column that has an AspectName. /// </summary> public virtual void GenerateAspectGetters() { for (int i = 0; i < this.ListView.Columns.Count; i++) this.GetColumn(i).GenerateAspectGetter(); } } /// <summary> /// A type-safe wrapper around an OLVColumn /// </summary> /// <typeparam name="T"></typeparam> public class TypedColumn<T> where T : class { /// <summary> /// Creates a TypedColumn /// </summary> /// <param name="column"></param> public TypedColumn(OLVColumn column) { this.column = column; } private OLVColumn column; /// <summary> /// /// </summary> /// <param name="rowObject"></param> /// <returns></returns> public delegate Object TypedAspectGetterDelegate(T rowObject); /// <summary> /// /// </summary> /// <param name="rowObject"></param> /// <param name="newValue"></param> public delegate void TypedAspectPutterDelegate(T rowObject, Object newValue); /// <summary> /// /// </summary> /// <param name="rowObject"></param> /// <returns></returns> public delegate Object TypedGroupKeyGetterDelegate(T rowObject); /// <summary> /// /// </summary> /// <param name="rowObject"></param> /// <returns></returns> public delegate Object TypedImageGetterDelegate(T rowObject); /// <summary> /// /// </summary> public TypedAspectGetterDelegate AspectGetter { get { return this.aspectGetter; } set { this.aspectGetter = value; if (value == null) this.column.AspectGetter = null; else this.column.AspectGetter = delegate(object x) { return this.aspectGetter((T)x); }; } } private TypedAspectGetterDelegate aspectGetter; /// <summary> /// /// </summary> public TypedAspectPutterDelegate AspectPutter { get { return aspectPutter; } set { this.aspectPutter = value; if (value == null) this.column.AspectPutter = null; else this.column.AspectPutter = delegate(object x, object newValue) { this.aspectPutter((T)x, newValue); }; } } private TypedAspectPutterDelegate aspectPutter; /// <summary> /// /// </summary> public TypedImageGetterDelegate ImageGetter { get { return imageGetter; } set { this.imageGetter = value; if (value == null) this.column.ImageGetter = null; else this.column.ImageGetter = delegate(object x) { return this.imageGetter((T)x); }; } } private TypedImageGetterDelegate imageGetter; /// <summary> /// /// </summary> public TypedGroupKeyGetterDelegate GroupKeyGetter { get { return groupKeyGetter; } set { this.groupKeyGetter = value; if (value == null) this.column.GroupKeyGetter = null; else this.column.GroupKeyGetter = delegate(object x) { return this.groupKeyGetter((T)x); }; } } private TypedGroupKeyGetterDelegate groupKeyGetter; #region Dynamic methods /// <summary> /// Generate an aspect getter that does the same thing as the AspectName, /// except without using reflection. /// </summary> /// <remarks> /// <para> /// If you have an AspectName of "Owner.Address.Postcode", this will generate /// the equivilent of: <code>this.AspectGetter = delegate (object x) { /// return x.Owner.Address.Postcode; /// } /// </code> /// </para> /// <para> /// If AspectName is empty, this method will do nothing, otherwise /// this will replace any existing AspectGetter. /// </para> /// </remarks> public void GenerateAspectGetter() { if (!String.IsNullOrEmpty(this.column.AspectName)) this.AspectGetter = this.GenerateAspectGetter(typeof(T), this.column.AspectName); } /// <summary> /// Generates an aspect getter method dynamically. The method will execute /// the given dotted chain of selectors against a model object given at runtime. /// </summary> /// <param name="type">The type of model object to be passed to the generated method</param> /// <param name="path">A dotted chain of selectors. Each selector can be the name of a /// field, property or parameter-less method.</param> /// <returns>A typed delegate</returns> private TypedAspectGetterDelegate GenerateAspectGetter(Type type, string path) { DynamicMethod getter = new DynamicMethod(String.Empty, typeof(Object), new Type[] { type }, type, true); this.GenerateIL(type, path, getter.GetILGenerator()); return (TypedAspectGetterDelegate)getter.CreateDelegate(typeof(TypedAspectGetterDelegate)); } /// <summary> /// This method generates the actual IL for the method. /// </summary> /// <param name="type"></param> /// <param name="path"></param> /// <param name="il"></param> private void GenerateIL(Type type, string path, ILGenerator il) { // Push our model object onto the stack il.Emit(OpCodes.Ldarg_0); // Generate the IL to access each part of the dotted chain string[] parts = path.Split('.'); for (int i = 0; i < parts.Length; i++) { type = this.GeneratePart(il, type, parts[i], (i == parts.Length - 1)); if (type == null) break; } // If the object to be returned is a value type (e.g. int, bool), it // must be boxed, since the delegate returns an Object if (type != null && type.IsValueType && !typeof(T).IsValueType) il.Emit(OpCodes.Box, type); il.Emit(OpCodes.Ret); } private Type GeneratePart(ILGenerator il, Type type, string pathPart, bool isLastPart) { // TODO: Generate check for null // Find the first member with the given nam that is a field, property, or parameter-less method List<MemberInfo> infos = new List<MemberInfo>(type.GetMember(pathPart)); MemberInfo info = infos.Find(delegate(MemberInfo x) { if (x.MemberType == MemberTypes.Field || x.MemberType == MemberTypes.Property) return true; if (x.MemberType == MemberTypes.Method) return ((MethodInfo)x).GetParameters().Length == 0; else return false; }); // If we couldn't find anything with that name, pop the current result and return an error if (info == null) { il.Emit(OpCodes.Pop); il.Emit(OpCodes.Ldstr, String.Format("'{0}' is not a parameter-less method, property or field of type '{1}'", pathPart, type.FullName)); return null; } // Generate the correct IL to access the member. We remember the type of object that is going to be returned // so that we can do a method lookup on it at the next iteration Type resultType = null; switch (info.MemberType) { case MemberTypes.Method: MethodInfo mi = (MethodInfo)info; if (mi.IsVirtual) il.Emit(OpCodes.Callvirt, mi); else il.Emit(OpCodes.Call, mi); resultType = mi.ReturnType; break; case MemberTypes.Property: PropertyInfo pi = (PropertyInfo)info; il.Emit(OpCodes.Call, pi.GetGetMethod()); resultType = pi.PropertyType; break; case MemberTypes.Field: FieldInfo fi = (FieldInfo)info; il.Emit(OpCodes.Ldfld, fi); resultType = fi.FieldType; break; } // If the method returned a value type, and something is going to call a method on that value, // we need to load its address onto the stack, rather than the object itself. if (resultType.IsValueType && !isLastPart) { LocalBuilder lb = il.DeclareLocal(resultType); il.Emit(OpCodes.Stloc, lb); il.Emit(OpCodes.Ldloca, lb); } return resultType; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.CodeDom; namespace Thinktecture.Tools.Web.Services.CodeGeneration { internal class CollectionTypeGenerator { #region Private Members private ICollectionTypeProvider collectionTypeProvider; private Dictionary<string, CodeTypeReference> generatedTypes; private ExtendedCodeDomTree code; #endregion #region Constructors public CollectionTypeGenerator(ICollectionTypeProvider collectionTypeProvider, ExtendedCodeDomTree code) { this.collectionTypeProvider = collectionTypeProvider; this.generatedTypes = new Dictionary<string, CodeTypeReference>(); this.code = code; } #endregion #region Public Methods public void Execute() { RunConverter(code.DataContracts); RunConverter(code.MessageContracts); RunConverter(code.ClientTypes); RunConverter(code.ServiceContracts); RunConverter(code.ServiceTypes); } #endregion #region Private Methods private void RunConverter(FilteredTypes collection) { // Get the initial count in the collection. int icount = collection.Count; // Do this for each type found in the filtered type collection. for (int i = 0; i < icount; i++ ) { CodeTypeExtension typeExtension = collection[i]; // Send the fields to members converter ConvertMembers(typeExtension.Fields); // Send the properties to the members converter. ConvertMembers(typeExtension.Properties); // Send the methods to the members converter. ConvertMembers(typeExtension.Methods); // Send the constructors to the members converter. ConvertMembers(typeExtension.Constructors); } } private void ConvertMembers(FilteredTypeMembers filteredTypeMembers) { foreach (CodeTypeMemberExtension memberExt in filteredTypeMembers) { // Move to the next item if this is not convertible. if (!IsConvertibleMemeber(memberExt)) { continue; } if (memberExt.Kind == CodeTypeMemberKind.Field) { CodeMemberField field = (CodeMemberField)memberExt.ExtendedObject; field.Type = GetCollectionTypeReference(field.Type); HandleShouldSerialize(memberExt); } else if (memberExt.Kind == CodeTypeMemberKind.Property) { CodeMemberProperty property = (CodeMemberProperty)memberExt.ExtendedObject; property.Type = GetCollectionTypeReference(property.Type); HandleShouldSerialize(memberExt); } else if (memberExt.Kind == CodeTypeMemberKind.Method || memberExt.Kind == CodeTypeMemberKind.Constructor || memberExt.Kind == CodeTypeMemberKind.StaticConstructor) { CodeMemberMethod method = (CodeMemberMethod)memberExt.ExtendedObject; ProcessMethod(method); } } } private static void HandleShouldSerialize(CodeTypeMemberExtension fieldPropertyMember) { CodeTypeDeclaration type = fieldPropertyMember.Parent.ExtendedObject as CodeTypeDeclaration; if (type == null) return; CodeAttributeDeclaration arrayAttribute = fieldPropertyMember.FindAttribute("System.Xml.Serialization.XmlArrayItemAttribute"); if (arrayAttribute == null) return; CodeAttributeArgument isNullableArgument = arrayAttribute.FindArgument("IsNullable"); if (isNullableArgument == null) return; bool isNullable = (bool)((CodePrimitiveExpression)isNullableArgument.Value).Value; if (isNullable) return; string name = fieldPropertyMember.ExtendedObject.Name; CodeMemberMethod shouldSerializeMethod = new CodeMemberMethod { Attributes = MemberAttributes.Public, Name = "ShouldSerialize" + name, ReturnType = new CodeTypeReference(typeof(bool)) }; CodeThisReferenceExpression thisReference = new CodeThisReferenceExpression(); CodeFieldReferenceExpression collectionField = new CodeFieldReferenceExpression(thisReference, name); CodeBinaryOperatorExpression notNullExpression = new CodeBinaryOperatorExpression { Left = collectionField, Operator = CodeBinaryOperatorType.IdentityInequality, Right = new CodePrimitiveExpression(null) }; CodeBinaryOperatorExpression greaterThanZeroExpression = new CodeBinaryOperatorExpression { Left = new CodePropertyReferenceExpression(collectionField, "Count"), Operator = CodeBinaryOperatorType.GreaterThan, Right = new CodePrimitiveExpression(0) }; CodeBinaryOperatorExpression andExpression = new CodeBinaryOperatorExpression { Left = notNullExpression, Operator = CodeBinaryOperatorType.BooleanAnd, Right = greaterThanZeroExpression }; CodeMethodReturnStatement returnStatement = new CodeMethodReturnStatement(andExpression); shouldSerializeMethod.Statements.Add(returnStatement); type.Members.Add(shouldSerializeMethod); } /// <summary> /// This method ensures that we can generate a collection type to substitute /// given members type. /// </summary> private bool IsConvertibleMemeber(CodeTypeMemberExtension memberExtension) { if (memberExtension.Kind == CodeTypeMemberKind.Field) { CodeMemberField field = (CodeMemberField)memberExtension.ExtendedObject; if (field.Type.ArrayElementType == null) { return false; } // The field is not convertible if it is used in a property that has invalid attributes. foreach (CodeTypeMemberExtension parent in memberExtension.Parent.Properties) { CodeMemberProperty property = (CodeMemberProperty)parent.ExtendedObject; foreach (CodeStatement statement in property.GetStatements) { // Get the return statement for the property getter. CodeMethodReturnStatement returnStatement = statement as CodeMethodReturnStatement; if (returnStatement != null) { // Do we have a field reference on the right side of the assignment statement? CodeFieldReferenceExpression fieldRef = returnStatement.Expression as CodeFieldReferenceExpression; if (fieldRef != null) { // Is the field referenced the one we are checking? if (fieldRef.FieldName == field.Name) { // Does the property have invalid attributes? if (HasInvalidAttributes(parent)) { // If so, then the field should not be processed! return false; } } } } } } // Return true if we don't have any invalid attributes. return !HasInvalidAttributes(memberExtension); } else if (memberExtension.Kind == CodeTypeMemberKind.Property) { CodeMemberProperty property = (CodeMemberProperty)memberExtension.ExtendedObject; if (property.Type.ArrayElementType == null) { return false; } // Return true if we don't have any invalid attributes. return !HasInvalidAttributes(memberExtension); } else if (memberExtension.Kind == CodeTypeMemberKind.Method) { return true; } else if (memberExtension.Kind == CodeTypeMemberKind.Constructor || memberExtension.Kind == CodeTypeMemberKind.StaticConstructor) { return true; } else { // Currently we support only converting properties, fields and methods. return false; } } /// <summary> /// This method checks whether a given CodeTypeMember contains any attributes that will /// prevent from converting its type from an array to a collection. /// </summary> private bool HasInvalidAttributes(CodeTypeMemberExtension memberExtension) { if (memberExtension.FindAttribute("System.Xml.Serialization.XmlChoiceIdentifierAttribute") != null) { return true; } else if (memberExtension.FindAttribute("System.Xml.Serialization.XmlIgnoreAttribute") != null) { return true; } else { return false; } } private void ProcessMethod(CodeMemberMethod method) { // First we process the parameters. foreach (CodeParameterDeclarationExpression paramExp in method.Parameters) { if (paramExp.Type.ArrayElementType != null) { paramExp.Type = GetCollectionTypeReference(paramExp.Type, false); } } // Now we process the return type. if (method.ReturnType != null && method.ReturnType.ArrayElementType != null) { method.ReturnType = GetCollectionTypeReference(method.ReturnType, false); } } private CodeTypeReference GetCollectionTypeReference(CodeTypeReference ctr) { return GetCollectionTypeReference(ctr, true); } private CodeTypeReference GetCollectionTypeReference(CodeTypeReference ctr, bool create) { CodeTypeReference nctr = CacheLookup(ctr); if (nctr == null) { if (create) { nctr = collectionTypeProvider.CreateCollectionType(ctr, code); CacheNewType(ctr, nctr); } else { nctr = ctr; } } return nctr; } private CodeTypeReference CacheLookup(CodeTypeReference type) { if (generatedTypes.ContainsKey(type.BaseType)) { return generatedTypes[type.BaseType]; } return null; } private void CacheNewType(CodeTypeReference oldTypeRef, CodeTypeReference newTypeRef) { generatedTypes.Add(oldTypeRef.BaseType, newTypeRef); } #endregion } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System.Collections; using System; using System.Collections.Generic; using Serialization; using System.Linq; using System.Reflection; [Serializer(typeof(Vector2))] public class SerializeVector2 : SerializerExtensionBase<Vector2> { public override IEnumerable<object> Save(Vector2 target) { return new object[] { target.x, target.y }; } public override object Load(object[] data, object instance) { #if US_LOGGING Radical.Log ("Vector3: {0},{1},{2}", data [0], data [1], data [2]); #endif return new Vector2((float)data[0], (float)data[1]); } } [Serializer(typeof(Vector3))] public class SerializeVector3 : SerializerExtensionBase<Vector3> { public override IEnumerable<object> Save(Vector3 target) { return new object[] { target.x, target.y, target.z }; } public override object Load(object[] data, object instance) { #if US_LOGGING Radical.Log ("Vector3: {0},{1},{2}", data [0], data [1], data [2]); #endif return new UnitySerializer.DeferredSetter(d => { if (!float.IsNaN((float)data[0]) && !float.IsNaN((float)data[1]) && !float.IsNaN((float)data[2])) return new Vector3((float)data[0], (float)data[1], (float)data[2]); else return Vector3.zero; } ); } } [Serializer(typeof(Vector4))] public class SerializeVector4 : SerializerExtensionBase<Vector4> { public override IEnumerable<object> Save(Vector4 target) { return new object[] { target.x, target.y, target.z, target.w }; } public override object Load(object[] data, object instance) { #if US_LOGGING Radical.Log ("Vector3: {0},{1},{2}", data [0], data [1], data [2]); #endif if (!float.IsNaN((float)data[0]) && !float.IsNaN((float)data[1]) && !float.IsNaN((float)data[2]) && !float.IsNaN((float)data[3])) return new Vector4((float)data[0], (float)data[1], (float)data[2], (float)data[3]); else return Vector4.zero; } } [Serializer(typeof(Quaternion))] public class SerializeQuaternion : SerializerExtensionBase<Quaternion> { public override IEnumerable<object> Save(Quaternion target) { return new object[] { target.x, target.y, target.z, target.w }; } public override object Load(object[] data, object instance) { return new UnitySerializer.DeferredSetter(d => new Quaternion((float)data[0], (float)data[1], (float)data[2], (float)data[3])); } } [Serializer(typeof(Color))] public class SerializeColor : SerializerExtensionBase<Color> { public override IEnumerable<object> Save(Color target) { return new object[] { target.r, target.g, target.b, target.a }; } public override object Load(object[] data, object instance) { #if US_LOGGING Radical.Log ("Vector3: {0},{1},{2}", data [0], data [1], data [2]); #endif return new Color((float)data[0], (float)data[1], (float)data[2], (float)data[3]); } } [Serializer(typeof(AnimationState))] public class SerializeAnimationState : SerializerExtensionBase<AnimationState> { public override IEnumerable<object> Save(AnimationState target) { return new object[] { target.name }; } public override object Load(object[] data, object instance) { var uo = UnitySerializer.DeserializingObject; return new UnitySerializer.DeferredSetter(d => { var p = uo.GetType().GetProperty("animation").GetGetMethod(); if (p != null) { var animation = (Animation)p.Invoke(uo, null); if (animation != null) { return animation[(string)data[0]]; } } return null; }); } } [Serializer(typeof(WaitForSeconds))] public class SerializeWaitForSeconds : SerializerExtensionBase<WaitForSeconds> { public override IEnumerable<object> Save(WaitForSeconds target) { var tp = target.GetType(); var f = tp.GetField("m_Seconds", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); return new object[] { f.GetValue(target) }; } public override object Load(object[] data, object instance) { return new WaitForSeconds((float)data[0]); } } [Serializer(typeof(Bounds))] public class SerializeBounds : SerializerExtensionBase<Bounds> { public override IEnumerable<object> Save(Bounds target) { return new object[] { target.center.x, target.center.y, target.center.z, target.size.x, target.size.y, target.size.z }; } public override object Load(object[] data, object instance) { return new Bounds( new Vector3((float)data[0], (float)data[1], (float)data[2]), new Vector3((float)data[3], (float)data[4], (float)data[5])); } } public abstract class ComponentSerializerExtensionBase<T> : IComponentSerializer where T : Component { public abstract IEnumerable<object> Save(T target); public abstract void LoadInto(object[] data, T instance); #region IComponentSerializer implementation public byte[] Serialize(Component component) { return UnitySerializer.Serialize(Save((T)component).ToArray()); } public void Deserialize(byte[] data, Component instance) { object[] dataArray; dataArray = UnitySerializer.Deserialize<object[]>(data); LoadInto(dataArray, (T)instance); } #endregion } public class SerializerExtensionBase<T> : ISerializeObjectEx { #region ISerializeObject implementation public object[] Serialize(object target) { return Save((T)target).ToArray(); } public object Deserialize(object[] data, object instance) { return Load(data, instance); } #endregion public virtual IEnumerable<object> Save(T target) { return new object[0]; } public virtual object Load(object[] data, object instance) { return null; } #region ISerializeObjectEx implementation public bool CanSerialize(Type targetType, object instance) { if (instance == null) return true; return CanBeSerialized(targetType, instance); } #endregion public virtual bool CanBeSerialized(Type targetType, object instance) { return true; } } [ComponentSerializerFor(typeof(BoxCollider))] public class SerializeBoxCollider : ComponentSerializerExtensionBase<BoxCollider> { public override IEnumerable<object> Save(BoxCollider target) { return new object[] { target.isTrigger, target.size.x, target.size.y, target.size.z, target.center.x, target.center.y, target.center.z, target.enabled, target.sharedMaterial }; } public override void LoadInto(object[] data, BoxCollider instance) { instance.isTrigger = (bool)data[0]; instance.size = new Vector3((float)data[1], (float)data[2], (float)data[3]); instance.center = new Vector3((float)data[4], (float)data[5], (float)data[6]); instance.enabled = (bool)data[7]; instance.sharedMaterial = (PhysicMaterial)data[8]; } } [ComponentSerializerFor(typeof(Terrain))] public class SerializeTerrain : ComponentSerializerExtensionBase<Terrain> { public override IEnumerable<object> Save(Terrain target) { return new object[] { target.enabled }; } public override void LoadInto(object[] data, Terrain instance) { instance.enabled = (bool)data[0]; } } [ComponentSerializerFor(typeof(TerrainCollider))] public class SerializeCollider : ComponentSerializerExtensionBase<TerrainCollider> { public override IEnumerable<object> Save(TerrainCollider target) { return new object[] { target.sharedMaterial, target.terrainData, target.enabled }; } public override void LoadInto(object[] data, TerrainCollider instance) { instance.sharedMaterial = (PhysicMaterial)data[0]; instance.terrainData = (TerrainData)data[1]; instance.enabled = (bool)data[2]; } } [ComponentSerializerFor(typeof(MeshCollider))] public class SerializeMeshCollider : ComponentSerializerExtensionBase<MeshCollider> { public override IEnumerable<object> Save(MeshCollider target) { return new object[] { target.convex, target.isTrigger, target.sharedMaterial, target.sharedMesh, target.enabled }; } public override void LoadInto(object[] data, MeshCollider instance) { instance.convex = (bool)data[0]; instance.isTrigger = (bool)data[1]; instance.sharedMaterial = (PhysicMaterial)data[2]; instance.sharedMesh = (Mesh)data[3]; instance.enabled = (bool)data[4]; } } [ComponentSerializerFor(typeof(WheelCollider))] public class SerializeWheelCollider : IComponentSerializer { public class StoredInformation { public bool Enabled; public float brakeTorque; public Vector3 center; public float forceAppPointDistance; public WheelFrictionCurve forwardFriction; public float mass; public float motorTorque; public float radius; public WheelFrictionCurve sidewaysFriction; public float steerAngle; public float suspensionDistance; public JointSpring suspensionSpring; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var collider = (WheelCollider)component; var si = new StoredInformation(); si.Enabled = collider.enabled; si.brakeTorque = collider.brakeTorque; si.center = collider.center; si.forceAppPointDistance = collider.forceAppPointDistance; si.forwardFriction = collider.forwardFriction; si.mass = collider.mass; si.motorTorque = collider.motorTorque; si.radius = collider.radius; si.sidewaysFriction = collider.sidewaysFriction; si.steerAngle = collider.steerAngle; si.suspensionDistance = collider.suspensionDistance; si.suspensionSpring = collider.suspensionSpring; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var collider = (WheelCollider)instance; collider.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a WheelCollider"); return; } collider.enabled = si.Enabled; collider.brakeTorque = si.brakeTorque; collider.center = si.center; collider.forceAppPointDistance = si.forceAppPointDistance; collider.forwardFriction = si.forwardFriction; collider.mass = si.mass; collider.motorTorque = si.motorTorque; collider.radius = si.radius; collider.sidewaysFriction = si.sidewaysFriction; collider.steerAngle = si.steerAngle; collider.suspensionDistance = si.suspensionDistance; collider.suspensionSpring = si.suspensionSpring; } } ); } #endregion } [ComponentSerializerFor(typeof(CapsuleCollider))] public class SerializeCapsuleCollider : ComponentSerializerExtensionBase<CapsuleCollider> { public override IEnumerable<object> Save(CapsuleCollider target) { return new object[] { target.isTrigger, target.radius, target.center.x, target.center.y, target.center.z, target.height, target.enabled, target.sharedMaterial, target.direction }; } public override void LoadInto(object[] data, CapsuleCollider instance) { instance.isTrigger = (bool)data[0]; instance.radius = (float)data[1]; instance.center = new Vector3((float)data[2], (float)data[3], (float)data[4]); instance.height = (float)data[5]; instance.enabled = (bool)data[6]; instance.sharedMaterial = (PhysicMaterial)data[7]; instance.direction = (int)data[8]; } } [ComponentSerializerFor(typeof(SphereCollider))] public class SerializeSphereCollider : ComponentSerializerExtensionBase<SphereCollider> { public override IEnumerable<object> Save(SphereCollider target) { return new object[] { target.isTrigger, target.radius, target.center.x, target.center.y, target.center.z, target.enabled, target.sharedMaterial }; } public override void LoadInto(object[] data, SphereCollider instance) { instance.isTrigger = (bool)data[0]; instance.radius = (float)data[1]; instance.center = new Vector3((float)data[2], (float)data[3], (float)data[4]); instance.enabled = (bool)data[5]; instance.sharedMaterial = (PhysicMaterial)data[6]; } } [Serializer(typeof(Texture2D))] public class SerializeTexture2D : SerializerExtensionBase<Texture2D> { public override IEnumerable<object> Save(Texture2D target) { if (target.GetInstanceID() >= 0) { return new object[] { true, SaveGameManager.Instance.GetAssetId(target) }; } else { return new object[] { false, target.anisoLevel, target.filterMode, target.format, target.mipMapBias, target.mipmapCount, target.name, target.texelSize, target.wrapMode, target.EncodeToPNG() }; } } public override object Load(object[] data, object instance) { if ((bool)data[0]) { return SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[1]); } Texture2D t; if (data.Length == 10) { t = new Texture2D(1, 1, (TextureFormat)data[3], (int)data[5] > 0 ? true : false); t.LoadImage((byte[])data[9]); t.anisoLevel = (int)data[1]; t.filterMode = (FilterMode)data[2]; t.mipMapBias = (float)data[4]; t.name = (string)data[6]; t.wrapMode = (TextureWrapMode)data[8]; t.Apply(); return t; } t = new Texture2D((int)data[9], (int)data[4], (TextureFormat)data[3], (int)data[6] > 0 ? true : false); t.anisoLevel = (int)data[1]; t.filterMode = (FilterMode)data[2]; t.mipMapBias = (float)data[5]; t.name = (string)data[7]; t.wrapMode = (TextureWrapMode)data[10]; t.SetPixels32((Color32[])data[11]); t.Apply(); return t; } public override bool CanBeSerialized(Type targetType, object instance) { var obj = instance as Texture2D; if (!obj) { return false; } if (obj.GetInstanceID() < 0 || SaveGameManager.Instance.GetAssetId(instance as UnityEngine.Object).index != -1) { return true; } return false; } } [Serializer(typeof(Material))] public class SerializeMaterial : SerializerExtensionBase<Material> { public override IEnumerable<object> Save(Material target) { var store = GetStore(); if (target.GetInstanceID() >= 0) { return new object[] { true, SaveGameManager.Instance.GetAssetId(target) }; } else { return new object[] { false, target.shader.name, target.name, target.renderQueue, store != null ? store.GetValues(target) : null }; } } StoreMaterials GetStore() { if (SerializeRenderer.Store != null) return SerializeRenderer.Store; if (UnitySerializer.currentlySerializingObject is Component) { var comp = UnitySerializer.currentlySerializingObject as Component; return comp.GetComponent<StoreMaterials>(); } return null; } public override object Load(object[] data, object instance) { if ((bool)data[0]) { return SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[1]); } Material m; var shdr = Shader.Find((string)data[1]); m = new Material(shdr); m.name = (string)data[2]; var store = GetStore(); m.renderQueue = (int)data[3]; if (data[4] != null && store != null) store.SetValues(m, (List<StoreMaterials.StoredValue>)data[4]); return m; } public override bool CanBeSerialized(Type targetType, object instance) { var obj = instance as Material; if (!obj) return false; if ((Shader.Find(obj.shader.name) != null && obj.GetInstanceID() < 0 && SerializeRenderer.Store != null) || SaveGameManager.Instance.GetAssetId(instance as UnityEngine.Object).index != -1) { return true; } return false; } } [SubTypeSerializer(typeof(Texture))] [Serializer(typeof(Font))] [Serializer(typeof(AudioClip))] [Serializer(typeof(TextAsset))] [SubTypeSerializer(typeof(Mesh))] [Serializer(typeof(AnimationClip))] [Serializer(typeof(Sprite))] [Serializer(typeof(Button.ButtonClickedEvent))] [Serializer(typeof(Slider.SliderEvent))] [Serializer(typeof(Scrollbar.ScrollEvent))] [Serializer(typeof(Toggle.ToggleEvent))] [Serializer(typeof(InputField.OnChangeEvent))] [Serializer(typeof(InputField.SubmitEvent))] public class SerializeAssetReference : SerializerExtensionBase<object> { public static SerializeAssetReference instance = new SerializeAssetReference(); public override IEnumerable<object> Save(object target) { return new object[] { SaveGameManager.Instance.GetAssetId(target as UnityEngine.Object) }; } public override bool CanBeSerialized(Type targetType, object instance) { return instance == null || typeof(UnityEngine.Object).IsAssignableFrom(targetType); } public override object Load(object[] data, object instance) { return SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[0]); } } [SubTypeSerializer(typeof(ScriptableObject))] public class SerializeScriptableObjectReference : SerializerExtensionBase<object> { public override IEnumerable<object> Save(object target) { var id = SaveGameManager.Instance.GetAssetId(target as UnityEngine.Object); if (id.index == -1) { byte[] data = null; data = UnitySerializer.SerializeForDeserializeInto(target); var result = new object[] { true, target.GetType().FullName, data }; return result; } else { return new object[] { false, id }; } } public override bool CanBeSerialized(Type targetType, object instance) { return instance != null; } public override object Load(object[] data, object instance) { if ((bool)data[0]) { var newInstance = ScriptableObject.CreateInstance(UnitySerializer.GetTypeEx(data[1])); UnitySerializer.DeserializeInto((byte[])data[2], newInstance); return newInstance; } else { return SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[1]); } } } /// <summary> /// Store a reference to a game object, first checking whether it is really another game /// object and not a prefab /// </summary> [Serializer(typeof(GameObject))] public class SerializeGameObjectReference : SerializerExtensionBase<GameObject> { static SerializeGameObjectReference() { UnitySerializer.CanSerialize += (tp) => { return !typeof(MeshFilter).IsAssignableFrom(tp); }; } public override IEnumerable<object> Save(GameObject target) { //Is this a reference to a prefab var assetId = SaveGameManager.Instance.GetAssetId(target); if (assetId.index != -1) { return new object[] { 0, true, null, assetId }; } return new object[] { target.GetId(), UniqueIdentifier.GetByName(target.gameObject.GetId()) != null /* Identify a prefab */ }; } public override object Load(object[] data, object instance) { if (instance != null) { return instance; } #if US_LOGGING if (!((bool)data [1])) { Radical.Log ("[[Disabled, will not be set]]"); } Radical.Log ("GameObject: {0}", data [0]); #endif if (data.Length > 3) { var asset = SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[3]) as GameObject; return asset; } return instance ?? new UnitySerializer.DeferredSetter((d) => { return UniqueIdentifier.GetByName((string)data[0]); }) { enabled = (bool)data[1] }; } } [ComponentSerializerFor(typeof(NavMeshAgent))] public class SerializeNavMeshAgent : IComponentSerializer { public class StoredInfo { public bool hasPath, offMesh, autoBraking, autoTraverseOffMeshLink, autoRepath; public float x, y, z, speed, angularSpeed, height, offset, acceleration, radius, stoppingDistance; public int passable = -1, avoidancePriority; public ObstacleAvoidanceType obstacleAvoidanceType; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { var agent = (NavMeshAgent)component; return UnitySerializer.Serialize(new StoredInfo { x = agent.destination.x, y = agent.destination.y, z = agent.destination.z, speed = agent.speed, acceleration = agent.acceleration, angularSpeed = agent.angularSpeed, height = agent.height, offset = agent.baseOffset, hasPath = agent.hasPath, offMesh = agent.isOnOffMeshLink, passable = agent.areaMask, radius = agent.radius, stoppingDistance = agent.stoppingDistance, autoBraking = agent.autoBraking, obstacleAvoidanceType = agent.obstacleAvoidanceType, avoidancePriority = agent.avoidancePriority, autoTraverseOffMeshLink = agent.autoTraverseOffMeshLink, autoRepath = agent.autoRepath }); } public void Deserialize(byte[] data, Component instance) { var path = new NavMeshPath(); var agent = (NavMeshAgent)instance; agent.enabled = false; Loom.QueueOnMainThread(() => { var si = UnitySerializer.Deserialize<StoredInfo>(data); agent.speed = si.speed; agent.acceleration = si.acceleration; agent.angularSpeed = si.angularSpeed; agent.height = si.height; agent.baseOffset = si.offset; agent.areaMask = si.passable; agent.radius = si.radius; agent.stoppingDistance = si.stoppingDistance; agent.autoBraking = si.autoBraking; agent.obstacleAvoidanceType = si.obstacleAvoidanceType; agent.avoidancePriority = si.avoidancePriority; agent.autoTraverseOffMeshLink = si.autoTraverseOffMeshLink; agent.autoRepath = si.autoRepath; if (si.hasPath && !agent.isOnOffMeshLink) { agent.enabled = true; //if(agent.CalculatePath( new Vector3 (si.x, si.y, si.z), path)) //{ // agent.SetPath(path); // } if (NavMesh.CalculatePath(agent.transform.position, new Vector3(si.x, si.y, si.z), si.passable, path)) agent.SetPath(path); } }, 0.1f); } #endregion } [ComponentSerializerFor(typeof(Camera))] public class SerializeCamera : IComponentSerializer { public class CameraData { public RenderingPath renderingPath; public float fieldOfView; public float nearClipPlane; public float farClipPlane; public float depth; public Rect rect; public bool useOcclusionCulling; public bool hdr; public RenderTexture targetTexture; public bool orthographic; public float orthographicSize; public Color backgroundColor; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { var camera = (Camera)component; var cd = new CameraData { renderingPath = camera.actualRenderingPath, fieldOfView = camera.fieldOfView, depth = camera.depth, nearClipPlane = camera.nearClipPlane, farClipPlane = camera.farClipPlane, rect = camera.rect, useOcclusionCulling = camera.useOcclusionCulling, hdr = camera.hdr, targetTexture = camera.targetTexture, orthographic = camera.orthographic, orthographicSize = camera.orthographicSize, backgroundColor = camera.backgroundColor }; return UnitySerializer.Serialize(cd); } public void Deserialize(byte[] data, Component instance) { var cd = UnitySerializer.Deserialize<CameraData>(data); var camera = (Camera)instance; camera.renderingPath = cd.renderingPath; camera.fieldOfView = cd.fieldOfView; camera.nearClipPlane = cd.nearClipPlane; camera.farClipPlane = cd.farClipPlane; camera.depth = cd.depth; camera.rect = cd.rect; camera.useOcclusionCulling = cd.useOcclusionCulling; camera.hdr = cd.hdr; camera.targetTexture = cd.targetTexture; camera.orthographic = cd.orthographic; camera.orthographicSize = cd.orthographicSize; camera.backgroundColor = cd.backgroundColor; } #endregion } [ComponentSerializerFor(typeof(Rigidbody))] public class SerializeRigidBody : IComponentSerializer { public class RigidBodyInfo { public bool isKinematic; public bool useGravity, freezeRotation, detectCollisions, useConeFriction; public Vector3 velocity, position, angularVelocity, centerOfMass, inertiaTensor; public Quaternion rotation, inertiaTensorRotation; public float drag, angularDrag, mass, sleepThreshold, maxAngularVelocity; public RigidbodyConstraints constraints; public CollisionDetectionMode collisionDetectionMode; public RigidbodyInterpolation interpolation; public int solverIterationCount; public RigidBodyInfo() { } public RigidBodyInfo(Rigidbody source) { isKinematic = source.isKinematic; useGravity = source.useGravity; freezeRotation = source.freezeRotation; detectCollisions = source.detectCollisions; useConeFriction = source.useConeFriction; velocity = source.velocity; position = source.position; rotation = source.rotation; angularVelocity = source.angularVelocity; centerOfMass = source.centerOfMass; inertiaTensor = source.inertiaTensor; inertiaTensorRotation = source.inertiaTensorRotation; drag = source.drag; angularDrag = source.angularDrag; mass = source.mass; sleepThreshold = source.sleepThreshold; maxAngularVelocity = source.maxAngularVelocity; constraints = source.constraints; collisionDetectionMode = source.collisionDetectionMode; interpolation = source.interpolation; solverIterationCount = source.solverIterationCount; } public void Configure(Rigidbody body) { body.isKinematic = true; body.freezeRotation = freezeRotation; body.useGravity = useGravity; body.detectCollisions = detectCollisions; body.useConeFriction = useConeFriction; if (centerOfMass != Vector3.zero) body.centerOfMass = centerOfMass; body.drag = drag; body.angularDrag = angularDrag; body.mass = mass; if (!rotation.Equals(zero)) body.rotation = rotation; body.sleepThreshold = sleepThreshold; body.maxAngularVelocity = maxAngularVelocity; body.constraints = constraints; body.collisionDetectionMode = collisionDetectionMode; body.interpolation = interpolation; body.solverIterationCount = solverIterationCount; body.isKinematic = isKinematic; if (!isKinematic) { body.velocity = velocity; body.useGravity = useGravity; body.angularVelocity = angularVelocity; if (inertiaTensor != Vector3.zero) body.inertiaTensor = inertiaTensor; if (!inertiaTensorRotation.Equals(zero)) body.inertiaTensorRotation = inertiaTensorRotation; } } } static Quaternion zero = new Quaternion(0, 0, 0, 0); #region IComponentSerializer implementation public byte[] Serialize(Component component) { return UnitySerializer.Serialize(new RigidBodyInfo((Rigidbody)component)); } public void Deserialize(byte[] data, Component instance) { var info = UnitySerializer.Deserialize<RigidBodyInfo>(data); info.Configure((Rigidbody)instance); UnitySerializer.AddFinalAction(() => { info.Configure((Rigidbody)instance); }); } #endregion } [SerializerPlugIn] public class RagePixelSupport { static RagePixelSupport() { new SerializePrivateFieldOfType("RagePixelSprite", "animationPingPongDirection"); new SerializePrivateFieldOfType("RagePixelSprite", "myTime"); } } //[ComponentSerializerFor(typeof(Renderer))] [ComponentSerializerFor(typeof(MeshRenderer))] public class SerializeRenderer : IComponentSerializer { public static StoreMaterials Store; public class StoredInformation { public bool Enabled; public List<Material> materials = new List<Material>(); public UnityEngine.Rendering.ShadowCastingMode shadowCastingMode; public bool receiveShadows; public bool useLightProbes; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var renderer = (Renderer)component; var si = new StoredInformation(); si.Enabled = renderer.enabled; if ((Store = renderer.GetComponent<StoreMaterials>()) != null) { si.materials = renderer.materials.ToList(); } si.shadowCastingMode = renderer.shadowCastingMode; si.receiveShadows = renderer.receiveShadows; si.useLightProbes = renderer.useLightProbes; var data = UnitySerializer.Serialize(si); Store = null; return data; } } public void Deserialize(byte[] data, Component instance) { var renderer = (Renderer)instance; renderer.enabled = false; UnitySerializer.AddFinalAction(() => { Store = renderer.GetComponent<StoreMaterials>(); using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a renderer"); return; } renderer.enabled = si.Enabled; if (si.materials.Count > 0) { if (Store != null) { renderer.materials = si.materials.ToArray(); } } renderer.shadowCastingMode = si.shadowCastingMode; renderer.receiveShadows = si.receiveShadows; renderer.useLightProbes = si.useLightProbes; } Store = null; } ); } #endregion } [ComponentSerializerFor(typeof(LineRenderer))] public class SerializeLineRenderer : IComponentSerializer { public static StoreMaterials Store; public class StoredInformation : SerializeRenderer.StoredInformation { public bool useWorldSpace; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var renderer = (LineRenderer)component; var si = new StoredInformation(); si.Enabled = renderer.enabled; if ((Store = renderer.GetComponent<StoreMaterials>()) != null) { si.materials = renderer.materials.ToList(); } si.shadowCastingMode = renderer.shadowCastingMode; si.receiveShadows = renderer.receiveShadows; si.useLightProbes = renderer.useLightProbes; si.useWorldSpace = renderer.useWorldSpace; var data = UnitySerializer.Serialize(si); Store = null; return data; } } public void Deserialize(byte[] data, Component instance) { var renderer = (LineRenderer)instance; renderer.enabled = false; UnitySerializer.AddFinalAction(() => { Store = renderer.GetComponent<StoreMaterials>(); using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a LineRenderer"); return; } renderer.enabled = si.Enabled; if (si.materials.Count > 0) { if (Store != null) { renderer.materials = si.materials.ToArray(); } } renderer.shadowCastingMode = si.shadowCastingMode; renderer.receiveShadows = si.receiveShadows; renderer.useLightProbes = si.useLightProbes; renderer.useWorldSpace = si.useWorldSpace; } Store = null; } ); } #endregion } [ComponentSerializerFor(typeof(TrailRenderer))] public class SerializeTrailRenderer : IComponentSerializer { public static StoreMaterials Store; public class StoredInformation : SerializeRenderer.StoredInformation { public bool autodestruct; public float startWidth; public float endWidth; public float time; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var renderer = (TrailRenderer)component; var si = new StoredInformation(); si.Enabled = renderer.enabled; if ((Store = renderer.GetComponent<StoreMaterials>()) != null) { si.materials = renderer.materials.ToList(); } si.shadowCastingMode = renderer.shadowCastingMode; si.receiveShadows = renderer.receiveShadows; si.useLightProbes = renderer.useLightProbes; si.autodestruct = renderer.autodestruct; si.startWidth = renderer.startWidth; si.endWidth = renderer.endWidth; si.time = renderer.time; var data = UnitySerializer.Serialize(si); Store = null; return data; } } public void Deserialize(byte[] data, Component instance) { var renderer = (TrailRenderer)instance; renderer.enabled = false; UnitySerializer.AddFinalAction(() => { Store = renderer.GetComponent<StoreMaterials>(); using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a TrailRenderer"); return; } renderer.enabled = si.Enabled; if (si.materials.Count > 0) { if (Store != null) { renderer.materials = si.materials.ToArray(); } } renderer.shadowCastingMode = si.shadowCastingMode; renderer.receiveShadows = si.receiveShadows; renderer.useLightProbes = si.useLightProbes; renderer.autodestruct = si.autodestruct; renderer.startWidth = si.startWidth; renderer.endWidth = si.endWidth; renderer.time = si.time; } Store = null; } ); } #endregion } [ComponentSerializerFor(typeof(SkinnedMeshRenderer))] public class SerializeSkinnedMeshRenderer : IComponentSerializer { public static StoreMaterials Store; public class StoredInformation : SerializeRenderer.StoredInformation { public Bounds localBounds; public SkinQuality quality; public bool updateWhenOffscreen; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var renderer = (SkinnedMeshRenderer)component; var si = new StoredInformation(); si.Enabled = renderer.enabled; if ((Store = renderer.GetComponent<StoreMaterials>()) != null) { si.materials = renderer.materials.ToList(); } si.shadowCastingMode = renderer.shadowCastingMode; si.receiveShadows = renderer.receiveShadows; si.useLightProbes = renderer.useLightProbes; si.localBounds = renderer.localBounds; si.quality = renderer.quality; si.updateWhenOffscreen = renderer.updateWhenOffscreen; var data = UnitySerializer.Serialize(si); Store = null; return data; } } public void Deserialize(byte[] data, Component instance) { var renderer = (SkinnedMeshRenderer)instance; renderer.enabled = false; UnitySerializer.AddFinalAction(() => { Store = renderer.GetComponent<StoreMaterials>(); using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a SkinnedMeshRenderer"); return; } renderer.enabled = si.Enabled; if (si.materials.Count > 0) { if (Store != null) { renderer.materials = si.materials.ToArray(); } } renderer.shadowCastingMode = si.shadowCastingMode; renderer.receiveShadows = si.receiveShadows; renderer.useLightProbes = si.useLightProbes; renderer.localBounds = si.localBounds; renderer.quality = si.quality; renderer.updateWhenOffscreen = si.updateWhenOffscreen; } Store = null; } ); } #endregion } [ComponentSerializerFor(typeof(AudioChorusFilter))] public class SerializeAudioChorusFilter : IComponentSerializer { public class StoredInformation { public bool enabled; public float delay; public float depth; public float dryMix; public float rate; public float wetMix1; public float wetMix2; public float wetMix3; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var filter = (AudioChorusFilter)component; var si = new StoredInformation(); si.enabled = filter.enabled; si.delay = filter.delay; si.depth = filter.depth; si.dryMix = filter.dryMix; si.rate = filter.rate; si.wetMix1 = filter.wetMix1; si.wetMix2 = filter.wetMix2; si.wetMix3 = filter.wetMix3; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var filter = (AudioChorusFilter)instance; filter.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a AudioChorusFilter"); return; } filter.delay = si.delay; filter.depth = si.depth; filter.dryMix = si.dryMix; filter.rate = si.rate; filter.wetMix1 = si.wetMix1; filter.wetMix2 = si.wetMix2; filter.wetMix3 = si.wetMix3; filter.enabled = si.enabled; } } ); } #endregion } [ComponentSerializerFor(typeof(AudioDistortionFilter))] public class SerializeAudioDistortionFilter : IComponentSerializer { public class StoredInformation { public bool enabled; public float distortionLevel; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var filter = (AudioDistortionFilter)component; var si = new StoredInformation(); si.enabled = filter.enabled; si.distortionLevel = filter.distortionLevel; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var filter = (AudioDistortionFilter)instance; filter.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a AudioDistortionFilter"); return; } filter.distortionLevel = si.distortionLevel; filter.enabled = si.enabled; } } ); } #endregion } [ComponentSerializerFor(typeof(AudioEchoFilter))] public class SerializeAudioEchoFilter : IComponentSerializer { public class StoredInformation { public bool enabled; public float decayRatio; public float delay; public float dryMix; public float wetMix; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var filter = (AudioEchoFilter)component; var si = new StoredInformation(); si.enabled = filter.enabled; si.decayRatio = filter.decayRatio; si.delay = filter.delay; si.wetMix = filter.wetMix; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var filter = (AudioEchoFilter)instance; filter.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a AudioEchoFilter"); return; } filter.decayRatio = si.decayRatio; filter.delay = si.delay; filter.wetMix = si.wetMix; filter.enabled = si.enabled; } } ); } #endregion } [ComponentSerializerFor(typeof(AudioLowPassFilter))] public class SerializeAudioLowPassFilter : IComponentSerializer { public class StoredInformation { public bool enabled; public float cutoffFrequency; public float lowpassResonanceQ; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var filter = (AudioLowPassFilter)component; var si = new StoredInformation(); si.enabled = filter.enabled; si.cutoffFrequency = filter.cutoffFrequency; si.lowpassResonanceQ = filter.lowpassResonanceQ; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var filter = (AudioLowPassFilter)instance; filter.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a AudioLowPassFilter"); return; } filter.cutoffFrequency = si.cutoffFrequency; filter.lowpassResonanceQ = si.lowpassResonanceQ; filter.enabled = si.enabled; } } ); } #endregion } [ComponentSerializerFor(typeof(AudioHighPassFilter))] public class SerializeAudioHighPassFilter : IComponentSerializer { public class StoredInformation { public bool enabled; public float cutoffFrequency; public float highpassResonanceQ; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var filter = (AudioHighPassFilter)component; var si = new StoredInformation(); si.enabled = filter.enabled; si.cutoffFrequency = filter.cutoffFrequency; si.highpassResonanceQ = filter.highpassResonanceQ; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var filter = (AudioHighPassFilter)instance; filter.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a AudioHighPassFilter"); return; } filter.cutoffFrequency = si.cutoffFrequency; filter.highpassResonanceQ = si.highpassResonanceQ; filter.enabled = si.enabled; } } ); } #endregion } [ComponentSerializerFor(typeof(EventSystem))] public class SerializeEventSystem : IComponentSerializer { public class StoredInformation { public bool enabled; public GameObject firstSelectedGameObject; public int pixelDragThreshold; public bool sendNavigationEvents; } #region IComponentSerializer implementation public byte[] Serialize(Component component) { using (new UnitySerializer.SerializationSplitScope()) { var system = (EventSystem)component; var si = new StoredInformation(); si.enabled = system.enabled; si.firstSelectedGameObject = system.firstSelectedGameObject; si.pixelDragThreshold = system.pixelDragThreshold; si.sendNavigationEvents = system.sendNavigationEvents; var data = UnitySerializer.Serialize(si); return data; } } public void Deserialize(byte[] data, Component instance) { var system = (EventSystem)instance; system.enabled = false; UnitySerializer.AddFinalAction(() => { using (new UnitySerializer.SerializationSplitScope()) { var si = UnitySerializer.Deserialize<StoredInformation>(data); if (si == null) { Debug.LogError("An error occured when getting the stored information for a EventSystem"); return; } system.firstSelectedGameObject = si.firstSelectedGameObject; system.pixelDragThreshold = si.pixelDragThreshold; system.sendNavigationEvents = si.sendNavigationEvents; system.enabled = si.enabled; } } ); } #endregion } [SubTypeSerializer(typeof(Component))] public class SerializeComponentReference : SerializerExtensionBase<Component> { public override IEnumerable<object> Save(Component target) { //Is this a reference to a prefab var assetId = SaveGameManager.Instance.GetAssetId(target); if (assetId.index != -1) { return new object[] { null, true, target.GetType().FullName, assetId }; } var index = target.gameObject.GetComponents(target.GetType()).FindIndex(c => c == target); if (UniqueIdentifier.GetByName(target.gameObject.GetId()) != null) { return new object[] { target.gameObject.GetId(), true, target.GetType().FullName, "", index /* Identify a prefab */ }; } else { return new object[] { target.gameObject.GetId(), false, target.GetType().FullName, "", index /* Identify a prefab */ }; } } public override object Load(object[] data, object instance) { #if US_LOGGING if (!((bool)data [1])) { Radical.Log ("[[Disabled, will not be set]]"); } Radical.Log ("Component: {0}.{1}", data [0], data [2]); #endif if (data[3] != null && data[3].GetType() == typeof(SaveGameManager.AssetReference)) { return SaveGameManager.Instance.GetAsset((SaveGameManager.AssetReference)data[3]); } if (data.Length == 5) { return new UnitySerializer.DeferredSetter((d) => { var item = UniqueIdentifier.GetByName((string)data[0]); if (item == null) { Debug.LogError("Could not find reference to " + data[0] + " a " + (string)data[2]); return null; } var allComponentsOfType = item.GetComponents(UnitySerializer.GetTypeEx(data[2])); if (allComponentsOfType.Length == 0) return null; if (allComponentsOfType.Length <= (int)data[4]) data[4] = 0; return item != null ? allComponentsOfType[(int)data[4]] : null; }) { enabled = (bool)data[1] }; } return new UnitySerializer.DeferredSetter((d) => { var item = UniqueIdentifier.GetByName((string)data[0]); return item != null ? item.GetComponent(UnitySerializer.GetTypeEx(data[2])) : null; }) { enabled = (bool)data[1] }; } } public class ProvideAttributes : IProvideAttributeList { private string[] _attributes; protected bool AllSimple = true; public ProvideAttributes(string[] attributes) : this(attributes, true) { } public ProvideAttributes(string[] attributes, bool allSimple) { _attributes = attributes; AllSimple = allSimple; } #region IProvideAttributeList implementation public IEnumerable<string> GetAttributeList(Type tp) { return _attributes; } #endregion #region IProvideAttributeList implementation public virtual bool AllowAllSimple(Type tp) { return AllSimple; } #endregion } [AttributeListProvider(typeof(Camera))] public class ProvideCameraAttributes : ProvideAttributes { public ProvideCameraAttributes() : base(new string[0]) { } } [AttributeListProvider(typeof(Transform))] public class ProviderTransformAttributes : ProvideAttributes { public ProviderTransformAttributes() : base(new string[] { "localPosition", "localRotation", "localScale" }, false) { } } [AttributeListProvider(typeof(RectTransform))] public class ProviderRectTransformAttributes : ProvideAttributes { public ProviderRectTransformAttributes() : base(new string[] { "anchoredPosition", "anchoredPosition3D", "anchorMax", "anchorMin", "offsetMax", "offsetMin", "pivot", "rect", "sizeDelta" }, false) { } } [AttributeListProvider(typeof(Collider))] public class ProvideColliderAttributes : ProvideAttributes { public ProvideColliderAttributes() : base(new string[] { "material", "active", "text", "mesh", "anchor", "targetPosition", "alignment", "lineSpacing", "spring", "useSpring", "motor", "useMotor", "limits", "useLimits", "axis", "breakForce", "breakTorque", "connectedBody", "offsetZ", "playAutomatically", "animatePhysics", "tabSize", "enabled", "isTrigger", "emit", "minSize", "maxSize", "clip", "loop", "playOnAwake", "bypassEffects", "volume", "priority", "pitch", "mute", "dopplerLevel", "spread", "panLevel", "volumeRolloff", "minDistance", "maxDistance", "pan2D", "castShadows", "receiveShadows", "slopeLimit", "stepOffset", "skinWidth", "minMoveDistance", "center", "radius", "height", "canControl", "damper", "useFixedUpdate", "movement", "jumping", "movingPlatform", "sliding", "autoRotate", "maxRotationSpeed", "range", "angle", "velocity", "intensity", "secondaryAxis", "xMotion", "yMotion", "zMotion", "angularXMotion", "angularYMotion", "angularZMotion", "linearLimit", "lowAngularXLimit", "highAngularXLimit", "angularYLimit", "angularZLimit", "targetVelocity", "xDrive", "yDrive", "zDrive", "targetAngularVelocity", "rotationDriveMode", "angularXDrive", "angularYZDrive", "slerpDrive", "projectionMode", "projectionDistance", "projectionAngle", "configuredInWorldSpace", "swapBodies", "cookie", "color", "drawHalo", "shadowType", "renderMode", "cullingMask", "lightmapping", "type", "lineSpacing", "text", "anchor", "alignment", "tabSize", "fontSize", "fontStyle", "font", "characterSize", "minEnergy", "maxEnergy", "minEmission", "maxEmission", "rndRotation", "rndVelocity", "rndAngularVelocity", "angularVelocity", "emitterVelocityScale", "localVelocity", "worldVelocity", "useWorldVelocity" }, false) { } } [AttributeListProvider(typeof(Renderer))] [AttributeListProvider(typeof(AudioListener))] [AttributeListProvider(typeof(ParticleEmitter))] [AttributeListProvider(typeof(Cloth))] [AttributeListProvider(typeof(Light))] [AttributeListProvider(typeof(Joint))] [AttributeListProvider(typeof(MeshFilter))] [AttributeListProvider(typeof(TextMesh))] public class ProviderRendererAttributes : ProvideAttributes { public ProviderRendererAttributes() : base(new string[] { "active", "text", "anchor", "sharedMesh", "targetPosition", "alignment", "lineSpacing", "spring", "useSpring", "motor", "useMotor", "limits", "useLimits", "axis", "breakForce", "breakTorque", "connectedBody", "offsetZ", "playAutomatically", "animatePhysics", "tabSize", "enabled", "isTrigger", "emit", "minSize", "maxSize", "clip", "loop", "playOnAwake", "bypassEffects", "volume", "priority", "pitch", "mute", "dopplerLevel", "spread", "panLevel", "volumeRolloff", "minDistance", "maxDistance", "pan2D", "castShadows", "receiveShadows", "slopeLimit", "stepOffset", "skinWidth", "minMoveDistance", "center", "radius", "height", "canControl", "damper", "useFixedUpdate", "movement", "jumping", "movingPlatform", "sliding", "autoRotate", "maxRotationSpeed", "range", "angle", "velocity", "intensity", "secondaryAxis", "xMotion", "yMotion", "zMotion", "angularXMotion", "angularYMotion", "angularZMotion", "linearLimit", "lowAngularXLimit", "highAngularXLimit", "angularYLimit", "angularZLimit", "targetVelocity", "xDrive", "yDrive", "zDrive", "targetAngularVelocity", "rotationDriveMode", "angularXDrive", "angularYZDrive", "slerpDrive", "projectionMode", "projectionDistance", "projectionAngle", "configuredInWorldSpace", "swapBodies", "cookie", "color", "drawHalo", "shadowType", "renderMode", "cullingMask", "lightmapping", "type", "lineSpacing", "text", "anchor", "alignment", "tabSize", "fontSize", "fontStyle", "font", "characterSize", "minEnergy", "maxEnergy", "minEmission", "maxEmission", "rndRotation", "rndVelocity", "rndAngularVelocity", "angularVelocity", "emitterVelocityScale", "localVelocity", "worldVelocity", "useWorldVelocity" }, false) { } }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code <<<<<<< Updated upstream // Generated from: CommandBase.proto // Note: requires additional types generated from: ManagementCommand.proto // Note: requires additional types generated from: ManagementResponse.proto namespace Alachisoft.NosDB.Common.Protobuf.ManagementCommands { [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"CommandBase")] public partial class CommandBase : global::ProtoBuf.IExtensible { public CommandBase() {} ======= using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Alachisoft.NoSDB.Common.Protobuf.ManagementCommands { namespace Proto { >>>>>>> Stashed changes [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class CommandBase { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Builder> internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static CommandBase() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFDb21tYW5kQmFzZS5wcm90bxIzQWxhY2hpc29mdC5Ob1NEQi5Db21tb24u", "UHJvdG9idWYuTWFuYWdlbWVudENvbW1hbmRzGhdNYW5hZ2VtZW50Q29tbWFu", "ZC5wcm90bxoYTWFuYWdlbWVudFJlc3BvbnNlLnByb3RvIuECCgtDb21tYW5k", "QmFzZRIRCglyZXF1ZXN0SWQYASABKAMSVwoHY29tbWFuZBgCIAEoCzJGLkFs", "YWNoaXNvZnQuTm9TREIuQ29tbW9uLlByb3RvYnVmLk1hbmFnZW1lbnRDb21t", "YW5kcy5NYW5hZ2VtZW50Q29tbWFuZBJZCghyZXNwb25zZRgDIAEoCzJHLkFs", "YWNoaXNvZnQuTm9TREIuQ29tbW9uLlByb3RvYnVmLk1hbmFnZW1lbnRDb21t", "YW5kcy5NYW5hZ2VtZW50UmVzcG9uc2USYQoLY29tbWFuZFR5cGUYBCABKA4y", "TC5BbGFjaGlzb2Z0Lk5vU0RCLkNvbW1vbi5Qcm90b2J1Zi5NYW5hZ2VtZW50", "Q29tbWFuZHMuQ29tbWFuZEJhc2UuQ29tbWFuZFR5cGUiKAoLQ29tbWFuZFR5", "cGUSCwoHQ09NTUFORBABEgwKCFJFU1BPTlNFEAJCNwokY29tLmFsYWNoaXNv", "ZnQubm9zZGIuY29tbW9uLnByb3RvYnVmQg9Db21tYW5kUHJvdG9jb2w=")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Builder>(internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__Descriptor, new string[] { "RequestId", "Command", "Response", "CommandType", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementCommand.Descriptor, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementResponse.Descriptor, }, assigner); } #endregion } <<<<<<< Updated upstream private Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementCommand _command = null; [global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"command", DataFormat = global::ProtoBuf.DataFormat.Default)] [global::System.ComponentModel.DefaultValue(null)] public Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementCommand command { get { return _command; } set { _command = value; } } private Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementResponse _response = null; [global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"response", DataFormat = global::ProtoBuf.DataFormat.Default)] [global::System.ComponentModel.DefaultValue(null)] public Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementResponse response { get { return _response; } set { _response = value; } } private Alachisoft.NosDB.Common.Protobuf.ManagementCommands.CommandBase.CommandType _commandType = Alachisoft.NosDB.Common.Protobuf.ManagementCommands.CommandBase.CommandType.COMMAND; [global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"commandType", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] [global::System.ComponentModel.DefaultValue(Alachisoft.NosDB.Common.Protobuf.ManagementCommands.CommandBase.CommandType.COMMAND)] public Alachisoft.NosDB.Common.Protobuf.ManagementCommands.CommandBase.CommandType commandType { get { return _commandType; } set { _commandType = value; } } [global::ProtoBuf.ProtoContract(Name=@"CommandType")] public enum CommandType { [global::ProtoBuf.ProtoEnum(Name=@"COMMAND", Value=1)] COMMAND = 1, [global::ProtoBuf.ProtoEnum(Name=@"RESPONSE", Value=2)] RESPONSE = 2 ======= } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class CommandBase : pb::GeneratedMessage<CommandBase, CommandBase.Builder> { private CommandBase() { } private static readonly CommandBase defaultInstance = new CommandBase().MakeReadOnly(); private static readonly string[] _commandBaseFieldNames = new string[] { "command", "commandType", "requestId", "response" }; private static readonly uint[] _commandBaseFieldTags = new uint[] { 18, 32, 8, 26 }; public static CommandBase DefaultInstance { get { return defaultInstance; } } public override CommandBase DefaultInstanceForType { get { return DefaultInstance; } } protected override CommandBase ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.CommandBase.internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<CommandBase, CommandBase.Builder> InternalFieldAccessors { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.CommandBase.internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_CommandBase__FieldAccessorTable; } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum CommandType { COMMAND = 1, RESPONSE = 2, } } #endregion public const int RequestIdFieldNumber = 1; private bool hasRequestId; private long requestId_; public bool HasRequestId { get { return hasRequestId; } } public long RequestId { get { return requestId_; } set { requestId_ = value; } } public const int CommandFieldNumber = 2; private bool hasCommand; private global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand command_; public bool HasCommand { get { return hasCommand; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand Command { get { return command_ ?? global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.DefaultInstance; } } public const int ResponseFieldNumber = 3; private bool hasResponse; private global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse response_; public bool HasResponse { get { return hasResponse; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse Response { get { return response_ ?? global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.DefaultInstance; } } public const int CommandTypeFieldNumber = 4; private bool hasCommandType; private global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Types.CommandType commandType_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Types.CommandType.COMMAND; public bool HasCommandType { get { return hasCommandType; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Types.CommandType CommandType { get { return commandType_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _commandBaseFieldNames; if (hasRequestId) { output.WriteInt64(1, field_names[2], RequestId); } if (hasCommand) { output.WriteMessage(2, field_names[0], Command); } if (hasResponse) { output.WriteMessage(3, field_names[3], Response); } if (hasCommandType) { output.WriteEnum(4, field_names[1], (int) CommandType, CommandType); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasRequestId) { size += pb::CodedOutputStream.ComputeInt64Size(1, RequestId); } if (hasCommand) { size += pb::CodedOutputStream.ComputeMessageSize(2, Command); } if (hasResponse) { size += pb::CodedOutputStream.ComputeMessageSize(3, Response); } if (hasCommandType) { size += pb::CodedOutputStream.ComputeEnumSize(4, (int) CommandType); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static CommandBase ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static CommandBase ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static CommandBase ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static CommandBase ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static CommandBase ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static CommandBase ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static CommandBase ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static CommandBase ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static CommandBase ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static CommandBase ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private CommandBase MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(CommandBase prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<CommandBase, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(CommandBase cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private CommandBase result; private CommandBase PrepareBuilder() { if (resultIsReadOnly) { CommandBase original = result; result = new CommandBase(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override CommandBase MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Descriptor; } } public override CommandBase DefaultInstanceForType { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.DefaultInstance; } } public override CommandBase BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is CommandBase) { return MergeFrom((CommandBase) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(CommandBase other) { if (other == global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.DefaultInstance) return this; PrepareBuilder(); if (other.HasRequestId) { RequestId = other.RequestId; } if (other.HasCommand) { MergeCommand(other.Command); } if (other.HasResponse) { MergeResponse(other.Response); } if (other.HasCommandType) { CommandType = other.CommandType; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_commandBaseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _commandBaseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { result.hasRequestId = input.ReadInt64(ref result.requestId_); break; } case 18: { global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Builder subBuilder = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.CreateBuilder(); if (result.hasCommand) { subBuilder.MergeFrom(Command); } input.ReadMessage(subBuilder, extensionRegistry); Command = subBuilder.BuildPartial(); break; } case 26: { global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.Builder subBuilder = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.CreateBuilder(); if (result.hasResponse) { subBuilder.MergeFrom(Response); } input.ReadMessage(subBuilder, extensionRegistry); Response = subBuilder.BuildPartial(); break; } case 32: { object unknown; if(input.ReadEnum(ref result.commandType_, out unknown)) { result.hasCommandType = true; } else if(unknown is int) { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } unknownFields.MergeVarintField(4, (ulong)(int)unknown); } break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasRequestId { get { return result.hasRequestId; } } public long RequestId { get { return result.RequestId; } set { SetRequestId(value); } } public Builder SetRequestId(long value) { PrepareBuilder(); result.hasRequestId = true; result.requestId_ = value; return this; } public Builder ClearRequestId() { PrepareBuilder(); result.hasRequestId = false; result.requestId_ = 0L; return this; } public bool HasCommand { get { return result.hasCommand; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand Command { get { return result.Command; } set { SetCommand(value); } } public Builder SetCommand(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasCommand = true; result.command_ = value; return this; } public Builder SetCommand(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasCommand = true; result.command_ = builderForValue.Build(); return this; } public Builder MergeCommand(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasCommand && result.command_ != global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.DefaultInstance) { result.command_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.CreateBuilder(result.command_).MergeFrom(value).BuildPartial(); } else { result.command_ = value; } result.hasCommand = true; return this; } public Builder ClearCommand() { PrepareBuilder(); result.hasCommand = false; result.command_ = null; return this; } public bool HasResponse { get { return result.hasResponse; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse Response { get { return result.Response; } set { SetResponse(value); } } public Builder SetResponse(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasResponse = true; result.response_ = value; return this; } public Builder SetResponse(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasResponse = true; result.response_ = builderForValue.Build(); return this; } public Builder MergeResponse(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasResponse && result.response_ != global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.DefaultInstance) { result.response_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementResponse.CreateBuilder(result.response_).MergeFrom(value).BuildPartial(); } else { result.response_ = value; } result.hasResponse = true; return this; } public Builder ClearResponse() { PrepareBuilder(); result.hasResponse = false; result.response_ = null; return this; } public bool HasCommandType { get { return result.hasCommandType; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Types.CommandType CommandType { get { return result.CommandType; } set { SetCommandType(value); } } public Builder SetCommandType(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Types.CommandType value) { PrepareBuilder(); result.hasCommandType = true; result.commandType_ = value; return this; } public Builder ClearCommandType() { PrepareBuilder(); result.hasCommandType = false; result.commandType_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.CommandBase.Types.CommandType.COMMAND; return this; } } static CommandBase() { object.ReferenceEquals(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.CommandBase.Descriptor, null); >>>>>>> Stashed changes } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Interception { using System.Data.Common; using System.Data.Entity.Core; using System.Data.Entity.Core.Common; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Data.Entity.Infrastructure.DependencyResolution; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.SqlServer; using System.Data.Entity.TestHelpers; using System.Data.SqlClient; using System.Linq; using System.Threading; using System.Threading.Tasks; using Moq; using Xunit; public class CommitFailureTests : FunctionalTestBase { [Fact] public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(()=> ExtendedSqlAzureExecutionStrategy.ExecuteNew(c)).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(()=> ExtendedSqlAzureExecutionStrategy.ExecuteNew(c)).ValidateMessage("CommitFailed"), expectedBlogs: 1, useTransactionHandler: false, useExecutionStrategy: false, rollbackOnFail: true); } [Fact] public void No_TransactionHandler_and_no_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 2, useTransactionHandler: false, useExecutionStrategy: false, rollbackOnFail: false); } [Fact] [UseDefaultExecutionStrategy] public void TransactionHandler_and_no_ExecutionStrategy_rethrows_original_exception_on_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<TimeoutException>(() => c()), c => { var exception = Assert.Throws<EntityException>(() => c()); Assert.IsType<TimeoutException>(exception.InnerException); }, expectedBlogs: 1, useTransactionHandler: true, useExecutionStrategy: false, rollbackOnFail: true); } [Fact] public void TransactionHandler_and_no_ExecutionStrategy_does_not_throw_on_false_commit_fail() { Execute_commit_failure_test( c => c(), c => c(), expectedBlogs: 2, useTransactionHandler: true, useExecutionStrategy: false, rollbackOnFail: false); } [Fact] public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 1, useTransactionHandler: false, useExecutionStrategy: true, rollbackOnFail: true); } [Fact] public void No_TransactionHandler_and_ExecutionStrategy_throws_CommitFailedException_on_false_commit_fail() { Execute_commit_failure_test( c => Assert.Throws<DataException>(() => c()).InnerException.ValidateMessage("CommitFailed"), c => Assert.Throws<CommitFailedException>(() => c()).ValidateMessage("CommitFailed"), expectedBlogs: 2, useTransactionHandler: false, useExecutionStrategy: true, rollbackOnFail: false); } [Fact] public void TransactionHandler_and_ExecutionStrategy_retries_on_commit_fail() { Execute_commit_failure_test( c => c(), c => c(), expectedBlogs: 2, useTransactionHandler: true, useExecutionStrategy: true, rollbackOnFail: true); } private void Execute_commit_failure_test( Action<Action> verifyInitialization, Action<Action> verifySaveChanges, int expectedBlogs, bool useTransactionHandler, bool useExecutionStrategy, bool rollbackOnFail) { var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true }; var failingTransactionInterceptor = failingTransactionInterceptorMock.Object; DbInterception.Add(failingTransactionInterceptor); if (useTransactionHandler) { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); } var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString); if (useExecutionStrategy) { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>) (() => isSqlAzure ? new TestSqlAzureExecutionStrategy() : (IDbExecutionStrategy) new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1)))); } try { using (var context = new BlogContextCommit()) { context.Database.Delete(); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = rollbackOnFail; verifyInitialization(() => context.Blogs.Count()); failingTransactionInterceptor.ShouldFailTimes = 0; Assert.Equal(1, context.Blogs.Count()); failingTransactionInterceptor.ShouldFailTimes = 1; context.Blogs.Add(new BlogContext.Blog()); verifySaveChanges(() => context.SaveChanges()); var expectedCommitCount = useTransactionHandler ? useExecutionStrategy ? 6 : rollbackOnFail ? 4 : 3 : 4; failingTransactionInterceptorMock.Verify( m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()), isSqlAzure ? Times.AtLeast(expectedCommitCount) : Times.Exactly(expectedCommitCount)); } using (var context = new BlogContextCommit()) { Assert.Equal(expectedBlogs, context.Blogs.Count()); using (var transactionContext = new TransactionContext(context.Database.Connection)) { using (var infoContext = GetInfoContext(transactionContext)) { Assert.True( !infoContext.TableExists("__Transactions") || !transactionContext.Transactions.Any()); } } } } finally { DbInterception.Remove(failingTransactionInterceptor); MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( context => context.SaveChanges()); } #if !NET40 [Fact] public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_async() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( context => context.SaveChangesAsync().Wait()); } #endif [Fact] public void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_with_custom_TransactionContext() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(c => new MyTransactionContext(c)), null, null)); TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( context => { context.SaveChanges(); using (var infoContext = GetInfoContext(context)) { Assert.True(infoContext.TableExists("MyTransactions")); var column = infoContext.Columns.Single(c => c.Name == "Time"); Assert.Equal("datetime2", column.Type); } }); } public class MyTransactionContext : TransactionContext { public MyTransactionContext(DbConnection connection) : base(connection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TransactionRow>() .ToTable("MyTransactions") .HasKey(e => e.Id) .Property(e => e.CreationTime).HasColumnName("Time").HasColumnType("datetime2"); } } private void TransactionHandler_and_ExecutionStrategy_does_not_retry_on_false_commit_fail_implementation( Action<BlogContextCommit> runAndVerify) { var failingTransactionInterceptorMock = new Mock<FailingTransactionInterceptor> { CallBase = true }; var failingTransactionInterceptor = failingTransactionInterceptorMock.Object; DbInterception.Add(failingTransactionInterceptor); var isSqlAzure = DatabaseTestHelpers.IsSqlAzure(ModelHelpers.BaseConnectionString); MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>) (() => isSqlAzure ? new TestSqlAzureExecutionStrategy() : (IDbExecutionStrategy)new SqlAzureExecutionStrategy(maxRetryCount: 2, maxDelay: TimeSpan.FromMilliseconds(1)))); try { using (var context = new BlogContextCommit()) { failingTransactionInterceptor.ShouldFailTimes = 0; context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); failingTransactionInterceptor.ShouldFailTimes = 2; failingTransactionInterceptor.ShouldRollBack = false; context.Blogs.Add(new BlogContext.Blog()); runAndVerify(context); failingTransactionInterceptorMock.Verify( m => m.Committing(It.IsAny<DbTransaction>(), It.IsAny<DbTransactionInterceptionContext>()), isSqlAzure ? Times.AtLeast(3) : Times.Exactly(3)); } using (var context = new BlogContextCommit()) { Assert.Equal(2, context.Blogs.Count()); using (var transactionContext = new TransactionContext(context.Database.Connection)) { using (var infoContext = GetInfoContext(transactionContext)) { Assert.True( !infoContext.TableExists("__Transactions") || !transactionContext.Transactions.Any()); } } } } finally { DbInterception.Remove(failingTransactionInterceptorMock.Object); MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void CommitFailureHandler_Dispose_does_not_use_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { c.TransactionHandler.Dispose(); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3)); }); } [Fact] public void CommitFailureHandler_Dispose_catches_exceptions() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { using (var transactionContext = new TransactionContext(((EntityConnection)c.Connection).StoreConnection)) { foreach (var tran in transactionContext.Set<TransactionRow>().ToList()) { transactionContext.Transactions.Remove(tran); } transactionContext.SaveChanges(); } c.TransactionHandler.Dispose(); }); } [Fact] public void CommitFailureHandler_prunes_transactions_after_set_amount() { CommitFailureHandler_prunes_transactions_after_set_amount_implementation(false); } [Fact] public void CommitFailureHandler_prunes_transactions_after_set_amount_and_handles_false_failure() { CommitFailureHandler_prunes_transactions_after_set_amount_implementation(true); } private void CommitFailureHandler_prunes_transactions_after_set_amount_implementation(bool shouldThrow) { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); var objectContext = ((IObjectContextAdapter)context).ObjectContext; var transactionHandler = (MyCommitFailureHandler)objectContext.TransactionHandler; for (var i = 0; i < transactionHandler.PruningLimit; i++) { context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); } AssertTransactionHistoryCount(context, transactionHandler.PruningLimit); if (shouldThrow) { failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = false; } context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); AssertTransactionHistoryCount(context, 1); Assert.Equal(1, transactionHandler.TransactionContext.ChangeTracker.Entries<TransactionRow>().Count()); } } finally { DbInterception.Remove(failingTransactionInterceptor); MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void CommitFailureHandler_ClearTransactionHistory_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory(); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4)); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_ClearTransactionHistory_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory()); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistory(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } [Fact] public void CommitFailureHandler_PruneTransactionHistory_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory(); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(4)); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_PruneTransactionHistory_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory()); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistory(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } #if !NET40 [Fact] public void CommitFailureHandler_ClearTransactionHistoryAsync_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait(); executionStrategyMock.Verify( e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once()); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_ClearTransactionHistoryAsync_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait())); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).ClearTransactionHistoryAsync().Wait(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } [Fact] public void CommitFailureHandler_PruneTransactionHistoryAsync_uses_ExecutionStrategy() { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait(); executionStrategyMock.Verify( e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Once()); Assert.Empty(((MyCommitFailureHandler)c.TransactionHandler).TransactionContext.ChangeTracker.Entries<TransactionRow>()); }); } [Fact] public void CommitFailureHandler_PruneTransactionHistoryAsync_does_not_catch_exceptions() { var failingTransactionInterceptor = new FailingTransactionInterceptor(); DbInterception.Add(failingTransactionInterceptor); try { CommitFailureHandler_with_ExecutionStrategy_test( (c, executionStrategyMock) => { MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new SimpleExecutionStrategy())); failingTransactionInterceptor.ShouldFailTimes = 1; failingTransactionInterceptor.ShouldRollBack = true; Assert.Throws<EntityException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait())); MutableResolver.ClearResolvers(); AssertTransactionHistoryCount(c, 1); ((MyCommitFailureHandler)c.TransactionHandler).PruneTransactionHistoryAsync().Wait(); AssertTransactionHistoryCount(c, 0); }); } finally { DbInterception.Remove(failingTransactionInterceptor); } } #endif private void CommitFailureHandler_with_ExecutionStrategy_test( Action<ObjectContext, Mock<TestSqlAzureExecutionStrategy>> pruneAndVerify) { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new MyCommitFailureHandler(c => new TransactionContext(c)), null, null)); var executionStrategyMock = new Mock<TestSqlAzureExecutionStrategy> { CallBase = true }; MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => executionStrategyMock.Object)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); context.Blogs.Add(new BlogContext.Blog()); context.SaveChanges(); AssertTransactionHistoryCount(context, 1); executionStrategyMock.Verify(e => e.Execute(It.IsAny<Func<int>>()), Times.Exactly(3)); #if !NET40 executionStrategyMock.Verify( e => e.ExecuteAsync(It.IsAny<Func<Task<int>>>(), It.IsAny<CancellationToken>()), Times.Never()); #endif var objectContext = ((IObjectContextAdapter)context).ObjectContext; pruneAndVerify(objectContext, executionStrategyMock); using (var transactionContext = new TransactionContext(context.Database.Connection)) { Assert.Equal(0, transactionContext.Transactions.Count()); } } } finally { MutableResolver.ClearResolvers(); } } private void AssertTransactionHistoryCount(DbContext context, int count) { AssertTransactionHistoryCount(((IObjectContextAdapter)context).ObjectContext, count); } private void AssertTransactionHistoryCount(ObjectContext context, int count) { using (var transactionContext = new TransactionContext(((EntityConnection)context.Connection).StoreConnection)) { Assert.Equal(count, transactionContext.Transactions.Count()); } } public class SimpleExecutionStrategy : IDbExecutionStrategy { public bool RetriesOnFailure { get { return false; } } public virtual void Execute(Action operation) { operation(); } public virtual TResult Execute<TResult>(Func<TResult> operation) { return operation(); } #if !NET40 public virtual Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken) { return operation(); } public virtual Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken) { return operation(); } #endif } public class MyCommitFailureHandler : CommitFailureHandler { public MyCommitFailureHandler(Func<DbConnection, TransactionContext> transactionContextFactory) : base(transactionContextFactory) { } public new void MarkTransactionForPruning(TransactionRow transaction) { base.MarkTransactionForPruning(transaction); } public new TransactionContext TransactionContext { get { return base.TransactionContext; } } public new virtual int PruningLimit { get { return base.PruningLimit; } } } [Fact] [UseDefaultExecutionStrategy] public void CommitFailureHandler_supports_nested_transactions() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); context.Blogs.Add(new BlogContext.Blog()); using (var transaction = context.Database.BeginTransaction()) { using (var innerContext = new BlogContextCommit()) { using (var innerTransaction = innerContext.Database.BeginTransaction()) { Assert.Equal(1, innerContext.Blogs.Count()); innerContext.Blogs.Add(new BlogContext.Blog()); innerContext.SaveChanges(); innerTransaction.Commit(); } } context.SaveChanges(); transaction.Commit(); } } using (var context = new BlogContextCommit()) { Assert.Equal(3, context.Blogs.Count()); } } finally { MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); MutableResolver.AddResolver<Func<IDbExecutionStrategy>>( key => (Func<IDbExecutionStrategy>)(() => new TestSqlAzureExecutionStrategy())); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); } MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(c => new TransactionContextNoInit(c)), null, null)); using (var context = new BlogContextCommit()) { context.Blogs.Add(new BlogContext.Blog()); Assert.Throws<EntityException>(() => context.SaveChanges()); context.Database.ExecuteSqlCommand( TransactionalBehavior.DoNotEnsureTransaction, ((IObjectContextAdapter)context).ObjectContext.TransactionHandler.BuildDatabaseInitializationScript()); context.SaveChanges(); } using (var context = new BlogContextCommit()) { Assert.Equal(2, context.Blogs.Count()); } } finally { MutableResolver.ClearResolvers(); } DbDispatchersHelpers.AssertNoInterceptors(); } [Fact] public void BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database_if_no_migration_generator() { var mockDbProviderServiceResolver = new Mock<IDbDependencyResolver>(); mockDbProviderServiceResolver .Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>())) .Returns(SqlProviderServices.Instance); MutableResolver.AddResolver<DbProviderServices>(mockDbProviderServiceResolver.Object); var mockDbProviderFactoryResolver = new Mock<IDbDependencyResolver>(); mockDbProviderFactoryResolver .Setup(r => r.GetService(It.IsAny<Type>(), It.IsAny<string>())) .Returns(SqlClientFactory.Instance); MutableResolver.AddResolver<DbProviderFactory>(mockDbProviderFactoryResolver.Object); BuildDatabaseInitializationScript_can_be_used_to_initialize_the_database(); } [Fact] public void FromContext_returns_the_current_handler() { MutableResolver.AddResolver<Func<TransactionHandler>>( new TransactionHandlerResolver(() => new CommitFailureHandler(), null, null)); try { using (var context = new BlogContextCommit()) { context.Database.Delete(); var commitFailureHandler = CommitFailureHandler.FromContext(((IObjectContextAdapter)context).ObjectContext); Assert.IsType<CommitFailureHandler>(commitFailureHandler); Assert.Same(commitFailureHandler, CommitFailureHandler.FromContext(context)); } } finally { MutableResolver.ClearResolvers(); } } [Fact] public void TransactionHandler_is_disposed_even_if_the_context_is_not() { var context = new BlogContextCommit(); context.Database.Delete(); Assert.Equal(1, context.Blogs.Count()); var weakDbContext = new WeakReference(context); var weakObjectContext = new WeakReference(((IObjectContextAdapter)context).ObjectContext); var weakTransactionHandler = new WeakReference(((IObjectContextAdapter)context).ObjectContext.TransactionHandler); context = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(weakDbContext.IsAlive); Assert.False(weakObjectContext.IsAlive); DbDispatchersHelpers.AssertNoInterceptors(); // Need a second pass as the TransactionHandler is removed from the interceptors in the ObjectContext finalizer GC.Collect(); Assert.False(weakTransactionHandler.IsAlive); } public class TransactionContextNoInit : TransactionContext { static TransactionContextNoInit() { Database.SetInitializer<TransactionContextNoInit>(null); } public TransactionContextNoInit(DbConnection connection) : base(connection) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<TransactionRow>() .ToTable("TransactionContextNoInit"); } } public class FailingTransactionInterceptor : IDbTransactionInterceptor { private int _timesToFail; private int _shouldFailTimes; public int ShouldFailTimes { get { return _shouldFailTimes; } set { _shouldFailTimes = value; _timesToFail = value; } } public bool ShouldRollBack; public FailingTransactionInterceptor() { _timesToFail = ShouldFailTimes; } public void ConnectionGetting(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext) { } public void ConnectionGot(DbTransaction transaction, DbTransactionInterceptionContext<DbConnection> interceptionContext) { } public void IsolationLevelGetting( DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext) { } public void IsolationLevelGot(DbTransaction transaction, DbTransactionInterceptionContext<IsolationLevel> interceptionContext) { } public virtual void Committing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { if (_timesToFail-- > 0) { if (ShouldRollBack) { transaction.Rollback(); } else { transaction.Commit(); } interceptionContext.Exception = new TimeoutException(); } else { _timesToFail = ShouldFailTimes; } } public void Committed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { if (interceptionContext.Exception != null) { _timesToFail--; } } public void Disposing(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } public void Disposed(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } public void RollingBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } public void RolledBack(DbTransaction transaction, DbTransactionInterceptionContext interceptionContext) { } } public class BlogContextCommit : BlogContext { static BlogContextCommit() { Database.SetInitializer<BlogContextCommit>(new BlogInitializer()); } } } }
/* * Author Luke Campbell <LCampbell@ASAScience.com> * netcdf3.test.TestNcGroup */ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using ASA.NetCDF4; namespace ASA.NetCDF4.Test { class TestNcGroup : UnitTest { protected const string filePath = "nc_clobber.nc"; public TestNcGroup() { AddTest(TestGetName, "TestGetName"); AddTest(TestGetParentGroup, "TestGetParentGroup"); AddTest(TestGetGroupCount, "TestGetGroupCount"); AddTest(TestGetGroups, "TestGetGroups"); AddTest(TestVlen, "TestVlen"); AddTest(TestOpaque, "TestOpaque"); AddTest(TestEnum, "TestEnum"); AddTest(TestGetCoordVars, "TestGetCoordVars"); AddTest(TestNestedGroups, "TestNestedGroups"); AddTest(TestDimGeneric, "TestDimGeneric"); AddTest(TestVarGeneric, "TestVarGeneric"); AddTest(TestGroupDefine, "TestGroupDefine"); } public NcFile newFile(string filePath) { return TestHelper.NewFile(filePath); } public bool TestGetName() { string groupName; int id; CheckDelete(filePath); NcFile file=null; NcGroup group; try { file = newFile(filePath); id = file.GetId(); Assert.NotEquals(id,0); group = file; groupName = group.GetName(); Assert.Equals(groupName, "/"); Assert.True(group.IsRootGroup()); } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestGetParentGroup() { NcGroup group; NcGroup grpTest; NcFile file=null; group = new NcGroup(); try { grpTest = group.GetParentGroup(); Assert.True(grpTest.IsNull()); throw new AssertFailedException("NcNullGrp not thrown"); } catch (exceptions.NcNullGrp) { } try { file = newFile(filePath); group = file.GetParentGroup(); Assert.True(group.IsNull()); } finally { file.Close(); } return true; } public bool TestGetGroupCount() { NcGroup group; NcFile file=null; try { file = newFile(filePath); group = file; int groupCount; groupCount = group.GetGroupCount(GroupLocation.AllGrps); Assert.Equals(groupCount, 1); // Only the root group/file so no groups are defined NcGroup childGroup = group.AddGroup("child1"); Assert.False(childGroup.IsNull()); Assert.Equals(group.GetGroupCount(GroupLocation.AllGrps), 2); Dictionary<string, NcGroup> groups = group.GetGroups(GroupLocation.AllGrps); for(int i=0;i<groups.Count;i++) { KeyValuePair<string, NcGroup> k = groups.ElementAt(i); if(i==0) Assert.Equals(k.Key, "/"); else if(i==1) Assert.Equals(k.Key, "child1"); } } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestGetGroups() { NcGroup group; NcFile file=null; NcGroup child1_1; NcGroup child1_2; try { file = newFile(filePath); group = file; /* -- Check differentiability for GetGroup -- */ child1_1 = file.AddGroup("group1"); file.AddGroup("group2"); group = file.GetGroup("group1"); Assert.Equals(group.GetName(), "group1"); /* -- Check that sets work for GetGroups -- */ child1_2 = child1_1.AddGroup("group1"); // Second one named group1 HashSet<NcGroup> groups = file.GetGroups("group1"); foreach(NcGroup g in groups) { if(g.GetId() != child1_1.GetId() && g.GetId() != child1_2.GetId()) { throw new AssertFailedException("Incorrect group in set"); } } } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestVlen() { NcFile file = null; NcVlenType vlen = null; NcDim dim = null; NcVar var = null; string stringVlenBuffer = "hi there"; string stringReadBuffer; int iLen=0; sbyte[] sbyteVlenBuffer = new sbyte[] { 0, -12, -4 }; sbyte[] sbyteReadBuffer = new sbyte[8]; byte[] byteVlenBuffer = new byte[] { 0, 12, 4 }; byte[] byteReadBuffer = new byte[8]; Int16[] Int16VlenBuffer = new Int16[] { 0, -12, -4 }; Int16[] Int16ReadBuffer = new Int16[8]; UInt16[] UInt16VlenBuffer = new UInt16[] { 0, 12, 4 }; UInt16[] UInt16ReadBuffer = new UInt16[8]; Int32[] Int32VlenBuffer = new Int32[] { 0, -12, -4 }; Int32[] Int32ReadBuffer = new Int32[8]; UInt32[] UInt32VlenBuffer = new UInt32[] { 0, 12, 4 }; UInt32[] UInt32ReadBuffer = new UInt32[8]; Int64[] Int64VlenBuffer = new Int64[] { 0, -12, -4 }; Int64[] Int64ReadBuffer = new Int64[8]; UInt64[] UInt64VlenBuffer = new UInt64[] { 0, 12, 4 }; UInt64[] UInt64ReadBuffer = new UInt64[8]; float[] floatVlenBuffer = new float[] { 0, 12, 4 }; float[] floatReadBuffer = new float[8]; double[] doubleVlenBuffer = new double[] { 0, 12, 4 }; double[] doubleReadBuffer = new double[8]; try { file = TestHelper.NewFile(filePath); dim = file.AddDim("time", 1); // string vlen = file.AddVlenType("vlenstring", NcChar.Instance); var = file.AddVar("string", vlen, dim); var.PutVar(new Int32[] { 0 }, stringVlenBuffer ); var.GetVar(new Int32[] { 0 }, out stringReadBuffer ); Assert.Equals(stringVlenBuffer, stringReadBuffer); // sbyte vlen = file.AddVlenType("vlensbyte", NcByte.Instance); var = file.AddVar("sbyte", vlen, dim); var.PutVar(new Int32[] { 0 }, sbyteVlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, sbyteReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(sbyteVlenBuffer[i], sbyteReadBuffer[i]); // byte vlen = file.AddVlenType("vlenbyte", NcByte.Instance); var = file.AddVar("byte", vlen, dim); var.PutVar(new Int32[] { 0 }, byteVlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, byteReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(byteVlenBuffer[i], byteReadBuffer[i]); // Int16 vlen = file.AddVlenType("vlenInt16", NcShort.Instance); var = file.AddVar("Int16", vlen, dim); var.PutVar(new Int32[] { 0 }, Int16VlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, Int16ReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(Int16VlenBuffer[i], Int16ReadBuffer[i]); // UInt16 vlen = file.AddVlenType("vlenUInt16", NcUshort.Instance); var = file.AddVar("UInt16", vlen, dim); var.PutVar(new Int32[] { 0 }, UInt16VlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, UInt16ReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(UInt16VlenBuffer[i], UInt16ReadBuffer[i]); // Int32 vlen = file.AddVlenType("vlenInt32", NcInt.Instance); var = file.AddVar("Int32", vlen, dim); var.PutVar(new Int32[] { 0 }, Int32VlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, Int32ReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(Int32VlenBuffer[i], Int32ReadBuffer[i]); // UInt32 vlen = file.AddVlenType("vlenUInt32", NcUint.Instance); var = file.AddVar("UInt32", vlen, dim); var.PutVar(new Int32[] { 0 }, UInt32VlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, UInt32ReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(UInt32VlenBuffer[i], UInt32ReadBuffer[i]); // Int64 vlen = file.AddVlenType("vlenInt64", NcInt64.Instance); var = file.AddVar("Int64", vlen, dim); var.PutVar(new Int32[] { 0 }, Int64VlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, Int64ReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(Int64VlenBuffer[i], Int64ReadBuffer[i]); // UInt64 vlen = file.AddVlenType("vlenUInt64", NcUint64.Instance); var = file.AddVar("UInt64", vlen, dim); var.PutVar(new Int32[] { 0 }, UInt64VlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, UInt64ReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(UInt64VlenBuffer[i], UInt64ReadBuffer[i]); // float vlen = file.AddVlenType("vlenfloat", NcFloat.Instance); var = file.AddVar("float", vlen, dim); var.PutVar(new Int32[] { 0 }, floatVlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, floatReadBuffer ); for(int i=0; i<iLen; i++) Assert.Equals(floatVlenBuffer[i], floatReadBuffer[i]); // double vlen = file.AddVlenType("vlendouble", NcDouble.Instance); var = file.AddVar("double", vlen, dim); var.PutVar(new Int32[] { 0 }, doubleVlenBuffer ); iLen=var.GetVar(new Int32[] { 0 }, doubleReadBuffer ); for(int i=0;i<iLen;i++) Assert.Equals(doubleVlenBuffer[i], doubleReadBuffer[i]); } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestOpaque() { NcFile file = null; NcVar var = null; NcDim dim = null; NcType type = null; NcOpaqueType opaqueType = null; byte[] opaqueBuffer = new byte[32]; byte[] readBuffer = new byte[32]; for(int i=0;i<32;i++) opaqueBuffer[i] = (byte)i; try { file = TestHelper.NewFile(filePath); type = file.AddOpaqueType("opaque", 32); opaqueType = new NcOpaqueType(type); Assert.Equals(type.GetTypeClass(), NcTypeEnum.NC_OPAQUE); Assert.Equals(opaqueType.GetTypeSize(), 32); dim = file.AddDim("time", 1); var = file.AddVar("opaqueVar", opaqueType, dim); int iLen = 0; var.PutVar(new Int32[] { 0 }, opaqueBuffer); iLen = var.GetVar(new Int32[] { 0 }, readBuffer); Assert.Equals(iLen, 32); for(int i=0;i<32;i++) Assert.Equals(readBuffer[i], opaqueBuffer[i]); } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestEnum() { NcFile file = null; NcType type = null; NcEnumType enumType = null; NcDim dim = null; NcVar var = null; sbyte[] sbyteBuffer = new sbyte[1]; byte[] byteBuffer = new byte[1]; Int16[] Int16Buffer = new Int16[1]; UInt16[] UInt16Buffer = new UInt16[1]; Int32[] Int32Buffer = new Int32[1]; UInt32[] UInt32Buffer = new UInt32[1]; Int64[] Int64Buffer = new Int64[1]; UInt64[] UInt64Buffer = new UInt64[1]; try { file = TestHelper.NewFile(filePath); dim = file.AddDim("time", 1); type = file.AddEnumType("sbyteenum", NcEnumType.Types.NC_BYTE); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "sbyteenum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcByte.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumsbyteVar", enumType, dim); var.PutVar(new sbyte[] { 3 }); var.GetVar(sbyteBuffer); Assert.Equals(sbyteBuffer[0], (sbyte)3); type = file.AddEnumType("byteenum", NcEnumType.Types.NC_UBYTE); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "byteenum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcUbyte.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumbyteVar", enumType, dim); var.PutVar(new byte[] { 3 }); var.GetVar(byteBuffer); Assert.Equals(byteBuffer[0], (byte)3); type = file.AddEnumType("Int16enum", NcEnumType.Types.NC_SHORT); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "Int16enum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcShort.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumInt16Var", enumType, dim); var.PutVar(new Int16[] { 3 }); var.GetVar(Int16Buffer); Assert.Equals(Int16Buffer[0], (Int16)3); type = file.AddEnumType("UInt16enum", NcEnumType.Types.NC_USHORT); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "UInt16enum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcUshort.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumUInt16Var", enumType, dim); var.PutVar(new UInt16[] { 3 }); var.GetVar(UInt16Buffer); Assert.Equals(UInt16Buffer[0], (UInt16)3); type = file.AddEnumType("Int32enum", NcEnumType.Types.NC_INT); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "Int32enum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcInt.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumInt32Var", enumType, dim); var.PutVar(new Int32[] { 3 }); var.GetVar(Int32Buffer); Assert.Equals(Int32Buffer[0], (Int32)3); type = file.AddEnumType("UInt32enum", NcEnumType.Types.NC_UINT); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "UInt32enum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcUint.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumUInt32Var", enumType, dim); var.PutVar(new UInt32[] { 3 }); var.GetVar(UInt32Buffer); Assert.Equals(UInt32Buffer[0], (UInt32)3); type = file.AddEnumType("Int64enum", NcEnumType.Types.NC_INT64); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "Int64enum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcInt64.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", (Int64)0); enumType.AddMember("VOR", (Int64)1); enumType.AddMember("DME", (Int64)2); enumType.AddMember("TAC", (Int64)3); Assert.Equals(enumType.GetMemberCount(), 4); Assert.Equals(enumType.GetMemberNameFromValue( (sbyte) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (byte) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (Int16) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (UInt16) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (Int32) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (UInt32) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (Int64) 1), "VOR"); Assert.Equals(enumType.GetMemberNameFromValue( (UInt64) 1), "VOR"); var = file.AddVar("enumInt64Var", enumType, dim); var.PutVar(new Int64[] { 3 }); var.GetVar(Int64Buffer); Assert.Equals(Int64Buffer[0], (Int64)3); type = file.AddEnumType("UInt64enum", NcEnumType.Types.NC_UINT64); enumType = new NcEnumType(type); Assert.Equals(enumType.GetName(), "UInt64enum"); Assert.Equals(enumType.GetMemberCount(), 0); Assert.True(NcUint64.Instance.Equals(enumType.GetBaseType())); enumType.AddMember("BASE", 0); enumType.AddMember("VOR", 1); enumType.AddMember("DME", 2); enumType.AddMember("TAC", 3); var = file.AddVar("enumUInt64Var", enumType, dim); var.PutVar(new UInt64[] { 3 }); var.GetVar(UInt64Buffer); Assert.Equals(UInt64Buffer[0], (UInt64)3); } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestGetCoordVars() { NcFile file = null; try { file = TestHelper.NewFile(filePath); NcDim dim1 = file.AddDim("time", 20); NcDim dim2 = file.AddDim("hdg", 20); NcVar var1 = file.AddVar("time", NcDouble.Instance, dim1); Assert.False(var1.IsNull()); NcVar var2 = file.AddVar("hdg", NcDouble.Instance, dim2); Assert.False(var2.IsNull()); NcVar var3 = file.AddVar("alt", NcDouble.Instance, new List<NcDim>() { dim1, dim2 }); Assert.False(var3.IsNull()); Dictionary<string, NcGroup> coordVars = file.GetCoordVars(); Assert.True(coordVars.ContainsKey("time") && coordVars["time"].GetId() == file.GetId()); Assert.True(coordVars.ContainsKey("hdg") && coordVars["hdg"].GetId() == file.GetId()); Assert.False(coordVars.ContainsKey("alt")); } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestNestedGroups() { NcFile file = null; NcDim dim; Dictionary<string, NcGroup> groups; try { file = TestHelper.NewFile(filePath); NcGroup a = file.AddGroup("a"); Assert.False(a.IsNull()); NcGroup b = file.AddGroup("b"); Assert.False(b.IsNull()); NcGroup a1 = a.AddGroup("a1"); Assert.False(a1.IsNull()); NcGroup a2 = a.AddGroup("a2"); Assert.False(a2.IsNull()); NcGroup b1 = b.AddGroup("b1"); Assert.False(b1.IsNull()); NcGroup b2 = b.AddGroup("b2"); Assert.False(b2.IsNull()); Assert.Equals(file.GetGroupCount(GroupLocation.AllGrps), 7); Assert.Equals(file.GetGroupCount(GroupLocation.AllChildrenGrps), 6); Assert.Equals(b2.GetGroupCount(GroupLocation.ParentsGrps), 2); Assert.Equals(a2.GetGroupCount(GroupLocation.ParentsGrps), 2); Assert.True(file.GetGroups(GroupLocation.AllChildrenGrps).ContainsKey("b1")); groups = a1.GetGroups(GroupLocation.ParentsGrps); Assert.True(groups.ContainsKey("/") && groups["/"].GetId() == file.GetId()); Assert.Equals(file.GetGroups("b1", GroupLocation.AllChildrenGrps).Count , 1); Assert.True(file.GetGroup("a2", GroupLocation.ChildrenGrps).IsNull()); Assert.Equals(file.GetGroup("a2", GroupLocation.AllChildrenGrps).GetId(), a2.GetId()); Assert.True(file.IsRootGroup()); Assert.False(a.IsRootGroup()); foreach(KeyValuePair<string, NcGroup> group in file.GetGroups(GroupLocation.AllGrps)) { dim = group.Value.AddDim("time" + (group.Value.IsRootGroup() ? "Root" : group.Key), 20); NcVar v = group.Value.AddVar("time" + (group.Value.IsRootGroup() ? "Root" : group.Key), NcUint64.Instance, dim); NcAtt att = group.Value.PutAtt("Attr" + (group.Value.IsRootGroup() ? "Root" : group.Key), "Value"); Assert.False(v.IsNull()); Assert.Equals(file.GetVar(v.GetName(), Location.All).GetId(), v.GetId()); } Assert.Equals(file.GetVarCount(Location.All), 7); Assert.Equals(file.GetVars(Location.All).Count, 7); foreach(KeyValuePair<string, NcVar> gvar in file.GetVars(Location.All)) { Assert.Equals(gvar.Key, gvar.Value.GetName()); NcGroup g = gvar.Value.GetParentGroup(); Assert.Equals(gvar.Key, "time" + (g.IsRootGroup() ? "Root" : g.GetName())); } Assert.Equals(file.GetVars("timeRoot", Location.All).Count, 1); Assert.Equals(file.GetAttCount(Location.All), 7); Assert.Equals(file.GetAtts(Location.All).Count, 7); foreach(KeyValuePair<string, NcGroupAtt> k in file.GetAtts(Location.All)) { Assert.Equals(k.Value.GetValues(), "Value"); } } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestDimGeneric() { NcFile file1 = null; NcFile file2 = null; try { file1 = TestHelper.NewFile(filePath); file2 = TestHelper.NewFile("other" + filePath); NcDim dim1 = file1.AddDim("time"); //Unlimited NcDim dim2 = file2.AddDim(dim1); Assert.True(dim2.IsUnlimited()); Assert.Equals(dim1.GetName(), dim2.GetName()); } finally { file1.Close(); file2.Close(); } CheckDelete(filePath); CheckDelete("other" + filePath); return true; } public bool TestVarGeneric() { NcFile file = null; try { file = TestHelper.NewFile(filePath); NcDim dim1 = file.AddDim("dim1", 5); NcVar testVar = file.AddVar("var1", "double", "dim1"); Assert.False(testVar.IsNull()); testVar = file.AddVar("var2", NcDouble.Instance, dim1); Assert.False(testVar.IsNull()); testVar = file.AddVar("var3", "double", new List<string>() { "dim1" }); Assert.False(testVar.IsNull()); testVar = file.AddVar("var4", NcDouble.Instance, new List<NcDim>() { dim1 }); Assert.False(testVar.IsNull()); } finally { file.Close(); } CheckDelete(filePath); return true; } public bool TestGroupDefine() { NcFile file = null; NcDim dim; NcVar var; try { file = new NcFile(filePath, NcFileMode.replace, NcFileFormat.classic); file.CheckData(); dim = file.AddDim("dim1", 1); file.CheckData(); var = file.AddVar("var1", NcInt.Instance, dim); file.CheckData(); var.PutAtt("blah","blah"); file.CheckDefine(); NcArray array = NcArray.Arange(NcInt.Instance, 1); var.PutVar(array); } finally { file.Close(); } CheckDelete(filePath); return true; } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gciv = Google.Cloud.Iam.V1; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.ResourceManager.V3.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedTagValuesClientTest { [xunit::FactAttribute] public void GetTagValueRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue response = client.GetTagValue(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagValueRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagValue>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue responseCallSettings = await client.GetTagValueAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagValue responseCancellationToken = await client.GetTagValueAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTagValue() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue response = client.GetTagValue(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagValueAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagValue>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue responseCallSettings = await client.GetTagValueAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagValue responseCancellationToken = await client.GetTagValueAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTagValueResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValue(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue response = client.GetTagValue(request.TagValueName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTagValueResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTagValueRequest request = new GetTagValueRequest { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), }; TagValue expectedResponse = new TagValue { TagValueName = TagValueName.FromTagValue("[TAG_VALUE]"), Parent = "parent7858e4d0", ShortName = "short_namec7ba9846", NamespacedName = "namespaced_namea4453147", Description = "description2cf9da67", CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetTagValueAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TagValue>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); TagValue responseCallSettings = await client.GetTagValueAsync(request.TagValueName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TagValue responseCancellationToken = await client.GetTagValueAsync(request.TagValueName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request.ResourceAsResourceName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request.ResourceAsResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request.ResourceAsResourceName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.Resource, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.Resource, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Resource, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request.ResourceAsResourceName, request.Policy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request.ResourceAsResourceName, request.Policy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.Resource, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Resource, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsResourceNames() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request.ResourceAsResourceName, request.Permissions); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsResourceNamesAsync() { moq::Mock<TagValues.TagValuesClient> mockGrpcClient = new moq::Mock<TagValues.TagValuesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); TagValuesClient client = new TagValuesClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.ResourceAsResourceName, request.Permissions, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Sync.V1.Service.SyncMap { /// <summary> /// Fetch a specific Sync Map Permission. /// </summary> public class FetchSyncMapPermissionOptions : IOptions<SyncMapPermissionResource> { /// <summary> /// The SID of the Sync Service with the Sync Map Permission resource to fetch /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Map with the Sync Map Permission resource to fetch /// </summary> public string PathMapSid { get; } /// <summary> /// The application-defined string that uniquely identifies the User's Sync Map Permission resource to fetch /// </summary> public string PathIdentity { get; } /// <summary> /// Construct a new FetchSyncMapPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Permission resource to fetch </param> /// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Permission resource to fetch </param> /// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync Map Permission /// resource to fetch </param> public FetchSyncMapPermissionOptions(string pathServiceSid, string pathMapSid, string pathIdentity) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; PathIdentity = pathIdentity; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Delete a specific Sync Map Permission. /// </summary> public class DeleteSyncMapPermissionOptions : IOptions<SyncMapPermissionResource> { /// <summary> /// The SID of the Sync Service with the Sync Map Permission resource to delete /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Map with the Sync Map Permission resource to delete /// </summary> public string PathMapSid { get; } /// <summary> /// The application-defined string that uniquely identifies the User's Sync Map Permission resource to delete /// </summary> public string PathIdentity { get; } /// <summary> /// Construct a new DeleteSyncMapPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Permission resource to delete </param> /// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Permission resource to delete </param> /// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync Map Permission /// resource to delete </param> public DeleteSyncMapPermissionOptions(string pathServiceSid, string pathMapSid, string pathIdentity) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; PathIdentity = pathIdentity; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// Retrieve a list of all Permissions applying to a Sync Map. /// </summary> public class ReadSyncMapPermissionOptions : ReadOptions<SyncMapPermissionResource> { /// <summary> /// The SID of the Sync Service with the Sync Map Permission resources to read /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Map with the Permission resources to read /// </summary> public string PathMapSid { get; } /// <summary> /// Construct a new ReadSyncMapPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Permission resources to read </param> /// <param name="pathMapSid"> The SID of the Sync Map with the Permission resources to read </param> public ReadSyncMapPermissionOptions(string pathServiceSid, string pathMapSid) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// Update an identity's access to a specific Sync Map. /// </summary> public class UpdateSyncMapPermissionOptions : IOptions<SyncMapPermissionResource> { /// <summary> /// The SID of the Sync Service with the Sync Map Permission resource to update /// </summary> public string PathServiceSid { get; } /// <summary> /// The SID of the Sync Map with the Sync Map Permission resource to update /// </summary> public string PathMapSid { get; } /// <summary> /// The application-defined string that uniquely identifies the User's Sync Map Permission resource to update /// </summary> public string PathIdentity { get; } /// <summary> /// Read access /// </summary> public bool? Read { get; } /// <summary> /// Write access /// </summary> public bool? Write { get; } /// <summary> /// Manage access /// </summary> public bool? Manage { get; } /// <summary> /// Construct a new UpdateSyncMapPermissionOptions /// </summary> /// <param name="pathServiceSid"> The SID of the Sync Service with the Sync Map Permission resource to update </param> /// <param name="pathMapSid"> The SID of the Sync Map with the Sync Map Permission resource to update </param> /// <param name="pathIdentity"> The application-defined string that uniquely identifies the User's Sync Map Permission /// resource to update </param> /// <param name="read"> Read access </param> /// <param name="write"> Write access </param> /// <param name="manage"> Manage access </param> public UpdateSyncMapPermissionOptions(string pathServiceSid, string pathMapSid, string pathIdentity, bool? read, bool? write, bool? manage) { PathServiceSid = pathServiceSid; PathMapSid = pathMapSid; PathIdentity = pathIdentity; Read = read; Write = write; Manage = manage; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Read != null) { p.Add(new KeyValuePair<string, string>("Read", Read.Value.ToString().ToLower())); } if (Write != null) { p.Add(new KeyValuePair<string, string>("Write", Write.Value.ToString().ToLower())); } if (Manage != null) { p.Add(new KeyValuePair<string, string>("Manage", Manage.Value.ToString().ToLower())); } return p; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace ConsoleApplication1 { public abstract class DuckBase { private static readonly ModuleBuilder Mb = SetupEmit(); private static AssemblyBuilder ab; protected internal static ModuleBuilder SetupEmit() { var aName = new AssemblyName("DuckType"); ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); return ab.DefineDynamicModule(aName.Name); } protected internal static TypeBuilder GetTypeBuilder<T, TInterface>() { return Mb.DefineType( "Duck_" + typeof (TInterface).Name + "_" + typeof (T).Name, TypeAttributes.Public, typeof (object), new[] {typeof (TInterface)}); } protected internal static Type MakeDuck<T, TInterface>() { var tb = GetTypeBuilder<T, TInterface>(); var underlyingObject = DefineUnderlyingObjectField<T>(tb); DefineConstructor<T>(tb, underlyingObject); DefineInterfaceProperties<T, TInterface>(tb, underlyingObject); DefineInterfaceMethods<T, TInterface>(tb, underlyingObject); var t = tb.CreateType(); //ab.Save("Test2.dll"); return t; } private static void DefineInterfaceMethods<T, TInterface>(TypeBuilder tb, FieldInfo underlyingObject) { var iType = typeof (TInterface); var tType = typeof (T); var tTypeMeths = tType.GetMethods(); foreach (var ip in iType.GetMethods()) { var tp = tTypeMeths.GetMethod(ip); if (tp == null) throw new ArgumentException( string.Format("Type [{0}] does not implement method [{1}] with parameters matching interface [{2}]", tType.Name, ip.Name, iType.Name)); // Define a method that passes the call along to the underlyingObject var mbM = tb.DefineMethod(ip.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Final);// public hidebysig newslot virtual final //var gp = mbM.DefineGenericParameters(""); //ip.GetGenericArguments() mbM.SetSignature(tp.ReturnType, null, null, ip.GetParameters().Select(p => p.ParameterType).ToArray(), null, null); var il = mbM.GetILGenerator(); if(tp.ReturnType != typeof(void)) il.DeclareLocal(tp.ReturnType); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, underlyingObject); var argnr = 1; for (var count = ip.GetParameters().Count(); count > 0; count--) { il.EmitLdArg(argnr++); } il.EmitCall(OpCodes.Callvirt, tp, null); if (tp.ReturnType != typeof (void)) { il.Emit(OpCodes.Stloc_0); var lab = il.DefineLabel(); il.Emit(OpCodes.Br_S, lab); il.MarkLabel(lab); il.Emit(OpCodes.Ldloc_0); } il.Emit(OpCodes.Ret); } } private static void DefineInterfaceProperties<T, TInterface>(TypeBuilder tb, FieldInfo underlyingObject) { var iType = typeof (TInterface); var tType = typeof (T); foreach (var ip in iType.GetProperties()) { var tp = tType.GetProperty(ip.Name, ip.PropertyType); if (tp == null) throw new ArgumentException( string.Format("Type [{0}] does not implement property [{1}] with type matching interface [{2}]", tType.Name, ip.Name, iType.Name)); var mprop = tb.DefineProperty(ip.Name, ip.Attributes, ip.PropertyType, null); if (tp.CanRead) { var rmeth = tb.DefineMethod(ip.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Final); rmeth.SetParameters(null); rmeth.SetReturnType(ip.PropertyType); var il = rmeth.GetILGenerator(); il.DeclareLocal(tp.PropertyType); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, underlyingObject); il.EmitCall(OpCodes.Callvirt, tp.GetGetMethod(), null); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloc_0); il.Emit(OpCodes.Ret); mprop.SetGetMethod(rmeth); } if (tp.CanWrite) { var rmeth = tb.DefineMethod(ip.Name, MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Final); rmeth.SetParameters(new []{ip.PropertyType}); rmeth.SetReturnType(typeof(void)); var il = rmeth.GetILGenerator(); il.DeclareLocal(tp.PropertyType); il.Emit(OpCodes.Nop); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, underlyingObject); il.Emit(OpCodes.Ldarg_1); il.EmitCall(OpCodes.Callvirt, tp.GetSetMethod(), null); il.Emit(OpCodes.Ret); mprop.SetSetMethod(rmeth); } } } private static void DefineConstructor<T>(TypeBuilder tb, FieldInfo underlyingObject) { var ctor1 = tb.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, new[] {typeof (T)}); var ctor1IL = ctor1.GetILGenerator(); // For a constructor, argument zero is a reference to the new // instance. Push it on the stack before calling the base // class constructor. Specify the default constructor of the // base class (System.Object) by passing an empty array of // types (Type.EmptyTypes) to GetConstructor. ctor1IL.Emit(OpCodes.Ldarg_0); ctor1IL.Emit(OpCodes.Call, // ReSharper disable once AssignNullToNotNullAttribute typeof(object).GetConstructor(Type.EmptyTypes)); // Push the instance on the stack before pushing the argument // that is to be assigned to the private field m_number. ctor1IL.Emit(OpCodes.Ldarg_0); ctor1IL.Emit(OpCodes.Ldarg_1); ctor1IL.Emit(OpCodes.Stfld, underlyingObject); ctor1IL.Emit(OpCodes.Ret); } private static FieldBuilder DefineUnderlyingObjectField<T>(TypeBuilder tb) { return tb.DefineField( "_underlyingObject", typeof (T), FieldAttributes.Private); } } public static class ILGeneratorExtensions { public static void EmitLdArg(this ILGenerator il, int argnr) { switch (argnr) { case 0: il.Emit(OpCodes.Ldarg_0); return; case 1: il.Emit(OpCodes.Ldarg_1); return; case 2: il.Emit(OpCodes.Ldarg_2); return; case 3: il.Emit(OpCodes.Ldarg_3); return; default: if (argnr < 256) il.Emit(OpCodes.Ldarg_S, (short)argnr); else il.Emit(OpCodes.Ldarg, argnr); return; } } public static MethodInfo GetMethod(this IEnumerable<MethodInfo> tTypeMeths, MethodInfo ip) { return tTypeMeths.FirstOrDefault(m => m.Name == ip.Name && m.ContainsGenericParameters == ip.ContainsGenericParameters && m.IsGenericMethod == ip.IsGenericMethod && m.IsGenericMethodDefinition == ip.IsGenericMethodDefinition && m.ReturnType == ip.ReturnType && m.GetParameters().All(p => ip.GetParameters().Any(f => f.Name == p.Name))); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Threading.Tasks; using System.Diagnostics; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. // public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. internal const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private const int DontCopyOnWriteLineThreshold = 512; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true); private Stream _stream; private Encoding _encoding; private Encoder _encoder; private byte[] _byteBuffer; private char[] _charBuffer; private int _charPos; private int _charLen; private bool _autoFlush; private bool _haveWrittenPreamble; private bool _closable; // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); } // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static volatile Encoding s_utf8NoBOM; internal static Encoding UTF8NoBOM { //[FriendAccessAllowed] get { if (s_utf8NoBOM == null) { // No need for double lock - we just want to avoid extra // allocations in the common case. s_utf8NoBOM = new UTF8Encoding(false, true); } return s_utf8NoBOM; } } internal StreamWriter() : base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) { throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding)); } if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } Init(stream, encoding, bufferSize, leaveOpen); } private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { _stream = streamArg; _encoding = encodingArg; _encoder = _encoding.GetEncoder(); if (bufferSize < MinBufferSize) { bufferSize = MinBufferSize; } _charBuffer = new char[bufferSize]; _byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)]; _charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (_stream.CanSeek && _stream.Position > 0) { _haveWrittenPreamble = true; } _closable = !shouldLeaveOpen; } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (_stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */) { CheckAsyncTaskInProgress(); Flush(true, true); } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && _stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) { _stream.Dispose(); } } finally { _stream = null; _byteBuffer = null; _charBuffer = null; _encoding = null; _encoder = null; _charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } // Perf boost for Flush on non-dirty writers. if (_charPos == 0 && !flushStream && !flushEncoder) { return; } if (!_haveWrittenPreamble) { _haveWrittenPreamble = true; byte[] preamble = _encoding.GetPreamble(); if (preamble.Length > 0) { _stream.Write(preamble, 0, preamble.Length); } } int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder); _charPos = 0; if (count > 0) { _stream.Write(_byteBuffer, 0, count); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { _stream.Flush(); } } public virtual bool AutoFlush { get { return _autoFlush; } set { CheckAsyncTaskInProgress(); _autoFlush = value; if (value) { Flush(true, false); } } } public virtual Stream BaseStream { get { return _stream; } } internal bool LeaveOpen { get { return !_closable; } } internal bool HaveWrittenPreamble { set { _haveWrittenPreamble = value; } } public override Encoding Encoding { get { return _encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = value; _charPos++; if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer) { // This may be faster than the one with the index & count since it // has to do less argument checking. if (buffer == null) { return; } CheckAsyncTaskInProgress(); int index = 0; int count = buffer.Length; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char)); _charPos += n; index += n; count -= n; } if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } CheckAsyncTaskInProgress(); while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), _charBuffer, _charPos * sizeof(char), n * sizeof(char)); _charPos += n; index += n; count -= n; } if (_autoFlush) { Flush(true, false); } } public override void Write(string value) { if (value != null) { CheckAsyncTaskInProgress(); int count = value.Length; int index = 0; while (count > 0) { if (_charPos == _charLen) { Flush(false, false); } int n = _charLen - _charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, _charBuffer, _charPos, n); _charPos += n; index += n; count -= n; } if (_autoFlush) { Flush(true, false); } } } #region Task based Async APIs public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(string value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (value != null) { if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, string value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char[] buffer, int index, int count, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(count == 0 || (count > 0 && buffer != null)); Debug.Assert(index >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer == null || (buffer != null && buffer.Length - index >= count)); while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.BlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, null, 0, 0, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(string value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.FlushAsync(); } // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos); _asyncWriteTask = task; return task; } private int CharPos_Prop { set { _charPos = value; } } private bool HaveWrittenPreamble_Prop { set { _haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, char[] sCharBuffer, int sCharPos) { // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) { return Task.CompletedTask; } Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble, _encoding, _encoder, _byteBuffer, _stream); _charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) { await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false); } } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) { await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { await stream.FlushAsync().ConfigureAwait(false); } } #endregion } // class StreamWriter } // namespace
// 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.Text; using System.Diagnostics; internal sealed class BitSet { private const int bitSlotShift = 5; private const int bitSlotMask = (1 << bitSlotShift) - 1; private int _count; private uint[] _bits; private BitSet() { } public BitSet(int count) { _count = count; _bits = new uint[Subscript(count + bitSlotMask)]; } public int Count { get { return _count; } } public bool this[int index] { get { return Get(index); } } public void Clear() { int bitsLength = _bits.Length; for (int i = bitsLength; i-- > 0;) { _bits[i] = 0; } } public void Clear(int index) { int nBitSlot = Subscript(index); EnsureLength(nBitSlot + 1); _bits[nBitSlot] &= ~((uint)1 << (index & bitSlotMask)); } public void Set(int index) { int nBitSlot = Subscript(index); EnsureLength(nBitSlot + 1); _bits[nBitSlot] |= (uint)1 << (index & bitSlotMask); } public bool Get(int index) { bool fResult = false; if (index < _count) { int nBitSlot = Subscript(index); fResult = ((_bits[nBitSlot] & (1 << (index & bitSlotMask))) != 0); } return fResult; } public int NextSet(int startFrom) { Debug.Assert(startFrom >= -1 && startFrom <= _count); int offset = startFrom + 1; if (offset == _count) { return -1; } int nBitSlot = Subscript(offset); offset &= bitSlotMask; uint word = _bits[nBitSlot] >> offset; // locate non-empty slot while (word == 0) { if ((++nBitSlot) == _bits.Length) { return -1; } offset = 0; word = _bits[nBitSlot]; } while ((word & (uint)1) == 0) { word >>= 1; offset++; } return (nBitSlot << bitSlotShift) + offset; } public void And(BitSet other) { /* * Need to synchronize both this and other-> * This might lead to deadlock if one thread grabs them in one order * while another thread grabs them the other order. * Use a trick from Doug Lea's book on concurrency, * somewhat complicated because BitSet overrides hashCode(). */ if (this == other) { return; } int bitsLength = _bits.Length; int setLength = other._bits.Length; int n = (bitsLength > setLength) ? setLength : bitsLength; for (int i = n; i-- > 0;) { _bits[i] &= other._bits[i]; } for (; n < bitsLength; n++) { _bits[n] = 0; } } public void Or(BitSet other) { if (this == other) { return; } int setLength = other._bits.Length; EnsureLength(setLength); for (int i = setLength; i-- > 0;) { _bits[i] |= other._bits[i]; } } public override int GetHashCode() { int h = 1234; for (int i = _bits.Length; --i >= 0;) { h ^= (int)_bits[i] * (i + 1); } return (int)((h >> 32) ^ h); } public override bool Equals(object obj) { // assume the same type if (obj != null) { if (this == obj) { return true; } BitSet other = (BitSet)obj; int bitsLength = _bits.Length; int setLength = other._bits.Length; int n = (bitsLength > setLength) ? setLength : bitsLength; for (int i = n; i-- > 0;) { if (_bits[i] != other._bits[i]) { return false; } } if (bitsLength > n) { for (int i = bitsLength; i-- > n;) { if (_bits[i] != 0) { return false; } } } else { for (int i = setLength; i-- > n;) { if (other._bits[i] != 0) { return false; } } } return true; } return false; } public BitSet Clone() { BitSet newset = new BitSet(); newset._count = _count; newset._bits = (uint[])_bits.Clone(); return newset; } public bool IsEmpty { get { uint k = 0; for (int i = 0; i < _bits.Length; i++) { k |= _bits[i]; } return k == 0; } } public bool Intersects(BitSet other) { int i = Math.Min(_bits.Length, other._bits.Length); while (--i >= 0) { if ((_bits[i] & other._bits[i]) != 0) { return true; } } return false; } private int Subscript(int bitIndex) { return bitIndex >> bitSlotShift; } private void EnsureLength(int nRequiredLength) { /* Doesn't need to be synchronized because it's an internal method. */ if (nRequiredLength > _bits.Length) { /* Ask for larger of doubled size or required size */ int request = 2 * _bits.Length; if (request < nRequiredLength) request = nRequiredLength; uint[] newBits = new uint[request]; Array.Copy(_bits, newBits, _bits.Length); _bits = newBits; } } #if DEBUG public void Dump(StringBuilder bb) { for (int i = 0; i < count; i ++) { bb.Append( Get(i) ? "1" : "0"); } } #endif }; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithLowerAndUpperSingle() { var test = new VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSingle(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithLowerAndUpper__GetAndWithLowerAndUpperSingle { private static readonly int LargestVectorSize = 16; private static readonly int ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); public bool Succeeded { get; set; } = true; public void RunBasicScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Single[] values = new Single[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSingle(); } Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]); Vector64<Single> lowerResult = value.GetLower(); Vector64<Single> upperResult = value.GetUpper(); ValidateGetResult(lowerResult, upperResult, values); Vector128<Single> result = value.WithLower(upperResult); result = result.WithUpper(lowerResult); ValidateWithResult(result, values); } public void RunReflectionScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Single[] values = new Single[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetSingle(); } Vector128<Single> value = Vector128.Create(values[0], values[1], values[2], values[3]); object lowerResult = typeof(Vector128) .GetMethod(nameof(Vector128.GetLower)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); object upperResult = typeof(Vector128) .GetMethod(nameof(Vector128.GetUpper)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value }); ValidateGetResult((Vector64<Single>)(lowerResult), (Vector64<Single>)(upperResult), values); object result = typeof(Vector128) .GetMethod(nameof(Vector128.WithLower)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { value, upperResult }); result = typeof(Vector128) .GetMethod(nameof(Vector128.WithUpper)) .MakeGenericMethod(typeof(Single)) .Invoke(null, new object[] { result, lowerResult }); ValidateWithResult((Vector128<Single>)(result), values); } private void ValidateGetResult(Vector64<Single> lowerResult, Vector64<Single> upperResult, Single[] values, [CallerMemberName] string method = "") { Single[] lowerElements = new Single[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref lowerElements[0]), lowerResult); Single[] upperElements = new Single[ElementCount / 2]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref upperElements[0]), upperResult); ValidateGetResult(lowerElements, upperElements, values, method); } private void ValidateGetResult(Single[] lowerResult, Single[] upperResult, Single[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (lowerResult[i] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single>.GetLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", lowerResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (upperResult[i - (ElementCount / 2)] != values[i]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single>.GetUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", upperResult)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } private void ValidateWithResult(Vector128<Single> result, Single[] values, [CallerMemberName] string method = "") { Single[] resultElements = new Single[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, method); } private void ValidateWithResult(Single[] result, Single[] values, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount / 2; i++) { if (result[i] != values[i + (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithLower(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = true; for (int i = ElementCount / 2; i < ElementCount; i++) { if (result[i] != values[i - (ElementCount / 2)]) { succeeded = false; break; } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128<Single.WithUpper(): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); 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. //////////////////////////////////////////////////////////////////////////// // // Class: RegionInfo // // Purpose: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // Date: March 31, 1999 // //////////////////////////////////////////////////////////////////////////// using System; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String m_name; // // The CultureData instance that we are going to read data from. // internal CultureData m_cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// [System.Security.SecuritySafeCritical] // auto-generated public RegionInfo(String name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, "name"); } Contract.EndContractBlock(); // // For CoreCLR we only want the region names that are full culture names // this.m_cultureData = CultureData.GetCultureDataForRegion(name, true); if (this.m_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), "name"); // Not supposed to be neutral if (this.m_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), "name"); SetName(name); } [System.Security.SecuritySafeCritical] // auto-generated internal RegionInfo(CultureData cultureData) { this.m_cultureData = cultureData; this.m_name = this.m_cultureData.SREGIONNAME; } [System.Security.SecurityCritical] // auto-generated private void SetName(string name) { // Use the name of the region we found this.m_name = this.m_cultureData.SREGIONNAME; } [OnSerializing] private void OnSerializing(StreamingContext ctx) { } [System.Security.SecurityCritical] // auto-generated [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { m_cultureData = CultureData.GetCultureData(m_name, true); if (m_cultureData == null) { throw new ArgumentException( String.Format(CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, m_name), "m_name"); } m_name = this.m_cultureData.SREGIONNAME; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { [System.Security.SecuritySafeCritical] // auto-generated get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData); // Need full name for custom cultures temp.m_name = temp.m_cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Contract.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already"); return (m_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual String NativeName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = this.m_cultureData.IMEASURE; return (value == 0); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { [System.Security.SecuritySafeCritical] // auto-generated get { return (this.m_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace osu.Game.IO.Legacy { /// <summary> SerializationReader. Extends BinaryReader to add additional data types, /// handle null strings and simplify use with ISerializable. </summary> public class SerializationReader : BinaryReader { private readonly Stream stream; public SerializationReader(Stream s) : base(s, Encoding.UTF8) { stream = s; } public int RemainingBytes => (int)(stream.Length - stream.Position); /// <summary> Static method to take a SerializationInfo object (an input to an ISerializable constructor) /// and produce a SerializationReader from which serialized objects can be read </summary>. public static SerializationReader GetReader(SerializationInfo info) { byte[] byteArray = (byte[])info.GetValue("X", typeof(byte[])); MemoryStream ms = new MemoryStream(byteArray); return new SerializationReader(ms); } /// <summary> Reads a string from the buffer. Overrides the base implementation so it can cope with nulls. </summary> public override string ReadString() { // ReSharper disable once AssignNullToNotNullAttribute if (ReadByte() == 0) return null; return base.ReadString(); } /// <summary> Reads a byte array from the buffer, handling nulls and the array length. </summary> public byte[] ReadByteArray() { int len = ReadInt32(); if (len > 0) return ReadBytes(len); if (len < 0) return null; return Array.Empty<byte>(); } /// <summary> Reads a char array from the buffer, handling nulls and the array length. </summary> public char[] ReadCharArray() { int len = ReadInt32(); if (len > 0) return ReadChars(len); if (len < 0) return null; return Array.Empty<char>(); } /// <summary> Reads a DateTime from the buffer. </summary> public DateTime ReadDateTime() { long ticks = ReadInt64(); if (ticks < 0) throw new IOException("Bad ticks count read!"); return new DateTime(ticks, DateTimeKind.Utc); } /// <summary> Reads a generic list from the buffer. </summary> public IList<T> ReadBList<T>(bool skipErrors = false) where T : ILegacySerializable, new() { int count = ReadInt32(); if (count < 0) return null; IList<T> d = new List<T>(count); SerializationReader sr = new SerializationReader(BaseStream); for (int i = 0; i < count; i++) { T obj = new T(); try { obj.ReadFromStream(sr); } catch (Exception) { if (skipErrors) continue; throw; } d.Add(obj); } return d; } /// <summary> Reads a generic list from the buffer. </summary> public IList<T> ReadList<T>() { int count = ReadInt32(); if (count < 0) return null; IList<T> d = new List<T>(count); for (int i = 0; i < count; i++) d.Add((T)ReadObject()); return d; } /// <summary> Reads a generic Dictionary from the buffer. </summary> public IDictionary<TKey, TValue> ReadDictionary<TKey, TValue>() { int count = ReadInt32(); if (count < 0) return null; IDictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); for (int i = 0; i < count; i++) d[(TKey)ReadObject()] = (TValue)ReadObject(); return d; } /// <summary> Reads an object which was added to the buffer by WriteObject. </summary> public object ReadObject() { ObjType t = (ObjType)ReadByte(); switch (t) { case ObjType.boolType: return ReadBoolean(); case ObjType.byteType: return ReadByte(); case ObjType.uint16Type: return ReadUInt16(); case ObjType.uint32Type: return ReadUInt32(); case ObjType.uint64Type: return ReadUInt64(); case ObjType.sbyteType: return ReadSByte(); case ObjType.int16Type: return ReadInt16(); case ObjType.int32Type: return ReadInt32(); case ObjType.int64Type: return ReadInt64(); case ObjType.charType: return ReadChar(); case ObjType.stringType: return base.ReadString(); case ObjType.singleType: return ReadSingle(); case ObjType.doubleType: return ReadDouble(); case ObjType.decimalType: return ReadDecimal(); case ObjType.dateTimeType: return ReadDateTime(); case ObjType.byteArrayType: return ReadByteArray(); case ObjType.charArrayType: return ReadCharArray(); case ObjType.otherType: return DynamicDeserializer.Deserialize(BaseStream); default: return null; } } public static class DynamicDeserializer { private static VersionConfigToNamespaceAssemblyObjectBinder versionBinder; private static BinaryFormatter formatter; private static void initialize() { versionBinder = new VersionConfigToNamespaceAssemblyObjectBinder(); formatter = new BinaryFormatter { // AssemblyFormat = FormatterAssemblyStyle.Simple, Binder = versionBinder }; } public static object Deserialize(Stream stream) { if (formatter == null) initialize(); Debug.Assert(formatter != null, "formatter != null"); // ReSharper disable once PossibleNullReferenceException return formatter.Deserialize(stream); } #region Nested type: VersionConfigToNamespaceAssemblyObjectBinder public sealed class VersionConfigToNamespaceAssemblyObjectBinder : SerializationBinder { private readonly Dictionary<string, Type> cache = new Dictionary<string, Type>(); public override Type BindToType(string assemblyName, string typeName) { if (cache.TryGetValue(assemblyName + typeName, out var typeToDeserialize)) return typeToDeserialize; List<Type> tmpTypes = new List<Type>(); Type genType = null; if (typeName.Contains("System.Collections.Generic") && typeName.Contains("[[")) { string[] splitTyps = typeName.Split('['); foreach (string typ in splitTyps) { if (typ.Contains("Version")) { string asmTmp = typ.Substring(typ.IndexOf(',') + 1); string asmName = asmTmp.Remove(asmTmp.IndexOf(']')).Trim(); string typName = typ.Remove(typ.IndexOf(',')); tmpTypes.Add(BindToType(asmName, typName)); } else if (typ.Contains("Generic")) { genType = BindToType(assemblyName, typ); } } if (genType != null && tmpTypes.Count > 0) { return genType.MakeGenericType(tmpTypes.ToArray()); } } string toAssemblyName = assemblyName.Split(',')[0]; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { if (a.FullName.Split(',')[0] == toAssemblyName) { typeToDeserialize = a.GetType(typeName); break; } } cache.Add(assemblyName + typeName, typeToDeserialize); return typeToDeserialize; } } #endregion } } public enum ObjType : byte { nullType, boolType, byteType, uint16Type, uint32Type, uint64Type, sbyteType, int16Type, int32Type, int64Type, charType, stringType, singleType, doubleType, decimalType, dateTimeType, byteArrayType, charArrayType, otherType, ILegacySerializableType } }
// $Id$ // // 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 Org.Apache.Etch.Bindings.Csharp.Msg; using Org.Apache.Etch.Bindings.Csharp.Support; using Org.Apache.Etch.Bindings.Csharp.Util; using NUnit.Framework; namespace Org.Apache.Etch.Bindings.Csharp.Transport.Fmt.Binary { /// <summary> /// Test binary input and output. /// </summary> [TestFixture] public class TestBinaryTaggedDataInOut { // private static readonly double DOUBLE_MIN_NORMAL = 0x1.0-1022; // Double.MIN_NORMAL; // private static readonly float FLOAT_MIN_NORMAL = 0x1.0p-126f; // Float.MIN_NORMAL; [TestFixtureSetUp] public void First() { Console.WriteLine( "TestBinaryTaggedDataInOut" ); } MyValueFactory vf; private XType mt_foo; private Field mf_x; public TestBinaryTaggedDataInOut() { vf = new MyValueFactory(); mt_foo = vf.GetType( "foo" ); mf_x = new Field( "x" ); } [Test] public void Test_Check_Value() { BinaryTaggedDataOutput btdo = new BinaryTaggedDataOutput(vf, "none:"); foreach (sbyte i in GetBytes( SByte.MinValue, 256 )) if (i >= TypeCode.MIN_TINY_INT && i <= TypeCode.MAX_TINY_INT) Assert.AreEqual( i, btdo.CheckValue( i ) ); else Assert.AreEqual(TypeCode.BYTE, btdo.CheckValue(i)); // short values foreach (short i in GetShorts( short.MinValue, 65536 )) if (i >= TypeCode.MIN_TINY_INT && i <= TypeCode.MAX_TINY_INT) Assert.AreEqual( (sbyte) i, btdo.CheckValue( i ) ); else if (i >= SByte.MinValue && i <= SByte.MaxValue) Assert.AreEqual( TypeCode.BYTE, btdo.CheckValue( i ) ); else Assert.AreEqual( TypeCode.SHORT, btdo.CheckValue( i ) ); // int values foreach (int i in GetTestInts()) if (i >= TypeCode.MIN_TINY_INT && i <= TypeCode.MAX_TINY_INT) Assert.AreEqual( (sbyte) i, btdo.CheckValue( i ) ); else if (i >= SByte.MinValue && i <= SByte.MaxValue) Assert.AreEqual( TypeCode.BYTE, btdo.CheckValue( i ) ); else if (i >= short.MinValue && i <= short.MaxValue) Assert.AreEqual( TypeCode.SHORT, btdo.CheckValue( i ) ); else Assert.AreEqual( TypeCode.INT, btdo.CheckValue( i ) ); // long values foreach (long i in GetTestLongs()) if (i >= TypeCode.MIN_TINY_INT && i <= TypeCode.MAX_TINY_INT) Assert.AreEqual( (sbyte) i, btdo.CheckValue( i ) ); else if (i >= SByte.MinValue && i <= SByte.MaxValue) Assert.AreEqual( TypeCode.BYTE, btdo.CheckValue( i ) ); else if (i >= short.MinValue && i <= short.MaxValue) Assert.AreEqual( TypeCode.SHORT, btdo.CheckValue( i ) ); else if (i >= int.MinValue && i <= int.MaxValue) Assert.AreEqual( TypeCode.INT, btdo.CheckValue( i ) ); else Assert.AreEqual( TypeCode.LONG, btdo.CheckValue( i ) ); // null value Assert.AreEqual(TypeCode.NULL, btdo.CheckValue(null)); // boolean values Assert.AreEqual(TypeCode.BOOLEAN_FALSE, btdo.CheckValue(false)); Assert.AreEqual(TypeCode.BOOLEAN_TRUE, btdo.CheckValue(true)); // float Assert.AreEqual(TypeCode.FLOAT, btdo.CheckValue(3.14159f)); // double Assert.AreEqual(TypeCode.DOUBLE, btdo.CheckValue(3.14159)); // byte array Assert.AreEqual(TypeCode.BYTES, btdo.CheckValue(new sbyte[0])); Assert.AreEqual(TypeCode.BYTES, btdo.CheckValue(new sbyte[1])); // string Assert.AreEqual(TypeCode.EMPTY_STRING, btdo.CheckValue("")); Assert.AreEqual(TypeCode.STRING, btdo.CheckValue("abc")); // struct Assert.AreEqual(TypeCode.CUSTOM, btdo.CheckValue(new StructValue(new XType("foo"), vf))); // custom Assert.AreEqual(TypeCode.CUSTOM, btdo.CheckValue(new DateTime())); // none Assert.AreEqual(TypeCode.NONE, btdo.CheckValue(BinaryTaggedData.NONE)); } [Test] public void Test_boolean() { // 2 dimensional bool[][] array1 = new bool[][] { new bool[] { false, true }, new bool[] { true, false } }; TestX( array1 , Validator_boolean.Get( 2 ) ); // 3 dimensional TestX( new bool[][][] { new bool[][] { new bool[] { true, false, false }, new bool[] { true, false, true } }, new bool[][] { new bool[] { false, true, false }, new bool[] { false, true, false } }, new bool[][] { new bool[] { false, false, false }, new bool[] { true, true, true } } }, Validator_boolean.Get( 3 ) ); } [Test] public void Test_byte() { // 2 dimensional TestX( new sbyte[][] { new sbyte[] { SByte.MinValue, -1, 0, 1, SByte.MaxValue }, new sbyte[] { 23 } }, Validator_byte.Get( 2 ) ); // 3 dimensional TestX( new sbyte[][][] { new sbyte[][] { new sbyte[] { SByte.MinValue, -1, 0, 1, SByte.MaxValue }, new sbyte[] { 23 } }, new sbyte[][] { new sbyte[] { SByte.MinValue, 1, 0, -1, SByte.MaxValue }, new sbyte[] { 23 } }, new sbyte[][] { new sbyte[] { SByte.MaxValue, -1, 0, 1, SByte.MinValue }, new sbyte[] { 23 } } }, Validator_byte.Get( 3 ) ); } [Test] public void Test_short() { // 2 dimensional TestX( new short[][] { new short[] { short.MinValue, SByte.MinValue, -1, 0, 1, SByte.MaxValue, short.MaxValue }, new short[] { 23 } }, Validator_short.Get( 2 ) ); // 3 dimensional TestX( new short[][][] { new short[][] { new short[] { short.MinValue, SByte.MinValue, -1, 0, 1, SByte.MaxValue, short.MaxValue }, new short[] { 23 } }, new short[][] { new short[] { short.MaxValue, SByte.MinValue, -1, 0, 1, SByte.MaxValue, short.MinValue }, new short[] { 23 } }, new short[][] { new short[] { short.MaxValue, SByte.MaxValue, 1, 0, -1, SByte.MinValue, short.MinValue }, new short[] { 23 } } }, Validator_short.Get( 3 ) ); } [Test] public void Test_int() { // 2 Dimensional TestX( new int[][] { new int[] { int.MinValue, short.MinValue, SByte.MinValue, -1, 0, 1, sbyte.MaxValue, short.MaxValue, int.MaxValue}, new int[] { 23 } }, Validator_int.Get( 2 ) ); // 3 dimensional TestX( new int[][][] { new int[][] { new int[] { int.MinValue, short.MinValue, SByte.MinValue, -1, 0, 1, sbyte.MaxValue, short.MaxValue, int.MaxValue}, new int[] { 23 } }, new int[][] { new int[] { int.MaxValue, short.MinValue, SByte.MinValue, -1, 0, 1, sbyte.MaxValue, short.MinValue, int.MaxValue}, new int[] { 23 } }, new int[][] { new int[] { int.MaxValue, short.MaxValue, SByte.MaxValue, -1, 0, 1, sbyte.MinValue, short.MinValue, int.MinValue}, new int[] { 23 } } }, Validator_int.Get( 3 ) ); } [Test] public void Test_long() { // 2 dimensional TestX( new long[][] { new long[] { long.MinValue, int.MinValue, short.MinValue, SByte.MinValue, -1, 0, 1, sbyte.MaxValue, short.MaxValue, int.MaxValue, long.MaxValue}, new long[] { 23 } }, Validator_long.Get( 2 ) ); // 3 dimensional TestX( new long[][][] { new long[][] { new long[] { long.MinValue, int.MinValue, short.MinValue, SByte.MinValue, -1, 0, 1, sbyte.MaxValue, short.MaxValue, int.MaxValue, long.MaxValue}, new long[] { 23 } }, new long[][] { new long[] { long.MinValue, int.MaxValue, short.MaxValue, SByte.MinValue, -1, 0, 1, sbyte.MaxValue, short.MinValue, int.MinValue, long.MaxValue}, new long[] { 23 } }, new long[][] { new long[] { long.MaxValue, int.MaxValue, short.MaxValue, SByte.MaxValue, -1, 0, 1, sbyte.MinValue, short.MinValue, int.MinValue, long.MinValue}, new long[] { 23 } } }, Validator_long.Get( 3 ) ); } [Test] public void Test_float() { // 2 dimensional TestX( new float[][] { new float[] { -1, 0, 1, float.MinValue, float.Epsilon, float.MaxValue, float.NaN, float.NegativeInfinity, float.PositiveInfinity, -0.0f, 1.1f, 3.141592653589793238462643383279f }, new float[] { 23 } }, Validator_float.Get( 2 ) ); // 3 dimensional TestX( new float[][][] { new float[][] { new float[] { -1, 0, 1, float.MinValue, float.Epsilon, float.MaxValue, float.NaN, float.NegativeInfinity, float.PositiveInfinity, -0.0f, 1.1f, 3.141592653589793238462643383279f }, new float[] { 23 } }, new float[][] { new float[] { -1, 0, 1, float.MaxValue, float.Epsilon, float.MinValue, float.NaN, float.NegativeInfinity, float.PositiveInfinity, 0.0f, -1.1f, 3.141592653589793238462643383279f }, new float[] { 23 } }, new float[][] { new float[] { -1, 0, 1, float.MaxValue, float.Epsilon, float.MaxValue, float.NaN, float.PositiveInfinity, float.NegativeInfinity, -0.0f, 1.1f, -3.141592653589793238462643383279f }, new float[] { 23 } } }, Validator_float.Get( 3 ) ); } [Test] public void Test_double() { // 2 dimensional TestX( new double[][] { new double[]{ -1, 0, 1, double.MinValue, double.Epsilon, double.MaxValue, double.NaN, double.NegativeInfinity, double.PositiveInfinity, -0.0f, 1.1f, 3.141592653589793238462643383279 }, new double[]{ 23 } }, Validator_double.Get( 2 ) ); // 3 dimensional TestX( new double[][][] { new double[][] { new double[]{ -1, 0, 1, double.MinValue, double.Epsilon, double.MaxValue, double.NaN, double.NegativeInfinity, double.PositiveInfinity, -0.0f, 1.1f, 3.141592653589793238462643383279 }, new double[]{ 23 } }, new double[][] { new double[]{ -1, 0, 1, double.MaxValue, double.Epsilon, double.MinValue, double.NaN, double.NegativeInfinity, double.PositiveInfinity, 0.0f, -1.1f, 3.141592653589793238462643383279 }, new double[]{ 23 } }, new double[][] { new double[]{ -1, 0, 1, double.MaxValue, double.Epsilon, double.MinValue, double.NaN, double.PositiveInfinity, double.NegativeInfinity, 0.0f, -1.1f, -3.141592653589793238462643383279 }, new double[]{ 23 } } }, Validator_double.Get( 3 ) ); } [Test] public void Test_String() { // 2 dimensional TestX( new String[][] { new String[] { "", "a", "ab", "abc" }, new String[] { "23" } }, Validator_string.Get( 2 ) ); // 3 dimensional TestX( new String[][][] { new String[][] { new String[] { "", "a", "ab", "abc" }, new String[] { "23" } }, new String[][] { new String[] { "abc", "ab", "a", "" }, new String[] { "23" } }, new String[][] { new String[] { "ab", "abc", "", "a" }, new String[] { "23" } } }, Validator_string.Get( 3 ) ); } [Test] public void Test_Add() { XType add = vf.GetType( "add" ); Field x = new Field( "x" ); add.PutValidator( x, Validator_int.Get( 0 ) ); Field y = new Field ("y" ); add.PutValidator( y, Validator_int.Get( 0 ) ); Field _mf__messageId = DefaultValueFactory._mf__messageId; add.PutValidator( _mf__messageId, Validator_long.Get( 0 ) ); long msgid = 0x0102030405060708L; Message msg = new Message( add, vf ); msg.Add( x, 1 ); msg.Add( y, 2 ); msg.Add( _mf__messageId, msgid ); testmsg2bytes(msg, null, new sbyte[] { 3, -122, 39, -23, -73, -100, 3, -122, 21, 10, 44, -77, 1, -122, 99, 6, -76, 104, -121, 1, 2, 3, 4, 5, 6, 7, 8, -122, 21, 10, 44, -76, 2, -127 }); testmsg2bytes(msg, false, new sbyte[] { 3, -122, 39, -23, -73, -100, 3, -122, 21, 10, 44, -77, 1, -122, 99, 6, -76, 104, -121, 1, 2, 3, 4, 5, 6, 7, 8, -122, 21, 10, 44, -76, 2, -127 }); testmsg2bytes(msg, true, new sbyte[] { 3, -109, 3, 97, 100, 100, 3, -109, 1, 120, 1, -109, 10, 95, 109, 101, 115, 115, 97, 103, 101, 73, 100, -121, 1, 2, 3, 4, 5, 6, 7, 8, -109, 1, 121, 2, -127 }); msg = new Message( add, vf ); msg.Add( x, 1000000000 ); msg.Add( y, 2000000000 ); msg.Add( _mf__messageId, msgid ); testmsg2bytes(msg, null, new sbyte[] { 3, -122, 39, -23, -73, -100, 3, -122, 21, 10, 44, -77, -122, 59, -102, -54, 0, -122, 99, 6, -76, 104, -121, 1, 2, 3, 4, 5, 6, 7, 8, -122, 21, 10, 44, -76, -122, 119, 53, -108, 0, -127 }); testmsg2bytes(msg, false, new sbyte[] { 3, -122, 39, -23, -73, -100, 3, -122, 21, 10, 44, -77, -122, 59, -102, -54, 0, -122, 99, 6, -76, 104, -121, 1, 2, 3, 4, 5, 6, 7, 8, -122, 21, 10, 44, -76, -122, 119, 53, -108, 0, -127 }); testmsg2bytes(msg, true, new sbyte[] { 3, -109, 3, 97, 100, 100, 3, -109, 1, 120, -122, 59, -102, -54, 0, -109, 10, 95, 109, 101, 115, 115, 97, 103, 101, 73, 100, -121, 1, 2, 3, 4, 5, 6, 7, 8, -109, 1, 121, -122, 119, 53, -108, 0, -127 }); } private void testmsg2bytes( Message msg, bool? stringTypeAndField, sbyte[] sexpected ) { byte[] expected = ToSByteArray(sexpected); byte[] actual = Msg2bytes( msg, stringTypeAndField ); try { AssertArrayEquals(expected, actual); } catch ( Exception ) { Dump( expected ); Dump( actual ); throw; } } private byte[] ToSByteArray(sbyte[] a) { return (byte[])(Array)a; } [Test] public void test_add_in() { XType add = vf.GetType( "add" ); Field x = new Field( "x" ); add.PutValidator( x, Validator_int.Get( 0 ) ); Field y = new Field( "y" ); add.PutValidator( y, Validator_int.Get( 0 ) ); Field _mf__messageId = DefaultValueFactory._mf__messageId; add.PutValidator( _mf__messageId, Validator_long.Get( 0 ) ); long msgid = 0x0123456789abcdefL; //sbyte[] _buf = { 1, -9, -100, -73, -23, 39, -9, 104, -76, 6, 99, -13, -17, -51, -85, -119, 103, 69, 35, 1, -9, -76, 44, 10, 21, 66, -9, -77, 44, 10, 21, 65, -22 } ; sbyte[] _buf = { 3, // version -122, // INT (Type) 39, -23, -73, -100, // add 3, // length -122, 99, 6, -76, 104, -121, // LONG (value) 1, 35, 69, 103, -119, -85, -51, -17, -122, // INT (key) 21, 10, 44, -76, // y 2, // tiny int = 2 (value) -122, // INT (key) 21, 10, 44, -77, // x 1, // tiny int =1 -127 // NONE }; byte[] buf = new byte[_buf.Length]; Buffer.BlockCopy(_buf,0,buf,0,_buf.Length); Message msg = Bytes2msg( buf ); msg.CheckType( add ); Assert.AreEqual( 3, msg.Count ); Assert.AreEqual( 1, msg[ x ] ); Assert.AreEqual( 2, msg[ y ] ); Assert.AreEqual( msgid, msg[ _mf__messageId ] ); //_buf = new sbyte[] { 1, -9, -100, -73, -23, 39, -9, 104, -76, 6, 99, -13, -17, -51, -85, -119, 103, 69, 35, 1, -9, -76, 44, 10, 21, -9, 0, -108, 53, 119, -9, -77, 44, 10, 21, -9, 0, -54, -102, 59, -22 }; // _buf = new sbyte[] { 3, -9, 39, -23, -73, -100, -9, 99, 6, -76, 104, -13, 1, 35, 69, 103, -119, -85, -51, -17, -9, 21, 10, 44, -76, -9, 119, 53, -108, 0, -9, 21, 10, 44, -77, -9, 59, -102, -54, 0, -22 }; _buf = new sbyte[] { 3, // version -122, // INT (type) 39, -23, -73, -100, // add 3, // length -122, // INT (key) 99, 6, -76, 104, -121, // LONG (value) 1, 35, 69, 103, -119, -85, -51, -17, -122, // INT (key) 21, 10, 44, -76, // y -122, // INT (value) 119, 53, -108, 0, -122, // INT (key) 21, 10, 44, -77, // x -122, // INT (value) 59, -102, -54, 0, -127 // NONE }; buf = new byte[_buf.Length]; Buffer.BlockCopy(_buf, 0, buf, 0, _buf.Length); msg = Bytes2msg( buf ); msg.CheckType( add ); Assert.AreEqual( 3, msg.Count ); Assert.AreEqual( 1000000000, msg[x ] ); Assert.AreEqual( 2000000000, msg[ y ] ); Assert.AreEqual( msgid, msg[ _mf__messageId ] ); } [Test] public void Test_add_perf() { vf = new MyValueFactory(); XType add = vf.GetType( "add" ); Field x = new Field( "x" ); add.PutValidator( x, Validator_int.Get( 0 ) ); Field y = new Field( "y" ); add.PutValidator( y, Validator_int.Get( 0 ) ); Field _mf__messageId = DefaultValueFactory._mf__messageId; add.PutValidator( _mf__messageId, Validator_long.Get( 0 ) ); long msgid = 0x0123456789abcdefL; Message msg = new Message( add, vf ); msg.Add( x, 123456789 ); msg.Add( y, 876543210 ); msg.Add( _mf__messageId, msgid ); Resources res = new Resources(); res.Add(TransportConsts.VALUE_FACTORY, vf); MyPacketSource ps = new MyPacketSource(); Messagizer m = new Messagizer(ps,"foo:?Messagizer.format=binary", res); m.TransportMessage(null,msg); int n = 900973; for ( int i = 0; i < 3; i++ ) { TestPerf( "test_add_perf", i, m, msg, n ); } } [Test] public void Test_sum_perf() { XType sum = vf.GetType( "sum" ); Field values = new Field( "values" ); sum.PutValidator( values, Validator_int.Get( 1 ) ); Field _mf__messageId = DefaultValueFactory._mf__messageId; sum.PutValidator( _mf__messageId, Validator_long.Get( 0 ) ); long msgid = 0x0123456789abcdefL; int[] array = new int[ 2 ]; for ( int i = 0; i < array.Length; i++ ) array[ i ] = 123456789; Message msg = new Message( sum, vf ); msg.Add( values, array ); msg.Add( _mf__messageId, msgid ); Resources res = new Resources(); res.Add(TransportConsts.VALUE_FACTORY, vf); MyPacketSource ps = new MyPacketSource(); Messagizer m = new Messagizer(ps,"foo:?Messagizer.format=binary", res); m.TransportMessage( null, msg ); int n = 509520; for (int i = 0; i < 1; i++) TestPerf( "test_sum_perf", i, m, msg, n ); } [Test] public void testValueToBytes() { assertValueToBytes(null, new sbyte[] { 3, 1, 0, -127 }); assertValueToBytes(new object[] { null }, new sbyte[] { 3, 1, 1, 2, -111, -106, 1, 1, -128, -127, -127 }); assertValueToBytes(false, new sbyte[] { 3, 1, 1, 2, -126, -127 }); assertValueToBytes(true, new sbyte[] { 3, 1, 1, 2, -125, -127 }); // tiny int: assertValueToBytes(0, new sbyte[] { 3, 1, 1, 2, 0, -127 }); assertValueToBytes(1, new sbyte[] { 3, 1, 1, 2, 1, -127 }); assertValueToBytes(-1, new sbyte[] { 3, 1, 1, 2, -1, -127 }); // byte: assertValueToBytes(-100, new sbyte[] { 3, 1, 1, 2, -124, -100, -127 }); // short: assertValueToBytes(10000, new sbyte[] { 3, 1, 1, 2, -123, 39, 16, -127 }); assertValueToBytes(-10000, new sbyte[] { 3, 1, 1, 2, -123, -40, -16, -127 }); // int: assertValueToBytes(1000000000, new sbyte[] { 3, 1, 1, 2, -122, 59, -102, -54, 0, -127 }); assertValueToBytes(-1000000000, new sbyte[] { 3, 1, 1, 2, -122, -60, 101, 54, 0, -127 }); // long: assertValueToBytes(1000000000000000000L, new sbyte[] { 3, 1, 1, 2, -121, 13, -32, -74, -77, -89, 100, 0, 0, -127 }); assertValueToBytes(-1000000000000000000L, new sbyte[] { 3, 1, 1, 2, -121, -14, 31, 73, 76, 88, -100, 0, 0, -127 }); // float: assertValueToBytes(12345f, new sbyte[] { 3, 1, 1, 2, -120, 70, 64, -28, 0, -127 }); // double: assertValueToBytes(23456d, new sbyte[] { 3, 1, 1, 2, -119, 64, -42, -24, 0, 0, 0, 0, 0, -127 }); // boolean[]: assertValueToBytes(new Boolean[] { true, false }, new sbyte[] { 3, 1, 1, 2, -111, -125, 1, 2, -125, -126, -127, -127 }); // byte[]: assertValueToBytes(new sbyte[] { 1, 2, 3 }, new sbyte[] { 3, 1, 1, 2, -117, 3, 1, 2, 3, -127 }); // byte[][]: assertValueToBytes(new sbyte[][] { new sbyte[] { 1, 2, 3 }, new sbyte[] { 2, 3, 4 } }, new sbyte[] { 3, 1, 1, 2, -111, -124, 2, 2, -117, 3, 1, 2, 3, -117, 3, 2, 3, 4, -127, -127 }); // short[]: assertValueToBytes(new short[] { 1, 2, 3 }, new sbyte[] { 3, 1, 1, 2, -111, -123, 1, 3, 1, 2, 3, -127, -127 }); // int[]: assertValueToBytes(new int[] { 1, 2, 3 }, new sbyte[] { 3, 1, 1, 2, -111, -122, 1, 3, 1, 2, 3, -127, -127 }); // long[]: assertValueToBytes(new long[] { 1, 2, 3 }, new sbyte[] { 3, 1, 1, 2, -111, -121, 1, 3, 1, 2, 3, -127, -127 }); // float[]: assertValueToBytes(new float[] { 1, 2, 3 }, new sbyte[] { 3, 1, 1, 2, -111, -120, 1, 3, -120, 63, -128, 0, 0, -120, 64, 0, 0, 0, -120, 64, 64, 0, 0, -127, -127 }); // double[]: assertValueToBytes(new double[] { 1, 2, 3 }, new sbyte[] { 3, 1, 1, 2, -111, -119, 1, 3, -119, 63, -16, 0, 0, 0, 0, 0, 0, -119, 64, 0, 0, 0, 0, 0, 0, 0, -119, 64, 8, 0, 0, 0, 0, 0, 0, -127, -127 }); // empty string: assertValueToBytes("", new sbyte[] { 3, 1, 1, 2, -110, -127 }); // string: assertValueToBytes("abc", new sbyte[] { 3, 1, 1, 2, -109, 3, 97, 98, 99, -127 }); // string[]: assertValueToBytes(new String[] { "a", "", "c" }, new sbyte[] { 3, 1, 1, 2, -111, -109, 1, 3, -109, 1, 97, -110, -109, 1, 99, -127, -127 }); // Date: assertValueToBytes(new DateTime(2008, 1, 2, 3, 4, 5, 6, DateTimeKind.Utc), new sbyte[] { 3, 1, 1, 2, -107, -122, 43, 57, 107, -52, 1, -122, 102, 0, 26, 64, -121, 0, 0, 1, 23, 56, 116, -88, -114, -127, -127 }); // Date[]: assertValueToBytes(new DateTime[] { new DateTime(2008, 1, 2, 3, 4, 5, 6, DateTimeKind.Utc), new DateTime(2008, 2, 3, 4, 5, 6, 7, DateTimeKind.Utc) }, new sbyte[] { 3, 1, 1, 2, -111, -107, -122, 43, 57, 107, -52, 1, 2, -107, -122, 43, 57, 107, -52, 1, -122, 102, 0, 26, 64, -121, 0, 0, 1, 23, 56, 116, -88, -114, -127, -107, -122, 43, 57, 107, -52, 1, -122, 102, 0, 26, 64, -121, 0, 0, 1, 23, -35, 120, 5, 87, -127, -127, -127 }); } [Test] public void badtype() { Message msg = Bytes2msg(new sbyte[] { 3, 1, 0, -127 }); Assert.AreEqual(1, msg.GetXType.Id); } [Test] [ExpectedException(typeof(ArgumentException))] public void badmsglen1() { Message msg = Bytes2msg(new sbyte[] { 3, 1, -1, -127 }); Console.WriteLine("msg = " + msg); } [Test] [ExpectedException(typeof(ArgumentException))] public void badmsglen2() { Message msg = Bytes2msg(new sbyte[] { 3, 1, 99, -127 }); Console.WriteLine("msg = " + msg); } [Test] public void badfield() { Message msg = Bytes2msg(new sbyte[] { 3, 1, 1, 2, 2, -127 }, Validator.Level.MISSING_OK); Console.WriteLine("msg = " + msg); } private void assertValueToBytes( Object value, sbyte[] expectedBytes ) { XType t = new XType(1, "a"); Field f = new Field(2, "b"); t.PutValidator(f, Validator_object.Get(0)); Message msg = new Message(t, vf); msg.Add(f, value); BinaryTaggedDataOutput btdo = new BinaryTaggedDataOutput( vf, "none:" ); FlexBuffer buf = new FlexBuffer(); btdo.WriteMessage(msg, buf); buf.SetIndex( 0 ); byte[] b = buf.GetAvailBytes(); sbyte[] b1 = new sbyte[b.Length]; Buffer.BlockCopy(b,0,b1,0,b.Length); Dump( b ); AssertArrayEquals( expectedBytes, b1 ); } private static void TestPerf( String name, int iter, Messagizer m, Message msg, int n ) { long t0 = HPTimer.Now(); for ( int i = 0; i < n; i++ ) m.TransportMessage( null, msg ); long t1 = HPTimer.NsSince( t0 ); double timeDiff = t1 / 1000000000.0; double r = n / timeDiff; Console.WriteLine( name + " -- iteration : " + iter + " time : " + timeDiff + " count : " + n + " rate : " + r ); } #region MyPacketSource public class MyPacketSource : TransportPacket { public int HeaderSize() { return 0; } public void Packet( Who recepient, FlexBuffer buf ) { // ignore } #region Source Members public object GetHandler() { return null; } public void SetHandler( object handler ) { // ignore } #endregion #region Transport Members public object TransportQuery( object query ) { return null; } public void TransportControl( object control, object value ) { // ignore } public void TransportNotify( object eventObj ) { // ignore } #endregion #region TransportPacket Members public void TransportPacket(Who recipient, FlexBuffer buf) { } #endregion #region Transport<SessionPacket> Members public void SetSession(SessionPacket session) { } #endregion #region Transport<SessionPacket> Members public SessionPacket GetSession() { throw new Exception("The method or operation is not implemented."); } #endregion } #endregion MyPacketSource private byte[] Msg2bytes(Message msg, bool? stringTypeAndField) { FlexBuffer buf = new FlexBuffer(); URL u = new URL("none:"); if (stringTypeAndField != null) u.AddTerm(BinaryTaggedDataOutput.STRING_TYPE_AND_FIELD, stringTypeAndField.ToString()); BinaryTaggedDataOutput btdo = new BinaryTaggedDataOutput(vf, u.ToString()); btdo.WriteMessage( msg, buf ); buf.SetIndex( 0 ); return buf.GetAvailBytes(); } private Message Bytes2msg(byte[] buf, Validator.Level level) { BinaryTaggedDataInput btdi = new BinaryTaggedDataInput(vf, "none:"); return btdi.ReadMessage(new FlexBuffer(buf)); } private Message Bytes2msg(byte[] buf) { return Bytes2msg(buf, Validator.Level.FULL); } private Message Bytes2msg(sbyte[] buf, Validator.Level level) { return Bytes2msg((byte[])(Array)buf, level); } private Message Bytes2msg(sbyte[] buf) { return Bytes2msg(buf, Validator.Level.FULL); } private void TestX( Object x, Validator v ) { if ( x is Array ) { int n = ( ( Array ) x ).GetLength( 0 ); for (int i = 0; i < n; i++) { Object getValue = ( ( Array ) x ).GetValue( i ); TestX( getValue, v.ElementValidator() ); } } Test(x, v, null); Test(x, v, false); Test(x, v, true); } private void Test(Object x, Validator v, bool? stringTypeAndField) { //Console.WriteLine( "-----------------------------------------" ); mt_foo.ClearValidator( mf_x ); mt_foo.PutValidator( mf_x, v ); Message msg = new Message( mt_foo, vf ); msg.Add( mf_x, x ); //Console.WriteLine( "msg = "+msg ); byte[] bufx = Msg2bytes(msg, stringTypeAndField); Dump(bufx); Message msg2 = Bytes2msg( bufx ); //Console.WriteLine( "msg2 = "+msg2 ); msg2.CheckType( mt_foo ); Assert.AreEqual( 1, msg2.Count ); Assert.IsTrue(msg.ContainsKey( mf_x )); Object y = msg2.Get(mf_x); AreEqual(x, y); } public void Dump(byte[] buf) { Console.Write("buf = {"); for (int i = 0; i < buf.Length; i++) { if (i > 0) Console.Write(", "); else Console.Write(" "); Console.Write((sbyte)buf[i]); } Console.WriteLine(" }"); } private void AreEqual( Object a, Object b ) { if (a == null || b == null) { Assert.AreEqual( a, b ); return; } Type aType = a.GetType(); Type bType = b.GetType(); if (aType == bType) { if ( ( a is Array ) && ( b is Array ) ) AssertArrayEquals( a, b ); else Assert.AreEqual( a, b ); } //else if (a instanceof Number && b instanceof Number) else { Console.WriteLine( "a {0}, b {1}\n", aType, bType ); Assert.AreEqual( a, b ); } } private void AssertArrayEquals( Object a, Object b ) { // jagged arrays ... one dimension int an = ( ( Array ) a ).GetLength( 0 ); int bn = ( ( Array ) b ).GetLength( 0 ); AreEqual( an, bn ); for ( int i = 0; i < an; i++ ) AreEqual( ( ( Array ) a ).GetValue( 0 ), ( ( Array ) b ).GetValue( 0 ) ); } private long[] GetTestLongs() { int n = 65536 + 2 + 6; int k = 65536 + 2; int min = short.MinValue - 1; long[] vals = new long[n]; int i = 0; while (k-- > 0) vals[i++] = min++; vals[i++] = int.MinValue; vals[i++] = int.MaxValue; vals[i++] = int.MinValue - 1L; vals[i++] = int.MaxValue + 1L; vals[i++] = long.MinValue; vals[i++] = long.MaxValue; return vals; } private int[] GetTestInts() { int n = 65536 + 2 + 2; int k = 65536 + 2; int min = short.MinValue - 1; int[] vals = new int[n]; int i = 0; while (k-- > 0) vals[i++] = min++; vals[i++] = int.MinValue; vals[i++] = int.MaxValue; return vals; } private short[] GetShorts(short min, int n) { short[] vals = new short[n]; int i = 0; while (n-- > 0) vals[i++] = min++; return vals; } private sbyte[] GetBytes(sbyte min, int n) { sbyte[] vals = new sbyte[n]; int i = 0; while (n-- > 0) vals[i++] = min++; return vals; } public class MyValueFactory : DefaultValueFactory { private readonly static TypeMap types = new TypeMap(); private readonly static Class2TypeMap class2type = new Class2TypeMap(); static MyValueFactory() { DefaultValueFactory.Init( types, class2type ); } public MyValueFactory() : base ("none:", types, class2type) { // nothing to do. } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CTYPES using System; using System.Collections.Generic; using System.Numerics; using System.Reflection.Emit; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { /// <summary> /// The meta class for ctypes pointers. /// </summary> [PythonType, PythonHidden] public class PointerType : PythonType, INativeType { internal INativeType _type; private readonly string _typeFormat; public PointerType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members) : base(context, name, bases, members) { object type; if (members.TryGetValue("_type_", out type) && !(type is INativeType)) { throw PythonOps.TypeError("_type_ must be a type"); } _type = (INativeType)type; if (_type != null) { _typeFormat = _type is ArrayType arrayType ? arrayType.ShapeAndFormatRepr() : _type.TypeFormat; } } private PointerType(Type underlyingSystemType) : base(underlyingSystemType) { } public object from_param([NotNull]CData obj) { return new NativeArgument((CData)PythonCalls.Call(this, obj), "P"); } /// <summary> /// Converts an object into a function call parameter. /// </summary> public object from_param(Pointer obj) { if (obj == null) { return ScriptingRuntimeHelpers.Int32ToObject(0); } if (obj.NativeType != this) { throw PythonOps.TypeError("assign to pointer of type {0} from {1} is not valid", Name, ((PythonType)obj.NativeType).Name); } Pointer res = (Pointer)PythonCalls.Call(this); res._memHolder.WriteIntPtr(0, obj._memHolder.ReadMemoryHolder(0)); return res; } public object from_param([NotNull]NativeArgument obj) { return (CData)PythonCalls.Call(this, obj._obj); } /// <summary> /// Access an instance at the specified address /// </summary> public object from_address(object obj) { throw new NotImplementedException("pointer from address"); } public void set_type(PythonType type) { _type = (INativeType)type; } internal static PythonType MakeSystemType(Type underlyingSystemType) { return PythonType.SetPythonType(underlyingSystemType, new PointerType(underlyingSystemType)); } public static ArrayType/*!*/ operator *(PointerType type, int count) { return MakeArrayType(type, count); } public static ArrayType/*!*/ operator *(int count, PointerType type) { return MakeArrayType(type, count); } #region INativeType Members int INativeType.Size { get { return IntPtr.Size; } } int INativeType.Alignment { get { return IntPtr.Size; } } object INativeType.GetValue(MemoryHolder owner, object readingFrom, int offset, bool raw) { if (!raw) { Pointer res = (Pointer)PythonCalls.Call(Context.SharedContext, this); res._memHolder.WriteIntPtr(0, owner.ReadIntPtr(offset)); res._memHolder.AddObject(offset, readingFrom); return res; } return owner.ReadIntPtr(offset).ToPython(); } object INativeType.SetValue(MemoryHolder address, int offset, object value) { Pointer ptr; _Array array; if (value == null) { address.WriteIntPtr(offset, IntPtr.Zero); } else if (value is int) { address.WriteIntPtr(offset, new IntPtr((int)value)); } else if (value is BigInteger) { address.WriteIntPtr(offset, new IntPtr((long)(BigInteger)value)); } else if ((ptr = value as Pointer) != null) { address.WriteIntPtr(offset, ptr._memHolder.ReadMemoryHolder(0)); return PythonOps.MakeDictFromItems(ptr, "0", ptr._objects, "1"); } else if ((array = value as _Array) != null) { address.WriteIntPtr(offset, array._memHolder); return array; } else { throw PythonOps.TypeErrorForTypeMismatch(Name, value); } return null; } Type INativeType.GetNativeType() { return typeof(IntPtr); } MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { Type argumentType = argIndex.Type; Label nextTry = method.DefineLabel(); Label done = method.DefineLabel(); if (!argumentType.IsValueType) { argIndex.Emit(method); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Bne_Un, nextTry); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Br, done); } method.MarkLabel(nextTry); nextTry = method.DefineLabel(); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } constantPool.Add(this); SimpleType st = _type as SimpleType; MarshalCleanup res = null; if (st != null && !argIndex.Type.IsValueType) { if (st._type == SimpleTypeKind.Char || st._type == SimpleTypeKind.WChar) { if (st._type == SimpleTypeKind.Char) { SimpleType.TryToCharPtrConversion(method, argIndex, argumentType, done); } else { SimpleType.TryArrayToWCharPtrConversion(method, argIndex, argumentType, done); } Label notStr = method.DefineLabel(); LocalOrArg str = argIndex; if (argumentType != typeof(string)) { LocalBuilder lb = method.DeclareLocal(typeof(string)); method.Emit(OpCodes.Isinst, typeof(string)); method.Emit(OpCodes.Brfalse, notStr); argIndex.Emit(method); method.Emit(OpCodes.Castclass, typeof(string)); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); str = new Local(lb); } if (st._type == SimpleTypeKind.Char) { res = SimpleType.MarshalCharPointer(method, str); } else { SimpleType.MarshalWCharPointer(method, str); } method.Emit(OpCodes.Br, done); method.MarkLabel(notStr); argIndex.Emit(method); } } // native argument being pased (byref) method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod(nameof(ModuleOps.CheckNativeArgument))); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod()); method.Emit(OpCodes.Br, done); // lone cdata being passed method.MarkLabel(nextTry); nextTry = method.DefineLabel(); method.Emit(OpCodes.Pop); // extra null native arg argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod(nameof(ModuleOps.TryCheckCDataPointerType))); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod()); method.Emit(OpCodes.Br, done); // pointer object being passed method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); // extra null cdata argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod(nameof(ModuleOps.CheckCDataType))); method.Emit(OpCodes.Call, typeof(CData).GetProperty(nameof(CData.UnsafeAddress)).GetGetMethod()); method.Emit(OpCodes.Ldind_I); method.MarkLabel(done); return res; } Type/*!*/ INativeType.GetPythonType() { return typeof(object); } void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) { value.Emit(method); EmitCDataCreation(this, method, constantPool, constantPoolArgument); } string INativeType.TypeFormat { get { return "&" + (_typeFormat ?? _type.TypeFormat); } } #endregion } } } #endif
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Linq; using QuantConnect.Data; using QuantConnect.Util; using System.Diagnostics; using QuantConnect.Logging; using System.Threading.Tasks; using System.Collections.Generic; using QuantConnect.ToolBox.CoinApi; namespace QuantConnect.ToolBox.CoinApiDataConverter { /// <summary> /// Console application for converting CoinApi raw data into Lean data format for high resolutions (tick, second and minute) /// </summary> public class CoinApiDataConverter { /// <summary> /// List of supported exchanges /// </summary> private static readonly HashSet<string> SupportedMarkets = new[] { Market.GDAX, Market.Bitfinex, Market.Binance, Market.FTX, Market.FTXUS, Market.Kraken }.ToHashSet(); private readonly DirectoryInfo _rawDataFolder; private readonly DirectoryInfo _destinationFolder; private readonly DateTime _processingDate; private readonly string _market; /// <summary> /// CoinAPI data converter. /// </summary> /// <param name="date">the processing date.</param> /// <param name="rawDataFolder">path to the raw data folder.</param> /// <param name="destinationFolder">destination of the newly generated files.</param> /// <param name="market">The market to process (optional). Defaults to processing all markets in parallel.</param> public CoinApiDataConverter(DateTime date, string rawDataFolder, string destinationFolder, string market = null) { _market = string.IsNullOrWhiteSpace(market) ? null : market.ToLowerInvariant(); _processingDate = date; _rawDataFolder = new DirectoryInfo(Path.Combine(rawDataFolder, SecurityType.Crypto.ToLower(), "coinapi")); if (!_rawDataFolder.Exists) { throw new ArgumentException($"CoinApiDataConverter(): Source folder not found: {_rawDataFolder.FullName}"); } _destinationFolder = new DirectoryInfo(destinationFolder); _destinationFolder.Create(); } /// <summary> /// Runs this instance. /// </summary> /// <returns></returns> public bool Run() { var stopwatch = Stopwatch.StartNew(); var symbolMapper = new CoinApiSymbolMapper(); var success = true; // There were cases of files with with an extra suffix, following pattern: // <TickType>-<ID>-<Exchange>_SPOT_<BaseCurrency>_<QuoteCurrency>_<ExtraSuffix>.csv.gz // Those cases should be ignored for SPOT prices. var tradesFolder = new DirectoryInfo( Path.Combine( _rawDataFolder.FullName, "trades", _processingDate.ToStringInvariant(DateFormat.EightCharacter))); var quotesFolder = new DirectoryInfo( Path.Combine( _rawDataFolder.FullName, "quotes", _processingDate.ToStringInvariant(DateFormat.EightCharacter))); var rawMarket = _market != null && CoinApiSymbolMapper.MapMarketsToExchangeIds.TryGetValue(_market, out var rawMarketValue) ? rawMarketValue : null; // Distinct by tick type and first two parts of the raw file name, separated by '-'. // This prevents us from double processing the same ticker twice, in case we're given // two raw data files for the same symbol. Related: https://github.com/QuantConnect/Lean/pull/3262 var apiDataReader = new CoinApiDataReader(symbolMapper); var filesToProcessCandidates = tradesFolder.EnumerateFiles("*.gz") .Concat(quotesFolder.EnumerateFiles("*.gz")) .Where(f => f.Name.Contains("SPOT") && (rawMarket == null || f.Name.Contains(rawMarket))) .Where(f => f.Name.Split('_').Length == 4) .ToList(); var filesToProcessKeys = new HashSet<string>(); var filesToProcess = new List<FileInfo>(); foreach (var candidate in filesToProcessCandidates) { try { var entryData = apiDataReader.GetCoinApiEntryData(candidate, _processingDate); CurrencyPairUtil.DecomposeCurrencyPair(entryData.Symbol, out var baseCurrency, out var quoteCurrency); if (!candidate.FullName.Contains(baseCurrency) && !candidate.FullName.Contains(quoteCurrency)) { throw new Exception($"Skipping {candidate.FullName} we have the wrong symbol {entryData.Symbol}!"); } var key = candidate.Directory.Parent.Name + entryData.Symbol.ID; if (filesToProcessKeys.Add(key)) { // Separate list from HashSet to preserve ordering of viable candidates filesToProcess.Add(candidate); } } catch (Exception err) { // Most likely the exchange isn't supported. Log exception message to avoid excessive stack trace spamming in console output Log.Error(err.Message); } } Parallel.ForEach(filesToProcess, (file, loopState) => { Log.Trace($"CoinApiDataConverter(): Starting data conversion from source file: {file.Name}..."); try { ProcessEntry(apiDataReader, file); } catch (Exception e) { Log.Error(e, $"CoinApiDataConverter(): Error processing entry: {file.Name}"); success = false; loopState.Break(); } } ); Log.Trace($"CoinApiDataConverter(): Finished in {stopwatch.Elapsed}"); return success; } /// <summary> /// Processes the entry. /// </summary> /// <param name="coinapiDataReader">The coinapi data reader.</param> /// <param name="file">The file.</param> private void ProcessEntry(CoinApiDataReader coinapiDataReader, FileInfo file) { var entryData = coinapiDataReader.GetCoinApiEntryData(file, _processingDate); if (!SupportedMarkets.Contains(entryData.Symbol.ID.Market)) { // only convert data for supported exchanges return; } var tickData = coinapiDataReader.ProcessCoinApiEntry(entryData, file); // in some cases the first data points from '_processingDate' get's included in the previous date file // so we will ready previous date data and drop most of it just to save these midnight ticks var yesterdayDate = _processingDate.AddDays(-1); var yesterdaysFile = new FileInfo(file.FullName.Replace( _processingDate.ToStringInvariant(DateFormat.EightCharacter), yesterdayDate.ToStringInvariant(DateFormat.EightCharacter))); if (yesterdaysFile.Exists) { var yesterdaysEntryData = coinapiDataReader.GetCoinApiEntryData(yesterdaysFile, yesterdayDate); tickData = tickData.Concat(coinapiDataReader.ProcessCoinApiEntry(yesterdaysEntryData, yesterdaysFile)); } else { Log.Error($"CoinApiDataConverter(): yesterdays data file not found '{yesterdaysFile.FullName}'"); } // materialize the enumerable into a list, since we need to enumerate over it twice var ticks = tickData.Where(tick => tick.Time.Date == _processingDate) .OrderBy(t => t.Time) .ToList(); var writer = new LeanDataWriter(Resolution.Tick, entryData.Symbol, _destinationFolder.FullName, entryData.TickType); writer.Write(ticks); Log.Trace($"CoinApiDataConverter(): Starting consolidation for {entryData.Symbol.Value} {entryData.TickType}"); var consolidators = new List<TickAggregator>(); if (entryData.TickType == TickType.Trade) { consolidators.AddRange(new[] { new TradeTickAggregator(Resolution.Second), new TradeTickAggregator(Resolution.Minute) }); } else { consolidators.AddRange(new[] { new QuoteTickAggregator(Resolution.Second), new QuoteTickAggregator(Resolution.Minute) }); } foreach (var tick in ticks) { if (tick.Suspicious) { // When CoinAPI loses connectivity to the exchange, they indicate // it in the data by providing a value of `-1` for bid/ask price. // We will keep it in tick data, but will remove it from consolidated data. continue; } foreach (var consolidator in consolidators) { consolidator.Update(tick); } } foreach (var consolidator in consolidators) { writer = new LeanDataWriter(consolidator.Resolution, entryData.Symbol, _destinationFolder.FullName, entryData.TickType); writer.Write(consolidator.Flush()); } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// a proxy connects a VM/VIF with a PVS site /// First published in XenServer 7.1. /// </summary> public partial class PVS_proxy : XenObject<PVS_proxy> { #region Constructors public PVS_proxy() { } public PVS_proxy(string uuid, XenRef<PVS_site> site, XenRef<VIF> VIF, bool currently_attached, pvs_proxy_status status) { this.uuid = uuid; this.site = site; this.VIF = VIF; this.currently_attached = currently_attached; this.status = status; } /// <summary> /// Creates a new PVS_proxy from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public PVS_proxy(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new PVS_proxy from a Proxy_PVS_proxy. /// </summary> /// <param name="proxy"></param> public PVS_proxy(Proxy_PVS_proxy proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given PVS_proxy. /// </summary> public override void UpdateFrom(PVS_proxy record) { uuid = record.uuid; site = record.site; VIF = record.VIF; currently_attached = record.currently_attached; status = record.status; } internal void UpdateFrom(Proxy_PVS_proxy proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site); VIF = proxy.VIF == null ? null : XenRef<VIF>.Create(proxy.VIF); currently_attached = (bool)proxy.currently_attached; status = proxy.status == null ? (pvs_proxy_status) 0 : (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)proxy.status); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this PVS_proxy /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("site")) site = Marshalling.ParseRef<PVS_site>(table, "site"); if (table.ContainsKey("VIF")) VIF = Marshalling.ParseRef<VIF>(table, "VIF"); if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); if (table.ContainsKey("status")) status = (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), Marshalling.ParseString(table, "status")); } public Proxy_PVS_proxy ToProxy() { Proxy_PVS_proxy result_ = new Proxy_PVS_proxy(); result_.uuid = uuid ?? ""; result_.site = site ?? ""; result_.VIF = VIF ?? ""; result_.currently_attached = currently_attached; result_.status = pvs_proxy_status_helper.ToString(status); return result_; } public bool DeepEquals(PVS_proxy other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._site, other._site) && Helper.AreEqual2(this._VIF, other._VIF) && Helper.AreEqual2(this._currently_attached, other._currently_attached) && Helper.AreEqual2(this._status, other._status); } public override string SaveChanges(Session session, string opaqueRef, PVS_proxy server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given PVS_proxy. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static PVS_proxy get_record(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_record(session.opaque_ref, _pvs_proxy); else return new PVS_proxy(session.XmlRpcProxy.pvs_proxy_get_record(session.opaque_ref, _pvs_proxy ?? "").parse()); } /// <summary> /// Get a reference to the PVS_proxy instance with the specified UUID. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PVS_proxy> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<PVS_proxy>.Create(session.XmlRpcProxy.pvs_proxy_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given PVS_proxy. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static string get_uuid(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_uuid(session.opaque_ref, _pvs_proxy); else return session.XmlRpcProxy.pvs_proxy_get_uuid(session.opaque_ref, _pvs_proxy ?? "").parse(); } /// <summary> /// Get the site field of the given PVS_proxy. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static XenRef<PVS_site> get_site(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_site(session.opaque_ref, _pvs_proxy); else return XenRef<PVS_site>.Create(session.XmlRpcProxy.pvs_proxy_get_site(session.opaque_ref, _pvs_proxy ?? "").parse()); } /// <summary> /// Get the VIF field of the given PVS_proxy. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static XenRef<VIF> get_VIF(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_vif(session.opaque_ref, _pvs_proxy); else return XenRef<VIF>.Create(session.XmlRpcProxy.pvs_proxy_get_vif(session.opaque_ref, _pvs_proxy ?? "").parse()); } /// <summary> /// Get the currently_attached field of the given PVS_proxy. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static bool get_currently_attached(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_currently_attached(session.opaque_ref, _pvs_proxy); else return (bool)session.XmlRpcProxy.pvs_proxy_get_currently_attached(session.opaque_ref, _pvs_proxy ?? "").parse(); } /// <summary> /// Get the status field of the given PVS_proxy. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static pvs_proxy_status get_status(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_status(session.opaque_ref, _pvs_proxy); else return (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)session.XmlRpcProxy.pvs_proxy_get_status(session.opaque_ref, _pvs_proxy ?? "").parse()); } /// <summary> /// Configure a VM/VIF to use a PVS proxy /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_site">PVS site that we proxy for</param> /// <param name="_vif">VIF for the VM that needs to be proxied</param> public static XenRef<PVS_proxy> create(Session session, string _site, string _vif) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_create(session.opaque_ref, _site, _vif); else return XenRef<PVS_proxy>.Create(session.XmlRpcProxy.pvs_proxy_create(session.opaque_ref, _site ?? "", _vif ?? "").parse()); } /// <summary> /// Configure a VM/VIF to use a PVS proxy /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_site">PVS site that we proxy for</param> /// <param name="_vif">VIF for the VM that needs to be proxied</param> public static XenRef<Task> async_create(Session session, string _site, string _vif) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_pvs_proxy_create(session.opaque_ref, _site, _vif); else return XenRef<Task>.Create(session.XmlRpcProxy.async_pvs_proxy_create(session.opaque_ref, _site ?? "", _vif ?? "").parse()); } /// <summary> /// remove (or switch off) a PVS proxy for this VM /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static void destroy(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) session.JsonRpcClient.pvs_proxy_destroy(session.opaque_ref, _pvs_proxy); else session.XmlRpcProxy.pvs_proxy_destroy(session.opaque_ref, _pvs_proxy ?? "").parse(); } /// <summary> /// remove (or switch off) a PVS proxy for this VM /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static XenRef<Task> async_destroy(Session session, string _pvs_proxy) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_pvs_proxy_destroy(session.opaque_ref, _pvs_proxy); else return XenRef<Task>.Create(session.XmlRpcProxy.async_pvs_proxy_destroy(session.opaque_ref, _pvs_proxy ?? "").parse()); } /// <summary> /// Return a list of all the PVS_proxys known to the system. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PVS_proxy>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_all(session.opaque_ref); else return XenRef<PVS_proxy>.Create(session.XmlRpcProxy.pvs_proxy_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the PVS_proxy Records at once, in a single XML RPC call /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PVS_proxy>, PVS_proxy> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.pvs_proxy_get_all_records(session.opaque_ref); else return XenRef<PVS_proxy>.Create<Proxy_PVS_proxy>(session.XmlRpcProxy.pvs_proxy_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// PVS site this proxy is part of /// </summary> [JsonConverter(typeof(XenRefConverter<PVS_site>))] public virtual XenRef<PVS_site> site { get { return _site; } set { if (!Helper.AreEqual(value, _site)) { _site = value; NotifyPropertyChanged("site"); } } } private XenRef<PVS_site> _site = new XenRef<PVS_site>("OpaqueRef:NULL"); /// <summary> /// VIF of the VM using the proxy /// </summary> [JsonConverter(typeof(XenRefConverter<VIF>))] public virtual XenRef<VIF> VIF { get { return _VIF; } set { if (!Helper.AreEqual(value, _VIF)) { _VIF = value; NotifyPropertyChanged("VIF"); } } } private XenRef<VIF> _VIF = new XenRef<VIF>("OpaqueRef:NULL"); /// <summary> /// true = VM is currently proxied /// </summary> public virtual bool currently_attached { get { return _currently_attached; } set { if (!Helper.AreEqual(value, _currently_attached)) { _currently_attached = value; NotifyPropertyChanged("currently_attached"); } } } private bool _currently_attached = false; /// <summary> /// The run-time status of the proxy /// </summary> [JsonConverter(typeof(pvs_proxy_statusConverter))] public virtual pvs_proxy_status status { get { return _status; } set { if (!Helper.AreEqual(value, _status)) { _status = value; NotifyPropertyChanged("status"); } } } private pvs_proxy_status _status = pvs_proxy_status.stopped; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Runtime.Remoting.Messaging { using System; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Runtime.Remoting.Metadata; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Proxies; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Reflection; using System.Threading; using System.Globalization; using System.Collections; using System.Security; using System.Security.Permissions; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public delegate bool MessageSurrogateFilter(String key, Object value); [System.Security.SecurityCritical] // auto-generated_required [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags=SecurityPermissionFlag.Infrastructure)] [System.Runtime.InteropServices.ComVisible(true)] public class RemotingSurrogateSelector : ISurrogateSelector { // Private static data private static Type s_IMethodCallMessageType = typeof(IMethodCallMessage); private static Type s_IMethodReturnMessageType = typeof(IMethodReturnMessage); private static Type s_ObjRefType = typeof(ObjRef); // Private member data private Object _rootObj = null; private ISurrogateSelector _next = null; private RemotingSurrogate _remotingSurrogate = new RemotingSurrogate(); private ObjRefSurrogate _objRefSurrogate = new ObjRefSurrogate(); private ISerializationSurrogate _messageSurrogate = null; private MessageSurrogateFilter _filter = null; public RemotingSurrogateSelector() { _messageSurrogate = new MessageSurrogate(this); } public MessageSurrogateFilter Filter { set { _filter = value; } get { return _filter; } } public void SetRootObject(Object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } Contract.EndContractBlock(); _rootObj = obj; SoapMessageSurrogate soapMsg = _messageSurrogate as SoapMessageSurrogate; if (null != soapMsg) { soapMsg.SetRootObject(_rootObj); } } public Object GetRootObject() { return _rootObj; } // Specifies the next ISurrogateSelector to be examined for surrogates if the current // instance doesn't have a surrogate for the given type and assembly in the given context. [System.Security.SecurityCritical] // auto-generated_required public virtual void ChainSelector(ISurrogateSelector selector) {_next = selector;} // Returns the appropriate surrogate for the given type in the given context. [System.Security.SecurityCritical] // auto-generated_required public virtual ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector ssout) { if (type == null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); Message.DebugOut("Entered GetSurrogate for " + type.FullName + "\n"); if (type.IsMarshalByRef) { Message.DebugOut("Selected surrogate for " + type.FullName); ssout = this; return _remotingSurrogate; } else if (s_IMethodCallMessageType.IsAssignableFrom(type) || s_IMethodReturnMessageType.IsAssignableFrom(type)) { ssout = this; return _messageSurrogate; } else if (s_ObjRefType.IsAssignableFrom(type)) { ssout = this; return _objRefSurrogate; } else if (_next != null) { return _next.GetSurrogate(type, context, out ssout); } else { ssout = null; return null; } } // GetSurrogate [System.Security.SecurityCritical] // auto-generated_required public virtual ISurrogateSelector GetNextSelector() { return _next;} public virtual void UseSoapFormat() { _messageSurrogate = new SoapMessageSurrogate(this); ((SoapMessageSurrogate)_messageSurrogate).SetRootObject(_rootObj); } } internal class RemotingSurrogate : ISerializationSurrogate { [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { if (obj == null) { throw new ArgumentNullException("obj"); } if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); // // This code is to special case marshalling types inheriting from RemotingClientProxy // Check whether type inherits from RemotingClientProxy and serialize the correct ObjRef // after getting the correct proxy to the actual server object // Message.DebugOut("RemotingSurrogate::GetObjectData obj.Type: " + obj.GetType().FullName + " \n"); if(RemotingServices.IsTransparentProxy(obj)) { RealProxy rp = RemotingServices.GetRealProxy(obj); rp.GetObjectData(info, context); } else { RemotingServices.GetObjectData(obj, info, context); } } [System.Security.SecurityCritical] // auto-generated_required public virtual Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_PopulateData")); } } // class RemotingSurrogate internal class ObjRefSurrogate : ISerializationSurrogate { [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { if (obj == null) { throw new ArgumentNullException("obj"); } if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); // // This code is to provide special handling for ObjRef's that are supposed // to be passed as parameters. // ((ObjRef)obj).GetObjectData(info, context); // add flag indicating the ObjRef was passed as a parameter info.AddValue("fIsMarshalled", 0); } // GetObjectData [System.Security.SecurityCritical] // auto-generated_required public virtual Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_PopulateData")); } } // class ObjRefSurrogate internal class SoapMessageSurrogate : ISerializationSurrogate { // Private static data private static Type _voidType = typeof(void); private static Type _soapFaultType = typeof(SoapFault); // Member data String DefaultFakeRecordAssemblyName = "http://schemas.microsoft.com/urt/SystemRemotingSoapTopRecord"; Object _rootObj = null; [System.Security.SecurityCritical] // auto-generated RemotingSurrogateSelector _ss; [System.Security.SecurityCritical] // auto-generated internal SoapMessageSurrogate(RemotingSurrogateSelector ss) { _ss = ss; } internal void SetRootObject(Object obj) { _rootObj = obj; } [System.Security.SecurityCritical] // auto-generated internal virtual String[] GetInArgNames(IMethodCallMessage m, int c) { String[] names = new String[c]; for (int i = 0; i < c; i++) { String name = m.GetInArgName(i); if (name == null) { name = "__param" + i; } names[i] = name; } return names; } [System.Security.SecurityCritical] // auto-generated internal virtual String[] GetNames(IMethodCallMessage m, int c) { String[] names = new String[c]; for (int i = 0; i < c; i++) { String name = m.GetArgName(i); if (name == null) { name = "__param" + i; } names[i] = name; } return names; } [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); if ( (obj!=null) && (obj !=_rootObj)) { (new MessageSurrogate(_ss)).GetObjectData(obj, info, context); } else { IMethodReturnMessage msg = obj as IMethodReturnMessage; if(null != msg) { if (msg.Exception == null) { String responseElementName; String responseElementNS; String returnElementName; // obtain response element name namespace MethodBase mb = msg.MethodBase; SoapMethodAttribute attr = (SoapMethodAttribute)InternalRemotingServices.GetCachedSoapAttribute(mb); responseElementName = attr.ResponseXmlElementName; responseElementNS = attr.ResponseXmlNamespace; returnElementName = attr.ReturnXmlElementName; ArgMapper mapper = new ArgMapper(msg, true /*fOut*/); Object[] args = mapper.Args; info.FullTypeName = responseElementName; info.AssemblyName = responseElementNS; Type retType = ((MethodInfo)mb).ReturnType; if (!((retType == null) || (retType == _voidType))) { info.AddValue(returnElementName, msg.ReturnValue, retType); } if (args != null) { Type[] types = mapper.ArgTypes; for (int i=0; i<args.Length; i++) { String name; name = mapper.GetArgName(i); if ((name == null) || (name.Length == 0)) { name = "__param" + i; } info.AddValue( name, args[i], types[i].IsByRef? types[i].GetElementType():types[i]); } } } else { Object oClientIsClr = CallContext.GetData("__ClientIsClr"); bool bClientIsClr = (oClientIsClr == null) ? true:(bool)oClientIsClr; info.FullTypeName = "FormatterWrapper"; info.AssemblyName = DefaultFakeRecordAssemblyName; Exception ex = msg.Exception; StringBuilder sb = new StringBuilder(); bool bMustUnderstandError = false; while(ex != null) { if (ex.Message.StartsWith("MustUnderstand", StringComparison.Ordinal)) bMustUnderstandError = true; sb.Append(" **** "); sb.Append(ex.GetType().FullName); sb.Append(" - "); sb.Append(ex.Message); ex = ex.InnerException; } ServerFault serverFault = null; if (bClientIsClr) serverFault = new ServerFault(msg.Exception); // Clr is the Client use full exception else serverFault = new ServerFault(msg.Exception.GetType().AssemblyQualifiedName, sb.ToString(), msg.Exception.StackTrace); String faultType = "Server"; if (bMustUnderstandError) faultType = "MustUnderstand"; SoapFault soapFault = new SoapFault(faultType, sb.ToString(), null, serverFault); info.AddValue("__WrappedObject", soapFault, _soapFaultType); } } else { IMethodCallMessage mcm = (IMethodCallMessage)obj; // obtain method namespace MethodBase mb = mcm.MethodBase; String methodElementNS = SoapServices.GetXmlNamespaceForMethodCall(mb); Object[] args = mcm.InArgs; String[] names = GetInArgNames(mcm, args.Length); Type[] sig = (Type[])mcm.MethodSignature; info.FullTypeName = mcm.MethodName; info.AssemblyName = methodElementNS; RemotingMethodCachedData cache = (RemotingMethodCachedData)InternalRemotingServices.GetReflectionCachedData(mb); int[] requestArgMap = cache.MarshalRequestArgMap; Contract.Assert( args!=null || sig.Length == args.Length, "Signature mismatch"); for (int i = 0; i < args.Length; i++) { String paramName = null; if ((names[i] == null) || (names[i].Length == 0)) paramName = "__param" + i; else paramName = names[i]; int sigPosition = requestArgMap[i]; Type argType = null; if (sig[sigPosition].IsByRef) argType = sig[sigPosition].GetElementType(); else argType = sig[sigPosition]; info.AddValue(paramName, args[i], argType); } } } } // GetObjectData [System.Security.SecurityCritical] // auto-generated_required public virtual Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_PopulateData")); } } internal class MessageSurrogate : ISerializationSurrogate { // Private static data private static Type _constructionCallType = typeof(ConstructionCall); private static Type _methodCallType = typeof(MethodCall); private static Type _constructionResponseType = typeof(ConstructionResponse); private static Type _methodResponseType = typeof(MethodResponse); private static Type _exceptionType = typeof(Exception); private static Type _objectType = typeof(Object); // Private static member data [System.Security.SecurityCritical] // auto-generated private RemotingSurrogateSelector _ss; [SecuritySafeCritical] static MessageSurrogate() { // static initialization of MessageSurrogate touches critical types, so // the static constructor needs to be critical as well. } [System.Security.SecurityCritical] // auto-generated internal MessageSurrogate(RemotingSurrogateSelector ss) { _ss = ss; } [System.Security.SecurityCritical] // auto-generated_required public virtual void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { if (obj == null) { throw new ArgumentNullException("obj"); } if (info==null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); bool returnMessage = false; bool constructionMessage = false; IMethodMessage msg = obj as IMethodMessage; if (null != msg) { IDictionaryEnumerator de = msg.Properties.GetEnumerator(); if (msg is IMethodCallMessage) { if (obj is IConstructionCallMessage) constructionMessage = true; info.SetType(constructionMessage ? _constructionCallType : _methodCallType); } else { IMethodReturnMessage mrm = msg as IMethodReturnMessage; if (null != mrm) { returnMessage = true; info.SetType((obj is IConstructionReturnMessage) ? _constructionResponseType : _methodResponseType); if (((IMethodReturnMessage)msg).Exception != null) { info.AddValue("__fault",((IMethodReturnMessage)msg).Exception, _exceptionType); } } else { throw new RemotingException(Environment.GetResourceString("Remoting_InvalidMsg")); } } while (de.MoveNext()) { if ((obj == _ss.GetRootObject()) && (_ss.Filter != null) && _ss.Filter((String)de.Key, de.Value)) continue; if (de.Value!=null) { String key = de.Key.ToString(); if (key.Equals("__CallContext")) { // If the CallContext has only the call Id, then there is no need to put the entire // LogicalCallContext type on the wire LogicalCallContext lcc = (LogicalCallContext)de.Value; if (lcc.HasInfo) info.AddValue(key, lcc); else info.AddValue(key, lcc.RemotingData.LogicalCallID); } else if (key.Equals("__MethodSignature")) { // If the method is not overloaded, the method signature does not need to go on the wire // note - IsMethodOverloaded does not work well with constructors if (constructionMessage || RemotingServices.IsMethodOverloaded(msg)) { info.AddValue(key, de.Value); continue; } Message.DebugOut("MessageSurrogate::GetObjectData. Method not overloaded, so no MethodSignature \n"); } else { #if false /* If the streaming context says this is a x-domain call, then there is no need to include the following fields in the return message. Right now I am not sure how to identify a cross-domain streaming context - Ashok */ if (returnMessage && (key.Equals("__Uri") || key.Equals("__MethodName") || key.Equals("__TypeName"))) continue; else #endif #pragma warning disable 1717 // assignment to self returnMessage = returnMessage; #pragma warning restore 1717 info.AddValue(key, de.Value); } } else { info.AddValue(de.Key.ToString(), de.Value, _objectType); } } } else { throw new RemotingException(Environment.GetResourceString("Remoting_InvalidMsg")); } } [System.Security.SecurityCritical] // auto-generated_required public virtual Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_PopulateData")); } } }
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.IO; using UnityEngine; using UnityEditor; using System.Text; using System.Collections.Generic; using System.Runtime.InteropServices; namespace TiltBrush { public class BuildWindow : EditorWindow { private class HeaderedHorizontalLayout : GUI.Scope { public HeaderedHorizontalLayout(string header, params GUILayoutOption[] options) { GUILayout.BeginVertical(new GUIContent(header), EditorStyles.helpBox, options); GUILayout.Space(20); GUILayout.BeginHorizontal(options); } protected override void CloseScope() { GUILayout.EndHorizontal(); GUILayout.EndVertical(); } } private class HeaderedVerticalLayout : GUI.Scope { public HeaderedVerticalLayout(string header, params GUILayoutOption[] options) { GUILayout.BeginVertical(new GUIContent(header), EditorStyles.helpBox, options); GUILayout.Space(20); } protected override void CloseScope() { GUILayout.EndVertical(); } } private class AndroidOperation { private Future<string[]> m_future; private Func<string[], bool> m_successTest; private string[] m_arguments; private string m_name; public string[] Output { get; private set; } public bool Succeeded { get; private set; } public bool Running { get { return m_future != null; } } public bool HasRun { get; private set; } public DateTime FinishTime { get; private set; } public string Title { get; set; } public bool Enabled { get; set; } // Called when a build process is completed, with success/failure as the parameter. public event Action<bool> Completed; public AndroidOperation( string name, Func<string[], bool> successTest, params string[] arguments) { m_successTest = successTest; m_name = name; m_arguments = arguments; Enabled = true; } public void Execute() { Debug.Assert(m_future == null); m_future = new Future<string[]>(() => RunAdb(m_arguments)); } public void Cancel() { Succeeded = false; Output = new string[] { "Cancelled by the user." }; FinishTime = DateTime.Now; HasRun = true; m_future = null; } public void Update() { if (m_future != null) { try { string[] results; if (m_future.TryGetResult(out results)) { Succeeded = m_successTest == null ? false : m_successTest(results); Output = results; FinishTime = DateTime.Now; m_future = null; HasRun = true; if (Completed != null) { Completed(Succeeded); Completed = null; } } } catch (FutureFailed ex) { Output = ex.Message.Split('\n'); FinishTime = DateTime.Now; m_future = null; Succeeded = false; HasRun = true; } } } public void OnGUI() { bool initialGuiEnabled = GUI.enabled; HeaderedVerticalLayout layout = null; if (Title != null) { layout = new HeaderedVerticalLayout(Title); } using (var bar = new GUILayout.HorizontalScope()) { string title = string.Format("{0} {1}", m_name, SpinnerString()); GUI.enabled = !Running && initialGuiEnabled; if (GUILayout.Button(title)) { Execute(); } GUI.enabled = Running && initialGuiEnabled; if (GUILayout.Button("Cancel")) { Cancel(); } GUI.enabled = initialGuiEnabled; } string shortName = m_name.Split(' ')[0]; if (HasRun) { GUILayout.Label( string.Format("{0} {1} at {2}", shortName, Succeeded ? "Succeeded" : "Failed", FinishTime)); } else if (Running) { GUILayout.Label(string.Format("{0} is running.", shortName)); } else { GUILayout.Label(string.Format("{0} has not run yet.", shortName)); } if (Output != null) { foreach (string line in Output) { GUILayout.Label(line); } } if (layout != null) { layout.Dispose(); } } private string SpinnerString() { if (!Running) { return ""; } var spinner = ".....".ToCharArray(); spinner[DateTime.Now.Second % 5] = '|'; return new string(spinner); } } private const double kSecondsBetweenDeviceScan = 1; private const string kAutoUploadAfterBuild = "BuildWindow.AutoUploadAfterBuild"; private const string kAutoRunAfterUpload= "BuildWindow.AutoRunAfterUpload"; private const string kSuccessfulBuildTime = "BuildWindow.SuccessfulBuildTime"; private const string kBuildStartTime = "BuildWindow.BuildStartTime"; private DateTime m_timeOfLastDeviceScan; private string[] m_androidDevices = new string[0]; private string m_selectedAndroid = ""; private Future<string[]> m_deviceListFuture = null; private string m_currentBuildPath = ""; private DateTime? m_currentBuildTime = null; private AndroidOperation m_upload; private AndroidOperation m_launch; private AndroidOperation m_turnOnAdbDebugging; private AndroidOperation m_launchWithProfile; private AndroidOperation m_terminate; private List<string> m_buildLog = new List<string>(); private StreamReader m_buildLogReader = null; private int? m_buildLogPosition; private System.IntPtr m_hwnd; private DateTime m_buildCompleteTime; private bool AndroidConnected { get { return !string.IsNullOrEmpty(m_selectedAndroid) && m_androidDevices.Length > 0; } } private bool UploadAfterBuild { get { return EditorPrefs.GetBool(kAutoUploadAfterBuild, false); } set { EditorPrefs.SetBool(kAutoUploadAfterBuild, value); } } private bool RunAfterUpload { get { return EditorPrefs.GetBool(kAutoRunAfterUpload, false); } set { EditorPrefs.SetBool(kAutoRunAfterUpload, value); } } [MenuItem("Tilt/Build/Build Window", false, 1)] public static void CreateWindow() { BuildWindow window = EditorWindow.GetWindow<BuildWindow>(); window.Show(); } protected void OnEnable() { titleContent = new GUIContent("Build Window"); m_timeOfLastDeviceScan = DateTime.Now; OnBuildSettingsChanged(); m_hwnd = GetActiveWindowHandle(); BuildTiltBrush.OnBackgroundBuildFinish += OnBuildComplete; } private void OnDisable() { BuildTiltBrush.OnBackgroundBuildFinish -= OnBuildComplete; } private void OnGUI() { EditorGUILayout.BeginVertical(); BuildSetupGui(); MakeBuildsGui(); if (BuildTiltBrush.GuiSelectedBuildTarget == BuildTarget.Android) { DeviceGui(); } BuildActionsGui(); EditorGUILayout.EndVertical(); } private void BuildSetupGui() { GUILayoutOption[] options = new GUILayoutOption[] { GUILayout.ExpandHeight(true), }; GUILayoutOption[] toggleOpt = new GUILayoutOption[] { GUILayout.Width(150), }; using (var changeScope = new EditorGUI.ChangeCheckScope()) { using (var setupBar = new GUILayout.HorizontalScope(GUILayout.Height(110))) { // Sdk Modes using (var sdkBar = new HeaderedVerticalLayout("VR SDK", options)) { SdkMode[] sdks = BuildTiltBrush.SupportedSdkModes(); SdkMode selectedSdk = BuildTiltBrush.GuiSelectedSdk; foreach (var sdk in sdks) { bool selected = sdk == selectedSdk; bool newSelected = GUILayout.Toggle(selected, sdk.ToString(), toggleOpt); if (selected != newSelected) { BuildTiltBrush.GuiSelectedSdk = sdk; } } } // Platforms using (var platformBar = new HeaderedVerticalLayout("Platform", options)) { BuildTarget[] targets = BuildTiltBrush.SupportedBuildTargets(); BuildTarget selectedTarget = BuildTiltBrush.GuiSelectedBuildTarget; SdkMode selectedSdk = BuildTiltBrush.GuiSelectedSdk; foreach (var target in targets) { GUI.enabled = BuildTiltBrush.BuildTargetSupported(selectedSdk, target); bool selected = target == selectedTarget; bool newSelected = GUILayout.Toggle(selected, target.ToString(), toggleOpt); if (selected != newSelected) { BuildTiltBrush.GuiSelectedBuildTarget = target; } } GUI.enabled = true; } // Runtime using (var runtimeBar = new HeaderedVerticalLayout("Runtime", options)) { bool isIl2cpp = BuildTiltBrush.GuiRuntimeIl2cpp; bool newIsMono = GUILayout.Toggle(!isIl2cpp, "Mono", toggleOpt); bool newIsIl2cpp = GUILayout.Toggle(isIl2cpp, "IL2CPP", toggleOpt); if (isIl2cpp != newIsIl2cpp || isIl2cpp != !newIsMono) { BuildTiltBrush.GuiRuntimeIl2cpp = !isIl2cpp; } } // Options using (var optionsBar = new HeaderedVerticalLayout("Options", options)) { BuildTiltBrush.GuiDevelopment = GUILayout.Toggle(BuildTiltBrush.GuiDevelopment, "Development"); BuildTiltBrush.GuiExperimental = GUILayout.Toggle(BuildTiltBrush.GuiExperimental, "Experimental"); BuildTiltBrush.GuiAutoProfile = GUILayout.Toggle(BuildTiltBrush.GuiAutoProfile, "Auto Profile"); } } if (changeScope.changed) { OnBuildSettingsChanged(); } } } private void MakeBuildsGui() { using (var buildBar = new HeaderedVerticalLayout("Build")) { using (var buttonBar = new GUILayout.HorizontalScope()) { bool build = GUILayout.Button("Build"); GUI.enabled = !BuildTiltBrush.DoingBackgroundBuild; bool buildBackground = GUILayout.Button("Background Build"); GUI.enabled = BuildTiltBrush.DoingBackgroundBuild; if (GUILayout.Button("Cancel")) { BuildTiltBrush.TerminateBackgroundBuild(); } GUI.enabled = true; if (build) { EditorApplication.delayCall += () => { bool oldBackground = BuildTiltBrush.BackgroundBuild; try { BuildTiltBrush.BackgroundBuild = false; ResetBuildLog(); BuildStartTime = DateTime.Now; BuildTiltBrush.MenuItem_Build(); } finally { BuildTiltBrush.BackgroundBuild = oldBackground; } }; } if (buildBackground) { ResetBuildLog(); BuildStartTime = DateTime.Now; BuildTiltBrush.DoBackgroundBuild(BuildTiltBrush.GetGuiOptions(), false); } } using (var optionsBar = new GUILayout.HorizontalScope()) { UploadAfterBuild = GUILayout.Toggle(UploadAfterBuild, "Upload after Build"); RunAfterUpload = GUILayout.Toggle(RunAfterUpload, "Run after Upload"); } int start = Mathf.Clamp(m_buildLog.Count - 11, 0, int.MaxValue); if (m_buildLogPosition.HasValue) { start = m_buildLogPosition.Value; } if (m_buildLog.Count > 0) { int width = (int) (position.width - 35); int end = Mathf.Clamp(start + 10, 0, m_buildLog.Count); using (var horizSection = new GUILayout.HorizontalScope()) { using (var vertSection = new GUILayout.VerticalScope(GUILayout.Width(width))) { for (int i = start; i < end; ++i) { GUILayout.Label(m_buildLog[i], GUILayout.Width(width)); } } float size = 10f / m_buildLog.Count; float newStart = GUILayout.VerticalScrollbar(start, size, 0, m_buildLog.Count, GUILayout.Height(180)); if (newStart >= (m_buildLog.Count - 11f)) { m_buildLogPosition = null; } else { m_buildLogPosition = (int) newStart; } } } if (BuildTiltBrush.DoingBackgroundBuild) { Rect r = EditorGUILayout.BeginVertical(); float buildSeconds = (float) (DateTime.Now - BuildStartTime).TotalSeconds; float progress = Mathf.Clamp01(buildSeconds / SuccessfulBuildSeconds) * 0.95f; float remaining = SuccessfulBuildSeconds - buildSeconds; string time = "???"; if (remaining > 0) { var span = TimeSpan.FromSeconds(remaining); time = string.Format("{0}:{1:00}", (int) span.TotalMinutes, span.Seconds); } EditorGUI.ProgressBar(r, progress, string.Format("Building - {0} remaining.", time)); GUILayout.Space(18); EditorGUILayout.EndVertical(); } } } private void ResetBuildLog() { m_buildLogPosition = null; if (m_buildLogReader != null) { m_buildLogReader.Close(); } m_buildLogReader = null; m_buildLog.Clear(); } private void DeviceGui() { using (var droids = new HeaderedVerticalLayout("Android devices")) { foreach (string device in m_androidDevices) { bool selected = device == m_selectedAndroid; bool newSelected = GUILayout.Toggle(selected, device); if (selected != newSelected) { m_selectedAndroid = device; } } } } private void BuildActionsGui() { using (var builds = new HeaderedVerticalLayout("Build")) { EditorGUILayout.LabelField("Build Path", m_currentBuildPath); if (m_currentBuildTime.HasValue) { TimeSpan age = DateTime.Now - m_currentBuildTime.Value; EditorGUILayout.LabelField("Creation Time", m_currentBuildTime.Value.ToString()); StringBuilder textAge = new StringBuilder(); if (age.Days > 0) { textAge.AppendFormat("{0}d ", age.Days); } if (age.Hours > 0) { textAge.AppendFormat("{0}h ", age.Hours);} if (age.Minutes > 0) { textAge.AppendFormat("{0}m ", age.Minutes);} textAge.AppendFormat("{0}s", age.Seconds); EditorGUILayout.LabelField("Age", textAge.ToString()); if (BuildTiltBrush.GuiSelectedBuildTarget == BuildTarget.Android) { GUI.enabled = AndroidConnected && !BuildTiltBrush.DoingBackgroundBuild; m_upload.OnGUI(); m_launch.OnGUI(); m_turnOnAdbDebugging.OnGUI(); m_launchWithProfile.OnGUI(); m_terminate.OnGUI(); GUI.enabled = true; } } else { GUILayout.Label("Not built yet."); } } } private void ScanAndroidDevices() { if (m_deviceListFuture == null) { if ((DateTime.Now - m_timeOfLastDeviceScan).TotalSeconds > kSecondsBetweenDeviceScan && !EditorApplication.isPlaying) { m_deviceListFuture = new Future<string[]>(() => RunAdb("devices")); } } else { string[] results; if (m_deviceListFuture.TryGetResult(out results)) { m_androidDevices = results.Skip(1).Where(x => !string.IsNullOrEmpty(x.Trim())) .Select(x => x.Split(' ', '\t')[0]).ToArray(); if (m_androidDevices.Length != 0 && !m_androidDevices.Contains(m_selectedAndroid)) { m_selectedAndroid = m_androidDevices[0]; } m_deviceListFuture = null; Repaint(); m_timeOfLastDeviceScan = DateTime.Now; } } } private void OnBuildSettingsChanged() { m_currentBuildPath = BuildTiltBrush.GetAppPathForGuiBuild(); if (File.Exists(m_currentBuildPath)) { m_currentBuildTime = File.GetLastWriteTime(m_currentBuildPath); } else { m_currentBuildTime = null; } string exeName = Path.GetFileName(m_currentBuildPath); string exeTitle = Path.GetFileNameWithoutExtension(exeName); if (m_upload != null) { m_upload.Cancel(); } m_upload = new AndroidOperation( string.Format("Upload {0} to {1}", exeName, m_selectedAndroid), (results) => results.Any(x => x.StartsWith("Success")), "-s", m_selectedAndroid, "install", "-r", "-g", m_currentBuildPath ); if (m_launch != null) { m_launch.Cancel(); } m_launch = new AndroidOperation( string.Format("Launch {0}", exeName), (results) => results.Any(x => x.Contains("Starting: Intent")), "-s", m_selectedAndroid, "shell", "am", "start", string.Format("{0}/com.unity3d.player.UnityPlayerActivity", exeTitle) ); if (m_turnOnAdbDebugging != null) { m_turnOnAdbDebugging.Cancel(); } m_turnOnAdbDebugging = new AndroidOperation( "Turn on adb debugging/profiling", (results) => true, "-s", m_selectedAndroid, "forward", "tcp:34999", string.Format("localabstract:Unity-{0}", exeTitle) ); if (m_launchWithProfile != null) { m_launchWithProfile.Cancel(); } m_launchWithProfile = new AndroidOperation( string.Format("Launch with deep profile {0}", exeName), (results) => results.Any(x => x.Contains("Starting: Intent")), "-s", m_selectedAndroid, "shell", "am", "start", string.Format("{0}/com.unity3d.player.UnityPlayerActivity", exeTitle), "-e", "unity", "-deepprofiling" ); if (m_terminate != null) { m_terminate.Cancel(); } m_terminate = new AndroidOperation( string.Format("Terminate {0}", exeName), (results) => true, "-s", m_selectedAndroid, "shell", "am", "force-stop", exeTitle ); } public static string[] RunAdb(params string[] arguments) { var process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("adb.exe", String.Join(" ", arguments)); process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.Start(); process.WaitForExit(); return process.StandardOutput.ReadToEnd().Split('\n'). Concat(process.StandardError.ReadToEnd().Split('\n')).ToArray(); } private void Update() { if (BuildTiltBrush.GuiSelectedBuildTarget == BuildTarget.Android) { ScanAndroidDevices(); m_upload.Update(); m_launch.Update(); m_turnOnAdbDebugging.Update(); m_launchWithProfile.Update(); m_terminate.Update(); } UpdateBuildLog(); } private void UpdateBuildLog() { if (!BuildTiltBrush.DoingBackgroundBuild) { return; } if (m_buildLogReader == null) { if (!File.Exists(BuildTiltBrush.BackgroundBuildLogPath)) { return; } var fileStream = new FileStream(BuildTiltBrush.BackgroundBuildLogPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (fileStream == null) { return; } m_buildLogReader = new StreamReader(fileStream); } string line = null; while ((line = m_buildLogReader.ReadLine()) != null) { m_buildLog.Add(line); } } private void OnBuildComplete(int exitCode) { m_buildCompleteTime = DateTime.Now; OnBuildSettingsChanged(); Repaint(); if (UploadAfterBuild && exitCode == 0) { m_upload.Completed += OnUploadComplete; EditorApplication.delayCall += m_upload.Execute; } else { EditorApplication.delayCall += () => { NotifyBuildFinished("Build", exitCode); }; } } private void NotifyBuildFinished(string operation, int exitCode) { NotifyFlash(10, FlashFlags.Tray); if (exitCode == 0) { EditorUtility.DisplayDialog(operation, operation +" Complete", "OK"); SuccessfulBuildSeconds = (float)(m_buildCompleteTime - BuildStartTime).TotalSeconds; } else { EditorUtility.DisplayDialog(operation, string.Format("{0} failed with exit code {1}", operation, exitCode), "OK"); } NotifyFlash(1, FlashFlags.Stop); } private void OnUploadComplete(bool success) { if (success && RunAfterUpload) { m_launch.Completed += OnRunComplete; m_launch.Execute(); } else { EditorApplication.delayCall += () => { NotifyBuildFinished("Build and Upload", 0); }; } } private void OnRunComplete(bool success) { EditorApplication.delayCall += () => { NotifyBuildFinished("Build, Upload, and Launch", 0); }; } private float SuccessfulBuildSeconds { get { return EditorPrefs.GetFloat(kSuccessfulBuildTime, 300); } set { EditorPrefs.SetFloat(kSuccessfulBuildTime, Mathf.Lerp(value, SuccessfulBuildSeconds, 0.8f)); } } private DateTime BuildStartTime { get { string datetimeString = EditorPrefs.GetString(kBuildStartTime, null); if (string.IsNullOrEmpty(datetimeString)) { return DateTime.Now - TimeSpan.FromMinutes(1); } return DateTime.Parse(datetimeString); } set { EditorPrefs.SetString(kBuildStartTime, value.ToString()); } } #if UNITY_EDITOR_WIN [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern Int32 FlashWindowEx(ref FLASHWINFO pwfi); [System.Runtime.InteropServices.DllImport("user32.dll")] private static extern System.IntPtr GetActiveWindow(); [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public Int32 dwFlags; public UInt32 uCount; public Int32 dwTimeout; } #endif public enum FlashFlags { Stop = 0, // Stop flashing Titlebar = 1, // Flash the window title Tray = 2, // Flash the taskbar button Continuously = 4, // Flash continuously NoForeground = 8, // Stop flashing if window comes to the foreground } private IntPtr GetActiveWindowHandle() { #if UNITY_EDITOR_WIN return GetActiveWindow(); #else return IntPtr.Zero; #endif } private void NotifyFlash(uint numFlashes, params FlashFlags[] flags) { #if UNITY_EDITOR_WIN int flagInt = flags.Cast<int>().Sum(); FLASHWINFO fw = new FLASHWINFO(); fw.cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(FLASHWINFO))); fw.hwnd = m_hwnd; fw.dwFlags = flagInt; fw.uCount = numFlashes; FlashWindowEx(ref fw); #endif } } }
using System; using System.Collections.Generic; using Lucene.Net.Attributes; using Lucene.Net.Documents; using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using Lucene.Net.Util; using NUnit.Framework; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Search { using BinaryDocValuesField = BinaryDocValuesField; using BytesRef = Lucene.Net.Util.BytesRef; /* * 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 Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using DoubleField = DoubleField; using English = Lucene.Net.Util.English; using Field = Field; using SingleDocValuesField = SingleDocValuesField; using SingleField = SingleField; using IndexReader = Lucene.Net.Index.IndexReader; using Int32Field = Int32Field; using Int64Field = Int64Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using NumericDocValuesField = NumericDocValuesField; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SortedDocValuesField = SortedDocValuesField; using StoredField = StoredField; using Term = Lucene.Net.Index.Term; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// Tests IndexSearcher's searchAfter() method /// </summary> [TestFixture] public class TestSearchAfter : LuceneTestCase { private bool isVerbose = false; private Directory Dir; private IndexReader Reader; private IndexSearcher Searcher; // LUCENENET specific - need to execute this AFTER the base setup, or it won't be right //internal bool supportsDocValues = Codec.Default.Name.Equals("Lucene3x") == false; private int Iter; private IList<SortField> AllSortFields; [SetUp] public override void SetUp() { base.SetUp(); // LUCENENET specific: Moved this logic here to ensure that it is executed // after the class is setup - a field is way to early to execute this. bool supportsDocValues = Codec.Default.Name.Equals("Lucene3x") == false; AllSortFields = new List<SortField>(Arrays.AsList(new SortField[] { #pragma warning disable 612,618 new SortField("byte", SortFieldType.BYTE, false), new SortField("short", SortFieldType.INT16, false), #pragma warning restore 612,618 new SortField("int", SortFieldType.INT32, false), new SortField("long", SortFieldType.INT64, false), new SortField("float", SortFieldType.SINGLE, false), new SortField("double", SortFieldType.DOUBLE, false), new SortField("bytes", SortFieldType.STRING, false), new SortField("bytesval", SortFieldType.STRING_VAL, false), #pragma warning disable 612,618 new SortField("byte", SortFieldType.BYTE, true), new SortField("short", SortFieldType.INT16, true), #pragma warning restore 612,618 new SortField("int", SortFieldType.INT32, true), new SortField("long", SortFieldType.INT64, true), new SortField("float", SortFieldType.SINGLE, true), new SortField("double", SortFieldType.DOUBLE, true), new SortField("bytes", SortFieldType.STRING, true), new SortField("bytesval", SortFieldType.STRING_VAL, true), SortField.FIELD_SCORE, SortField.FIELD_DOC })); if (supportsDocValues) { AllSortFields.AddRange(Arrays.AsList(new SortField[] { new SortField("intdocvalues", SortFieldType.INT32, false), new SortField("floatdocvalues", SortFieldType.SINGLE, false), new SortField("sortedbytesdocvalues", SortFieldType.STRING, false), new SortField("sortedbytesdocvaluesval", SortFieldType.STRING_VAL, false), new SortField("straightbytesdocvalues", SortFieldType.STRING_VAL, false), new SortField("intdocvalues", SortFieldType.INT32, true), new SortField("floatdocvalues", SortFieldType.SINGLE, true), new SortField("sortedbytesdocvalues", SortFieldType.STRING, true), new SortField("sortedbytesdocvaluesval", SortFieldType.STRING_VAL, true), new SortField("straightbytesdocvalues", SortFieldType.STRING_VAL, true) })); } // Also test missing first / last for the "string" sorts: foreach (string field in new string[] { "bytes", "sortedbytesdocvalues" }) { for (int rev = 0; rev < 2; rev++) { bool reversed = rev == 0; SortField sf = new SortField(field, SortFieldType.STRING, reversed); sf.MissingValue = SortField.STRING_FIRST; AllSortFields.Add(sf); sf = new SortField(field, SortFieldType.STRING, reversed); sf.MissingValue = SortField.STRING_LAST; AllSortFields.Add(sf); } } int limit = AllSortFields.Count; for (int i = 0; i < limit; i++) { SortField sf = AllSortFields[i]; if (sf.Type == SortFieldType.INT32) { SortField sf2 = new SortField(sf.Field, SortFieldType.INT32, sf.IsReverse); sf2.MissingValue = Random().Next(); AllSortFields.Add(sf2); } else if (sf.Type == SortFieldType.INT64) { SortField sf2 = new SortField(sf.Field, SortFieldType.INT64, sf.IsReverse); sf2.MissingValue = Random().NextLong(); AllSortFields.Add(sf2); } else if (sf.Type == SortFieldType.SINGLE) { SortField sf2 = new SortField(sf.Field, SortFieldType.SINGLE, sf.IsReverse); sf2.MissingValue = (float)Random().NextDouble(); AllSortFields.Add(sf2); } else if (sf.Type == SortFieldType.DOUBLE) { SortField sf2 = new SortField(sf.Field, SortFieldType.DOUBLE, sf.IsReverse); sf2.MissingValue = Random().NextDouble(); AllSortFields.Add(sf2); } } Dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter(Random(), Dir, Similarity, TimeZone); int numDocs = AtLeast(200); for (int i = 0; i < numDocs; i++) { IList<Field> fields = new List<Field>(); fields.Add(NewTextField("english", English.IntToEnglish(i), Field.Store.NO)); fields.Add(NewTextField("oddeven", (i % 2 == 0) ? "even" : "odd", Field.Store.NO)); fields.Add(NewStringField("byte", "" + ((sbyte)Random().Next()), Field.Store.NO)); fields.Add(NewStringField("short", "" + ((short)Random().Next()), Field.Store.NO)); fields.Add(new Int32Field("int", Random().Next(), Field.Store.NO)); fields.Add(new Int64Field("long", Random().NextLong(), Field.Store.NO)); fields.Add(new SingleField("float", (float)Random().NextDouble(), Field.Store.NO)); fields.Add(new DoubleField("double", Random().NextDouble(), Field.Store.NO)); fields.Add(NewStringField("bytes", TestUtil.RandomRealisticUnicodeString(Random()), Field.Store.NO)); fields.Add(NewStringField("bytesval", TestUtil.RandomRealisticUnicodeString(Random()), Field.Store.NO)); fields.Add(new DoubleField("double", Random().NextDouble(), Field.Store.NO)); if (supportsDocValues) { fields.Add(new NumericDocValuesField("intdocvalues", Random().Next())); fields.Add(new SingleDocValuesField("floatdocvalues", (float)Random().NextDouble())); fields.Add(new SortedDocValuesField("sortedbytesdocvalues", new BytesRef(TestUtil.RandomRealisticUnicodeString(Random())))); fields.Add(new SortedDocValuesField("sortedbytesdocvaluesval", new BytesRef(TestUtil.RandomRealisticUnicodeString(Random())))); fields.Add(new BinaryDocValuesField("straightbytesdocvalues", new BytesRef(TestUtil.RandomRealisticUnicodeString(Random())))); } Document document = new Document(); document.Add(new StoredField("id", "" + i)); if (isVerbose) { Console.WriteLine(" add doc id=" + i); } foreach (Field field in fields) { // So we are sometimes missing that field: if (Random().Next(5) != 4) { document.Add(field); if (isVerbose) { Console.WriteLine(" " + field); } } } iw.AddDocument(document); if (Random().Next(50) == 17) { iw.Commit(); } } Reader = iw.Reader; iw.Dispose(); Searcher = NewSearcher(Reader); if (isVerbose) { Console.WriteLine(" searcher=" + Searcher); } } [TearDown] public override void TearDown() { Reader.Dispose(); Dir.Dispose(); base.TearDown(); } [Test, LongRunningTest] public virtual void TestQueries() { // LUCENENET specific: NUnit will crash with an OOM if we do the full test // with verbosity enabled. So, making this a manual setting that can be // turned on if, and only if, needed for debugging. If the setting is turned // on, we are decresing the number of iterations to only 1, which seems to // keep it from crashing. // Enable verbosity at the top of this file: isVerbose = true; // because the first page has a null 'after', we get a normal collector. // so we need to run the test a few times to ensure we will collect multiple // pages. int n = isVerbose ? 1 : AtLeast(20); for (int i = 0; i < n; i++) { Filter odd = new QueryWrapperFilter(new TermQuery(new Term("oddeven", "odd"))); AssertQuery(new MatchAllDocsQuery(), null); AssertQuery(new TermQuery(new Term("english", "one")), null); AssertQuery(new MatchAllDocsQuery(), odd); AssertQuery(new TermQuery(new Term("english", "four")), odd); BooleanQuery bq = new BooleanQuery(); bq.Add(new TermQuery(new Term("english", "one")), Occur.SHOULD); bq.Add(new TermQuery(new Term("oddeven", "even")), Occur.SHOULD); AssertQuery(bq, null); } } internal virtual void AssertQuery(Query query, Filter filter) { AssertQuery(query, filter, null); AssertQuery(query, filter, Sort.RELEVANCE); AssertQuery(query, filter, Sort.INDEXORDER); foreach (SortField sortField in AllSortFields) { AssertQuery(query, filter, new Sort(new SortField[] { sortField })); } for (int i = 0; i < 20; i++) { AssertQuery(query, filter, RandomSort); } } internal virtual Sort RandomSort { get { SortField[] sortFields = new SortField[TestUtil.NextInt(Random(), 2, 7)]; for (int i = 0; i < sortFields.Length; i++) { sortFields[i] = AllSortFields[Random().Next(AllSortFields.Count)]; } return new Sort(sortFields); } } internal virtual void AssertQuery(Query query, Filter filter, Sort sort) { int maxDoc = Searcher.IndexReader.MaxDoc; TopDocs all; int pageSize = TestUtil.NextInt(Random(), 1, maxDoc * 2); if (isVerbose) { Console.WriteLine("\nassertQuery " + (Iter++) + ": query=" + query + " filter=" + filter + " sort=" + sort + " pageSize=" + pageSize); } bool doMaxScore = Random().NextBoolean(); bool doScores = Random().NextBoolean(); if (sort == null) { all = Searcher.Search(query, filter, maxDoc); } else if (sort == Sort.RELEVANCE) { all = Searcher.Search(query, filter, maxDoc, sort, true, doMaxScore); } else { all = Searcher.Search(query, filter, maxDoc, sort, doScores, doMaxScore); } if (isVerbose) { Console.WriteLine(" all.TotalHits=" + all.TotalHits); int upto = 0; foreach (ScoreDoc scoreDoc in all.ScoreDocs) { Console.WriteLine(" hit " + (upto++) + ": id=" + Searcher.Doc(scoreDoc.Doc).Get("id") + " " + scoreDoc); } } int pageStart = 0; ScoreDoc lastBottom = null; while (pageStart < all.TotalHits) { TopDocs paged; if (sort == null) { if (isVerbose) { Console.WriteLine(" iter lastBottom=" + lastBottom); } paged = Searcher.SearchAfter(lastBottom, query, filter, pageSize); } else { if (isVerbose) { Console.WriteLine(" iter lastBottom=" + lastBottom); } if (sort == Sort.RELEVANCE) { paged = Searcher.SearchAfter(lastBottom, query, filter, pageSize, sort, true, doMaxScore); } else { paged = Searcher.SearchAfter(lastBottom, query, filter, pageSize, sort, doScores, doMaxScore); } } if (isVerbose) { Console.WriteLine(" " + paged.ScoreDocs.Length + " hits on page"); } if (paged.ScoreDocs.Length == 0) { break; } AssertPage(pageStart, all, paged); pageStart += paged.ScoreDocs.Length; lastBottom = paged.ScoreDocs[paged.ScoreDocs.Length - 1]; } Assert.AreEqual(all.ScoreDocs.Length, pageStart); } internal virtual void AssertPage(int pageStart, TopDocs all, TopDocs paged) { Assert.AreEqual(all.TotalHits, paged.TotalHits); for (int i = 0; i < paged.ScoreDocs.Length; i++) { ScoreDoc sd1 = all.ScoreDocs[pageStart + i]; ScoreDoc sd2 = paged.ScoreDocs[i]; if (isVerbose) { Console.WriteLine(" hit " + (pageStart + i)); Console.WriteLine(" expected id=" + Searcher.Doc(sd1.Doc).Get("id") + " " + sd1); Console.WriteLine(" actual id=" + Searcher.Doc(sd2.Doc).Get("id") + " " + sd2); } Assert.AreEqual(sd1.Doc, sd2.Doc); Assert.AreEqual(sd1.Score, sd2.Score, 0f); if (sd1 is FieldDoc) { Assert.IsTrue(sd2 is FieldDoc); Assert.AreEqual(((FieldDoc)sd1).Fields, ((FieldDoc)sd2).Fields); } } } } }
// 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; /// <summary> /// System.Enum.ToObject(Type,object value) /// </summary> public class EnumToObject { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Return the enum object whose value is -100 "); try { object o1 = Enum.ToObject(typeof(color), -100); if ((color)o1 != color.blue) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Return the enum object whose value is -0"); try { object o1 = Enum.ToObject(typeof(color), -0); if ((color)o1 != color.white) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Return the enum object whose value is int32.maxvalue"); try { object o1 = Enum.ToObject(typeof(e_test), Int32.MaxValue); if ((e_test)o1 != e_test.itemA) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Return the enum object whose value is int64.MinValue "); try { object o1 = Enum.ToObject(typeof(e_test), Int64.MinValue); if ((e_test)o1 != e_test.itemC) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Test the situation when none of the value could match the value of the enum"); try { object o1 = Enum.ToObject(typeof(e_test), 1); if (((e_test)o1).ToString() != "1") { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The type of the enum is null reference "); try { object o1 = Enum.ToObject(null, -100); TestLibrary.TestFramework.LogError("101", "The ArgumentNullException was not thrown as expected"); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: The first argument is not a type of enum "); try { object o1 = Enum.ToObject(typeof(Array), 0); TestLibrary.TestFramework.LogError("103", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: The type of the value is invalid"); try { object o1 = Enum.ToObject(typeof(e_test), "itemC"); TestLibrary.TestFramework.LogError("105", "The ArgumentException was not thrown as expected"); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { EnumToObject test = new EnumToObject(); TestLibrary.TestFramework.BeginTestCase("EnumToObject"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } enum color { blue = -100, white = -0, red = 0, } enum e_test : long { itemA = Int32.MaxValue, itemB = Int32.MinValue, itemC = Int64.MinValue, itemD = -0, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; #pragma warning disable 414 #pragma warning disable 67 #pragma warning disable 3009 #pragma warning disable 3016 #pragma warning disable 3001 #pragma warning disable 3015 #pragma warning disable 169 #pragma warning disable 649 [assembly: SampleMetadata.SimpleStringCa("assembly")] public class SimpleTopLevelClass { public void MethodWithDefaultParamValue(int a1 = 32) { } } namespace SampleMetadata { public class Outer { public class Inner { public class ReallyInner { } } } public class Outer2 { public class Inner2 { protected class ProtectedInner { } internal class InternalInner { } private class PrivateInner { } } private class PrivateInner2 { public class ReallyInner2 { } } } internal class Hidden { public class PublicInsideHidden { } } public class SimpleGenericType<T> { } [SimpleStringCa("type")] public class GenericTypeWithThreeParameters<X, Y, Z> { public GenericTypeWithThreeParameters(int x) { } [SimpleStringCa("ctor")] private GenericTypeWithThreeParameters(String s) { } [return: SimpleStringCa("return")] public void SimpleMethod() { } [SimpleStringCa("method")] public M SimpleGenericMethod<M, N>(X arg1, N arg2) { throw null; } public X SimpleReadOnlyProperty { get { throw null; } } [SimpleStringCa("property")] public Y SimpleMutableProperty { get { throw null; } [SimpleStringCa("setter")] set { throw null; } } [IndexerName("SimpleIndexedProperty")] public X this[int i1, Y i2] { get { throw null; } } public int MyField1; [SimpleStringCa("field")] public static String MyField2; private double MyField3 = 0.0; [SimpleStringCa("event")] public event Action SimpleEvent { add { throw null; } remove { throw null; } } [SimpleStringCa("nestedtype")] public class InnerType { } public class InnerGenericType<W> { } static GenericTypeWithThreeParameters() { } } public class Derived : SampleMetadata.Extra.Deep.BaseContainer.SubmergedBaseClass { } public interface IFoo { } public interface IBar { } public interface IComplex : IFoo, IBar, IList, IEnumerable { } public class CFoo : IFoo { } public class GenericTypeWithConstraints<A, B, C, D, E, F, G, H, AA, BB, CC, DD, EE, FF, GG, HH> where B : CFoo, IList where C : IList where D : struct where E : class where F : new() where G : class, new() where H : IList, new() where AA : A where BB : B where CC : C // where DD : D // cannot use a "struct"-constrainted generic parameter as a constraint. where EE : E where FF : F where GG : G where HH : H { } public struct SimpleStruct { } public struct SimpleGenericStruct<T> { } public interface ISimpleGenericInterface<T> { } public class MethodContainer<T> { public String Moo(int i, T g, String[] s, IEnumerable<String> e, ref double d, out Object o) { throw null; } [IndexerName("SimpleIndexedSetterOnlyProperty")] public int this[String i1, T i2] { set { throw null; } } } public enum SimpleEnum { Red = 1, Blue = 2, Green = 3, Green_a = 3, Green_b = 3, } public enum ByteEnum : byte { Min = 0, One = 1, Two = 2, Max = 0xff, } public enum SByteEnum : sbyte { Min = -128, One = 1, Two = 2, Max = 127, } public enum UInt16Enum : ushort { Min = 0, One = 1, Two = 2, Max = 0xffff, } public enum Int16Enum : short { Min = unchecked((short)0x8000), One = 1, Two = 2, Max = 0x7fff, } public enum UInt32Enum : uint { Min = 0, One = 1, Two = 2, Max = 0xffffffff, } public enum Int32Enum : int { Min = unchecked((int)0x80000000), One = 1, Two = 2, Max = 0x7fffffff, } public enum UInt64Enum : ulong { Min = 0, One = 1, Two = 2, Max = 0xffffffffffffffff, } public enum Int64Enum : long { Min = unchecked((long)0x8000000000000000L), One = 1, Two = 2, Max = 0x7fffffffffffffff, } public class SimpleCaAttribute : Attribute { public SimpleCaAttribute() { } } public class SimpleStringCaAttribute : Attribute { public SimpleStringCaAttribute(String s) { } } public class SimpleCaWithBigCtorAttribute : Attribute { public SimpleCaWithBigCtorAttribute(bool b, char c, float f, double d, sbyte sb, short sh, int i, long l, byte by, ushort us, uint ui, ulong ul, String s, Type t) { } } public class SimpleArrayCaAttribute : Attribute { public SimpleArrayCaAttribute(bool[] b) { } public SimpleArrayCaAttribute(char[] b) { } public SimpleArrayCaAttribute(float[] b) { } public SimpleArrayCaAttribute(double[] b) { } public SimpleArrayCaAttribute(sbyte[] b) { } public SimpleArrayCaAttribute(short[] b) { } public SimpleArrayCaAttribute(int[] b) { } public SimpleArrayCaAttribute(long[] b) { } public SimpleArrayCaAttribute(byte[] b) { } public SimpleArrayCaAttribute(ushort[] b) { } public SimpleArrayCaAttribute(uint[] b) { } public SimpleArrayCaAttribute(ulong[] b) { } public SimpleArrayCaAttribute(String[] b) { } public SimpleArrayCaAttribute(Type[] b) { } } public class SimpleObjectArrayCaAttribute : Attribute { public SimpleObjectArrayCaAttribute(object[] o) { } } public class SimpleEnumCaAttribute : Attribute { public SimpleEnumCaAttribute(SimpleEnum e) { } public SimpleEnumCaAttribute(SimpleEnum[] e) { } } public class AnnoyingSpecialCaseAttribute : Attribute { public AnnoyingSpecialCaseAttribute(Object o) { } public Object Oops; } public class SimpleCaWithNamedParametersAttribute : Attribute { public SimpleCaWithNamedParametersAttribute(int i, String s) { } public double DParameter; public Type TParameter { get; set; } } [SimpleCaWithBigCtor(true, 'c', (float)1.5f, 1.5, (sbyte)(-2), (short)(-2), (int)(-2), (long)(-2), (byte)0xfe, (ushort)0xfedc, (uint)0xfedcba98, (ulong)0xfedcba9876543210, "Hello", typeof(IEnumerable<String>))] public class CaHolder { [AnnoyingSpecialCase(SimpleEnum.Blue, Oops = SimpleEnum.Red)] public class ObjectCa { } [SimpleObjectArrayCa(new object[] { SimpleEnum.Red, 123 })] public class ObjectArrayCa { } [SimpleEnumCa(SimpleEnum.Green)] public class EnumCa { } [SimpleEnumCa(new SimpleEnum[] { SimpleEnum.Green, SimpleEnum.Red })] public class EnumArray { } [SimpleCaWithNamedParameters(42, "Yo", DParameter = 2.3, TParameter = typeof(IList<String>))] public class Named { } [SimpleArrayCa(new bool[] { true, false, true, true, false, false, false, true })] public class BoolArray { } [SimpleArrayCa(new char[] { 'a', 'b', 'c', 'd', 'e' })] public class CharArray { } [SimpleArrayCa(new byte[] { 1, 2, 0xfe, 0xff })] public class ByteArray { } [SimpleArrayCa(new sbyte[] { 1, 2, -2, -1 })] public class SByteArray { } [SimpleArrayCa(new ushort[] { 1, 2, 0xfedc })] public class UShortArray { } [SimpleArrayCa(new short[] { 1, 2, -2, -1 })] public class ShortArray { } [SimpleArrayCa(new uint[] { 1, 2, 0xfedcba98 })] public class UIntArray { } [SimpleArrayCa(new int[] { 1, 2, -2, -1 })] public class IntArray { } [SimpleArrayCa(new ulong[] { 1, 2, 0xfedcba9876543210 })] public class ULongArray { } [SimpleArrayCa(new long[] { 1, 2, -2, -1 })] public class LongArray { } [SimpleArrayCa(new float[] { 1.2f, 3.5f })] public class FloatArray { } [SimpleArrayCa(new double[] { 1.2, 3.5 })] public class DoubleArray { } [SimpleArrayCa(new String[] { "Hello", "There" })] public class StringArray { } [SimpleArrayCa(new Type[] { typeof(Object), typeof(String), null })] public class TypeArray { } } public class DefaultValueHolder { public static void LotsaDefaults( bool b = true, char c = 'a', sbyte sb = -2, byte by = 0xfe, short sh = -2, ushort ush = 0xfedc, int i = -2, uint ui = 0xfedcba98, long l = -2, ulong ul = 0xfedcba9876543210, float f = 1.5f, double d = 1.5, String s = "Hello", String sn = null, Object o = null, SimpleEnum e = SimpleEnum.Blue ) { } } public class SimpleIntCustomAttributeAttribute : Attribute { public SimpleIntCustomAttributeAttribute(int a1) { } } [SimpleIntCustomAttribute(32)] public class SimpleTypeWithCustomAttribute { [SimpleIntCustomAttribute(64)] public void SimpleMethodWithCustomAttribute() { } } public interface IMethodImplTest { void MethodImplFunc(); } public class MethodImplTest : IMethodImplTest { void IMethodImplTest.MethodImplFunc() { } } public class GenericOutside<S> { public class Inside { public class ReallyInside<I> { public S TypeS_Field; public I TypeI_Field; public class Really2Inside { public class Really3Inside<D> { public class Really4Inside<O> { public GenericTypeWithThreeParameters<S, I, D> TypeSID_Field; public GenericTypeWithThreeParameters<S, I, O> TypeSIO_Field; } } } } } } public class NonGenericOutside { public class GenericInside<T> { } } public static class SimpleStaticClass { public class NestedInsideSimpleStatic { } public static void Foo(int x) { } } public static class SimpleGenericStaticClass<T> { public class NestedInsideSimpleStatic { } public static void Foo(T x) { } } } namespace SampleMetadata.Extra.Deep { public class BaseContainer { [SimpleStringCa("base")] public class SubmergedBaseClass { } } } namespace SampleMetadata { // Create two types with the exact same shape. Ensure that MdTranform and Reflection can // distinguish the members. public class DoppleGanger1 { public DoppleGanger1() { } public void Moo() { } public int Field; public int Prop { get; set; } public event Action Event { add { throw null; } remove { throw null; } } public class NestedType { } } public class DoppleGanger2 { public DoppleGanger2() { } public void Moo() { } public int Field; public int Prop { get; set; } public event Action Event { add { throw null; } remove { throw null; } } public class NestedType { } } } namespace SampleMetadata { // Create two types with "identical" methods. public class ProtoType { [SimpleStringCa("1")] public void Meth() { } public void Foo([SimpleStringCa("p1")] int twin, Object differentTypes) { } } public class Similar { [SimpleStringCa("2")] public void Meth() { } public void Foo([SimpleStringCa("p2")] int twin, String differentTypes) { } } } namespace SampleMetadata { public class MethodFamilyIsInstance { public void MethodFamily() { } } public class MethodFamilyIsStatic { public static void MethodFamily() { } } public class MethodFamilyIsPrivate { private void MethodFamily() { } } public class MethodFamilyIsGeneric { public void MethodFamily<M1>() where M1 : IEquatable<M1> { } } public class MethodFamilyIsAlsoGeneric { public void MethodFamily<M2>() where M2 : IEquatable<M2> { } } public class MethodFamilyIsUnary { public void MethodFamily(int m) { } } public class MethodFamilyReturnsSomething { public String MethodFamily() { return null; } } public class MethodFamilyHasCtor1 { [Circular(1)] public void MethodFamily() { } } public class MethodFamilyHasCtor2 { [Circular(2)] public void MethodFamily() { } } } namespace SampleMetadata { [Circular(1)] public class CircularAttribute : Attribute { [Circular(2)] public CircularAttribute([Circular(3)] int x) { } } } namespace SampleMetadata.NS1 { public class Twin { } } namespace SampleMetadata.NS2 { public class Twin { } } namespace SampleMetadata { public class FieldInvokeSampleBase { public String InheritedField; } public class FieldInvokeSample : FieldInvokeSampleBase { public String InstanceField; public static String StaticField; public const int LiteralInt32Field = 42; public const SimpleEnum LiteralEnumField = SimpleEnum.Green; public const String LiteralStringField = "Hello"; public const Object LiteralNullField = null; } public class PropertyInvokeSample { public PropertyInvokeSample(String name) { this.Name = name; } public String InstanceProperty { get; set; } public static String StaticProperty { get; set; } public String ReadOnlyInstanceProperty { get { return "rip:"; } } public static String ReadOnlyStaticProperty { get { return "rsp"; } } [IndexerName("IndexedProperty")] public String this[int i1, int i2] { get { return _indexed; } set { _indexed = value; } } private String _indexed; public String Name; } public class MethodInvokeSample { public MethodInvokeSample(String name) { this.Name = name; } public void InstanceMethod(int x, String s) { } public void InstanceMethodWithSingleParameter(String s) { } public static void StaticMethod(int x, String s) { } public String InstanceFunction(int x, String s) { throw null; } public static String StaticFunction(int x, String s) { throw null; } public static String LastStaticCall { get; set; } public String LastCall { get; set; } public String Name; } } namespace SampleMetadataEx { public enum Color { Red = 1, Green = 2, Blue = 3, } //========================================================================================= //========================================================================================= public class DataTypeTestAttribute : Attribute { public DataTypeTestAttribute(int i, String s, Type t, Color c, int[] iArray, String[] sArray, Type[] tArray, Color[] cArray) { this.I = i; this.S = s; this.T = t; this.C = c; this.IArray = iArray; this.SArray = sArray; this.TArray = tArray; this.CArray = cArray; } public int I { get; private set; } public String S { get; private set; } public Type T { get; private set; } public Color C { get; private set; } public int[] IArray { get; private set; } public String[] SArray { get; private set; } public Type[] TArray { get; private set; } public Color[] CArray { get; private set; } } //========================================================================================= // Named arguments. //========================================================================================= public class NamedArgumentsAttribute : Attribute { public NamedArgumentsAttribute() { } public int F1; public Color F2; public int P1 { get; set; } public Color P2 { get; set; } } //========================================================================================= // The annoying special case where the formal parameter type is Object. //========================================================================================= public class ObjectTypeTestAttribute : Attribute { public ObjectTypeTestAttribute(Object o) { this.O = o; } public Object O { get; private set; } public Object F; public Object P { get; set; } } public class BaseAttribute : Attribute { public BaseAttribute(String s) { S = s; } public BaseAttribute(String s, int i) { } public int F; public int P { get; set; } public String S { get; private set; } public sealed override String ToString() { throw null; } } public class MidAttribute : BaseAttribute { public MidAttribute(String s) : base(s) { } public MidAttribute(String s, int i) : base(s, i) { } public new int F; public new int P { get; set; } } public class DerivedAttribute : MidAttribute { public DerivedAttribute(String s) : base(s) { } public new int F; public new int P { get; set; } } public class NonInheritableAttribute : BaseAttribute { public NonInheritableAttribute(String s) : base(s) { } } public class BaseAmAttribute : Attribute { public BaseAmAttribute(String s) { S = s; } public BaseAmAttribute(String s, int i) { } public String S { get; private set; } public sealed override String ToString() { throw null; } } public class MidAmAttribute : BaseAmAttribute { public MidAmAttribute(String s) : base(s) { } } public class DerivedAmAttribute : MidAmAttribute { public DerivedAmAttribute(String s) : base(s) { } } } namespace SampleMetadataEx { public class CaHolder { [DataTypeTest( 42, "FortyTwo", typeof(IList<String>), Color.Green, new int[] { 1, 2, 3 }, new String[] { "One", "Two", "Three" }, new Type[] { typeof(int), typeof(String) }, new Color[] { Color.Red, Color.Blue } )] public int DataTypeTest = 1; [NamedArguments(F1 = 42, F2 = Color.Blue, P1 = 77, P2 = Color.Green)] public int NamedArgumentsTest = 1; [ObjectTypeTest(Color.Red, F = Color.Blue, P = Color.Green)] public int ObjectTest = 1; [Base("B", F = 1, P = 2)] public int BaseTest = 1; [Mid("M", F = 5, P = 6)] public int MidTest = 1; [Derived("D", F = 8, P = 9)] public int DerivedTest = 1; } [BaseAttribute("[Base]SearchType.Field")] [MidAttribute("[Mid]SearchType.Field")] [DerivedAttribute("[Derived]SearchType.Field")] public class SearchType1 { public int Field; } [BaseAttribute("[Base]B")] [MidAttribute("[Mid]B", 42)] // This is hidden by down-level MidAttributes, even though the down-level MidAttributes are using a different .ctor [DerivedAttribute("[Derived]B")] [BaseAmAttribute("[BaseAm]B")] [MidAmAttribute("[MidAm]B")] [DerivedAmAttribute("[DerivedAm]B")] public abstract class B { [BaseAm("[BaseAm]B.M1()")] public virtual void M1([BaseAm("[BaseAm]B.M1.x")] int x) { } [BaseAm("[BaseAm]B.M2()")] public void M2([BaseAm("[BaseAm]B.M2.x")] int x) { } [BaseAm("[BaseAm]B.P1")] public virtual int P1 { get; set; } [BaseAm("[BaseAm]B.P2")] public int P2 { get; set; } [BaseAm("[BaseAm]B.E1")] public virtual event Action E1 { add { } remove { } } [BaseAm("[BaseAm]B.E2")] public event Action E2 { add { } remove { } } } [NonInheritable("[Noninheritable]M")] [MidAttribute("[Mid]M")] [DerivedAttribute("[Derived]M")] [MidAmAttribute("[MidAm]M")] [DerivedAmAttribute("[DerivedAm]M")] public abstract class M : B { public override void M1(int x) { } public override int P1 { get; set; } public override event Action E1 { add { } remove { } } } [DerivedAttribute("[Derived]D")] [DerivedAmAttribute("[DerivedAm]D")] public abstract class D : M, ID { public void Foo() { } public new virtual void M1(int x) { } public new void M2(int x) { } public new virtual int P1 { get; set; } public new int P2 { get; set; } public new virtual event Action E1 { add { } remove { } } public new event Action E2 { add { } remove { } } } // These attributes won't be inherited as the CA inheritance only walks base classes, not interfaces. [BaseAttribute("[Base]ID")] [MidAttribute("[Mid]ID")] [DerivedAttribute("[Derived]ID")] [BaseAmAttribute("[BaseAm]ID")] [MidAmAttribute("[MidAm]ID")] [DerivedAmAttribute("[DerivedAm]ID")] public interface ID { [BaseAmAttribute("[BaseAm]ID.Foo()")] void Foo(); } } namespace SampleMetadataRex { public class DelegateBinding { public static void M1() { } public static void M2() { } } public class MethodLookup { public void Moo(int x) { } public void Moo(String s) { } public void Moo(String s, int x) { } } public interface IFoo { void Foo(); void Hidden(); int FooProp { get; set; } event Action FooEvent; } public interface IBar : IFoo { void Bar(); new void Hidden(); } public abstract class CBar : IBar { public void Bar() { } public void Hidden() { } public void Foo() { } public int FooProp { get { throw null; } set { throw null; } } public event Action FooEvent { add { } remove { } } } public abstract class Base { // Instance fields public int B_InstFieldPublic; protected int B_InstFieldFamily; private int B_InstFieldPrivate; internal int B_InstFieldAssembly; protected internal int B_InstFieldFamOrAssembly; // Hidden fields public int B_HiddenFieldPublic; protected int B_HiddenFieldFamily; private int B_HiddenFieldPrivate; internal int B_HiddenFieldAssembly; protected internal int B_HiddenFieldFamOrAssembly; // Static fields public static int B_StaticFieldPublic; protected static int B_StaticFieldFamily; private static int B_StaticFieldPrivate; internal static int B_StaticFieldAssembly; protected internal static int B_StaticFieldFamOrAssembly; // Instance methods public void B_InstMethPublic() { } protected void B_InstMethFamily() { } private void B_InstMethPrivate() { } internal void B_InstMethAssembly() { } protected internal void B_InstMethFamOrAssembly() { } // Hidden methods public void B_HiddenMethPublic() { } protected void B_HiddenMethFamily() { } private void B_HiddenMethPrivate() { } internal void B_HiddenMethAssembly() { } protected internal void B_HiddenMethFamOrAssembly() { } // Static methods public static void B_StaticMethPublic() { } protected static void B_StaticMethFamily() { } private static void B_StaticMethPrivate() { } internal static void B_StaticMethAssembly() { } protected internal static void B_StaticMethFamOrAssembly() { } // Virtual methods public virtual void B_VirtualMethPublic() { } protected virtual void B_VirtualMethFamily() { } internal virtual void B_VirtualMethAssembly() { } protected virtual internal void B_VirtualMethFamOrAssembly() { } // Instance properties public int B_InstPropPublic { get { return 5; } } protected int B_InstPropFamily { get { return 5; } } private int B_InstPropPrivate { get { return 5; } } internal int B_InstPropAssembly { get { return 5; } } protected internal int B_InstPropFamOrAssembly { get { return 5; } } // Hidden properties public int B_HiddenPropPublic { get { return 5; } } protected int B_HiddenPropFamily { get { return 5; } } private int B_HiddenPropPrivate { get { return 5; } } internal int B_HiddenPropAssembly { get { return 5; } } protected internal int B_HiddenPropFamOrAssembly { get { return 5; } } // Static properties public static int B_StaticPropPublic { get { return 5; } } protected static int B_StaticPropFamily { get { return 5; } } private static int B_StaticPropPrivate { get { return 5; } } internal static int B_StaticPropAssembly { get { return 5; } } protected internal static int B_StaticPropFamOrAssembly { get { return 5; } } // Virtual properties public virtual int B_VirtualPropPublic { get { return 5; } } protected virtual int B_VirtualPropFamily { get { return 5; } } internal virtual int B_VirtualPropAssembly { get { return 5; } } protected virtual internal int B_VirtualPropFamOrAssembly { get { return 5; } } // Instance events public event Action B_InstEventPublic { add { } remove { } } protected event Action B_InstEventFamily { add { } remove { } } private event Action B_InstEventPrivate { add { } remove { } } internal event Action B_InstEventAssembly { add { } remove { } } protected internal event Action B_InstEventFamOrAssembly { add { } remove { } } // Hidden events public event Action B_HiddenEventPublic { add { } remove { } } protected event Action B_HiddenEventFamily { add { } remove { } } private event Action B_HiddenEventPrivate { add { } remove { } } internal event Action B_HiddenEventAssembly { add { } remove { } } protected internal event Action B_HiddenEventFamOrAssembly { add { } remove { } } // Static events public static event Action B_StaticEventPublic { add { } remove { } } protected static event Action B_StaticEventFamily { add { } remove { } } private static event Action B_StaticEventPrivate { add { } remove { } } internal static event Action B_StaticEventAssembly { add { } remove { } } protected internal static event Action B_StaticEventFamOrAssembly { add { } remove { } } // Virtual events public virtual event Action B_VirtualEventPublic { add { } remove { } } protected virtual event Action B_VirtualEventFamily { add { } remove { } } internal virtual event Action B_VirtualEventAssembly { add { } remove { } } protected virtual internal event Action B_VirtualEventFamOrAssembly { add { } remove { } } } public abstract class Mid : Base { // Instance fields public int M_InstFieldPublic; protected int M_InstFieldFamily; private int M_InstFieldPrivate; internal int M_InstFieldAssembly; protected internal int M_InstFieldFamOrAssembly; // Hidden fields public new int B_HiddenFieldPublic; protected new int B_HiddenFieldFamily; private /*new*/ int B_HiddenFieldPrivate; internal new int B_HiddenFieldAssembly; protected internal new int B_HiddenFieldFamOrAssembly; // Static fields public static int M_StaticFieldPublic; protected static int M_StaticFieldFamily; private static int M_StaticFieldPrivate; internal static int M_StaticFieldAssembly; protected internal static int M_StaticFieldFamOrAssembly; // Instance methods public void M_InstMethPublic() { } protected void M_InstMethFamily() { } private void M_InstMethPrivate() { } internal void M_InstMethAssembly() { } protected internal void M_InstMethFamOrAssembly() { } // Hidden methods public new void B_HiddenMethPublic() { } protected new void B_HiddenMethFamily() { } private void B_HiddenMethPrivate() { } internal new void B_HiddenMethAssembly() { } protected new internal void B_HiddenMethFamOrAssembly() { } // Static methods public static void M_StaticMethPublic() { } protected static void M_StaticMethFamily() { } private static void M_StaticMethPrivate() { } internal static void M_StaticMethAssembly() { } protected internal static void M_StaticMethFamOrAssembly() { } // Overriding Virtual methods public override void B_VirtualMethPublic() { } protected override void B_VirtualMethFamily() { } internal override void B_VirtualMethAssembly() { } protected override internal void B_VirtualMethFamOrAssembly() { } // Instance properties public int M_InstPropPublic { get { return 5; } } protected int M_InstPropFamily { get { return 5; } } private int M_InstPropPrivate { get { return 5; } } internal int M_InstPropAssembly { get { return 5; } } protected internal int M_InstPropFamOrAssembly { get { return 5; } } // Hidden properties public new int B_HiddenPropPublic { get { return 5; } } protected new int B_HiddenPropFamily { get { return 5; } } private int B_HiddenPropPrivate { get { return 5; } } internal new int B_HiddenPropAssembly { get { return 5; } } protected new internal int B_HiddenPropFamOrAssembly { get { return 5; } } // Static properties public static int M_StaticPropPublic { get { return 5; } } protected static int M_StaticPropFamily { get { return 5; } } private static int M_StaticPropPrivate { get { return 5; } } internal static int M_StaticPropAssembly { get { return 5; } } protected internal static int M_StaticPropFamOrAssembly { get { return 5; } } // Overriding Virtual properties public override int B_VirtualPropPublic { get { return 5; } } protected override int B_VirtualPropFamily { get { return 5; } } internal override int B_VirtualPropAssembly { get { return 5; } } protected override internal int B_VirtualPropFamOrAssembly { get { return 5; } } // Instance events public event Action M_InstEventPublic { add { } remove { } } protected event Action M_InstEventFamily { add { } remove { } } private event Action M_InstEventPrivate { add { } remove { } } internal event Action M_InstEventAssembly { add { } remove { } } protected internal event Action M_InstEventFamOrAssembly { add { } remove { } } // Hidden events public new event Action B_HiddenEventPublic { add { } remove { } } protected new event Action B_HiddenEventFamily { add { } remove { } } private event Action B_HiddenEventPrivate { add { } remove { } } internal new event Action B_HiddenEventAssembly { add { } remove { } } protected new internal event Action B_HiddenEventFamOrAssembly { add { } remove { } } // Static events public static event Action M_StaticEventPublic { add { } remove { } } protected static event Action M_StaticEventFamily { add { } remove { } } private static event Action M_StaticEventPrivate { add { } remove { } } internal static event Action M_StaticEventAssembly { add { } remove { } } protected internal static event Action M_StaticEventFamOrAssembly { add { } remove { } } // Overriding Virtual events public override event Action B_VirtualEventPublic { add { } remove { } } protected override event Action B_VirtualEventFamily { add { } remove { } } internal override event Action B_VirtualEventAssembly { add { } remove { } } protected override internal event Action B_VirtualEventFamOrAssembly { add { } remove { } } } public abstract class Derived : Mid { // New Virtual methods public new virtual void B_VirtualMethPublic() { } protected new virtual void B_VirtualMethFamily() { } internal new virtual void B_VirtualMethAssembly() { } protected new virtual internal void B_VirtualMethFamOrAssembly() { } // New Virtual properties public new virtual int B_VirtualPropPublic { get { return 5; } } protected new virtual int B_VirtualPropFamily { get { return 5; } } internal new virtual int B_VirtualPropAssembly { get { return 5; } } protected new virtual internal int B_VirtualPropFamOrAssembly { get { return 5; } } // New Virtual events public new virtual event Action B_VirtualEventPublic { add { } remove { } } protected new virtual event Action B_VirtualEventFamily { add { } remove { } } internal new virtual event Action B_VirtualEventAssembly { add { } remove { } } protected new virtual internal event Action B_VirtualEventFamOrAssembly { add { } remove { } } } public abstract class S1 { public int Prop1 { get; set; } public int Prop2 { get; set; } public event Action Event1 { add { } remove { } } public event Action Event2 { add { } remove { } } protected abstract void M1(); protected virtual void M3() { } protected virtual void M4() { } } public abstract class S2 : S1 { private new int Prop1 { get; set; } private new event Action Event1 { add { } remove { } } protected virtual void M2() { } protected new virtual void M4() { } } public abstract class S3 : S2 { public static new int Prop2 { get; set; } public static new event Action Event2 { add { } remove { } } protected override void M1() { } protected abstract override void M2(); protected override void M4() { } } public abstract class S4 : S3 { protected override void M2() { } protected override void M3() { } protected new virtual void M4() { } } public interface INov1 { void Foo(); } public interface INov2 : INov1 { } public class Nov : INov2 { public static void S() { } public void I() { } public void Foo() { } } public class GetRuntimeMethodBase { public void Hidden1(int x) { } public void DefinedInBaseOnly(int x) { } public void InExact(Object o) { } public void Close1(String s) { } public void VarArgs(int x, params Object[] varargs) { } public void Primitives(int i) { } } public class GetRuntimeMethodDerived : GetRuntimeMethodBase { public new void Hidden1(int x) { } public void Close1(Object s) { } } } namespace SampleMetadataMethodImpl { interface ICloneable { void Clone(); void GenericClone<T>(); } class ImplementsICloneable : ICloneable { void ICloneable.Clone() { } void ICloneable.GenericClone<T>() { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using Shielded; namespace ShieldedTests { [TestFixture] public class BasicTests { [Test] public void TransactionSafetyTest() { Shielded<int> a = new Shielded<int>(5); Assert.AreEqual(5, a); Assert.Throws<InvalidOperationException>(() => a.Modify((ref int n) => n = 10)); Assert.IsFalse(Shield.IsInTransaction); Shield.InTransaction(() => { a.Modify((ref int n) => n = 20); // the TPL sometimes executes tasks on the same thread. int x1 = 0; var t = new Thread(() => { Assert.IsFalse(Shield.IsInTransaction); x1 = a; }); t.Start(); t.Join(); Assert.IsTrue(Shield.IsInTransaction); Assert.AreEqual(5, x1); Assert.AreEqual(20, a); }); Assert.IsFalse(Shield.IsInTransaction); int x2 = 0; var t2 = new Thread(() => { Assert.IsFalse(Shield.IsInTransaction); x2 = a; }); t2.Start(); t2.Join(); Assert.AreEqual(20, x2); Assert.AreEqual(20, a); } [Test] public void RaceTest() { var x = new Shielded<int>(); int transactionCount = 0; Task.WaitAll( Enumerable.Range(1, 100).Select(i => Task.Factory.StartNew(() => { bool committed = false; try { Shield.InTransaction(() => { Shield.SideEffect(() => { committed = true; }); Interlocked.Increment(ref transactionCount); int a = x; Thread.Sleep(5); x.Value = a + i; if (i == 100) throw new InvalidOperationException(); }); Assert.AreNotEqual(100, i); Assert.IsTrue(committed); } catch { Assert.AreEqual(100, i); Assert.IsFalse(committed); } }, TaskCreationOptions.LongRunning)).ToArray()); Assert.AreEqual(4950, x); // just to confirm validity of test! not really a fail if this fails. Assert.Greater(transactionCount, 100); } [Test] public void SkewWriteTest() { var cats = new Shielded<int>(1); var dogs = new Shielded<int>(1); int transactionCount = 0; Task.WaitAll( Enumerable.Range(1, 2).Select(i => Task.Factory.StartNew(() => Shield.InTransaction(() => { Interlocked.Increment(ref transactionCount); if (cats + dogs < 3) { Thread.Sleep(200); if (i == 1) cats.Modify((ref int n) => n++); else dogs.Modify((ref int n) => n++); } }), TaskCreationOptions.LongRunning)).ToArray()); Assert.AreEqual(3, cats + dogs); Assert.AreEqual(3, transactionCount); } class IgnoreMe : Exception {} [Test] public void SideEffectTest() { var x = new Shielded<DateTime>(DateTime.UtcNow); try { Shield.InTransaction(() => { Shield.SideEffect(() => { Assert.Fail("Suicide transaction has committed."); }, () => { throw new IgnoreMe(); }); // in case Assign() becomes commutative, we use Modify() to ensure conflict. x.Modify((ref DateTime d) => d = DateTime.UtcNow); var t = new Thread(() => Shield.InTransaction(() => x.Modify((ref DateTime d) => d = DateTime.UtcNow))); t.Start(); t.Join(); }); Assert.Fail("Suicide transaction did not throw."); } catch (AggregateException aggr) { Assert.AreEqual(1, aggr.InnerExceptions.Count); Assert.AreEqual(typeof(IgnoreMe), aggr.InnerException.GetType()); } bool commitFx = false; Shield.InTransaction(() => { Shield.SideEffect(() => { Assert.IsFalse(commitFx); commitFx = true; }); }); Assert.IsTrue(commitFx); bool outOfTransFx = false, outOfTransOnRollback = false; Shield.SideEffect(() => outOfTransFx = true, () => outOfTransOnRollback = true); Assert.IsTrue(outOfTransFx); Assert.IsFalse(outOfTransOnRollback); } [Test] public void ConditionalTest() { var x = new Shielded<int>(); var testCounter = 0; var triggerCommits = 0; Shield.Conditional(() => { Interlocked.Increment(ref testCounter); return x > 0 && (x & 1) == 0; }, () => { Shield.SideEffect(() => Interlocked.Increment(ref triggerCommits)); Assert.IsTrue(x > 0 && (x & 1) == 0); }); const int count = 1000; ParallelEnumerable.Repeat(1, count).ForAll(i => Shield.InTransaction(() => x.Modify((ref int n) => n++))); // one more, for the first call to Conditional()! btw, if this conditional were to // write anywhere, he might conflict, and an interlocked counter would give more due to // repetitions. so, this confirms reader progress too. Assert.AreEqual(count + 1, testCounter); // every change triggers it, but by the time it starts, another transaction might have // committed, so this is not a fixed number. Assert.Greater(triggerCommits, 0); // a conditional which does not depend on any Shielded is not allowed! int a = 5; Assert.Throws<InvalidOperationException>(() => Shield.Conditional(() => a > 10, () => { })); bool firstTime = true; var x2 = new Shielded<int>(); // this one succeeds in registering, but fails as soon as it gets triggered, due to changing it's // test's access pattern to an empty set. Shield.Conditional(() => { if (firstTime) { firstTime = false; return x2 == 0; } else // this is of course invalid, and when reaching here we have not touched any Shielded obj. return true; }, () => { }); try { // this will trigger the conditional Shield.InTransaction(() => x2.Modify((ref int n) => n++)); Assert.Fail(); } catch (AggregateException aggr) { Assert.AreEqual(1, aggr.InnerExceptions.Count); Assert.AreEqual(typeof(InvalidOperationException), aggr.InnerException.GetType()); } } [Test] public void EventTest() { var a = new Shielded<int>(1); var eventCount = new Shielded<int>(); EventHandler<EventArgs> ev = (sender, arg) => eventCount.Commute((ref int e) => e++); Assert.Throws<InvalidOperationException>(() => a.Changed.Subscribe(ev)); Shield.InTransaction(() => { a.Changed.Subscribe(ev); var t = new Thread(() => Shield.InTransaction(() => a.Modify((ref int x) => x++))); t.Start(); t.Join(); var t2 = new Thread(() => Shield.InTransaction(() => a.Modify((ref int x) => x++))); t2.Start(); t2.Join(); }); Assert.AreEqual(0, eventCount); Shield.InTransaction(() => { a.Modify((ref int x) => x++); }); Assert.AreEqual(1, eventCount); Thread tUnsub = null; Shield.InTransaction(() => { a.Changed.Unsubscribe(ev); a.Modify((ref int x) => x++); if (tUnsub == null) { tUnsub = new Thread(() => { Shield.InTransaction(() => { a.Modify((ref int x) => x++); a.Modify((ref int x) => x++); }); }); tUnsub.Start(); tUnsub.Join(); } }); // the other thread must still see the subscription... Assert.AreEqual(3, eventCount); Shield.InTransaction(() => a.Modify((ref int x) => x++)); Assert.AreEqual(3, eventCount); } } }
// 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 Xunit; using Xunit.Abstractions; public class Tests { private readonly ITestOutputHelper output; public Tests(ITestOutputHelper output) { this.output = output; } [Fact] public void TwoSpansCreatedOverSameIntArrayAreEqual() { for (int i = 0; i < 2; i++) { var ints = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Try out two ways of creating a slice: Span<int> slice; if (i == 0) { slice = new Span<int>(ints); } else { slice = ints.Slice(); } Assert.Equal(ints.Length, slice.Length); // Now try out two ways of walking the slice's contents: for (int j = 0; j < ints.Length; j++) { Assert.Equal(ints[j], slice[j]); } { int j = 0; foreach (var x in slice) { Assert.Equal(ints[j], x); j++; } } } } [Fact] public void TwoReadOnlySpansCreatedOverSameIntArrayAreEqual() { for (int i = 0; i < 2; i++) { var ints = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Try out two ways of creating a slice: ReadOnlySpan<int> slice; if (i == 0) { slice = new ReadOnlySpan<int>(ints); } else { slice = ints.Slice(); } Assert.Equal(ints.Length, slice.Length); // Now try out two ways of walking the slice's contents: for (int j = 0; j < ints.Length; j++) { Assert.Equal(ints[j], slice[j]); } { int j = 0; foreach (var x in slice) { Assert.Equal(ints[j], x); j++; } } } } [Fact] public void TestEndsWith() { var str = "Hello, Slice!"; ReadOnlySpan<char> slice = str.Slice(); ReadOnlySpan<char> slice2 = "Slice!".Slice(); slice.EndsWith(slice2); } [Fact] public void TwoSpansCreatedOverSameStringsAreEqual() { var str = "Hello, Slice!"; ReadOnlySpan<char> slice = str.Slice(); Assert.Equal(str.Length, slice.Length); // Now try out two ways of walking the slice's contents: for (int j = 0; j < str.Length; j++) { Assert.Equal(str[j], slice[j]); } { int j = 0; foreach (var x in slice) { Assert.Equal(str[j], x); j++; } } } [Fact] public void TwoSpansCreatedOverSameByteArayAreEqual() { unsafe { byte* buffer = stackalloc byte[256]; for (int i = 0; i < 256; i++) { buffer[i] = (byte)i; } Span<byte> slice = new Span<byte>(buffer, 256); Assert.Equal(256, slice.Length); // Now try out two ways of walking the slice's contents: for (int j = 0; j < slice.Length; j++) { Assert.Equal(buffer[j], slice[j]); } { int j = 0; foreach (var x in slice) { Assert.Equal(buffer[j], x); j++; } } } } [Fact] public void TwoReadOnlySpansCreatedOverSameByteArayAreEqual() { unsafe { byte* buffer = stackalloc byte[256]; for (int i = 0; i < 256; i++) { buffer[i] = (byte)i; } ReadOnlySpan<byte> slice = new ReadOnlySpan<byte>(buffer, 256); Assert.Equal(256, slice.Length); // Now try out two ways of walking the slice's contents: for (int j = 0; j < slice.Length; j++) { Assert.Equal(buffer[j], slice[j]); } { int j = 0; foreach (var x in slice) { Assert.Equal(buffer[j], x); j++; } } } } [Fact] public void TwoSpansCreatedOverSameIntSubarrayAreEqual() { var slice = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }.Slice(); // First a simple subslice over the whole array, using start. { var subslice1 = slice.Slice(0); Assert.Equal(slice.Length, subslice1.Length); for (int i = 0; i < slice.Length; i++) { Assert.Equal(slice[i], subslice1[i]); } } // Next a simple subslice over the whole array, using start and end. { var subslice2 = slice.Slice(0, slice.Length); Assert.Equal(slice.Length, subslice2.Length); for (int i = 0; i < slice.Length; i++) { Assert.Equal(slice[i], subslice2[i]); } } // Now do something more interesting; just take half the array. { int mid = slice.Length / 2; var subslice3 = slice.Slice(mid); Assert.Equal(mid, subslice3.Length); for (int i = mid, j = 0; i < slice.Length; i++, j++) { Assert.Equal(slice[i], subslice3[j]); } } // Now take a hunk out of the middle. { int st = 3; int ed = 7; var subslice4 = slice.Slice(st, 4); Assert.Equal(ed - st, subslice4.Length); for (int i = ed, j = 0; i < ed; i++, j++) { Assert.Equal(slice[i], subslice4[j]); } } } [Fact] public void IntArraySpanCastedToByteArraySpanHasSameBytesAsOriginalArray() { var ints = new int[100000]; Random r = new Random(42324232); for (int i = 0; i < ints.Length; i++) { ints[i] = r.Next(); } var bytes = ints.Slice().Cast<int, byte>(); Assert.Equal(bytes.Length, ints.Length * sizeof(int)); for (int i = 0; i < ints.Length; i++) { Assert.Equal(bytes[i * 4], (ints[i] & 0xff)); Assert.Equal(bytes[i * 4 + 1], (ints[i] >> 8 & 0xff)); Assert.Equal(bytes[i * 4 + 2], (ints[i] >> 16 & 0xff)); Assert.Equal(bytes[i * 4 + 3], (ints[i] >> 24 & 0xff)); } } [Fact] public bool TestPerfLoop() { var ints = new int[10000]; Random r = new Random(1234); for (int i = 0; i < ints.Length; i++) { ints[i] = r.Next(); } Tester.CleanUpMemory(); var sw = System.Diagnostics.Stopwatch.StartNew(); int x = 0; for (int i = 0; i < 10000; i++) { for (int j = 0; j < ints.Length; j++) { x += ints[i]; } } sw.Stop(); output.WriteLine(" - ints : {0}", sw.Elapsed); Tester.CleanUpMemory(); var slice = ints.Slice(); sw.Reset(); sw.Start(); int y = 0; for (int i = 0; i < 10000; i++) { for (int j = 0; j < slice.Length; j++) { y += slice[i]; } } sw.Stop(); output.WriteLine(" - slice: {0}", sw.Elapsed); Assert.Equal(x, y); return true; } }
using Microsoft.DirectX.Direct3D; using System.Drawing; using System.Windows.Forms; using TGC.Core.Geometry; using TGC.Core.Mathematica; using TGC.Core.SceneLoader; using TGC.Core.Shaders; using TGC.Core.SkeletalAnimation; using TGC.Examples.Camara; using TGC.Examples.Example; using TGC.Examples.UserControls; using TGC.Examples.UserControls.Modifier; namespace TGC.Examples.Lights { /// <summary> /// Ejemplo EjemploPointLight: /// Unidades Involucradas: /// # Unidad 4 - Texturas e Iluminacion - Iluminacion dinamica /// # Unidad 5 - Animacion - Skeletal Animation /// # Unidad 8 - Adaptadores de Video - Shaders /// Ejemplo avanzado. Ver primero ejemplos "SceneLoader/CustomMesh", "Animation/SkeletalAnimation" y luego /// "Shaders/EjemploShaderTgcMesh". /// Muestra como aplicar iluminacion dinamica a mesh estaticos o a un personaje animado con Skeletal Mesh, con /// PhongShading por pixel en un Pixel Shader, para un tipo de luz "Point Light". /// Permite una unica luz por objeto. /// Calcula todo el modelo de iluminacion completo (Ambient, Diffuse, Specular) /// Las luces poseen atenuacion por la distancia. /// Autor: Matias Leone, Leandro Barbagallo /// </summary> public class EjemploPointLight : TGCExampleViewer { private TGCBooleanModifier lightEnableModifier; private TGCVertex3fModifier lightPosModifier; private TGCColorModifier lightColorModifier; private TGCFloatModifier lightIntensityModifier; private TGCFloatModifier lightAttenuationModifier; private TGCFloatModifier specularExModifier; private TGCColorModifier mEmissiveModifier; private TGCColorModifier mAmbientModifier; private TGCColorModifier mDiffuseModifier; private TGCColorModifier mSpecularModifier; private TGCBox lightMesh; private TgcScene scene; private TgcSkeletalMesh skeletalMesh; public EjemploPointLight(string mediaDir, string shadersDir, TgcUserVars userVars, Panel modifiersPanel) : base(mediaDir, shadersDir, userVars, modifiersPanel) { Category = "Pixel Shaders"; Name = "TGC Point light skeletal pong shading"; Description = "Iluminacion dinamica por PhongShading de una luz del tipo Point Light."; } public override void Init() { //Cargar escenario var loader = new TgcSceneLoader(); scene = loader.loadSceneFromFile(MediaDir + "MeshCreator\\Scenes\\Deposito\\Deposito-TgcScene.xml"); //Cargar mesh con animaciones var skeletalLoader = new TgcSkeletalLoader(); skeletalMesh = skeletalLoader.loadMeshAndAnimationsFromFile(MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml", new[] { MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml" }); //Configurar animacion inicial skeletalMesh.playAnimation("Parado", true); //Corregir normales skeletalMesh.computeNormals(); //Pongo al mesh en posicion skeletalMesh.Position = new TGCVector3(0, 0, 100); skeletalMesh.Transform = TGCMatrix.RotationY(skeletalMesh.Rotation.Y + FastMath.PI) * TGCMatrix.Translation(skeletalMesh.Position); //Camara en 1ra persona Camera = new TgcFpsCamera(new TGCVector3(250, 140, 150), Input); //Mesh para la luz lightMesh = TGCBox.fromSize(new TGCVector3(10, 10, 10)); //Pongo al mesh en posicion lightMesh.Position = new TGCVector3(0, 150, 150); lightMesh.Transform = TGCMatrix.Translation(lightMesh.Position); //Modifiers de la luz lightEnableModifier = AddBoolean("lightEnable", "lightEnable", lightMesh.Enabled); lightPosModifier = AddVertex3f("lightPos", new TGCVector3(-200, -100, -200), new TGCVector3(200, 200, 300), lightMesh.Position); lightColorModifier = AddColor("lightColor", lightMesh.Color); lightIntensityModifier = AddFloat("lightIntensity", 0, 150, 20); lightAttenuationModifier = AddFloat("lightAttenuation", 0.1f, 2, 0.3f); specularExModifier = AddFloat("specularEx", 0, 20, 9f); //Modifiers de material mEmissiveModifier = AddColor("mEmissive", Color.Black); mAmbientModifier = AddColor("mAmbient", Color.White); mDiffuseModifier = AddColor("mDiffuse", Color.White); mSpecularModifier = AddColor("mSpecular", Color.White); } public override void Update() { //Actualizo los valores de la luz lightMesh.Enabled = lightEnableModifier.Value; lightMesh.Position = lightPosModifier.Value; lightMesh.Transform = TGCMatrix.Translation(lightMesh.Position); lightMesh.Color = lightColorModifier.Value; lightMesh.updateValues(); } public override void Render() { PreRender(); Effect currentShader; Effect currentShaderSkeletalMesh; if (lightMesh.Enabled) { //Con luz: Cambiar el shader actual por el shader default que trae el framework para iluminacion dinamica con PointLight currentShader = TGCShaders.Instance.TgcMeshPointLightShader; //Con luz: Cambiar el shader actual por el shader default que trae el framework para iluminacion dinamica con PointLight para Skeletal Mesh currentShaderSkeletalMesh = TGCShaders.Instance.TgcSkeletalMeshPointLightShader; } else { //Sin luz: Restaurar shader default currentShader = TGCShaders.Instance.TgcMeshShader; currentShaderSkeletalMesh = TGCShaders.Instance.TgcSkeletalMeshShader; } //Aplicar a cada mesh el shader actual foreach (var mesh in scene.Meshes) { mesh.Effect = currentShader; //El Technique depende del tipo RenderType del mesh mesh.Technique = TGCShaders.Instance.GetTGCMeshTechnique(mesh.RenderType); } //Aplicar al mesh el shader actual skeletalMesh.Effect = currentShaderSkeletalMesh; //El Technique depende del tipo RenderType del mesh skeletalMesh.Technique = TGCShaders.Instance.GetTGCSkeletalMeshTechnique(skeletalMesh.RenderType); //Renderizar meshes foreach (var mesh in scene.Meshes) { if (lightMesh.Enabled) { //Cargar variables shader de la luz mesh.Effect.SetValue("lightColor", ColorValue.FromColor(lightMesh.Color)); mesh.Effect.SetValue("lightPosition", TGCVector3.TGCVector3ToFloat4Array(lightMesh.Position)); mesh.Effect.SetValue("eyePosition", TGCVector3.TGCVector3ToFloat4Array(Camera.Position)); mesh.Effect.SetValue("lightIntensity", lightIntensityModifier.Value); mesh.Effect.SetValue("lightAttenuation", lightAttenuationModifier.Value); //Cargar variables de shader de Material. El Material en realidad deberia ser propio de cada mesh. Pero en este ejemplo se simplifica con uno comun para todos mesh.Effect.SetValue("materialEmissiveColor", ColorValue.FromColor(mEmissiveModifier.Value)); mesh.Effect.SetValue("materialAmbientColor", ColorValue.FromColor(mAmbientModifier.Value)); mesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(mDiffuseModifier.Value)); mesh.Effect.SetValue("materialSpecularColor", ColorValue.FromColor(mSpecularModifier.Value)); mesh.Effect.SetValue("materialSpecularExp", specularExModifier.Value); } //Renderizar modelo mesh.Render(); } //Renderizar mesh if (lightMesh.Enabled) { //Cargar variables shader de la luz skeletalMesh.Effect.SetValue("lightColor", ColorValue.FromColor(lightMesh.Color)); skeletalMesh.Effect.SetValue("lightPosition", TGCVector3.TGCVector3ToFloat4Array(lightMesh.Position)); skeletalMesh.Effect.SetValue("eyePosition", TGCVector3.TGCVector3ToFloat4Array(Camera.Position)); skeletalMesh.Effect.SetValue("lightIntensity", lightIntensityModifier.Value); skeletalMesh.Effect.SetValue("lightAttenuation", lightAttenuationModifier.Value); //Cargar variables de shader de Material. El Material en realidad deberia ser propio de cada mesh. Pero en este ejemplo se simplifica con uno comun para todos skeletalMesh.Effect.SetValue("materialEmissiveColor", ColorValue.FromColor(mEmissiveModifier.Value)); skeletalMesh.Effect.SetValue("materialAmbientColor", ColorValue.FromColor(mAmbientModifier.Value)); skeletalMesh.Effect.SetValue("materialDiffuseColor", ColorValue.FromColor(mDiffuseModifier.Value)); skeletalMesh.Effect.SetValue("materialSpecularColor", ColorValue.FromColor(mSpecularModifier.Value)); skeletalMesh.Effect.SetValue("materialSpecularExp", specularExModifier.Value); } skeletalMesh.animateAndRender(ElapsedTime); //Renderizar mesh de luz lightMesh.Render(); PostRender(); } public override void Dispose() { scene.DisposeAll(); skeletalMesh.Dispose(); lightMesh.Dispose(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Aurora.DataManager; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using ChatSessionMember = Aurora.Framework.ChatSessionMember; namespace Aurora.Modules.Groups { public class AuroraDataGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector { public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; private readonly Dictionary<UUID, ChatSession> ChatSessions = new Dictionary<UUID, ChatSession>(); private IGroupsServiceConnector GroupsConnector; private IUserAccountService m_accountService; private bool m_connectorEnabled; #region IGroupsServicesConnector Members /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); // Would this be cleaner as (GroupPowers)ulong.MaxValue; GroupPowers OwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; GroupsConnector.CreateGroup(GroupID, name, charter, showInList, insigniaID, 0, openEnrollment, allowPublish, maturePublish, founderID, ((ulong) m_DefaultEveryonePowers), OwnerRoleID, ((ulong) OwnerPowers)); return GroupID; } public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { GroupsConnector.UpdateGroup(requestingAgentID, groupID, charter, showInList ? 1 : 0, insigniaID, membershipFee, openEnrollment ? 1 : 0, allowPublish ? 1 : 0, maturePublish ? 1 : 0); } public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { GroupsConnector.AddRoleToGroup(requestingAgentID, groupID, roleID, name, description, title, powers); } public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID) { GroupsConnector.RemoveRoleFromGroup(requestingAgentID, roleID, groupID); } public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { GroupsConnector.UpdateRole(requestingAgentID, groupID, roleID, name, description, title, powers); } public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName) { return GroupsConnector.GetGroupRecord(requestingAgentID, GroupID, GroupName); } public string SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { return GroupsConnector.SetAgentActiveGroup(AgentID, GroupID); } public string SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { return GroupsConnector.SetAgentGroupSelectedRole(AgentID, GroupID, RoleID); } public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { GroupsConnector.SetAgentGroupInfo(requestingAgentID, AgentID, GroupID, AcceptNotices ? 1 : 0, ListInProfile ? 1 : 0); } public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID, string FromAgentName) { GroupsConnector.AddAgentGroupInvite(requestingAgentID, inviteID, groupID, roleID, agentID, FromAgentName); } public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { return GroupsConnector.GetAgentToGroupInvite(requestingAgentID, inviteID); } public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { GroupsConnector.RemoveAgentInvite(requestingAgentID, inviteID); } public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { GroupsConnector.AddAgentToGroup(requestingAgentID, AgentID, GroupID, RoleID); } public bool RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { return GroupsConnector.RemoveAgentFromGroup(requestingAgentID, AgentID, GroupID); } public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { GroupsConnector.AddAgentToRole(requestingAgentID, AgentID, GroupID, RoleID); } public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { GroupsConnector.RemoveAgentFromRole(requestingAgentID, AgentID, GroupID, RoleID); } public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search, int queryStart, uint queryflags) { //TODO: Fix this.. should be in the search module return GroupsConnector.FindGroups(requestingAgentID, search, queryStart, queryflags); } public GroupProfileData GetGroupProfile(UUID requestingAgentID, UUID GroupID) { return GroupsConnector.GetGroupProfile(requestingAgentID, GroupID); } public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID) { return GroupsConnector.GetGroupMembershipData(requestingAgentID, GroupID, AgentID); } public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID) { return GroupsConnector.GetGroupMembershipData(requestingAgentID, UUID.Zero, AgentID); } public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID) { return GroupsConnector.GetAgentGroupMemberships(requestingAgentID, AgentID); } public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID) { return GroupsConnector.GetAgentGroupRoles(requestingAgentID, AgentID, GroupID); } public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID) { return GroupsConnector.GetGroupRoles(requestingAgentID, GroupID); } public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID) { return GroupsConnector.GetGroupMembers(requestingAgentID, GroupID); } public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID) { return GroupsConnector.GetGroupRoleMembers(requestingAgentID, GroupID); } public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID) { return GetGroupNotices(requestingAgentID, 0, 0, GroupID); } public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, uint start, uint count, UUID GroupID) { return GroupsConnector.GetGroupNotices(requestingAgentID, start, count, GroupID); } public List<GroupTitlesData> GetGroupTitles(UUID requestingAgentID, UUID GroupID) { return GroupsConnector.GetGroupTitles(requestingAgentID, GroupID); } public uint GetNumberOfGroupNotices(UUID requestingAgentID, UUID GroupID) { return GroupsConnector.GetNumberOfGroupNotices(requestingAgentID, GroupID); } public uint GetNumberOfGroupNotices(UUID requestingAgentID, List<UUID> GroupIDs) { return GroupsConnector.GetNumberOfGroupNotices(requestingAgentID, GroupIDs); } public GroupNoticeData GetGroupNoticeData(UUID requestingAgentID, UUID noticeID) { return GroupsConnector.GetGroupNoticeData(requestingAgentID, noticeID); } public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID) { return GroupsConnector.GetGroupNotice(requestingAgentID, noticeID); } public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, UUID ItemID, int AssetType, string ItemName) { GroupsConnector.AddGroupNotice(requestingAgentID, groupID, noticeID, fromName, subject, message, ItemID, AssetType, ItemName); } public void AddGroupProposal(UUID agentID, GroupProposalInfo info) { GroupsConnector.AddGroupProposal(agentID, info); } public void VoteOnActiveProposals(UUID agentID, UUID groupID, UUID proposalID, string vote) { GroupsConnector.VoteOnActiveProposals(agentID, groupID, proposalID, vote); } public List<GroupInviteInfo> GetGroupInvites(UUID requestingAgentID) { return GroupsConnector.GetGroupInvites(requestingAgentID); } public List<GroupProposalInfo> GetActiveProposals(UUID agentID, UUID groupID) { return GroupsConnector.GetActiveProposals(agentID, groupID); } public List<GroupProposalInfo> GetInactiveProposals(UUID agentID, UUID groupID) { return GroupsConnector.GetInactiveProposals(agentID, groupID); } /// <summary> /// Add this member to the friend conference /// </summary> /// <param name = "member"></param> /// <param name = "SessionID"></param> public void AddMemberToGroup(ChatSessionMember member, UUID SessionID) { ChatSession session; ChatSessions.TryGetValue(SessionID, out session); ChatSessionMember oldMember = FindMember(SessionID, member.AvatarKey); if ((oldMember == null) || (oldMember.AvatarKey == UUID.Zero)) session.Members.Add(member); else oldMember.HasBeenAdded = true; //Reset this } /// <summary> /// Create a new friend conference session /// </summary> /// <param name = "session"></param> public bool CreateSession(ChatSession session) { ChatSession oldSession = null; if (ChatSessions.TryGetValue(session.SessionID, out oldSession)) if (GetMemeberCount(session) == 0) RemoveSession(session.SessionID); else return false; //Already have one ChatSessions.Add(session.SessionID, session); return true; } public void RemoveSession(UUID sessionid) { ChatSessions.Remove(sessionid); } /// <summary> /// Get a session by a user's sessionID /// </summary> /// <param name = "SessionID"></param> /// <returns></returns> public ChatSession GetSession(UUID SessionID) { ChatSession session; ChatSessions.TryGetValue(SessionID, out session); return session; } /// <summary> /// Find the member from X sessionID /// </summary> /// <param name = "sessionid"></param> /// <param name = "Agent"></param> /// <returns></returns> public ChatSessionMember FindMember(UUID sessionid, UUID Agent) { ChatSession session; ChatSessions.TryGetValue(sessionid, out session); if (session == null) return null; ChatSessionMember thismember = new ChatSessionMember {AvatarKey = UUID.Zero}; #if (!ISWIN) foreach (ChatSessionMember testmember in session.Members) { if (testmember.AvatarKey == Agent) { thismember = testmember; } } #else foreach (ChatSessionMember testmember in session.Members.Where(testmember => testmember.AvatarKey == Agent)) { thismember = testmember; } #endif return thismember; } #endregion #region ISharedRegionModule Members public string Name { get { return "AuroraDataGroupsServicesConnectorModule"; } } // this module is not intended to be replaced, but there should only be 1 of them. public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name)) { m_connectorEnabled = false; return; } //MainConsole.Instance.InfoFormat("[AURORA-GROUPS-CONNECTOR]: Initializing {0}", this.Name); m_connectorEnabled = true; } } public void Close() { MainConsole.Instance.InfoFormat("[AURORA-GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(IScene scene) { GroupsConnector = Aurora.DataManager.DataManager.RequestPlugin<IGroupsServiceConnector>(); if (GroupsConnector == null) { MainConsole.Instance.Warn("[AURORA-GROUPS-CONNECTOR]: GroupsConnector is null"); m_connectorEnabled = false; } if (m_connectorEnabled) { if (m_accountService == null) { m_accountService = scene.UserAccountService; } scene.RegisterModuleInterface<IGroupsServicesConnector>(this); } } public void RemoveRegion(IScene scene) { if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) { scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); } } public void RegionLoaded(IScene scene) { } public void PostInitialise() { // NoOp } #endregion public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID) { GroupMembershipData MemberInfo = GroupsConnector.GetGroupMembershipData(requestingAgentID, GroupID, AgentID); GroupProfileData MemberGroupProfile = GroupsConnector.GetMemberGroupProfile(requestingAgentID, GroupID, AgentID); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } private int GetMemeberCount(ChatSession session) { #if (!ISWIN) int count = 0; foreach (ChatSessionMember member in session.Members) { if (member.HasBeenAdded) count++; } return count; #else return session.Members.Count(member => member.HasBeenAdded); #endif } /// <summary> /// Add the agent to the in-memory session lists and give them the default permissions /// </summary> /// <param name = "AgentID"></param> /// <param name = "SessionID"></param> private void AddDefaultPermsMemberToSession(UUID AgentID, UUID SessionID) { ChatSession session; ChatSessions.TryGetValue(SessionID, out session); ChatSessionMember member = new ChatSessionMember { AvatarKey = AgentID, CanVoiceChat = true, IsModerator = false, MuteText = false, MuteVoice = false, HasBeenAdded = false }; session.Members.Add(member); } } }
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 dotnetapi.Areas.HelpPage.ModelDescriptions; using dotnetapi.Areas.HelpPage.Models; namespace dotnetapi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding { public class ModelMetadataTest { // IsComplexType private readonly struct IsComplexTypeModel { } [Theory] [InlineData(typeof(string))] [InlineData(typeof(Nullable<int>))] [InlineData(typeof(int))] public void IsComplexType_ReturnsFalseForSimpleTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.False(modelMetadata.IsComplexType); } [Theory] [InlineData(typeof(object))] [InlineData(typeof(IDisposable))] [InlineData(typeof(IsComplexTypeModel))] [InlineData(typeof(Nullable<IsComplexTypeModel>))] public void IsComplexType_ReturnsTrueForComplexTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.True(modelMetadata.IsComplexType); } // IsCollectionType / IsEnumerableType private class NonCollectionType { } private class DerivedList : List<int> { } private class JustEnumerable : IEnumerable { public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public static TheoryData<Type> NonCollectionNonEnumerableData { get { return new TheoryData<Type> { typeof(object), typeof(int), typeof(NonCollectionType), typeof(string), }; } } public static TheoryData<Type> CollectionAndEnumerableData { get { return new TheoryData<Type> { typeof(int[]), typeof(List<string>), typeof(DerivedList), typeof(Collection<int>), typeof(Dictionary<object, object>), typeof(CollectionImplementation), }; } } [Theory] [MemberData(nameof(NonCollectionNonEnumerableData))] [InlineData(typeof(IEnumerable))] [InlineData(typeof(IEnumerable<string>))] [InlineData(typeof(JustEnumerable))] public void IsCollectionType_ReturnsFalseForNonCollectionTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.False(modelMetadata.IsCollectionType); } [Theory] [MemberData(nameof(CollectionAndEnumerableData))] public void IsCollectionType_ReturnsTrueForCollectionTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.True(modelMetadata.IsCollectionType); } [Theory] [MemberData(nameof(NonCollectionNonEnumerableData))] public void IsEnumerableType_ReturnsFalseForNonEnumerableTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.False(modelMetadata.IsEnumerableType); } [Theory] [MemberData(nameof(CollectionAndEnumerableData))] [InlineData(typeof(IEnumerable))] [InlineData(typeof(IEnumerable<string>))] [InlineData(typeof(JustEnumerable))] public void IsEnumerableType_ReturnsTrueForEnumerableTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.True(modelMetadata.IsEnumerableType); } // IsNullableValueType [Theory] [InlineData(typeof(string), false)] [InlineData(typeof(IDisposable), false)] [InlineData(typeof(Nullable<int>), true)] [InlineData(typeof(int), false)] [InlineData(typeof(DerivedList), false)] [InlineData(typeof(IsComplexTypeModel), false)] [InlineData(typeof(Nullable<IsComplexTypeModel>), true)] public void IsNullableValueType_ReturnsExpectedValue(Type modelType, bool expected) { // Arrange & Act var modelMetadata = new TestModelMetadata(modelType); // Assert Assert.Equal(expected, modelMetadata.IsNullableValueType); } // IsReferenceOrNullableType [Theory] [InlineData(typeof(string), true)] [InlineData(typeof(IDisposable), true)] [InlineData(typeof(Nullable<int>), true)] [InlineData(typeof(int), false)] [InlineData(typeof(DerivedList), true)] [InlineData(typeof(IsComplexTypeModel), false)] [InlineData(typeof(Nullable<IsComplexTypeModel>), true)] public void IsReferenceOrNullableType_ReturnsExpectedValue(Type modelType, bool expected) { // Arrange & Act var modelMetadata = new TestModelMetadata(modelType); // Assert Assert.Equal(expected, modelMetadata.IsReferenceOrNullableType); } // UnderlyingOrModelType [Theory] [InlineData(typeof(string), typeof(string))] [InlineData(typeof(IDisposable), typeof(IDisposable))] [InlineData(typeof(Nullable<int>), typeof(int))] [InlineData(typeof(int), typeof(int))] [InlineData(typeof(DerivedList), typeof(DerivedList))] [InlineData(typeof(IsComplexTypeModel), typeof(IsComplexTypeModel))] [InlineData(typeof(Nullable<IsComplexTypeModel>), typeof(IsComplexTypeModel))] public void UnderlyingOrModelType_ReturnsExpectedValue(Type modelType, Type expected) { // Arrange & Act var modelMetadata = new TestModelMetadata(modelType); // Assert Assert.Equal(expected, modelMetadata.UnderlyingOrModelType); } // ElementType [Theory] [InlineData(typeof(object))] [InlineData(typeof(int))] [InlineData(typeof(NonCollectionType))] [InlineData(typeof(string))] public void ElementType_ReturnsNull_ForNonCollections(Type modelType) { // Arrange var metadata = new TestModelMetadata(modelType); // Act var elementType = metadata.ElementType; // Assert Assert.Null(elementType); } [Theory] [InlineData(typeof(int[]), typeof(int))] [InlineData(typeof(List<string>), typeof(string))] [InlineData(typeof(DerivedList), typeof(int))] [InlineData(typeof(IEnumerable), typeof(object))] [InlineData(typeof(IEnumerable<string>), typeof(string))] [InlineData(typeof(Collection<int>), typeof(int))] [InlineData(typeof(Dictionary<object, object>), typeof(KeyValuePair<object, object>))] [InlineData(typeof(DerivedDictionary), typeof(KeyValuePair<string, int>))] public void ElementType_ReturnsExpectedMetadata(Type modelType, Type expected) { // Arrange var metadata = new TestModelMetadata(modelType); // Act var elementType = metadata.ElementType; // Assert Assert.NotNull(elementType); Assert.Equal(expected, elementType); } // ContainerType [Fact] public void ContainerType_IsNull_ForType() { // Arrange & Act var metadata = new TestModelMetadata(typeof(int)); // Assert Assert.Null(metadata.ContainerType); } [Fact] public void ContainerType_IsNull_ForParameter() { // Arrange & Act var method = typeof(CollectionImplementation).GetMethod(nameof(CollectionImplementation.Add)); var parameter = method.GetParameters()[0]; // Add(string item) var metadata = new TestModelMetadata(parameter); // Assert Assert.Null(metadata.ContainerType); } [Fact] public void ContainerType_ReturnExpectedMetadata_ForProperty() { // Arrange & Act var property = typeof(string).GetProperty(nameof(string.Length)); var metadata = new TestModelMetadata(property, typeof(int), typeof(string)); // Assert Assert.Equal(typeof(string), metadata.ContainerType); } // Name / ParameterName / PropertyName [Fact] public void Names_ReturnExpectedMetadata_ForType() { // Arrange & Act var metadata = new TestModelMetadata(typeof(int)); // Assert Assert.Null(metadata.Name); Assert.Null(metadata.ParameterName); Assert.Null(metadata.PropertyName); } [Fact] public void Names_ReturnExpectedMetadata_ForParameter() { // Arrange & Act var method = typeof(CollectionImplementation).GetMethod(nameof(CollectionImplementation.Add)); var parameter = method.GetParameters()[0]; // Add(string item) var metadata = new TestModelMetadata(parameter); // Assert Assert.Equal("item", metadata.Name); Assert.Equal("item", metadata.ParameterName); Assert.Null(metadata.PropertyName); } [Fact] public void Names_ReturnExpectedMetadata_ForProperty() { // Arrange & Act var property = typeof(string).GetProperty(nameof(string.Length)); var metadata = new TestModelMetadata(property, typeof(int), typeof(string)); // Assert Assert.Equal(nameof(string.Length), metadata.Name); Assert.Null(metadata.ParameterName); Assert.Equal(nameof(string.Length), metadata.PropertyName); } // GetDisplayName() [Fact] public void GetDisplayName_ReturnsDisplayName_IfSet() { // Arrange var property = typeof(string).GetProperty(nameof(string.Length)); var metadata = new TestModelMetadata(property, typeof(int), typeof(string)); metadata.SetDisplayName("displayName"); // Act var result = metadata.GetDisplayName(); // Assert Assert.Equal("displayName", result); } [Fact] public void GetDisplayName_ReturnsParameterName_WhenSetAndDisplayNameIsNull() { // Arrange var method = typeof(CollectionImplementation).GetMethod(nameof(CollectionImplementation.Add)); var parameter = method.GetParameters()[0]; // Add(string item) var metadata = new TestModelMetadata(parameter); // Act var result = metadata.GetDisplayName(); // Assert Assert.Equal("item", result); } [Fact] public void GetDisplayName_ReturnsPropertyName_WhenSetAndDisplayNameIsNull() { // Arrange var property = typeof(string).GetProperty(nameof(string.Length)); var metadata = new TestModelMetadata(property, typeof(int), typeof(string)); // Act var result = metadata.GetDisplayName(); // Assert Assert.Equal("Length", result); } [Fact] public void GetDisplayName_ReturnsTypeName_WhenPropertyNameAndDisplayNameAreNull() { // Arrange var metadata = new TestModelMetadata(typeof(string)); // Act var result = metadata.GetDisplayName(); // Assert Assert.Equal("String", result); } // Virtual methods and properties that throw NotImplementedException in the abstract class. [Fact] public void GetContainerMetadata_ThrowsNotImplementedException_ByDefault() { // Arrange var metadata = new TestModelMetadata(typeof(DerivedList)); // Act & Assert Assert.Throws<NotImplementedException>(() => metadata.ContainerMetadata); } [Fact] public void GetMetadataForType_ByDefaultThrows_NotImplementedException() { // Arrange var metadata = new TestModelMetadata(typeof(string)); // Act & Assert var result = Assert.Throws<NotImplementedException>(() => metadata.GetMetadataForType(typeof(string))); } [Fact] public void GetMetadataForProperties_ByDefaultThrows_NotImplementedException() { // Arrange var metadata = new TestModelMetadata(typeof(string)); // Act & Assert var result = Assert.Throws<NotImplementedException>(() => metadata.GetMetadataForProperties(typeof(string))); } private class TestModelMetadata : ModelMetadata { private string _displayName; public TestModelMetadata(Type modelType) : base(ModelMetadataIdentity.ForType(modelType)) { } public TestModelMetadata(ParameterInfo parameter) : base(ModelMetadataIdentity.ForParameter(parameter)) { } public TestModelMetadata(PropertyInfo propertyInfo, Type modelType, Type containerType) : base(ModelMetadataIdentity.ForProperty(propertyInfo, modelType, containerType)) { } public override IReadOnlyDictionary<object, object> AdditionalValues { get { throw new NotImplementedException(); } } public override string BinderModelName { get { throw new NotImplementedException(); } } public override Type BinderType { get { throw new NotImplementedException(); } } public override BindingSource BindingSource { get { throw new NotImplementedException(); } } public override bool ConvertEmptyStringToNull { get { throw new NotImplementedException(); } } public override string DataTypeName { get { throw new NotImplementedException(); } } public override string Description { get { throw new NotImplementedException(); } } public override string DisplayFormatString { get { throw new NotImplementedException(); } } public override string DisplayName { get { return _displayName; } } public void SetDisplayName(string displayName) { _displayName = displayName; } public override string EditFormatString { get { throw new NotImplementedException(); } } public override ModelMetadata ElementMetadata { get { throw new NotImplementedException(); } } public override IEnumerable<KeyValuePair<EnumGroupAndName, string>> EnumGroupedDisplayNamesAndValues { get { throw new NotImplementedException(); } } public override IReadOnlyDictionary<string, string> EnumNamesAndValues { get { throw new NotImplementedException(); } } public override bool HasNonDefaultEditFormat { get { throw new NotImplementedException(); } } public override bool HideSurroundingHtml { get { throw new NotImplementedException(); } } public override bool HtmlEncode { get { throw new NotImplementedException(); } } public override bool IsBindingAllowed { get { throw new NotImplementedException(); } } public override bool IsBindingRequired { get { throw new NotImplementedException(); } } public override bool IsEnum { get { throw new NotImplementedException(); } } public override bool IsFlagsEnum { get { throw new NotImplementedException(); } } public override bool IsReadOnly { get { throw new NotImplementedException(); } } public override bool IsRequired { get { throw new NotImplementedException(); } } public override ModelBindingMessageProvider ModelBindingMessageProvider { get { throw new NotImplementedException(); } } public override string NullDisplayText { get { throw new NotImplementedException(); } } public override int Order { get { throw new NotImplementedException(); } } public override string Placeholder { get { throw new NotImplementedException(); } } public override ModelPropertyCollection Properties { get { throw new NotImplementedException(); } } public override IPropertyFilterProvider PropertyFilterProvider { get { throw new NotImplementedException(); } } public override bool ShowForDisplay { get { throw new NotImplementedException(); } } public override bool ShowForEdit { get { throw new NotImplementedException(); } } public override string SimpleDisplayProperty { get { throw new NotImplementedException(); } } public override string TemplateHint { get { throw new NotImplementedException(); } } public override IPropertyValidationFilter PropertyValidationFilter { get { throw new NotImplementedException(); } } public override bool ValidateChildren { get { throw new NotImplementedException(); } } public override IReadOnlyList<object> ValidatorMetadata { get { throw new NotImplementedException(); } } public override Func<object, object> PropertyGetter { get { throw new NotImplementedException(); } } public override Action<object, object> PropertySetter { get { throw new NotImplementedException(); } } public override ModelMetadata BoundConstructor => throw new NotImplementedException(); public override Func<object[], object> BoundConstructorInvoker => throw new NotImplementedException(); public override IReadOnlyList<ModelMetadata> BoundConstructorParameters => throw new NotImplementedException(); } private class CollectionImplementation : ICollection<string> { public int Count { get { throw new NotImplementedException(); } } public bool IsReadOnly { get { throw new NotImplementedException(); } } public void Add(string item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(string item) { throw new NotImplementedException(); } public void CopyTo(string[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<string> GetEnumerator() { throw new NotImplementedException(); } public bool Remove(string item) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } private class DerivedDictionary : Dictionary<string, int> { } } }
namespace BooCompiler.Tests { using NUnit.Framework; [TestFixture] public class GenericsTestFixture : AbstractCompilerTestCase { override protected void RunCompilerTestCase(string name) { if (System.Environment.Version.Major < 2) Assert.Ignore("Test requires .net 2."); System.ResolveEventHandler resolver = InstallAssemblyResolver(BaseTestCasesPath); try { base.RunCompilerTestCase(name); } finally { RemoveAssemblyResolver(resolver); } } override protected void CopyDependencies() { CopyAssembliesFromTestCasePath(); } [Test] public void ambiguous_1() { RunCompilerTestCase(@"ambiguous-1.boo"); } [Test] public void array_enumerable_1() { RunCompilerTestCase(@"array-enumerable-1.boo"); } [Test] public void array_enumerable_2() { RunCompilerTestCase(@"array-enumerable-2.boo"); } [Test] public void automatic_generic_method_stub() { RunCompilerTestCase(@"automatic-generic-method-stub.boo"); } [Test] public void callable_1() { RunCompilerTestCase(@"callable-1.boo"); } [Test] public void callable_2() { RunCompilerTestCase(@"callable-2.boo"); } [Test] public void collections_1() { RunCompilerTestCase(@"collections-1.boo"); } [Test] public void collections_2() { RunCompilerTestCase(@"collections-2.boo"); } [Test] public void enumerable_shorthand_1() { RunCompilerTestCase(@"enumerable-shorthand-1.boo"); } [Test] public void enumerable_type_inference_1() { RunCompilerTestCase(@"enumerable-type-inference-1.boo"); } [Test] public void enumerable_type_inference_2() { RunCompilerTestCase(@"enumerable-type-inference-2.boo"); } [Test] public void enumerable_type_inference_4() { RunCompilerTestCase(@"enumerable-type-inference-4.boo"); } [Test] public void enumerable_type_inference_5() { RunCompilerTestCase(@"enumerable-type-inference-5.boo"); } [Ignore("generic generators not supported yet")][Test] public void generator_with_type_constraint_1() { RunCompilerTestCase(@"generator-with-type-constraint-1.boo"); } [Test] public void generators_1() { RunCompilerTestCase(@"generators-1.boo"); } [Test] public void generators_2() { RunCompilerTestCase(@"generators-2.boo"); } [Test] public void generators_3() { RunCompilerTestCase(@"generators-3.boo"); } [Test] public void generators_4() { RunCompilerTestCase(@"generators-4.boo"); } [Test] public void generators_5() { RunCompilerTestCase(@"generators-5.boo"); } [Test] public void generators_6() { RunCompilerTestCase(@"generators-6.boo"); } [Test] public void generators_7() { RunCompilerTestCase(@"generators-7.boo"); } [Test] public void generic_array_1() { RunCompilerTestCase(@"generic-array-1.boo"); } [Test] public void generic_array_2() { RunCompilerTestCase(@"generic-array-2.boo"); } [Test] public void generic_array_3() { RunCompilerTestCase(@"generic-array-3.boo"); } [Test] public void generic_extension_1() { RunCompilerTestCase(@"generic-extension-1.boo"); } [Test] public void generic_extension_2() { RunCompilerTestCase(@"generic-extension-2.boo"); } [Test] public void generic_field_1() { RunCompilerTestCase(@"generic-field-1.boo"); } [Test] public void generic_generator_type_1() { RunCompilerTestCase(@"generic-generator-type-1.boo"); } [Test] public void generic_inheritance_1() { RunCompilerTestCase(@"generic-inheritance-1.boo"); } [Test] public void generic_instance_overload() { RunCompilerTestCase(@"generic-instance-overload.boo"); } [Category("FailsOnMono4")][Test] public void generic_list_of_callable() { RunCompilerTestCase(@"generic-list-of-callable.boo"); } [Test] public void generic_matrix_1() { RunCompilerTestCase(@"generic-matrix-1.boo"); } [Test] public void generic_method_1() { RunCompilerTestCase(@"generic-method-1.boo"); } [Test] public void generic_method_2() { RunCompilerTestCase(@"generic-method-2.boo"); } [Test] public void generic_method_3() { RunCompilerTestCase(@"generic-method-3.boo"); } [Test] public void generic_method_4() { RunCompilerTestCase(@"generic-method-4.boo"); } [Test] public void generic_method_5() { RunCompilerTestCase(@"generic-method-5.boo"); } [Test] public void generic_method_invocation_1() { RunCompilerTestCase(@"generic-method-invocation-1.boo"); } [Test] public void generic_method_invocation_2() { RunCompilerTestCase(@"generic-method-invocation-2.boo"); } [Test] public void generic_overload_1() { RunCompilerTestCase(@"generic-overload-1.boo"); } [Test] public void generic_overload_2() { RunCompilerTestCase(@"generic-overload-2.boo"); } [Test] public void generic_overload_3() { RunCompilerTestCase(@"generic-overload-3.boo"); } [Test] public void generic_overload_4() { RunCompilerTestCase(@"generic-overload-4.boo"); } [Test] public void generic_overload_5() { RunCompilerTestCase(@"generic-overload-5.boo"); } [Ignore("FIXME: Covariance support is incomplete, generates unverifiable IL (BOO-1155)")][Test] public void generic_overload_6() { RunCompilerTestCase(@"generic-overload-6.boo"); } [Test] public void generic_ref_parameter() { RunCompilerTestCase(@"generic-ref-parameter.boo"); } [Test] public void generic_type_resolution_1() { RunCompilerTestCase(@"generic-type-resolution-1.boo"); } [Test] public void generic_type_resolution_2() { RunCompilerTestCase(@"generic-type-resolution-2.boo"); } [Test] public void generic_type_resolution_3() { RunCompilerTestCase(@"generic-type-resolution-3.boo"); } [Test] public void inference_1() { RunCompilerTestCase(@"inference-1.boo"); } [Test] public void inference_10() { RunCompilerTestCase(@"inference-10.boo"); } [Test] public void inference_2() { RunCompilerTestCase(@"inference-2.boo"); } [Test] public void inference_3() { RunCompilerTestCase(@"inference-3.boo"); } [Test] public void inference_4() { RunCompilerTestCase(@"inference-4.boo"); } [Test] public void inference_5() { RunCompilerTestCase(@"inference-5.boo"); } [Test] public void inference_6() { RunCompilerTestCase(@"inference-6.boo"); } [Test] public void inference_7() { RunCompilerTestCase(@"inference-7.boo"); } [Ignore("Anonymous callable types involving generic type arguments are not handled correctly yet (BOO-854)")][Test] public void inference_8() { RunCompilerTestCase(@"inference-8.boo"); } [Test] public void inference_9() { RunCompilerTestCase(@"inference-9.boo"); } [Test] public void inheritance_1() { RunCompilerTestCase(@"inheritance-1.boo"); } [Test] public void inheritance_2() { RunCompilerTestCase(@"inheritance-2.boo"); } [Test] public void inheritance_3() { RunCompilerTestCase(@"inheritance-3.boo"); } [Test] public void interface_1() { RunCompilerTestCase(@"interface-1.boo"); } [Test] public void interface_with_generic_method() { RunCompilerTestCase(@"interface-with-generic-method.boo"); } [Test] public void internal_generic_callable_type_1() { RunCompilerTestCase(@"internal-generic-callable-type-1.boo"); } [Test] public void internal_generic_callable_type_2() { RunCompilerTestCase(@"internal-generic-callable-type-2.boo"); } [Test] public void internal_generic_callable_type_3() { RunCompilerTestCase(@"internal-generic-callable-type-3.boo"); } [Test] public void internal_generic_type_1() { RunCompilerTestCase(@"internal-generic-type-1.boo"); } [Test] public void internal_generic_type_10() { RunCompilerTestCase(@"internal-generic-type-10.boo"); } [Test] public void internal_generic_type_11() { RunCompilerTestCase(@"internal-generic-type-11.boo"); } [Test] public void internal_generic_type_2() { RunCompilerTestCase(@"internal-generic-type-2.boo"); } [Test] public void internal_generic_type_3() { RunCompilerTestCase(@"internal-generic-type-3.boo"); } [Test] public void internal_generic_type_4() { RunCompilerTestCase(@"internal-generic-type-4.boo"); } [Test] public void internal_generic_type_5() { RunCompilerTestCase(@"internal-generic-type-5.boo"); } [Test] public void internal_generic_type_6() { RunCompilerTestCase(@"internal-generic-type-6.boo"); } [Test] public void internal_generic_type_7() { RunCompilerTestCase(@"internal-generic-type-7.boo"); } [Test] public void internal_generic_type_8() { RunCompilerTestCase(@"internal-generic-type-8.boo"); } [Test] public void internal_generic_type_9() { RunCompilerTestCase(@"internal-generic-type-9.boo"); } [Test] public void method_ref_1() { RunCompilerTestCase(@"method-ref-1.boo"); } [Test] public void mixed_1() { RunCompilerTestCase(@"mixed-1.boo"); } [Test] public void mixed_2() { RunCompilerTestCase(@"mixed-2.boo"); } [Test] public void mixed_3() { RunCompilerTestCase(@"mixed-3.boo"); } [Test] public void mixed_4() { RunCompilerTestCase(@"mixed-4.boo"); } [Test] public void mixed_ref_parameter_1() { RunCompilerTestCase(@"mixed-ref-parameter-1.boo"); } [Test] public void mixed_ref_parameter_2() { RunCompilerTestCase(@"mixed-ref-parameter-2.boo"); } [Test] public void naked_type_constraints_1() { RunCompilerTestCase(@"naked-type-constraints-1.boo"); } [Ignore("generics with nested types not supported yet")][Test] public void nested_generic_type_1() { RunCompilerTestCase(@"nested-generic-type-1.boo"); } [Test] public void nullable_1() { RunCompilerTestCase(@"nullable-1.boo"); } [Test] public void nullable_2() { RunCompilerTestCase(@"nullable-2.boo"); } [Test] public void nullable_3() { RunCompilerTestCase(@"nullable-3.boo"); } [Test] public void nullable_4() { RunCompilerTestCase(@"nullable-4.boo"); } [Test] public void nullable_5() { RunCompilerTestCase(@"nullable-5.boo"); } [Test] public void nullable_6() { RunCompilerTestCase(@"nullable-6.boo"); } [Test] public void override_1() { RunCompilerTestCase(@"override-1.boo"); } [Test] public void override_2() { RunCompilerTestCase(@"override-2.boo"); } [Test] public void override_3() { RunCompilerTestCase(@"override-3.boo"); } [Test] public void override_4() { RunCompilerTestCase(@"override-4.boo"); } [Test] public void override_5() { RunCompilerTestCase(@"override-5.boo"); } [Test] public void type_reference_1() { RunCompilerTestCase(@"type-reference-1.boo"); } [Test] public void type_reference_2() { RunCompilerTestCase(@"type-reference-2.boo"); } [Test] public void type_reference_3() { RunCompilerTestCase(@"type-reference-3.boo"); } override protected string GetRelativeTestCasesPath() { return "net2/generics"; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebChat.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using BTDB.StreamLayer; namespace BTDB.KVDBLayer.BTree { class BTreeRoot : IBTreeRootNode { readonly long _transactionId; long _keyValueCount; IBTreeNode? _rootNode; public BTreeRoot(long transactionId) { _transactionId = transactionId; } public void CreateOrUpdate(ref CreateOrUpdateCtx ctx) { ctx.TransactionId = _transactionId; if (ctx.Stack == null) ctx.Stack = new List<NodeIdxPair>(); else ctx.Stack.Clear(); if (_rootNode == null) { _rootNode = ctx.Key.Length > BTreeLeafComp.MaxTotalLen ? BTreeLeaf.CreateFirst(ref ctx) : BTreeLeafComp.CreateFirst(ref ctx); _keyValueCount = 1; ctx.Stack!.Add(new NodeIdxPair { Node = _rootNode, Idx = 0 }); ctx.KeyIndex = 0; ctx.Created = true; return; } ctx.Depth = 0; _rootNode.CreateOrUpdate(ref ctx); if (ctx.Split) { _rootNode = new BTreeBranch(ctx.TransactionId, ctx.Node1!, ctx.Node2!); ctx.Stack!.Insert(0, new NodeIdxPair { Node = _rootNode, Idx = ctx.SplitInRight ? 1 : 0 }); } else if (ctx.Update) { _rootNode = ctx.Node1; } if (ctx.Created) { _keyValueCount++; } } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key) { throw new InvalidOperationException(); } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key, uint prefixLen) { stack.Clear(); if (_rootNode == null) { keyIndex = -1; return FindResult.NotFound; } var result = _rootNode.FindKey(stack, out keyIndex, key); if (result == FindResult.Previous) { if (keyIndex < 0) { keyIndex = 0; stack[^1] = new NodeIdxPair { Node = stack[^1].Node, Idx = 0 }; result = FindResult.Next; } else { if (!KeyStartsWithPrefix(key.Slice(0, (int)prefixLen), GetKeyFromStack(stack))) { result = FindResult.Next; keyIndex++; if (!FindNextKey(stack)) { return FindResult.NotFound; } } } if (!KeyStartsWithPrefix(key.Slice(0, (int)prefixLen), GetKeyFromStack(stack))) { return FindResult.NotFound; } } return result; } internal static bool KeyStartsWithPrefix(in ReadOnlySpan<byte> prefix, in ReadOnlySpan<byte> key) { if (prefix.Length == 0) return true; if (key.Length < prefix.Length) return false; return prefix.SequenceEqual(key.Slice(0, prefix.Length)); } static ReadOnlySpan<byte> GetKeyFromStack(List<NodeIdxPair> stack) { var last = stack[^1]; return ((IBTreeLeafNode)last.Node).GetKey(last.Idx); } public long CalcKeyCount() { return _keyValueCount; } public byte[] GetLeftMostKey() { return _rootNode!.GetLeftMostKey(); } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { Debug.Assert(keyIndex >= 0 && keyIndex < _keyValueCount); stack.Clear(); _rootNode!.FillStackByIndex(stack, keyIndex); } public long FindLastWithPrefix(in ReadOnlySpan<byte> prefix) { if (_rootNode == null) return -1; return _rootNode.FindLastWithPrefix(prefix); } public bool NextIdxValid(int idx) { return false; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { stack.Add(new NodeIdxPair { Node = _rootNode!, Idx = 0 }); _rootNode.FillStackByLeftMost(stack, 0); } public void FillStackByRightMost(List<NodeIdxPair> stack, int idx) { throw new ArgumentException(); } public int GetLastChildrenIdx() { return 0; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { throw new ArgumentException(); } public IBTreeNode EraseOne(long transactionId, long keyIndex) { throw new ArgumentException(); } public void Iterate(ValuesIterateAction action) { _rootNode?.Iterate(action); } public long TransactionId => _transactionId; public string? DescriptionForLeaks { get; set; } public uint TrLogFileId { get; set; } public uint TrLogOffset { get; set; } public int UseCount { get; set; } public ulong CommitUlong { get; set; } ulong[]? CloneUlongs() { ulong[]? newulongs = null; if (_ulongs != null) { newulongs = new ulong[_ulongs.Length]; Array.Copy(_ulongs, newulongs, newulongs.Length); } return newulongs; } public IBTreeRootNode NewTransactionRoot() { return new BTreeRoot(_transactionId + 1) { _keyValueCount = _keyValueCount, _rootNode = _rootNode, TrLogFileId = TrLogFileId, TrLogOffset = TrLogOffset, CommitUlong = CommitUlong, _ulongs = CloneUlongs() }; } public IBTreeRootNode CloneRoot() { return new BTreeRoot(_transactionId) { _keyValueCount = _keyValueCount, _rootNode = _rootNode, TrLogFileId = TrLogFileId, TrLogOffset = TrLogOffset, CommitUlong = CommitUlong, _ulongs = CloneUlongs() }; } public void EraseOne(long keyIndex) { Debug.Assert(keyIndex >= 0); Debug.Assert(keyIndex < _keyValueCount); if (1 == _keyValueCount) { _rootNode = null; _keyValueCount = 0; return; } _keyValueCount --; _rootNode = _rootNode!.EraseOne(TransactionId, keyIndex); } public void EraseRange(long firstKeyIndex, long lastKeyIndex) { Debug.Assert(firstKeyIndex >= 0); Debug.Assert(lastKeyIndex < _keyValueCount); if (firstKeyIndex == 0 && lastKeyIndex == _keyValueCount - 1) { _rootNode = null; _keyValueCount = 0; return; } _keyValueCount -= lastKeyIndex - firstKeyIndex + 1; _rootNode = _rootNode!.EraseRange(TransactionId, firstKeyIndex, lastKeyIndex); } public bool FindNextKey(List<NodeIdxPair> stack) { var idx = stack.Count - 1; while (idx >= 0) { var pair = stack[idx]; if (pair.Node.NextIdxValid(pair.Idx)) { stack.RemoveRange(idx + 1, stack.Count - idx - 1); stack[idx] = new NodeIdxPair { Node = pair.Node, Idx = pair.Idx + 1 }; pair.Node.FillStackByLeftMost(stack, pair.Idx + 1); return true; } idx--; } return false; } public bool FindPreviousKey(List<NodeIdxPair> stack) { int idx = stack.Count - 1; while (idx >= 0) { var pair = stack[idx]; if (pair.Idx > 0) { stack.RemoveRange(idx + 1, stack.Count - idx - 1); stack[idx] = new NodeIdxPair { Node = pair.Node, Idx = pair.Idx - 1 }; pair.Node.FillStackByRightMost(stack, pair.Idx - 1); return true; } idx--; } return false; } public void BuildTree(long keyCount, ref SpanReader reader, BuildTreeCallback memberGenerator) { _keyValueCount = keyCount; if (keyCount == 0) { _rootNode = null; return; } _rootNode = BuildTreeNode(keyCount, ref reader, memberGenerator); } IBTreeNode IBTreeNode.ReplaceValues(ReplaceValuesCtx ctx) { throw new InvalidOperationException(); } public void ReplaceValues(ReplaceValuesCtx ctx) { if (_rootNode == null) return; ctx._transactionId = TransactionId; _rootNode = _rootNode.ReplaceValues(ctx); } IBTreeNode BuildTreeNode(long keyCount, ref SpanReader outsideReader, BuildTreeCallback memberGenerator) { var leafs = (keyCount + BTreeLeafComp.MaxMembers - 1) / BTreeLeafComp.MaxMembers; var order = 0L; var done = 0L; return BuildBranchNode(leafs, ref outsideReader, (ref SpanReader reader) => { order++; var reach = keyCount * order / leafs; var todo = (int)(reach - done); done = reach; var keyValues = new BTreeLeafMember[todo]; long totalKeyLen = 0; for (var i = 0; i < keyValues.Length; i++) { keyValues[i] = memberGenerator(ref reader); totalKeyLen += keyValues[i].Key.Length; } if (totalKeyLen > BTreeLeafComp.MaxTotalLen) { return new BTreeLeaf(_transactionId, keyValues); } return new BTreeLeafComp(_transactionId, keyValues); }); } IBTreeNode BuildBranchNode(long count, ref SpanReader reader, BuildBranchNodeGenerator generator) { if (count == 1) return generator(ref reader); var children = (count + BTreeBranch.MaxChildren - 1) / BTreeBranch.MaxChildren; var order = 0L; var done = 0L; return BuildBranchNode(children, ref reader, (ref SpanReader reader2) => { order++; var reach = count * order / children; var todo = (int)(reach - done); done = reach; return new BTreeBranch(_transactionId, todo, ref reader2, generator); }); } ulong[]? _ulongs; public ulong GetUlong(uint idx) { if (_ulongs == null) return 0; if (idx >= _ulongs.Length) return 0; return _ulongs[idx]; } public void SetUlong(uint idx, ulong value) { if (_ulongs == null || idx >= _ulongs.Length) Array.Resize(ref _ulongs, (int)(idx + 1)); _ulongs[idx] = value; } public ulong[]? UlongsArray { get => _ulongs; set => _ulongs = value; } } }
using System; using System.Linq; using InAudioSystem.ExtensionMethods; using InAudioSystem.Internal; using InAudioSystem.TreeDrawer; using UnityEditor; using UnityEngine; namespace InAudioSystem.InAudioEditor { public class AudioCreatorGUI : BaseCreatorGUI<InAudioNode> { public AudioCreatorGUI(InAudioWindow window) : base(window) { this.window = window; } private int leftWidth; private int height; public bool OnGUI(int leftWidth, int height) { BaseOnGUI(); this.leftWidth = leftWidth; this.height = height; EditorGUIHelper.DrawColums(DrawLeftSide, DrawRightSide); return isDirty; } public override void OnEnable() { base.OnEnable(); treeDrawer.CanPlaceHere = CanPlaceHere; treeDrawer.AssignNewParent = AssignNewParent; treeDrawer.DeattachFromParent = DeattachFromParent; } private void AssignNewParent(InAudioNode newParent, InAudioNode node, int index) { if (newParent._type == AudioNodeType.Random) { var randomData = newParent._nodeData as RandomData; InUndoHelper.RecordObject(randomData, "Random weights"); randomData.weights.Insert(index, 50); } newParent._children.Insert(index, node); node._parent = newParent; } private void DeattachFromParent(InAudioNode node) { var parent = node._parent; if (parent._type == AudioNodeType.Random) { Undo.RecordObject(parent._nodeData, "Random weights"); int currentIndexInParent = parent._children.IndexOf(node); (parent._nodeData as RandomData).weights.RemoveAt(currentIndexInParent); } parent._getChildren.Remove(node); } private bool CanPlaceHere(InAudioNode newParent, InAudioNode toPlace) { if (newParent._type == AudioNodeType.Audio) return false; return true; } private void DrawLeftSide(Rect area) { Rect treeArea = EditorGUILayout.BeginVertical(GUILayout.Width(leftWidth), GUILayout.Height(height)); DrawSearchBar(); EditorGUILayout.BeginVertical(); isDirty |= treeDrawer.DrawTree(InAudioInstanceFinder.DataManager.AudioTree, treeArea); SelectedNode = treeDrawer.SelectedNode; if (GUIData != null) { GUIData.SelectedNode = treeDrawer.SelectedNode._ID; } EditorGUILayout.EndVertical(); EditorGUILayout.EndVertical(); } private void DrawRightSide(Rect area) { EditorGUILayout.BeginVertical(); if (SelectedNode != null) { DrawTypeControls(SelectedNode); GUI.enabled = true; } EditorGUILayout.EndVertical(); } private void DrawTypeControls(InAudioNode node) { try { var type = node._type; if (node._nodeData != null) { switch (type) { case AudioNodeType.Audio: AudioDataDrawer.Draw(node); break; case AudioNodeType.Sequence: SequenceDataDrawer.Draw(node); break; case AudioNodeType.Random: RandomDataDrawer.Draw(node); break; case AudioNodeType.Multi: MultiDataDrawer.Draw(node); break; case AudioNodeType.Folder: FolderDrawer.Draw(node); break; case AudioNodeType.Track: TrackDataDrawer.Draw(node); break; case AudioNodeType.Root: FolderDrawer.Draw(node); break; } } else if (SelectedNode._type == AudioNodeType.Folder || SelectedNode._type == AudioNodeType.Root) { FolderDrawer.Draw(node); } else { EditorGUILayout.HelpBox("Corrupt data. The data for this node does either not exist or is corrupt.", MessageType.Error, true); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Create new element", GUILayout.Width(150))) { AudioNodeWorker.AddDataClass(node); } EditorGUILayout.EndHorizontal(); } } catch (ExitGUIException e) { throw e; } catch (ArgumentException e) { throw e; } /*catch (Exception e) { //While this catch was made to catch persistent errors, like a missing null check, it can also catch other errors EditorGUILayout.BeginVertical(); EditorGUILayout.HelpBox("An exception is getting caught while trying to draw node. ", MessageType.Error, true); if (GUILayout.Button("Create new element", GUILayout.Width(150))) { AudioNodeWorker.AddDataClass(node); } EditorGUILayout.TextArea(e.ToString()); EditorGUILayout.EndVertical(); }*/ } protected override bool CanDropObjects(InAudioNode node, UnityEngine.Object[] objects) { if (node == null || objects == null) return false; int clipCount = DragAndDrop.objectReferences.Count(p => p is AudioClip); int nodeCount = DragAndDrop.objectReferences.Count(p => p is InAudioNode); if (DragAndDrop.objectReferences.Length == 0) return false; if (clipCount == objects.Length) //Handle clip count { //clipCount == 1 means it overrides the current clip if (node._type == AudioNodeType.Audio && clipCount != 1) return false; return true; } else if (nodeCount == objects.Length) //Handle audio node drag n drop { if (node._type == AudioNodeType.Audio) //Can't drop on an audionode as it can't have children return false; var draggingNode = objects[0] as InAudioNode; if (!node.IsRootOrFolder && draggingNode.IsRootOrFolder) return false; if (node == draggingNode) return false; return !NodeWorker.IsChildOf(objects[0] as InAudioNode, node); } return false; } protected override void OnDrop(InAudioNode node, UnityEngine.Object[] objects) { if (objects[0] as InAudioNode != null) //Drag N Drop internally in the tree, change the parent { InUndoHelper.DoInGroup(() => { node.EditorSettings.IsFoldedOut = true; var nodeToMove = objects[0] as InAudioNode; if (node.gameObject != nodeToMove.gameObject) { if (EditorUtility.DisplayDialog("Move?", "Warning, this will break all external references to this and all child nodes!\n" + "Move node from\"" + nodeToMove.gameObject.name + "\" to \"" + node.gameObject.name + "\"?", "Ok", "Cancel")) { treeDrawer.SelectedNode = treeDrawer.SelectedNode._getParent; isDirty = false; AudioNodeWorker.CopyTo(nodeToMove, node); AudioNodeWorker.DeleteNodeNoGroup(nodeToMove); } } else { MoveNode(node, nodeToMove); } }); } else if (node._type != AudioNodeType.Audio) //Create new audio nodes when we drop clips { InUndoHelper.DoInGroup(() => { InUndoHelper.RecordObject(InUndoHelper.NodeUndo(node), "Adding Nodes to " + node.Name); AudioClip[] clips = objects.Convert(o => o as AudioClip); Array.Sort(clips, (clip, audioClip) => StringLogicalComparer.Compare(clip.name, audioClip.name)); for (int i = 0; i < clips.Length; ++i) { var clip = clips[i]; var child = AudioNodeWorker.CreateChild(node, AudioNodeType.Audio); var path = AssetDatabase.GetAssetPath(clip); try { //Try and get the name of the clip. Gets the name and removes the end. Assets/IntroSound.mp3 -> IntroSound int lastIndex = path.LastIndexOf('/') + 1; child.Name = path.Substring(lastIndex, path.LastIndexOf('.') - lastIndex); } catch (Exception) //If it happens to be a mutant path. Not even sure if this is possible, but better safe than sorry { child.Name = node.Name + " Child"; } var audioData = (child._nodeData as InAudioData); audioData.AudioClip = clip; Event.current.UseEvent(); } }); } else //Then it must be an audio clip dropped on an audio node, so assign the clip to that node { InUndoHelper.DoInGroup(() => { var nodeData = (node._nodeData as InAudioData); if (nodeData != null) { InUndoHelper.RecordObject(InUndoHelper.NodeUndo(node), "Change Audio Clip In " + node.Name); nodeData.AudioClip = objects[0] as AudioClip; } }); Event.current.UseEvent(); } } private static void MoveNode(InAudioNode node, InAudioNode nodeToMove) { InUndoHelper.RecordObject( new UnityEngine.Object[] {node, node._nodeData, node._parent, node._parent != null ? node._parent._nodeData : null, nodeToMove._parent._nodeData, nodeToMove, nodeToMove._parent, nodeToMove._parent._nodeData}.AddObj(), "Audio Node Move"); NodeWorker.ReasignNodeParent(nodeToMove, node); Event.current.UseEvent(); } protected override void OnContext(InAudioNode node) { var menu = new GenericMenu(); menu.AddDisabledItem(new GUIContent(node.Name)); menu.AddSeparator(""); #region Duplicate if (!node.IsRoot) menu.AddItem(new GUIContent("Duplicate"), false, data => AudioNodeWorker.Duplicate(node), node); else menu.AddDisabledItem(new GUIContent("Duplicate")); menu.AddSeparator(""); #endregion if (node.IsRootOrFolder) { menu.AddItem(new GUIContent("Create child folder in new prefab"), false, obj => { CreateFolderInNewPrefab(node); }, node); menu.AddSeparator(""); } #region Create child if (node._type == AudioNodeType.Audio || node._type == AudioNodeType.Voice) //If it is a an audio source, it cannot have any children { menu.AddDisabledItem(new GUIContent(@"Create Child/Folder")); menu.AddDisabledItem(new GUIContent(@"Create Child/Audio")); menu.AddDisabledItem(new GUIContent(@"Create Child/Random")); menu.AddDisabledItem(new GUIContent(@"Create Child/Sequence")); menu.AddDisabledItem(new GUIContent(@"Create Child/Multi")); #if UNITY_TRACK menu.AddDisabledItem(new GUIContent(@"Create Child/Track")); #endif //menu.AddDisabledItem(new GUIContent(@"Create Child/Voice")); } else { if (node.IsRootOrFolder) menu.AddItem(new GUIContent(@"Create Child/Folder"), false, (obj) => CreateChild(node, AudioNodeType.Folder), node); else menu.AddDisabledItem(new GUIContent(@"Create Child/Folder")); menu.AddItem(new GUIContent(@"Create Child/Audio"), false, (obj) => CreateChild(node, AudioNodeType.Audio), node); menu.AddItem(new GUIContent(@"Create Child/Random"), false, (obj) => CreateChild(node, AudioNodeType.Random), node); menu.AddItem(new GUIContent(@"Create Child/Sequence"), false, (obj) => CreateChild(node, AudioNodeType.Sequence), node); menu.AddItem(new GUIContent(@"Create Child/Multi"), false, (obj) => CreateChild(node, AudioNodeType.Multi), node); #if UNITY_TRACK if (node.IsRootOrFolder) { menu.AddItem(new GUIContent(@"Create Child/Track"), false, (obj) => CreateChild(node, AudioNodeType.Track), node); } else { menu.AddDisabledItem(new GUIContent(@"Create Child/Track")); } #endif //menu.AddItem(new GUIContent(@"Create Child/Track"), false, (obj) => CreateChild(node, AudioNodeType.Track), node); //menu.AddItem(new GUIContent(@"Create Child/Voice"), false, (obj) => CreateChild(node, AudioNodeType.Voice), node); } #endregion menu.AddSeparator(""); #region Add new parent if (node._parent != null && (node._parent._type == AudioNodeType.Folder || node._parent._type == AudioNodeType.Root)) menu.AddItem(new GUIContent(@"Add Parent/Folder"), false, (obj) => AudioNodeWorker.AddNewParent(node, AudioNodeType.Folder), node); else menu.AddDisabledItem(new GUIContent(@"Add Parent/Folder")); menu.AddDisabledItem(new GUIContent(@"Add Parent/Audio")); if (node._parent != null && node._type != AudioNodeType.Folder) { menu.AddItem(new GUIContent(@"Add Parent/Random"), false, (obj) => AudioNodeWorker.AddNewParent(node, AudioNodeType.Random), node); menu.AddItem(new GUIContent(@"Add Parent/Sequence"), false, (obj) => AudioNodeWorker.AddNewParent(node, AudioNodeType.Sequence), node); menu.AddItem(new GUIContent(@"Add Parent/Multi"), false, (obj) => AudioNodeWorker.AddNewParent(node, AudioNodeType.Multi), node); //menu.AddItem(new GUIContent(@"Add Parent/Track"), false, (obj) => AudioNodeWorker.AddNewParent(node, AudioNodeType.Track), node); } else { menu.AddDisabledItem(new GUIContent(@"Add Parent/Random")); menu.AddDisabledItem(new GUIContent(@"Add Parent/Sequence")); menu.AddDisabledItem(new GUIContent(@"Add Parent/Multi")); //menu.AddDisabledItem(new GUIContent(@"Add Parent/Track")); } //menu.AddDisabledItem(new GUIContent(@"Add Parent/Voice")); #endregion menu.AddSeparator(""); #region Convert to if (node._children.Count == 0 && !node.IsRootOrFolder) menu.AddItem(new GUIContent(@"Convert To/Audio"), false, (obj) => AudioNodeWorker.ConvertNodeType(node, AudioNodeType.Audio), node); else menu.AddDisabledItem(new GUIContent(@"Convert To/Audio")); if (!node.IsRootOrFolder) { menu.AddItem(new GUIContent(@"Convert To/Random"), false, (obj) => AudioNodeWorker.ConvertNodeType(node, AudioNodeType.Random), node); menu.AddItem(new GUIContent(@"Convert To/Sequence"), false, (obj) => AudioNodeWorker.ConvertNodeType(node, AudioNodeType.Sequence), node); menu.AddItem(new GUIContent(@"Convert To/Multi"), false, (obj) => AudioNodeWorker.ConvertNodeType(node, AudioNodeType.Multi), node); //menu.AddItem(new GUIContent(@"Convert To/Track"), false, (obj) => AudioNodeWorker.ConvertNodeType(node, AudioNodeType.Track), node); } else { menu.AddDisabledItem(new GUIContent(@"Convert To/Random")); menu.AddDisabledItem(new GUIContent(@"Convert To/Sequence")); menu.AddDisabledItem(new GUIContent(@"Convert To/Multi")); //menu.AddDisabledItem(new GUIContent(@"Add Parent/Track")); } #endregion menu.AddSeparator(""); #region Send to event if (!node.IsRootOrFolder) { menu.AddItem(new GUIContent("Send to Event Window"), false, () => EditorWindow.GetWindow<EventWindow>().ReceiveNode(node)); } else { menu.AddDisabledItem(new GUIContent("Send to Event Window")); } #endregion menu.AddSeparator(""); #region Delete if (node._type != AudioNodeType.Root) menu.AddItem(new GUIContent("Delete"), false, obj => { treeDrawer.SelectedNode = TreeWalker.GetPreviousVisibleNode(treeDrawer.SelectedNode); AudioNodeWorker.DeleteNode(node); }, node); else menu.AddDisabledItem(new GUIContent("Delete")); #endregion menu.ShowAsContext(); } private void CreateFolderInNewPrefab(InAudioNode parent) { InAudioWindowOpener.ShowNewDataWindow((gameObject => { var node = AudioNodeWorker.CreateChild(gameObject, parent, AudioNodeType.Folder); node.Name += " (External)"; (node._nodeData as InFolderData).ExternalPlacement = true; })); } private void CreateChild(InAudioNode parent, AudioNodeType type) { InUndoHelper.RecordObjectFull(new UnityEngine.Object[] { parent }, "Create Audio Node"); AudioNodeWorker.CreateChild(parent, type); } protected override bool OnNodeDraw(InAudioNode node, bool isSelected, out bool clicked) { return GenericTreeNodeDrawer.Draw(node, isSelected, out clicked); } protected override InAudioNode Root() { if (InAudioInstanceFinder.DataManager == null) { return null; } return InAudioInstanceFinder.DataManager.AudioTree; } protected override GUIPrefs GUIData { get { if(InAudioInstanceFinder.InAudioGuiUserPrefs != null) return InAudioInstanceFinder.InAudioGuiUserPrefs.AudioGUIData; else return null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Tools.ServiceModel.SvcUtil.XmlSerializer { using System; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Text; internal abstract class OutputModule { protected const string defaultFilename = "output"; protected const string configFileExtension = ".config"; private readonly string _directoryPath; protected OutputModule(Options options) { _directoryPath = PathHelper.TryGetDirectoryPath(options.DirectoryArg); } protected string BuildFilePath(string filepath, string extension, string option) { return PathHelper.BuildFilePath(_directoryPath, filepath, extension, option); } protected static class PathHelper { internal static string BuildFilePath(string directoryPath, string filepath, string extension, string option) { Tool.Assert(!string.IsNullOrEmpty(filepath), "filename must have a valid value"); Tool.Assert(!string.IsNullOrEmpty(extension), "extension must have a valid value"); string outputFileWithExtension = GetFilepathWithExtension(filepath, extension); string combinedPath = Path.Combine(directoryPath, outputFileWithExtension); return TryGetFullPath(combinedPath, option); } internal static string GetFilepathWithExtension(string outputFile, string extension) { string outputFileWithExtension; if (extension != null && (!Path.HasExtension(outputFile) || !Path.GetExtension(outputFile).Equals(extension, StringComparison.OrdinalIgnoreCase))) { outputFileWithExtension = outputFile + extension; } else { outputFileWithExtension = outputFile; } return outputFileWithExtension; } internal static string TryGetDirectoryPath(string directory) { if (directory == null || directory.Length == 0) return ".\\"; else { if (!directory.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) return TryGetFullPath(directory + Path.DirectorySeparatorChar, null); else return TryGetFullPath(directory, null); } } private static string TryGetFullPath(string path, string option) { try { return Path.GetFullPath(path); } catch (PathTooLongException ptle) { if (!string.IsNullOrEmpty(option)) { throw new ToolArgumentException(SR.Format(SR.ErrPathTooLong, path, Options.Cmd.Directory, option), ptle); } else { throw new ToolArgumentException(SR.Format(SR.ErrPathTooLongDirOnly, path, Options.Cmd.Directory), ptle); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolArgumentException(SR.Format(SR.ErrInvalidPath, path, option), e); } } } internal static void CreateDirectoryIfNeeded(string path) { try { string directoryPath = Path.GetDirectoryName(path); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolRuntimeException(SR.Format(SR.ErrCannotCreateDirectory, path), e); } } internal static class FilenameHelper { private const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; private static int s_dataContractXsdBaseNamespaceLength = DataContractXsdBaseNamespace.Length; private static readonly List<string> s_existingFileNames = new List<string>(); internal static string UniquifyFileName(string filename, string extension) { string fileNameWithExtension = PathHelper.GetFilepathWithExtension(filename, extension); if (!UniquifyFileName_NameExists(fileNameWithExtension)) { s_existingFileNames.Add(fileNameWithExtension); return filename; } for (uint i = 1; i < uint.MaxValue; i++) { string uniqueFileName = filename + i.ToString(NumberFormatInfo.InvariantInfo); string uniqueFileNameWithExtension = PathHelper.GetFilepathWithExtension(uniqueFileName, extension); if (!UniquifyFileName_NameExists(uniqueFileNameWithExtension)) { s_existingFileNames.Add(uniqueFileNameWithExtension); return uniqueFileName; } } throw new ToolRuntimeException(SR.Format(SR.ErrUnableToUniquifyFilename, fileNameWithExtension), null); } private static bool UniquifyFileName_NameExists(string fileName) { for (int i = 0; i < s_existingFileNames.Count; i++) { if (String.Compare(fileName, s_existingFileNames[i], StringComparison.OrdinalIgnoreCase) == 0) return true; } return false; } internal static string FilenameFromUri(string ns) { StringBuilder fileNameBuilder = new StringBuilder(); if (string.IsNullOrEmpty(ns)) FilenameFromUri_Add(fileNameBuilder, "noNamespace"); else { Uri nsUri = null; if (Uri.TryCreate(ns, UriKind.RelativeOrAbsolute, out nsUri)) { if (nsUri.IsAbsoluteUri) { string absoluteUriString = nsUri.AbsoluteUri; if (absoluteUriString.StartsWith(DataContractXsdBaseNamespace, StringComparison.Ordinal)) { int length = absoluteUriString.Length - s_dataContractXsdBaseNamespaceLength; if (absoluteUriString.EndsWith("/", StringComparison.Ordinal)) length--; if (length > 0) { FilenameFromUri_Add(fileNameBuilder, absoluteUriString.Substring(s_dataContractXsdBaseNamespaceLength, length).Replace('/', '.')); } else { FilenameFromUri_Add(fileNameBuilder, "schema"); } } else { FilenameFromUri_Add(fileNameBuilder, nsUri.Host); string absolutePath = nsUri.AbsolutePath; if (absolutePath.EndsWith("/", StringComparison.Ordinal)) absolutePath = absolutePath.Substring(0, absolutePath.Length - 1); FilenameFromUri_Add(fileNameBuilder, absolutePath.Replace('/', '.')); } } else { FilenameFromUri_Add(fileNameBuilder, nsUri.OriginalString.Replace('/', '.')); } } } string filename = fileNameBuilder.ToString(); return filename; } private static void FilenameFromUri_Add(StringBuilder path, string segment) { if (segment != null) { char[] chars = segment.ToCharArray(); for (int i = 0; i < chars.Length; i++) { char c = chars[i]; if (Array.IndexOf(Path.GetInvalidFileNameChars(), c) == -1) path.Append(c); } } } } } }
using NUnit.Framework; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class RectangleUnitTests : BaseTestFixture { [Test] public void TestRectangleConstruction () { var rect = new Rectangle (); Assert.AreEqual (0, rect.X); Assert.AreEqual (0, rect.Y); Assert.AreEqual (0, rect.Width); Assert.AreEqual (0, rect.Height); rect = new Rectangle (2, 3, 4, 5); Assert.AreEqual (2, rect.X); Assert.AreEqual (3, rect.Y); Assert.AreEqual (4, rect.Width); Assert.AreEqual (5, rect.Height); rect = new Rectangle (new Point (2, 3), new Size (4, 5)); Assert.AreEqual (2, rect.X); Assert.AreEqual (3, rect.Y); Assert.AreEqual (4, rect.Width); Assert.AreEqual (5, rect.Height); } [Test] public void TestRectangleFromLTRB () { var rect = Rectangle.FromLTRB (10, 10, 30, 40); Assert.AreEqual (new Rectangle (10, 10, 20, 30), rect); } [Test] public void TestRectangleCalculatedPoints () { var rect = new Rectangle (2, 3, 4, 5); Assert.AreEqual (2, rect.Left); Assert.AreEqual (3, rect.Top); Assert.AreEqual (6, rect.Right); Assert.AreEqual (8, rect.Bottom); Assert.AreEqual (new Size (4, 5), rect.Size); Assert.AreEqual (new Point (2, 3), rect.Location); Assert.AreEqual (new Point (4, 5.5), rect.Center); rect.Left = 1; Assert.AreEqual (1, rect.X); rect.Right = 3; Assert.AreEqual (2, rect.Width); rect.Top = 1; Assert.AreEqual (1, rect.Y); rect.Bottom = 2; Assert.AreEqual (1, rect.Height); } [Test] public void TestRectangleContains () { var rect = new Rectangle (0, 0, 10, 10); Assert.True (rect.Contains (5, 5)); Assert.True (rect.Contains (new Point (5, 5))); Assert.True (rect.Contains (new Rectangle (1, 1, 3, 3))); Assert.True (rect.Contains (0, 0)); Assert.False (rect.Contains (10, 10)); } [Test] public void TestRectangleInflate () { var rect = new Rectangle (0, 0, 10, 10); rect = rect.Inflate (5, 5); Assert.AreEqual (new Rectangle (-5, -5, 20, 20), rect); rect = rect.Inflate (new Size (-5, -5)); Assert.AreEqual (new Rectangle (0, 0, 10, 10), rect); } [Test] public void TestRectangleOffset () { var rect = new Rectangle (0, 0, 10, 10); rect = rect.Offset (10, 10); Assert.AreEqual (new Rectangle (10, 10, 10, 10), rect); rect = rect.Offset (new Point (-10, -10)); Assert.AreEqual (new Rectangle (0, 0, 10, 10), rect); } [Test] public void TestRectangleRound () { var rect = new Rectangle (0.2, 0.3, 0.6, 0.7); Assert.AreEqual (new Rectangle (0, 0, 1, 1), rect.Round ()); } [Test] public void TestRectangleIntersect () { var rect1 = new Rectangle (0, 0, 10, 10); var rect2 = new Rectangle (2, 2, 6, 6); var intersection = rect1.Intersect (rect2); Assert.AreEqual (rect2, intersection); rect2 = new Rectangle(2, 2, 12, 12); intersection = rect1.Intersect (rect2); Assert.AreEqual (new Rectangle (2, 2, 8, 8), intersection); rect2 = new Rectangle (20, 20, 2, 2); intersection = rect1.Intersect (rect2); Assert.AreEqual (Rectangle.Zero, intersection); } [Test] [TestCase(0, 0, ExpectedResult = true)] [TestCase(0, 5, ExpectedResult = true)] [TestCase(5, 0, ExpectedResult = true)] [TestCase(2, 3, ExpectedResult = false)] public bool TestIsEmpty (int w, int h) { return new Rectangle (0, 0, w, h).IsEmpty; } [Test] [TestCase(0, 0, 8, 8, 0, 0, 5, 5, ExpectedResult = true)] [TestCase(0, 0, 5, 5, 5, 5, 5, 5, ExpectedResult = false)] [TestCase(0, 0, 2, 2, 3, 0, 5, 5, ExpectedResult = false)] public bool TestIntersectsWith (double x1, double y1, double w1, double h1, double x2, double y2, double w2, double h2) { return new Rectangle (x1, y1, w1, h1).IntersectsWith (new Rectangle (x2, y2, w2, h2)); } [Test] public void TestSetSize () { var rect = new Rectangle (); rect.Size = new Size (10, 20); Assert.AreEqual (new Rectangle (0, 0, 10, 20), rect); } [Test] public void TestSetLocation () { var rect = new Rectangle (); rect.Location = new Point (10, 20); Assert.AreEqual (new Rectangle (10, 20, 0, 0), rect); } [Test] public void TestUnion () { Assert.AreEqual (new Rectangle (0, 3, 13, 10), new Rectangle (3, 3, 10, 10).Union (new Rectangle(0, 5, 2, 2))); } [Test] [TestCase(0, 0, 2, 2, ExpectedResult = "{X=0 Y=0 Width=2 Height=2}")] [TestCase(1, 0, 3, 2, ExpectedResult = "{X=1 Y=0 Width=3 Height=2}")] public string TestRectangleToString (double x, double y, double w, double h) { return new Rectangle (x, y, w, h).ToString (); } [Test] public void TestRectangleEquals () { Assert.True (new Rectangle (0, 0, 10, 10).Equals (new Rectangle(0, 0, 10, 10))); Assert.False (new Rectangle (0, 0, 10, 10).Equals ("Rectangle")); Assert.False (new Rectangle (0, 0, 10, 10).Equals (null)); Assert.True (new Rectangle (0, 0, 10, 10) == new Rectangle (0, 0, 10, 10)); Assert.True (new Rectangle (0, 0, 10, 10) != new Rectangle (0, 0, 10, 5)); } [Test] public void TestRectangleGetHashCode ([Range(3, 4)] double x1, [Range(3, 4)] double y1, [Range(3, 4)] double w1, [Range(3, 4)] double h1, [Range(3, 4)] double x2, [Range(3, 4)] double y2, [Range(3, 4)] double w2, [Range(3, 4)] double h2) { bool result = new Rectangle (x1, y1, w1, h1).GetHashCode () == new Rectangle (x2, y2, w2, h2).GetHashCode (); if (x1 == x2 && y1 == y2 && w1 == w2 && h1 == h2) Assert.True (result); else Assert.False (result); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using NuGet.Common; using NuGet.Packaging.Core; using NuGet.Versioning; namespace Sleet { public static class DeleteCommand { /// <summary> /// Lock the feed and delete a single package or all packages of a given id if no version is provided. /// </summary> /// <param name="packageId"></param> /// <param name="version">If empty all versions will be deleted.</param> public static async Task<bool> RunAsync(LocalSettings settings, ISleetFileSystem source, string packageId, string version, string reason, bool force, ILogger log) { var success = true; var token = CancellationToken.None; log.LogMinimal($"Reading feed {source.BaseURI.AbsoluteUri}"); // Check if already initialized using (var feedLock = await SourceUtility.VerifyInitAndLock(settings, source, "Delete", log, token)) { // Validate source await SourceUtility.ValidateFeedForClient(source, log, token); // Get sleet.settings.json var sourceSettings = await FeedSettingsUtility.GetSettingsOrDefault(source, log, token); // Settings context used for all operations var context = new SleetContext() { LocalSettings = settings, SourceSettings = sourceSettings, Log = log, Source = source, Token = token }; var packageIndex = new PackageIndex(context); var existingPackageSets = await packageIndex.GetPackageSetsAsync(); var packages = new HashSet<PackageIdentity>(); if (!string.IsNullOrEmpty(version)) { // Delete a single version of the package var packageVersion = NuGetVersion.Parse(version); packages.Add(new PackageIdentity(packageId, packageVersion)); } else { // Delete all versions of the package packages.UnionWith(await existingPackageSets.Packages.GetPackagesByIdAsync(packageId)); packages.UnionWith(await existingPackageSets.Symbols.GetPackagesByIdAsync(packageId)); } if (string.IsNullOrEmpty(reason)) { reason = string.Empty; } await RemovePackages(force, log, context, existingPackageSets, packages); // Save all log.LogMinimal($"Committing changes to {source.BaseURI.AbsoluteUri}"); success &= await source.Commit(log, token); } if (success) { log.LogMinimal($"Successfully deleted packages."); } else { log.LogError($"Failed to delete packages."); } return success; } /// <summary> /// Lock the feed and delete all packages given. /// </summary> public static async Task<bool> DeletePackagesAsync(LocalSettings settings, ISleetFileSystem source, IEnumerable<PackageIdentity> packagesToDelete, string reason, bool force, ILogger log) { var success = true; var token = CancellationToken.None; log.LogMinimal($"Reading feed {source.BaseURI.AbsoluteUri}"); // Check if already initialized using (var feedLock = await SourceUtility.VerifyInitAndLock(settings, source, "Delete", log, token)) { // Validate source await SourceUtility.ValidateFeedForClient(source, log, token); // Get sleet.settings.json var sourceSettings = await FeedSettingsUtility.GetSettingsOrDefault(source, log, token); // Settings context used for all operations var context = new SleetContext() { LocalSettings = settings, SourceSettings = sourceSettings, Log = log, Source = source, Token = token }; var packageIndex = new PackageIndex(context); var existingPackageSets = await packageIndex.GetPackageSetsAsync(); var packages = new HashSet<PackageIdentity>(packagesToDelete); if (string.IsNullOrEmpty(reason)) { reason = string.Empty; } await RemovePackages(force, log, context, existingPackageSets, packages); // Save all log.LogMinimal($"Committing changes to {source.BaseURI.AbsoluteUri}"); success &= await source.Commit(log, token); } if (success) { log.LogMinimal($"Successfully deleted packages."); } else { log.LogError($"Failed to delete packages."); } return success; } private static async Task RemovePackages(bool force, ILogger log, SleetContext context, PackageSets existingPackageSets, HashSet<PackageIdentity> packages) { var toRemove = new HashSet<PackageIdentity>(); var toRemoveSymbols = new HashSet<PackageIdentity>(); foreach (var package in packages) { var exists = existingPackageSets.Packages.Exists(package); var symbolsExists = existingPackageSets.Symbols.Exists(package); if (!exists && !symbolsExists) { log.LogInformation($"{package.ToString()} does not exist."); if (force) { // ignore failures continue; } else { throw new InvalidOperationException($"Package does not exists: {package.ToString()}"); } } if (exists) { toRemove.Add(package); } if (symbolsExists) { toRemoveSymbols.Add(package); } var message = $"Removing {package.ToString()}"; if (exists && symbolsExists) { message = $"Removing {package.ToString()} and symbols package for {package.ToString()}"; } else if (symbolsExists) { message = $"Removing symbols package {package.ToString()}"; } await log.LogAsync(LogLevel.Information, message); } // Update feed await log.LogAsync(LogLevel.Information, "Removing packages from feed locally"); // Add/Remove packages var changeContext = SleetOperations.CreateDelete(existingPackageSets, toRemove, toRemoveSymbols); await SleetUtility.ApplyPackageChangesAsync(context, changeContext); } } }
/// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class Frame { private string framestringsField; private string framefretsField; private FirstFret _firstFretField; private FrameNote[] _frameNoteField; private decimal defaultxField; private bool defaultxFieldSpecified; private decimal defaultyField; private bool defaultyFieldSpecified; private decimal relativexField; private bool relativexFieldSpecified; private decimal relativeyField; private bool relativeyFieldSpecified; private string colorField; private LeftCenterRight halignField; private bool halignFieldSpecified; private ValignImage valignField; private bool valignFieldSpecified; private decimal heightField; private bool heightFieldSpecified; private decimal widthField; private bool widthFieldSpecified; private string unplayedField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("frame-strings", DataType="positiveInteger")] public string framestrings { get { return this.framestringsField; } set { this.framestringsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("frame-frets", DataType="positiveInteger")] public string framefrets { get { return this.framefretsField; } set { this.framefretsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("first-fret")] public FirstFret FirstFret { get { return this._firstFretField; } set { this._firstFretField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("frame-note")] public FrameNote[] FrameNote { get { return this._frameNoteField; } set { this._frameNoteField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("default-x")] public decimal defaultx { get { return this.defaultxField; } set { this.defaultxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool defaultxSpecified { get { return this.defaultxFieldSpecified; } set { this.defaultxFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("default-y")] public decimal defaulty { get { return this.defaultyField; } set { this.defaultyField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool defaultySpecified { get { return this.defaultyFieldSpecified; } set { this.defaultyFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("relative-x")] public decimal relativex { get { return this.relativexField; } set { this.relativexField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool relativexSpecified { get { return this.relativexFieldSpecified; } set { this.relativexFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("relative-y")] public decimal relativey { get { return this.relativeyField; } set { this.relativeyField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool relativeySpecified { get { return this.relativeyFieldSpecified; } set { this.relativeyFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string color { get { return this.colorField; } set { this.colorField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public LeftCenterRight halign { get { return this.halignField; } set { this.halignField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool halignSpecified { get { return this.halignFieldSpecified; } set { this.halignFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public ValignImage valign { get { return this.valignField; } set { this.valignField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool valignSpecified { get { return this.valignFieldSpecified; } set { this.valignFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public decimal height { get { return this.heightField; } set { this.heightField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool heightSpecified { get { return this.heightFieldSpecified; } set { this.heightFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public decimal width { get { return this.widthField; } set { this.widthField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool widthSpecified { get { return this.widthFieldSpecified; } set { this.widthFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string unplayed { get { return this.unplayedField; } set { this.unplayedField = value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IncidentCS { internal class WebRandomizer : IWebRandomizer { private static string[] ccTLDs = null; private static IRandomWheel<string> standardTLDs = null; private static IRandomWheel<int> hashtagWordsCountWheel; private static IRandomWheel<Func<string>> emailLocalPartWheel; private static IRandomWheel<Func<string>> emailLocalPartNamesOnlyWheel; private static IRandomWheel<Func<string>> domainWheel; private static IRandomWheel<Func<string>> customUrlWheel; private static IRandomWheel<string> customUrlExtensions; private static IRandomWheel<Func<string>> twitterWheel; public string CountryCodeTLD { get { if (ccTLDs == null) ccTLDs = "ccTLD.txt".LinesFromResource().ToArray(); return ccTLDs.ChooseAtRandom(); } } public string StandardTLD { get { if (standardTLDs == null) standardTLDs = Incident.Utils.CreateWheel(new Dictionary<string, double> { { "com", 100 }, { "net", 50 }, { "org", 40 }, { "info", 30 }, { "edu", 20 }, { "gov", 5 }, { "mil", 2 } }); return standardTLDs.RandomElement; } } public string TLD { get { return Incident.Primitive.DoubleUnit < 0.75 ? StandardTLD : CountryCodeTLD; } } public string Hashtag { get { if (hashtagWordsCountWheel == null) { hashtagWordsCountWheel = Incident.Utils.CreateWheel(new Dictionary<int, double> { { 1, 100 }, { 2, 10 }, { 3, 5} }); } return "#" + Incident.Utils.Repeat(() => Incident.Text.Word, hashtagWordsCountWheel.RandomElement); } } public string Email { get { return CustomEmail(); } } public string CustomEmail(string tld = null, bool namesOnly = false) { if (emailLocalPartWheel == null) { emailLocalPartWheel = Incident.Utils.CreateWheel(new Dictionary<Func<string>, double> { { () => Incident.Human.FirstName, 2 }, { () => string.Format("{0}.{1}", Incident.Human.FirstName, Incident.Human.LastName), 2 }, { () => string.Format("{0}{1}", Incident.Human.FirstName.Substring(0, 1), Incident.Human.LastName), 2 }, { () => Incident.Text.Word, 2 }, { () => Incident.Text.Word + Incident.Text.Word, 1 }, { () => string.Format("{0}.{1}", Incident.Text.Word, Incident.Text.Word), 1 } }); } if (emailLocalPartNamesOnlyWheel == null) { emailLocalPartNamesOnlyWheel = Incident.Utils.CreateWheel(new Dictionary<Func<string>, double> { { () => Incident.Human.FirstName, 1 }, { () => string.Format("{0}.{1}", Incident.Human.FirstName, Incident.Human.LastName), 2 }, { () => string.Format("{0}{1}", Incident.Human.FirstName.Substring(0, 1), Incident.Human.LastName), 1 } }); } if (string.IsNullOrEmpty(tld)) tld = StandardTLD; tld = tld.Where(c => char.IsLetterOrDigit(c)).StringJoin(); var localPartSource = namesOnly ? emailLocalPartNamesOnlyWheel : emailLocalPartWheel; var domain = CustomDomain(tld, false); return string.Format("{0}@{1}", localPartSource.RandomElement(), domain).ToLower(); } public string Domain { get { return CustomDomain(); } } public string CustomDomain(string tld = null, bool includeWWW = true) { if (domainWheel == null) { // TODO: add company domain generation after implementing Incident.Business.Company domainWheel = Incident.Utils.CreateWheel(new Dictionary<Func<string>, double> { { () => Incident.Text.Word, 3 }, { () => string.Format("{0}-{1}", Incident.Text.Word, Incident.Text.Word), 2 }, { () => string.Format("www.{0}", Incident.Text.Word), 6 }, { () => string.Format("{0}.{1}", Incident.Text.Word, Incident.Text.Word), 3 }, { () => Incident.Human.LastName, 2 }, { () => string.Format("{0}.{1}", Incident.Human.FirstName, Incident.Human.LastName), 1 }, }); } if (string.IsNullOrEmpty(tld)) tld = TLD; var domainName = domainWheel.RandomElement(); if (!includeWWW && domainName.StartsWith("www.")) domainName = domainName.Substring("www.".Length); return string.Format("{0}.{1}", domainName, tld).ToLower(); } public string Url { get { return CustomUrl(); } } public string CustomUrl(string protocol = "http", string extension = null) { if (customUrlExtensions == null) { customUrlExtensions = Incident.Utils.CreateWheel(new Dictionary<string, double> { { "", 200 }, { "php", 80 }, { "html", 100 }, { "htm", 20 }, { "asp", 20 }, { "aspx", 40 }, { "cgi", 10 }, { "pl", 5 }, { "gif", 10 }, { "jpg", 25 }, { "png", 20 }, { "swf", 5 }, { "json", 5 }, { "js", 5 }, { "css", 5 } }); } if (customUrlWheel == null) { customUrlWheel = Incident.Utils.CreateWheel(new Dictionary<Func<string>, double> { { () => Incident.Text.Word, 30 }, { () => string.Format("{0}/{1}", Incident.Text.Word, Incident.Text.Word), 8 }, { () => string.Format("{0}-{1}", Incident.Text.Word, Incident.Text.Word), 4 }, { () => string.Format("{0}/{1}", Incident.Text.Word, Incident.Primitive.IntegerBetween(1, 1000)), 2 }, { () => string.Format("{0}/{1}/{2}", Incident.Text.Word, Incident.Text.Word, Incident.Primitive.IntegerBetween(1, 1000)), 1 }, }); } extension = extension ?? customUrlExtensions.RandomElement; if (!extension.StartsWith(".") && !string.IsNullOrEmpty(extension)) extension = "." + extension; return string.Format("{0}://{1}/{2}{3}", protocol, Domain, customUrlWheel.RandomElement(), extension); } public string IPv4 { get { return string.Format("{0}.{1}.{2}.{3}", Incident.Primitive.Byte, Incident.Primitive.Byte, Incident.Primitive.Byte, Incident.Primitive.Byte); } } public string LocalIPv4 { get { return string.Format("192.168.{0}.{1}", Incident.Primitive.Byte, Incident.Primitive.Byte); } } public string CustomIPv4(byte? A = null, byte? B = null, byte? C = null) { A = A ?? Incident.Primitive.Byte; B = B ?? Incident.Primitive.Byte; C = C ?? Incident.Primitive.Byte; return string.Format("{0}.{1}.{2}.{3}", A, B, C, Incident.Primitive.Byte); } public string IPv6 { get { return Enumerable.Range(0, 8) .Select(_ => Incident.Primitive.UnsignedShort.ToString("x4")) .StringJoin(":"); } } public string Twitter { get { if (twitterWheel == null) { // TODO: add company twitter generation after implementing Incident.Business.Company twitterWheel = Incident.Utils.CreateWheel(new Dictionary<Func<string>, double> { { () => Incident.Text.Word, 5 }, { () => Incident.Text.Word + Incident.Text.Word, 2 }, { () => Incident.Human.FirstName.Substring(0, 1) + Incident.Human.LastName, 1 }, { () => Incident.Human.FirstName + Incident.Human.LastName, 3 }, }); } return "@" + twitterWheel.RandomElement().ToLower(); } } public string HexColor { get { return string.Format("{0:x2}{1:x2}{2:x2}", Incident.Primitive.Byte, Incident.Primitive.Byte, Incident.Primitive.Byte); } } public string RgbColor { get { return string.Format("rgb({0}, {1}, {2})", Incident.Primitive.Byte, Incident.Primitive.Byte, Incident.Primitive.Byte); } } public string RgbaColor { get { return string.Format("rgba({0}, {1}, {2}, {3})", Incident.Primitive.Byte, Incident.Primitive.Byte, Incident.Primitive.Byte, Math.Round(Incident.Primitive.DoubleUnit, 2)); } } public string GoogleAnalyticsId { get { return string.Format("UA-{0:000000}-{1:00}", Incident.Primitive.IntegerBetween(0, 1000000), Incident.Primitive.IntegerBetween(0, 100)); } } public int Port { get { return Incident.Primitive.IntegerBetween(1, 65536); } } } }
/* * 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 * * 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. */ using System; using System.Collections.Generic; using Avro.IO; namespace Avro.Generic { /// <summary> /// <see cref="PreresolvingDatumReader{T}"/> for reading data to <see cref="GenericRecord"/> /// classes or primitives. /// <see cref="PreresolvingDatumReader{T}">For more information about performance considerations /// for choosing this implementation</see>. /// </summary> /// <typeparam name="T">Type to deserialize data into.</typeparam> public class GenericDatumReader<T> : PreresolvingDatumReader<T> { /// <summary> /// Initializes a new instance of the <see cref="GenericDatumReader{T}"/> class. /// </summary> /// <param name="writerSchema">Schema that was used to write the data.</param> /// <param name="readerSchema">Schema to use to read the data.</param> public GenericDatumReader(Schema writerSchema, Schema readerSchema) : base(writerSchema, readerSchema) { } /// <inheritdoc/> protected override bool IsReusable(Schema.Type tag) { switch (tag) { case Schema.Type.Double: case Schema.Type.Boolean: case Schema.Type.Int: case Schema.Type.Long: case Schema.Type.Float: case Schema.Type.Bytes: case Schema.Type.String: case Schema.Type.Null: return false; } return true; } /// <inheritdoc/> protected override ArrayAccess GetArrayAccess(ArraySchema readerSchema) { return new GenericArrayAccess(); } /// <inheritdoc/> protected override EnumAccess GetEnumAccess(EnumSchema readerSchema) { return new GenericEnumAccess(readerSchema); } /// <inheritdoc/> protected override MapAccess GetMapAccess(MapSchema readerSchema) { return new GenericMapAccess(); } /// <inheritdoc/> protected override RecordAccess GetRecordAccess(RecordSchema readerSchema) { return new GenericRecordAccess(readerSchema); } /// <inheritdoc/> protected override FixedAccess GetFixedAccess(FixedSchema readerSchema) { return new GenericFixedAccess(readerSchema); } class GenericEnumAccess : EnumAccess { private EnumSchema schema; public GenericEnumAccess(EnumSchema schema) { this.schema = schema; } public object CreateEnum(object reuse, int ordinal) { if (reuse is GenericEnum) { var ge = (GenericEnum) reuse; if (ge.Schema.Equals(this.schema)) { ge.Value = this.schema[ordinal]; return ge; } } return new GenericEnum(this.schema, this.schema[ordinal]); } } internal class GenericRecordAccess : RecordAccess { private RecordSchema schema; public GenericRecordAccess(RecordSchema schema) { this.schema = schema; } public object CreateRecord(object reuse) { GenericRecord ru = (reuse == null || !(reuse is GenericRecord) || !(reuse as GenericRecord).Schema.Equals(this.schema)) ? new GenericRecord(this.schema) : reuse as GenericRecord; return ru; } public object GetField(object record, string fieldName, int fieldPos) { object result; if(!((GenericRecord)record).TryGetValue(fieldPos, out result)) { return null; } return result; } public void AddField(object record, string fieldName, int fieldPos, object fieldValue) { ((GenericRecord)record).Add(fieldName, fieldValue); } } class GenericFixedAccess : FixedAccess { private FixedSchema schema; public GenericFixedAccess(FixedSchema schema) { this.schema = schema; } public object CreateFixed(object reuse) { return (reuse is GenericFixed && (reuse as GenericFixed).Schema.Equals(this.schema)) ? reuse : new GenericFixed(this.schema); } public byte[] GetFixedBuffer( object f ) { return ((GenericFixed)f).Value; } } class GenericArrayAccess : ArrayAccess { public object Create(object reuse) { return (reuse is object[]) ? reuse : new object[0]; } public void EnsureSize(ref object array, int targetSize) { if (((object[])array).Length < targetSize) SizeTo(ref array, targetSize); } public void Resize(ref object array, int targetSize) { SizeTo(ref array, targetSize); } public void AddElements( object arrayObj, int elements, int index, ReadItem itemReader, Decoder decoder, bool reuse ) { var array = (object[]) arrayObj; for (int i = index; i < index + elements; i++) { array[i] = reuse ? itemReader(array[i], decoder) : itemReader(null, decoder); } } private static void SizeTo(ref object array, int targetSize) { var o = (object[]) array; Array.Resize(ref o, targetSize); array = o; } } class GenericMapAccess : MapAccess { public object Create(object reuse) { if (reuse is IDictionary<string, object>) { var result = (IDictionary<string, object>)reuse; result.Clear(); return result; } return new Dictionary<string, object>(); } public void AddElements(object mapObj, int elements, ReadItem itemReader, Decoder decoder, bool reuse) { var map = (IDictionary<string, object>)mapObj; for (int i = 0; i < elements; i++) { var key = decoder.ReadString(); map[key] = itemReader(null, decoder); } } } } }
/* ==================================================================== Licensed To the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file To You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed To in writing, software distributed under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ namespace NPOI.HPSF.Wellknown { using System; using System.Collections; /// <summary> /// This is a dictionary which maps property ID values To property /// ID strings. /// The methods {@link #GetSummaryInformationProperties} and {@link /// #GetDocumentSummaryInformationProperties} return singleton {@link /// PropertyIDMap}s. An application that wants To extend these maps /// should treat them as unmodifiable, copy them and modifiy the /// copies. /// @author Rainer Klute /// <a href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a> /// @since 2002-02-09 /// </summary> public class PropertyIDMap : Hashtable { /* * The following definitions are for property IDs in the first * (and only) section of the Summary Information property Set. */ /** ID of the property that denotes the document's title */ public const int PID_TITLE = 2; /** ID of the property that denotes the document's subject */ public const int PID_SUBJECT = 3; /** ID of the property that denotes the document's author */ public const int PID_AUTHOR = 4; /** ID of the property that denotes the document's keywords */ public const int PID_KEYWORDS = 5; /** ID of the property that denotes the document's comments */ public const int PID_COMMENTS = 6; /** ID of the property that denotes the document's template */ public const int PID_TEMPLATE = 7; /** ID of the property that denotes the document's last author */ public const int PID_LASTAUTHOR = 8; /** ID of the property that denotes the document's revision number */ public const int PID_REVNUMBER = 9; /** ID of the property that denotes the document's edit time */ public const int PID_EDITTIME = 10; /** ID of the property that denotes the DateTime and time the document was * last printed */ public const int PID_LASTPRINTED = 11; /** ID of the property that denotes the DateTime and time the document was * Created. */ public const int PID_Create_DTM = 12; /** ID of the property that denotes the DateTime and time the document was * saved */ public const int PID_LASTSAVE_DTM = 13; /** ID of the property that denotes the number of pages in the * document */ public const int PID_PAGECOUNT = 14; /** ID of the property that denotes the number of words in the * document */ public const int PID_WORDCOUNT = 15; /** ID of the property that denotes the number of characters in the * document */ public const int PID_CHARCOUNT = 16; /** ID of the property that denotes the document's thumbnail */ public const int PID_THUMBNAIL = 17; /** ID of the property that denotes the application that Created the * document */ public const int PID_APPNAME = 18; /** ID of the property that denotes whether Read/Write access To the * document is allowed or whether is should be opened as Read-only. It can * have the following values: * * <table> * <tbody> * <tr> * <th>Value</th> * <th>Description</th> * </tr> * <tr> * <th>0</th> * <th>No restriction</th> * </tr> * <tr> * <th>2</th> * <th>Read-only recommended</th> * </tr> * <tr> * <th>4</th> * <th>Read-only enforced</th> * </tr> * </tbody> * </table> */ public const int PID_SECURITY = 19; /* * The following definitions are for property IDs in the first * section of the Document Summary Information property Set. */ /** * The entry is a dictionary. */ public const int PID_DICTIONARY = 0; /** * The entry denotes a code page. */ public const int PID_CODEPAGE = 1; /** * The entry is a string denoting the category the file belongs * To, e.g. review, memo, etc. This is useful To Find documents of * same type. */ public const int PID_CATEGORY = 2; /** * TarGet format for power point presentation, e.g. 35mm, * printer, video etc. */ public const int PID_PRESFORMAT = 3; /** * Number of bytes. */ public const int PID_BYTECOUNT = 4; /** * Number of lines. */ public const int PID_LINECOUNT = 5; /** * Number of paragraphs. */ public const int PID_PARCOUNT = 6; /** * Number of slides in a power point presentation. */ public const int PID_SLIDECOUNT = 7; /** * Number of slides with notes. */ public const int PID_NOTECOUNT = 8; /** * Number of hidden slides. */ public const int PID_HIDDENCOUNT = 9; /** * Number of multimedia clips, e.g. sound or video. */ public const int PID_MMCLIPCOUNT = 10; /** * This entry is Set To -1 when scaling of the thumbnail Is * desired. Otherwise the thumbnail should be cropped. */ public const int PID_SCALE = 11; /** * This entry denotes an internally used property. It is a * vector of variants consisting of pairs of a string (VT_LPSTR) * and a number (VT_I4). The string is a heading name, and the * number tells how many document parts are under that * heading. */ public const int PID_HEADINGPAIR = 12; /** * This entry Contains the names of document parts (word: names * of the documents in the master document, excel: sheet names, * power point: slide titles, binder: document names). */ public const int PID_DOCPARTS = 13; /** * This entry Contains the name of the project manager. */ public const int PID_MANAGER = 14; /** * This entry Contains the company name. */ public const int PID_COMPANY = 15; /** * If this entry is -1 the links are dirty and should be * re-evaluated. */ public const int PID_LINKSDIRTY = 0x10; /** * The entry specifies an estimate of the number of characters * in the document, including whitespace, as an integer */ public static int PID_CCHWITHSPACES = 0x11; // 0x12 Unused // 0x13 GKPIDDSI_SHAREDDOC - Must be False // 0x14 GKPIDDSI_LINKBASE - Must not be written // 0x15 GKPIDDSI_HLINKS - Must not be written /** * This entry contains a boolean which marks if the User Defined * Property Set has been updated outside of the Application, if so the * hyperlinks should be updated on document load. */ public static int PID_HYPERLINKSCHANGED = 0x16; /** * This entry contains the version of the Application which wrote the * Property set, stored with the two high order bytes having the major * version number, and the two low order bytes the minor version number. */ public static int PID_VERSION = 0x17; /** * This entry contains the VBA digital signature for the VBA project * embedded in the document. */ public static int PID_DIGSIG = 0x18; // 0x19 Unused /** * This entry contains a string of the content type of the file. */ public static int PID_CONTENTTYPE = 0x1A; /** * This entry contains a string of the document status. */ public static int PID_CONTENTSTATUS = 0x1B; /** * This entry contains a string of the document language, but * normally should be empty. */ public static int PID_LANGUAGE = 0x1C; /** * This entry contains a string of the document version, but * normally should be empty */ public static int PID_DOCVERSION = 0x1D; /** * <p>The highest well-known property ID. Applications are free to use * higher values for custom purposes. (This value is based on Office 12, * earlier versions of Office had lower values)</p> */ public const int PID_MAX = 0x1F; /** * Contains the summary information property ID values and * associated strings. See the overall HPSF documentation for * details! */ private static PropertyIDMap summaryInformationProperties; /** * Contains the summary information property ID values and * associated strings. See the overall HPSF documentation for * details! */ private static PropertyIDMap documentSummaryInformationProperties; /// <summary> /// Initializes a new instance of the <see cref="PropertyIDMap"/> class. /// </summary> /// <param name="initialCapacity">initialCapacity The initial capacity as defined for /// {@link HashMap}</param> /// <param name="loadFactor">The load factor as defined for {@link HashMap}</param> public PropertyIDMap(int initialCapacity, float loadFactor):base(initialCapacity, loadFactor) { } /// <summary> /// Initializes a new instance of the <see cref="PropertyIDMap"/> class. /// </summary> /// <param name="map">The instance To be Created is backed by this map.</param> public PropertyIDMap(IDictionary map):base(map) { } /// <summary> /// Puts a ID string for an ID into the {@link /// PropertyIDMap}. /// </summary> /// <param name="id">The ID string.</param> /// <param name="idString">The id string.</param> /// <returns>As specified by the {@link java.util.Map} interface, this method /// returns the previous value associated with the specified id</returns> public Object Put(long id, String idString) { return this[id]=idString; } /// <summary> /// Gets the ID string for an ID from the {@link /// PropertyIDMap}. /// </summary> /// <param name="id">The ID.</param> /// <returns>The ID string associated with id</returns> public Object Get(long id) { return this[id]; } /// <summary> /// Gets the Summary Information properties singleton /// </summary> /// <returns></returns> public static PropertyIDMap SummaryInformationProperties { get { if (summaryInformationProperties == null) { PropertyIDMap m = new PropertyIDMap(18, (float)1.0); m.Put(PID_TITLE, "PID_TITLE"); m.Put(PID_SUBJECT, "PID_SUBJECT"); m.Put(PID_AUTHOR, "PID_AUTHOR"); m.Put(PID_KEYWORDS, "PID_KEYWORDS"); m.Put(PID_COMMENTS, "PID_COMMENTS"); m.Put(PID_TEMPLATE, "PID_TEMPLATE"); m.Put(PID_LASTAUTHOR, "PID_LASTAUTHOR"); m.Put(PID_REVNUMBER, "PID_REVNUMBER"); m.Put(PID_EDITTIME, "PID_EDITTIME"); m.Put(PID_LASTPRINTED, "PID_LASTPRINTED"); m.Put(PID_Create_DTM, "PID_Create_DTM"); m.Put(PID_LASTSAVE_DTM, "PID_LASTSAVE_DTM"); m.Put(PID_PAGECOUNT, "PID_PAGECOUNT"); m.Put(PID_WORDCOUNT, "PID_WORDCOUNT"); m.Put(PID_CHARCOUNT, "PID_CHARCOUNT"); m.Put(PID_THUMBNAIL, "PID_THUMBNAIL"); m.Put(PID_APPNAME, "PID_APPNAME"); m.Put(PID_SECURITY, "PID_SECURITY"); summaryInformationProperties = m; //new PropertyIDMap(m); } return summaryInformationProperties; } } /// <summary> /// Gets the Document Summary Information properties /// singleton. /// </summary> /// <returns>The Document Summary Information properties singleton.</returns> public static PropertyIDMap DocumentSummaryInformationProperties { get { if (documentSummaryInformationProperties == null) { PropertyIDMap m = new PropertyIDMap(17, (float)1.0); m.Put(PID_DICTIONARY, "PID_DICTIONARY"); m.Put(PID_CODEPAGE, "PID_CODEPAGE"); m.Put(PID_CATEGORY, "PID_CATEGORY"); m.Put(PID_PRESFORMAT, "PID_PRESFORMAT"); m.Put(PID_BYTECOUNT, "PID_BYTECOUNT"); m.Put(PID_LINECOUNT, "PID_LINECOUNT"); m.Put(PID_PARCOUNT, "PID_PARCOUNT"); m.Put(PID_SLIDECOUNT, "PID_SLIDECOUNT"); m.Put(PID_NOTECOUNT, "PID_NOTECOUNT"); m.Put(PID_HIDDENCOUNT, "PID_HIDDENCOUNT"); m.Put(PID_MMCLIPCOUNT, "PID_MMCLIPCOUNT"); m.Put(PID_SCALE, "PID_SCALE"); m.Put(PID_HEADINGPAIR, "PID_HEADINGPAIR"); m.Put(PID_DOCPARTS, "PID_DOCPARTS"); m.Put(PID_MANAGER, "PID_MANAGER"); m.Put(PID_COMPANY, "PID_COMPANY"); m.Put(PID_LINKSDIRTY, "PID_LINKSDIRTY"); documentSummaryInformationProperties = m; //new PropertyIDMap(m); } return documentSummaryInformationProperties; } } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using System.Diagnostics; namespace Simbiosis { /// <summary> /// Implements a learning servo, which learns to produce (DC) outputs that reduce the difference between /// a DESIRE signal and an ACTUAL signal. /// /// The output is calculated from a surface defined by four points at the ends of each axis: /// /// Z defines the value of an output parameter for a given X and Y, where X is the desire and Y is the actual. /// /// /// </summary> public class LinearServo : Physiology { private float desire = 0.5f; // current inputs private float actual = 0.5f; private float lastDesire = -1f; // check for changes, so we don't waste time calculating surface levels unnecessarily private float lastActual = -1f; /// <summary> /// The four corner points describing the surface. /// The corners are stored in the order x0,y0; x1;y0; x0,y1; x1,y1 /// </summary> private float[] surface = new float[4]; /// <summary> /// x,y coordinates of the four corners, in order /// </summary> private float[] x = { 0, 1, 0, 1 }; private float[] y = { 0, 0, 1, 1 }; /// <summary> /// current rate of change for each corner due to adaptation /// </summary> private float[] velocity = new float[4]; public LinearServo() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Buoyancy = 0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] // DOWNSTREAM { new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 0, 0f, "Desired"), // input channel - desired state new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 1, 0f, "Actual"), // input channel - actual state new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S0, 0, 0f, "Output"), // output channel - response new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.S0, 0, 0f, "Bypass"), // bypass channel from plug to skt0 }, new ChannelData[] // UPSTREAM { new ChannelData(ChannelData.Socket.S0, ChannelData.Socket.XX, 0, 0f, "Desired"), // input channel - desired state new ChannelData(ChannelData.Socket.S0, ChannelData.Socket.XX, 1, 0f, "Actual"), // input channel - actual state new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 0, 0f, "Output"), // output channel - response new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.S0, 0, 0f, "Bypass"), // bypass channel from plug to skt0 } }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { // initialise the response curve. Start with just a DC signal whose output tries to negate the difference between // desire and actual, as in a conventional servo. Treat an o/p of 0.5 as neutral. // In other words, when desire is less than actual, o/p is a low value (<0.5) // and when desire > actual, o/p is higher than 0.5 surface[0] = 0.5f; surface[1] = 1.0f; surface[2] = 0.0f; surface[3] = 0.5f; } /// <summary> /// Called every frame /// </summary> public override void FastUpdate(float elapsedTime) { desire = Input(0); actual = Input(1); if ((desire != lastDesire) || (actual != lastActual)) { // Store the present set lastActual = actual; lastDesire = desire; // Get new output from surface Output(0, ReadSurface(desire, actual)); } } /// <summary> /// Slow update: adjust surface through learning. /// The more A differs from D, the less well the servo is doing in this region of the surface. /// But we don't know the direction of the error, so calculate whether we're getting worse/better faster or slower. /// If we're getting worse faster, we need to shift the surface in the other direction. /// Each corner is given a rate of change. This rate is adjusted in proportion to how close the current A,D is to the corner /// (i.e. how much influence this corner has on the relevant part of the surface). /// /// If the error is not zero, add a small corner velocity. /// if we're getting better, increase the velocity in the current direction. /// If we're getting worse, add a force in the opposite direction, to slow the velocity and cross zero. /// The faster we're getting better or worse, the more force should be applied. /// So, force = de. /// /// /// </summary> public override void SlowUpdate() { base.SlowUpdate(); // We only need to adapt servo every few seconds or so if (--adaptCount < 0) { adaptCount = 40; // How are we doing? float e = (float)Math.Abs(desire - actual); // magnitude of error float de = laste - e; // rate of change of error (<0 if we're getting worse) laste = e; Debug.WriteLine("Desire=" + desire + " Actual=" + actual + " Error=" + e + " DeltaError=" + de); // for each corner, adjust its rate of change in proportion to how much it influences the current D,A region of the surface. for (int i = 0; i < 4; i++) { // Calc D,A distance from this corner (keep it as the square for speed) float dist = (desire - x[i]) * (desire - x[i]) + (actual - y[i]) * (actual - y[i]); // Calculate new force to accelerate/reverse motion float force = de * (1.415f-dist) * 0.01f; // 1.415 because the largest distance is root 2 // Add current force to velocity velocity[i] += force; // add velocity to corner height surface[i] += velocity[i]; if (surface[i] < 0) surface[i] = 0; else if (surface[i] > 1) surface[i] = 1; Debug.WriteLine("corner=" + x[i] + "'" + y[i] + " force=" + force + " velocity=" + velocity[i] + " height=" + surface[i]); } } } private float laste = 0; // last error magnitude for calculating delta private int adaptCount = 0; // countdown to next learning update /// <summary> /// Read the height of a given surface by interpolating the four corners /// Simplified bilinear interpolation is: /// f(x,y) = f(0,0) * (1-x) * (1-y) + f(1,0) * x * (1-y) + f(0,1) * (1-x) * y + f(1,1) * x * y /// </summary> /// <param name="desire">current x value</param> /// <param name="actual">current y value</param> /// <returns>z value at x,y</returns> private float ReadSurface(float desire, float actual) { return surface[0] * (1 - desire) * (1 - actual) + surface[1] * desire * (1 - actual) + surface[2] * (1 - desire) * actual + surface[3] * desire * actual; } } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Finish later? ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ /// <summary> /// Implements a learning, nonlinear "servo", which learns to produce outputs that reduce the difference between /// a DESIRE signal and an ACTUAL signal. /// /// The output is calculated from a series of 3D graphs, each defining the value of a parameter. /// Each graph is a surface defined by four points at the ends of each axis: /// /// Z defines the value of an output parameter for a given X and Y, where X is the desire and Y is the actual. /// /// Each parameter controls the nature of the output signal, which has an attack/decay envelope. /// The parameters are: /// - Attack period /// - Sustain period. If this is zero, the decay starts immediately after the attack /// - Sustain level /// - Decay period /// - Pause period. If this is zero, the sustain is infinite, giving us a DC output at the sustain level /// - pause level (level after decay and before next attack) /// /// The envelope is integrated (moving average) to smooth it a little. /// /// Whenever the desire or actual change, the new value for the present phase of the cycle replaces the old, so an infinite sustain might /// turn into an oscillation, etc. /// /// /// /// /// /// </summary> public class NonlinearServo : Physiology { /// <summary> /// Phases of the cycle /// </summary> private enum State { Pause, Attack, Sustain, Decay }; /// <summary> /// Surfaces /// </summary> private enum Sfc { AttackPeriod, SustainPeriod, SustainLevel, DecayPeriod, PausePeriod, PauseLevel, NUMSURFACES }; /// <summary> /// Scaling factors for the periods. /// A factor of 1 means that a surface value of 1 will create a period of 1 second. /// A factor of 10 means the maximum period will last 10 seconds /// </summary> private float[] scale = { 5f, // max attack 5f, // max sustain 1f, // dummy - this is a level, not a period 5f, // max decay 5f, // max pause 1f // dummy - this is a level, not a period }; private float lastDesire = -1f; // check for changes, so we don't waste time calculating surface levels unnecessarily private float lastActual = -1f; private float signal = 0f; // current output private State state = State.Pause; // state of the system private float time = 0f; // time until next phase starts, in seconds /// <summary> /// The four corner points describing each of the six surfaces. /// The corners are stored in the order x0,y0; x1;y0; x0,y1; x1,y1 /// </summary> private float[,] surface = new float[(int)Sfc.NUMSURFACES, 4]; public NonlinearServo() { // Define my properties Mass = 0.1f; Resistance = 0.1f; Bouyancy = 0f; // Define my channels channelData = new ChannelData[][] { new ChannelData[] // DOWNSTREAM { new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 0, 0f, "Desired"), // input channel - desired state new ChannelData(ChannelData.Socket.PL, ChannelData.Socket.XX, 1, 0f, "Actual"), // input channel - actual state new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.S0, 0, 0f, "Output"), // output channel - response }, new ChannelData[] // UPSTREAM { new ChannelData(ChannelData.Socket.S0, ChannelData.Socket.XX, 0, 0f, "Desired"), // input channel - desired state new ChannelData(ChannelData.Socket.S0, ChannelData.Socket.XX, 1, 0f, "Actual"), // input channel - actual state new ChannelData(ChannelData.Socket.XX, ChannelData.Socket.PL, 0, 0f, "Output"), // output channel - response } }; } /// <summary> /// Called once .owner etc. have been set up by the cell. Do your main initialisation here. /// </summary> public override void Init() { // initialise the response curves. Start with just a DC signal whose output tries to negate the difference between // desire and actual, as in a linear servo. Treat an o/p of 0.5 as neutral. // In other words, when desire is less than actual, o/p is a low value (<0.5) // and when desire > actual, o/p is higher than 0.5 // Attack period: inverted servo, so that if actual < desire, attack gets faster (this will be ignored until pause!=0) SetSurface(Sfc.AttackPeriod, 0.5f, 0f, 1f, 0.5f); // Sustain period: start with one second (this will be ignored until pause!=0) float v = 1f / scale[(int)Sfc.SustainPeriod] * 1f; SetSurface(Sfc.SustainPeriod, v, v, v, v); // Sustain level: standard servo pattern - 0.5 when desire==actual, <0.5 when desire < actual, >0.5 when desire > actual SetSurface(Sfc.SustainLevel, 0.5f, 1f, 0f, 0.5f); // Decay period: start with one second (this will be ignored until pause!=0) v = 1f / scale[(int)Sfc.DecayPeriod] * 1f; SetSurface(Sfc.DecayPeriod, v, v, v, v); // Pause period: start with flat 0, so that there is no AC component and only the servoed sustain level counts SetSurface(Sfc.PausePeriod, 0, 0, 0, 0); // Pause level: start with flat zero SetSurface(Sfc.PauseLevel, 0, 0, 0, 0); } private void SetSurface(Sfc sfc, float x0y0, float x1y0, float x0y1, float x1y1) { surface[(int)sfc, 0] = x0y0; surface[(int)sfc, 1] = x1y0; surface[(int)sfc, 2] = x0y1; surface[(int)sfc, 3] = x1y1; } /// <summary> /// Called every frame /// </summary> public override void FastUpdate(float elapsedTime) { float desire = Input(0); float actual = Input(1); if ((desire != lastDesire) || (actual != lastActual)) { // Store the present set lastActual = actual; lastDesire = desire; // Load } } /// <summary> /// Read the height of a given surface by interpolating the four corners /// Simplified bilinear interpolation is: /// f(x,y) = f(0,0) * (1-x) * (1-y) + f(1,0) * x * (1-y) + f(0,1) * (1-x) * y + f(1,1) * x * y /// </summary> /// <param name="sfc">index of the surface to be read</param> /// <param name="desire">current x value</param> /// <param name="actual">current y value</param> /// <returns>z value at x,y</returns> private float ReadSurface(int sfc, float desire, float actual) { return surface[sfc, 0] * (1 - desire) * (1 - actual) + surface[sfc, 1] * desire * (1 - actual) + surface[sfc, 2] * (1 - desire) * actual + surface[sfc, 3] * desire * actual; } } ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using Alachisoft.NGroups.Blocks; using Alachisoft.NGroups.Util; using Alachisoft.NCache.Common.Logger; using Alachisoft.NCache.Common.Net; namespace Alachisoft.NCache.Caching.Topologies.Clustered { internal class SubCluster { /// <summary> identifier of group </summary> private string _groupid; private ClusterService _service; private ILogger _ncacheLog; ILogger NCacheLog { get { return _ncacheLog; } } /// <summary> keeps track of all group members </summary> protected ArrayList _members = ArrayList.Synchronized(new ArrayList(11)); /// <summary> keeps track of all server members </summary> protected ArrayList _servers = ArrayList.Synchronized(new ArrayList(11)); /// <summary> The hashtable that contains members and their info. </summary> public ArrayList Members { get { return _members; } } /// <summary> The hashtable that contains members and their info. </summary> public ArrayList Servers { get { return _servers; } } /// <summary> /// /// </summary> /// <param name="gpid"></param> public SubCluster(string gpid, ClusterService service) { _groupid = gpid; _service = service; _ncacheLog = _service.NCacheLog; } /// <summary> /// Returns name of the current sub-cluster. /// </summary> public string Name { get { return _groupid; } } /// <summary> /// returns true if the node is operating in coordinator mode. /// </summary> public bool IsCoordinator { get { Address address = Coordinator; if (address != null && _service.LocalAddress.CompareTo(address) == 0) return true; return false; } } /// <summary> /// check if the given address exists in this cluster /// </summary> /// <param name="node"></param> /// <returns></returns> public bool IsMember(Address node) { if (Members.Contains(node) || _servers.Contains(node)) { return true; } return false; } /// <summary> /// returns the coordinator in the cluster. /// </summary> public Address Coordinator { get { lock (_servers.SyncRoot) { if (_servers.Count > 0) return _servers[0] as Address; } return null; } } /// <summary> /// Called when a new member joins the group. /// </summary> /// <param name="address">address of the joining member</param> /// <param name="identity">additional identity information</param> /// <returns>true if the node joined successfuly</returns> internal virtual int OnMemberJoined(Address address, NodeIdentity identity) { if (identity.SubGroupName != _groupid) { return -1; } NCacheLog.Warn("SubCluster.OnMemberJoined()", "Memeber " + address + " added to sub-cluster " + _groupid); _members.Add(address); if (identity.HasStorage && !identity.IsStartedAsMirror) _servers.Add(address); return _members.Count; } /// <summary> /// Called when an existing member leaves the group. /// </summary> /// <param name="address">address of the joining member</param> /// <returns>true if the node left successfuly</returns> internal virtual int OnMemberLeft(Address address, Hashtable bucketsOwnershipMap) { if (_members.Contains(address)) { NCacheLog.Warn("SubCluster.OnMemberJoined()", "Memeber " + address + " left sub-cluster " + _groupid); _members.Remove(address); _servers.Remove(address); return _members.Count; } return -1; } public override bool Equals(object obj) { bool result = false; if (obj is SubCluster) { SubCluster other = obj as SubCluster; result = this._groupid.CompareTo(other._groupid) == 0; if (result) { result = this._members.Count == other._members.Count; if (result) { foreach (Address mbr in this._members) { if (!other._members.Contains(mbr)) { result = false; break; } } } } } return result; } #region / --- Messages --- / /// <summary> /// Sends message to every member of the group. Returns its reponse as well. /// </summary> /// <param name="msg"></param> /// <param name="mode"></param> /// <param name="timeout"></param> /// <returns></returns> public RspList BroadcastMessage(object msg, byte mode, long timeout) { return _service.BroadcastToMultiple(_members, msg, mode, timeout); } /// <summary> /// Send a broadcast no reply message to a specific partition /// </summary> /// <param name="msg"></param> /// <param name="part"></param> public void BroadcastNoReplyMessage(Object msg) { _service.BroadcastToMultiple(_members, msg, GroupRequest.GET_NONE, -1); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.ServiceAuth; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class PresenceServicesConnector : BaseServiceConnector, IPresenceService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public PresenceServicesConnector() { } public PresenceServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public PresenceServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["PresenceService"]; if (gridConfig == null) { m_log.Error("[PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini"); throw new Exception("Presence connector init error"); } string serviceURI = gridConfig.GetString("PresenceServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[PRESENCE CONNECTOR]: No Server URI named in section PresenceService"); throw new Exception("Presence connector init error"); } m_ServerURI = serviceURI; base.Initialise(source, "PresenceService"); } #region IPresenceService public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "login"; sendData["UserID"] = userID; sendData["SessionID"] = sessionID.ToString(); sendData["SecureSessionID"] = secureSessionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public bool LogoutAgent(UUID sessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "logout"; sendData["SessionID"] = sessionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public bool LogoutRegionAgents(UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "logoutregion"; sendData["RegionID"] = regionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public bool ReportAgent(UUID sessionID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "report"; sendData["SessionID"] = sessionID.ToString(); sendData["RegionID"] = regionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } return false; } public PresenceInfo GetAgent(UUID sessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagent"; sendData["SessionID"] = sessionID.ToString(); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); PresenceInfo pinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) { pinfo = new PresenceInfo((Dictionary<string, object>)replyData["result"]); } } return pinfo; } public PresenceInfo[] GetAgents(string[] userIDs) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagents"; sendData["uuids"] = new List<string>(userIDs); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/presence"; //m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server at {0}: {1}", uri, e.Message); } List<PresenceInfo> rinfos = new List<PresenceInfo>(); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && (replyData["result"].ToString() == "null" || replyData["result"].ToString() == "Failure")) { return new PresenceInfo[0]; } Dictionary<string, object>.ValueCollection pinfosList = replyData.Values; //m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object presence in pinfosList) { if (presence is Dictionary<string, object>) { PresenceInfo pinfo = new PresenceInfo((Dictionary<string, object>)presence); rinfos.Add(pinfo); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received invalid response type {0}", presence.GetType()); } } else m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null response"); return rinfos.ToArray(); } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if UseSingularityPDB /////////////////////////////////////////////////////////////////////////////// // // Microsoft Research Singularity PDB Info Library // // Copyright (c) Microsoft Corporation. All rights reserved. // // File: BitAccess.cs // using System; using System.IO; using System.Text; namespace Microsoft.Singularity.PdbInfo.Features { public class BitAccess { private byte[] buffer; private int offset; public int Position { get { return offset; } set { offset = value; } } public BitAccess(int capacity) { this.buffer = new byte[capacity]; this.offset = 0; } internal void FillBuffer(Stream stream, int capacity) { MinCapacity(capacity); stream.Read(buffer, 0, capacity); offset = 0; } internal void WriteBuffer(Stream stream, int count) { stream.Write(buffer, 0, count); } internal void MinCapacity(int capacity) { if (buffer.Length < capacity) { buffer = new byte[capacity]; } offset = 0; } public byte[] Buffer // [GalenH] Just for PdbDump { get { return buffer; } } public void Align(int alignment) { while ((offset % alignment) != 0) { offset++; } } public void WriteInt32(int value) { buffer[offset + 0] = (byte) value; buffer[offset + 1] = (byte) (value >> 8); buffer[offset + 2] = (byte) (value >> 16); buffer[offset + 3] = (byte) (value >> 24); offset += 4; } public void WriteInt32(int[] values) { for (int i = 0; i < values.Length; i++) { WriteInt32(values[i]); } } public void WriteBytes(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { buffer[offset++] = bytes[i]; } } public void ReadInt16(out short value) { value = (short)((buffer[offset + 0] & 0xFF) | (buffer[offset + 1] << 8)); offset += 2; } public void ReadInt32(out int value) { value = (int)((buffer[offset + 0] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)); offset += 4; } public void ReadUInt16(out ushort value) { value = (ushort)((buffer[offset + 0] & 0xFF) | (buffer[offset + 1] << 8)); offset += 2; } public void ReadUInt8(out byte value) { value = (byte)((buffer[offset + 0] & 0xFF)); offset += 1; } public void ReadUInt32(out uint value) { value = (uint)((buffer[offset + 0] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)); offset += 4; } public void ReadInt32(int[] values) { for (int i = 0; i < values.Length; i++) { ReadInt32(out values[i]); } } public void ReadUInt32(uint[] values) { for (int i = 0; i < values.Length; i++) { ReadUInt32(out values[i]); } } public void ReadBytes(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { bytes[i] = buffer[offset++]; } } public void ReadCString(out string value) { int len = 0; while (offset + len < buffer.Length && buffer[offset + len] != 0) { len++; } value = Encoding.UTF8.GetString(buffer, offset, len); offset += len + 1; } public void SkipCString(out string value) { int len = 0; while (offset + len < buffer.Length && buffer[offset + len] != 0) { len++; } offset += len + 1; value= null; } public void ReadGuid(out Guid guid) { uint a; ushort b; ushort c; byte d; byte e; byte f; byte g; byte h; byte i; byte j; byte k; ReadUInt32(out a); ReadUInt16(out b); ReadUInt16(out c); ReadUInt8(out d); ReadUInt8(out e); ReadUInt8(out f); ReadUInt8(out g); ReadUInt8(out h); ReadUInt8(out i); ReadUInt8(out j); ReadUInt8(out k); guid = new Guid(a, b, c, d, e, f, g, h, i, j, k); } } } #endif
// ReSharper disable All using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Custom Field Views. /// </summary> [RoutePrefix("api/v1.0/config/custom-field-view")] public class CustomFieldViewController : FrapidApiController { /// <summary> /// The CustomFieldView repository. /// </summary> private ICustomFieldViewRepository CustomFieldViewRepository; public CustomFieldViewController() { } public CustomFieldViewController(ICustomFieldViewRepository repository) { this.CustomFieldViewRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.CustomFieldViewRepository == null) { this.CustomFieldViewRepository = new Frapid.Config.DataAccess.CustomFieldView { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Counts the number of custom field views. /// </summary> /// <returns>Returns the count of the custom field views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/custom-field-view/count")] [RestAuthorize] public long Count() { try { return this.CustomFieldViewRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of custom field view for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("all")] [Route("~/api/config/custom-field-view/export")] [Route("~/api/config/custom-field-view/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldView> Get() { try { return this.CustomFieldViewRepository.Get(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 custom field views on each page, sorted by the property . /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/custom-field-view")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldView> GetPaginatedResult() { try { return this.CustomFieldViewRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 custom field views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/custom-field-view/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldView> GetPaginatedResult(long pageNumber) { try { return this.CustomFieldViewRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of custom field views using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered custom field views.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/custom-field-view/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.CustomFieldViewRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 custom field views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/custom-field-view/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldView> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.CustomFieldViewRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of custom field views using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered custom field views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/custom-field-view/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.CustomFieldViewRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 custom field views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/custom-field-view/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldView> GetFiltered(long pageNumber, string filterName) { try { return this.CustomFieldViewRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
using System; using System.Collections; using System.Text; using UnityEngine; //using Microsoft.Xna.Framework; //using Microsoft.Xna.Framework.Audio; //using Microsoft.Xna.Framework.Content; //using Microsoft.Xna.Framework.GamerServices; //using Microsoft.Xna.Framework.Graphics; //using Microsoft.Xna.Framework.Input; //using Microsoft.Xna.Framework.Net; //using Microsoft.Xna.Framework.Storage; public class GameState : MonoBehaviour { #region Member Variables private System.IO.TextWriter stateStream; //Player orientation private Quaternion orientation = Quaternion.identity; //world rotation so that we can transform between the two private Matrix4x4 worldRotation; //Player's velocity in vector format private Vector3 playerVelocityVector; //grab the player's transform so that we can use it public Transform playerTransform; //If we've paused the game private bool movementFrozen = false; //player Velocity as a scalar magnitude public double playerVelocity; //time passed since last frame in the world frame private double deltaTimeWorld; //time passed since last frame in the player frame private double deltaTimePlayer; //total time passed in the player frame private double totalTimePlayer; //total time passed in the world frame private double totalTimeWorld; //speed of light private double c = 200; //Speed of light that is affected by the Unity editor public double totalC = 200; //max speed the player can achieve (starting value accessible from Unity Editor) public double maxPlayerSpeed; //max speed, for game use, not accessible from Unity Editor private double maxSpeed; //speed of light squared, kept for easy access in many calculations private double cSqrd; //Use this to determine the state of the color shader. If it's True, all you'll see is the lorenz transform. private bool shaderOff = false; //Did we hit the menu key? public bool menuKeyDown = false; //Did we hit the shader key? public bool shaderKeyDown = false; //This is a value that gets used in many calculations, so we calculate it each frame private double sqrtOneMinusVSquaredCWDividedByCSquared; //Player rotation and change in rotation since last frame public Vector3 playerRotation = new Vector3(0, 0, 0); public Vector3 deltaRotation = new Vector3(0, 0, 0); public double pctOfSpdUsing = 0; // Percent of velocity you are using #endregion #region Properties public float finalMaxSpeed = .99f; public bool MovementFrozen { get { return movementFrozen; } set { movementFrozen = value; } } public Matrix4x4 WorldRotation { get { return worldRotation; } } public Quaternion Orientation { get { return orientation; } } public Vector3 PlayerVelocityVector { get { return playerVelocityVector; } set { playerVelocityVector = value; } } public double PctOfSpdUsing { get { return pctOfSpdUsing; } set { pctOfSpdUsing = value; } } public double PlayerVelocity { get { return playerVelocity; } } public double SqrtOneMinusVSquaredCWDividedByCSquared { get { return sqrtOneMinusVSquaredCWDividedByCSquared; } } public double DeltaTimeWorld { get { return deltaTimeWorld; } } public double DeltaTimePlayer { get { return deltaTimePlayer; } } public double TotalTimePlayer { get { return totalTimePlayer; } } public double TotalTimeWorld { get { return totalTimeWorld; } } public double SpeedOfLight { get { return c; } set { c = value; cSqrd = value * value; } } public double SpeedOfLightSqrd { get { return cSqrd; } } public bool keyHit = false; public double MaxSpeed { get { return maxSpeed; } set { maxSpeed = value; } } #endregion #region consts private const float ORB_SPEED_INC = 0.05f; private const float ORB_DECEL_RATE = 0.6f; private const float ORB_SPEED_DUR = 2f; private const float MAX_SPEED = 20.00f; public const float NORM_PERCENT_SPEED = .99f; public const int splitDistance = 21000; #endregion public void Awake() { //Initialize the player's speed to zero playerVelocityVector = Vector3.zero; playerVelocity = 0; //Set our constants MaxSpeed = MAX_SPEED; pctOfSpdUsing = NORM_PERCENT_SPEED; c = totalC; cSqrd = c*c; //And ensure that the game starts/ movementFrozen = false; } public void reset() { //Reset everything not level-based playerRotation.x = 0; playerRotation.y = 0; playerRotation.z = 0; pctOfSpdUsing = 0; } //Call this function to pause and unpause the game public void ChangeState() { if (movementFrozen) { //When we unpause, lock the cursor and hide it so that it doesn't get in the way movementFrozen = false; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } else { //When we pause, set our velocity to zero, show the cursor and unlock it. GameObject.FindGameObjectWithTag(Tags.playerMesh).GetComponent<Rigidbody>().velocity = Vector3.zero; movementFrozen = true; Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } } //We set this in late update because of timing issues with collisions public void LateUpdate() { //Set the pause code in here so that our other objects can access it. if (Input.GetAxis("Menu Key") > 0 && !menuKeyDown) { menuKeyDown = true; ChangeState(); } //set up our buttonUp function else if (!(Input.GetAxis("Menu Key") > 0)) { menuKeyDown = false; } //Set our button code for the shader on/off button if (Input.GetAxis("Shader") > 0 && !shaderKeyDown) { if(shaderOff) shaderOff = false; else shaderOff = true; shaderKeyDown = true; } //set up our buttonUp function else if (!(Input.GetAxis("Shader") > 0)) { shaderKeyDown = false; } //If we're not paused, update everything if (!movementFrozen) { //Put our player position into the shader so that it can read it. Shader.SetGlobalVector("_playerOffset", new Vector4(playerTransform.position.x, playerTransform.position.y, playerTransform.position.z, 0)); //if we reached max speed, forward or backwards, keep at max speed if (playerVelocityVector.magnitude >= (float)MaxSpeed-.01f) { playerVelocityVector = playerVelocityVector.normalized * ((float)MaxSpeed-.01f); } //update our player velocity playerVelocity = playerVelocityVector.magnitude; //During colorshift on/off, during the last level we don't want to have the funky //colors changing so they can apperciate the other effects if (shaderOff) { Shader.SetGlobalFloat("_colorShift", (float)0.0); } else { Shader.SetGlobalFloat("_colorShift", (float)1); } //Send v/c to shader Shader.SetGlobalVector("_vpc", new Vector4(-playerVelocityVector.x, -playerVelocityVector.y, -playerVelocityVector.z, 0) / (float)c); //Send world time to shader Shader.SetGlobalFloat("_wrldTime", (float)TotalTimeWorld); /****************************** * PART TWO OF ALGORITHM * THE NEXT 4 LINES OF CODE FIND * THE TIME PASSED IN WORLD FRAME * ****************************/ //find this constant sqrtOneMinusVSquaredCWDividedByCSquared = (double)Math.Sqrt(1 - (playerVelocity * playerVelocity) / cSqrd); //Set by Unity, time since last update deltaTimePlayer = (double)Time.deltaTime; //Get the total time passed of the player and world for display purposes if (keyHit) { totalTimePlayer += deltaTimePlayer; if (!double.IsNaN(sqrtOneMinusVSquaredCWDividedByCSquared)) { //Get the delta time passed for the world, changed by relativistic effects deltaTimeWorld = deltaTimePlayer / sqrtOneMinusVSquaredCWDividedByCSquared; //and get the total time passed in the world totalTimeWorld += deltaTimeWorld; } } //Set our rigidbody's velocity if (!double.IsNaN(deltaTimePlayer) && !double.IsNaN(sqrtOneMinusVSquaredCWDividedByCSquared)) { GameObject.FindGameObjectWithTag(Tags.playerMesh).GetComponent<Rigidbody>().velocity = -1*(playerVelocityVector / (float)sqrtOneMinusVSquaredCWDividedByCSquared); } //But if either of those two constants is null due to a zero error, that means our velocity is zero anyways. else { GameObject.FindGameObjectWithTag(Tags.playerMesh).GetComponent<Rigidbody>().velocity = Vector3.zero; } /***************************** * PART 3 OF ALGORITHM * FIND THE ROTATION MATRIX * AND CHANGE THE PLAYERS VELOCITY * BY THIS ROTATION MATRIX * ***************************/ //Find the turn angle //Steering constant angular velocity in the player frame //Rotate around the y-axis orientation = Quaternion.AngleAxis(playerRotation.y, Vector3.up) * Quaternion.AngleAxis(playerRotation.x, Vector3.right); Quaternion WorldOrientation = Quaternion.Inverse(orientation); Normalize(orientation); worldRotation = CreateFromQuaternion(WorldOrientation); //Add up our rotation so that we know where the character (NOT CAMERA) should be facing playerRotation += deltaRotation; } } #region Matrix/Quat math //They are functions that XNA had but Unity doesn't, so I had to make them myself //This function takes in a quaternion and creates a rotation matrix from it public Matrix4x4 CreateFromQuaternion(Quaternion q) { double w = q.w; double x = q.x; double y = q.y; double z = q.z; double wSqrd = w * w; double xSqrd = x * x; double ySqrd = y * y; double zSqrd = z * z; Matrix4x4 matrix; matrix.m00 = (float)(wSqrd + xSqrd - ySqrd - zSqrd); matrix.m01 = (float)(2 * x * y - 2 * w * z); matrix.m02 = (float)(2 * x * z + 2 * w * y); matrix.m03 = (float)0; matrix.m10 = (float)(2 * x * y + 2 * w * z); matrix.m11 = (float)(wSqrd - xSqrd + ySqrd - zSqrd); matrix.m12 = (float)(2 * y * z + 2 * w * x); matrix.m13 = (float)0; matrix.m20 = (float)(2 * x * z - 2 * w * y); matrix.m21 = (float)(2 * y * z - 2 * w * x); matrix.m22 = (float)(wSqrd - xSqrd - ySqrd + zSqrd); matrix.m23 = 0; matrix.m30 = 0; matrix.m31 = 0; matrix.m32 = 0; matrix.m33 = 1; return matrix; } //Normalize the given quaternion so that its magnitude is one. public Quaternion Normalize(Quaternion quat) { Quaternion q = quat; double magnitudeSqr = q.w * q.w + q.x * q.x + q.y * q.y + q.z * q.z; if (magnitudeSqr != 1) { double magnitude = (double)Math.Sqrt(magnitudeSqr); q.w = (float)((double)q.w / magnitude); q.x = (float)((double)q.x / magnitude); q.y = (float)((double)q.y / magnitude); q.z = (float)((double)q.z / magnitude); } return q; } //Transform the matrix by a vector3 public Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix) { Vector3 final; final.x = matrix.m00 * normal.x + matrix.m10 * normal.y + matrix.m20 * normal.z; final.y = matrix.m02 * normal.x + matrix.m11 * normal.y + matrix.m21 * normal.z; final.z = matrix.m03 * normal.x + matrix.m12 * normal.y + matrix.m22 * normal.z; return final; } #endregion }
// Copyright 2017, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Generated by the protocol buffer compiler. DO NOT EDIT! // source: Chat/protos/chat.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 Com.Example.Grpc.Chat { /// <summary>Holder for reflection information generated from Chat/protos/chat.proto</summary> public static partial class ChatReflection { #region Descriptor /// <summary>File descriptor for Chat/protos/chat.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ChatReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChZDaGF0L3Byb3Rvcy9jaGF0LnByb3RvEhVjb20uZXhhbXBsZS5ncnBjLmNo", "YXQiLAoLQ2hhdE1lc3NhZ2USDAoEZnJvbRgBIAEoCRIPCgdtZXNzYWdlGAIg", "ASgJIkwKFUNoYXRNZXNzYWdlRnJvbVNlcnZlchIzCgdtZXNzYWdlGAIgASgL", "MiIuY29tLmV4YW1wbGUuZ3JwYy5jaGF0LkNoYXRNZXNzYWdlMmsKC0NoYXRT", "ZXJ2aWNlElwKBGNoYXQSIi5jb20uZXhhbXBsZS5ncnBjLmNoYXQuQ2hhdE1l", "c3NhZ2UaLC5jb20uZXhhbXBsZS5ncnBjLmNoYXQuQ2hhdE1lc3NhZ2VGcm9t", "U2VydmVyKAEwAWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Com.Example.Grpc.Chat.ChatMessage), global::Com.Example.Grpc.Chat.ChatMessage.Parser, new[]{ "From", "Message" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Com.Example.Grpc.Chat.ChatMessageFromServer), global::Com.Example.Grpc.Chat.ChatMessageFromServer.Parser, new[]{ "Message" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ChatMessage : pb::IMessage<ChatMessage> { private static readonly pb::MessageParser<ChatMessage> _parser = new pb::MessageParser<ChatMessage>(() => new ChatMessage()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChatMessage> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Com.Example.Grpc.Chat.ChatReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChatMessage() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChatMessage(ChatMessage other) : this() { from_ = other.from_; message_ = other.message_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChatMessage Clone() { return new ChatMessage(this); } /// <summary>Field number for the "from" field.</summary> public const int FromFieldNumber = 1; private string from_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string From { get { return from_; } set { from_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 2; private string message_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Message { get { return message_; } set { message_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChatMessage); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChatMessage other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (From != other.From) return false; if (Message != other.Message) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (From.Length != 0) hash ^= From.GetHashCode(); if (Message.Length != 0) hash ^= Message.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 (From.Length != 0) { output.WriteRawTag(10); output.WriteString(From); } if (Message.Length != 0) { output.WriteRawTag(18); output.WriteString(Message); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (From.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(From); } if (Message.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Message); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChatMessage other) { if (other == null) { return; } if (other.From.Length != 0) { From = other.From; } if (other.Message.Length != 0) { Message = other.Message; } } [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: { From = input.ReadString(); break; } case 18: { Message = input.ReadString(); break; } } } } } public sealed partial class ChatMessageFromServer : pb::IMessage<ChatMessageFromServer> { private static readonly pb::MessageParser<ChatMessageFromServer> _parser = new pb::MessageParser<ChatMessageFromServer>(() => new ChatMessageFromServer()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ChatMessageFromServer> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Com.Example.Grpc.Chat.ChatReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChatMessageFromServer() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChatMessageFromServer(ChatMessageFromServer other) : this() { Message = other.message_ != null ? other.Message.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ChatMessageFromServer Clone() { return new ChatMessageFromServer(this); } /// <summary>Field number for the "message" field.</summary> public const int MessageFieldNumber = 2; private global::Com.Example.Grpc.Chat.ChatMessage message_; /// <summary> /// google.protobuf.Timestamp timestamp = 1; /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Com.Example.Grpc.Chat.ChatMessage Message { get { return message_; } set { message_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ChatMessageFromServer); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ChatMessageFromServer other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Message, other.Message)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (message_ != null) hash ^= Message.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 (message_ != null) { output.WriteRawTag(18); output.WriteMessage(Message); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (message_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Message); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ChatMessageFromServer other) { if (other == null) { return; } if (other.message_ != null) { if (message_ == null) { message_ = new global::Com.Example.Grpc.Chat.ChatMessage(); } Message.MergeFrom(other.Message); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 18: { if (message_ == null) { message_ = new global::Com.Example.Grpc.Chat.ChatMessage(); } input.ReadMessage(message_); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; namespace Umbraco.Core.ObjectResolution { /// <summary> /// The base class for all many-objects resolvers. /// </summary> /// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam> /// <typeparam name="TResolved">The type of the resolved objects.</typeparam> public abstract class ManyObjectsResolverBase<TResolver, TResolved> : ResolverBase<TResolver> where TResolved : class where TResolver : ResolverBase { private Lazy<IEnumerable<TResolved>> _applicationInstances = null; private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); private readonly string _httpContextKey; private readonly List<Type> _instanceTypes = new List<Type>(); private IEnumerable<TResolved> _sortedValues = null; private int _defaultPluginWeight = 10; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects, /// and an optional lifetime scope. /// </summary> /// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param> /// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks> /// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception> protected ManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application) { CanResolveBeforeFrozen = false; if (scope == ObjectLifetimeScope.HttpRequest) { if (HttpContext.Current == null) throw new InvalidOperationException("Use alternative constructor accepting a HttpContextBase object in order to set the lifetime scope to HttpRequest when HttpContext.Current is null"); CurrentHttpContext = new HttpContextWrapper(HttpContext.Current); } LifetimeScope = scope; if (scope == ObjectLifetimeScope.HttpRequest) _httpContextKey = this.GetType().FullName; _instanceTypes = new List<Type>(); InitializeAppInstances(); } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects, /// with creation of objects based on an HttpRequest lifetime scope. /// </summary> /// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param> /// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception> protected ManyObjectsResolverBase(HttpContextBase httpContext) { CanResolveBeforeFrozen = false; if (httpContext == null) throw new ArgumentNullException("httpContext"); LifetimeScope = ObjectLifetimeScope.HttpRequest; _httpContextKey = this.GetType().FullName; CurrentHttpContext = httpContext; _instanceTypes = new List<Type>(); InitializeAppInstances(); } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of object types, /// and an optional lifetime scope. /// </summary> /// <param name="value">The list of object types.</param> /// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param> /// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks> /// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception> protected ManyObjectsResolverBase(IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : this(scope) { _instanceTypes = value.ToList(); } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of objects, /// with creation of objects based on an HttpRequest lifetime scope. /// </summary> /// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param> /// <param name="value">The list of object types.</param> /// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception> protected ManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Type> value) : this(httpContext) { _instanceTypes = value.ToList(); } #endregion private void InitializeAppInstances() { _applicationInstances = new Lazy<IEnumerable<TResolved>>(() => CreateInstances().ToArray()); } /// <summary> /// Gets or sets a value indicating whether the resolver can resolve objects before resolution is frozen. /// </summary> /// <remarks>This is false by default and is used for some special internal resolvers.</remarks> internal bool CanResolveBeforeFrozen { get; set; } /// <summary> /// Gets the list of types to create instances from. /// </summary> protected virtual IEnumerable<Type> InstanceTypes { get { return _instanceTypes; } } /// <summary> /// Gets or sets the <see cref="HttpContextBase"/> used to initialize this object, if any. /// </summary> /// <remarks>If not null, then <c>LifetimeScope</c> will be <c>ObjectLifetimeScope.HttpRequest</c>.</remarks> protected HttpContextBase CurrentHttpContext { get; private set; } /// <summary> /// Gets or sets the lifetime scope of resolved objects. /// </summary> protected ObjectLifetimeScope LifetimeScope { get; private set; } /// <summary> /// Gets the resolved object instances, sorted by weight. /// </summary> /// <returns>The sorted resolved object instances.</returns> /// <remarks> /// <para>The order is based upon the <c>WeightedPluginAttribute</c> and <c>DefaultPluginWeight</c>.</para> /// <para>Weights are sorted ascendingly (lowest weights come first).</para> /// </remarks> protected IEnumerable<TResolved> GetSortedValues() { if (_sortedValues == null) { var values = Values.ToList(); values.Sort((f1, f2) => GetObjectWeight(f1).CompareTo(GetObjectWeight(f2))); _sortedValues = values; } return _sortedValues; } /// <summary> /// Gets or sets the default type weight. /// </summary> /// <remarks>Determines the weight of types that do not have a <c>WeightedPluginAttribute</c> set on /// them, when calling <c>GetSortedValues</c>.</remarks> protected virtual int DefaultPluginWeight { get { return _defaultPluginWeight; } set { _defaultPluginWeight = value; } } /// <summary> /// Returns the weight of an object for user with GetSortedValues /// </summary> /// <param name="o"></param> /// <returns></returns> protected virtual int GetObjectWeight(object o) { var type = o.GetType(); var attr = type.GetCustomAttribute<WeightedPluginAttribute>(true); return attr == null ? DefaultPluginWeight : attr.Weight; } /// <summary> /// Gets the resolved object instances. /// </summary> /// <exception cref="InvalidOperationException"><c>CanResolveBeforeFrozen</c> is false, and resolution is not frozen.</exception> protected IEnumerable<TResolved> Values { get { using (Resolution.Reader(CanResolveBeforeFrozen)) { // note: we apply .ToArray() to the output of CreateInstance() because that is an IEnumerable that // comes from the PluginManager we want to be _sure_ that it's not a Linq of some sort, but the // instances have actually been instanciated when we return. switch (LifetimeScope) { case ObjectLifetimeScope.HttpRequest: // create new instances per HttpContext if (CurrentHttpContext.Items[_httpContextKey] == null) { CurrentHttpContext.Items[_httpContextKey] = CreateInstances().ToArray(); } return (TResolved[])CurrentHttpContext.Items[_httpContextKey]; case ObjectLifetimeScope.Application: return _applicationInstances.Value; case ObjectLifetimeScope.Transient: default: // create new instances each time return CreateInstances().ToArray(); } } } } /// <summary> /// Creates the object instances for the types contained in the types collection. /// </summary> /// <returns>A list of objects of type <typeparamref name="TResolved"/>.</returns> protected virtual IEnumerable<TResolved> CreateInstances() { return PluginManager.Current.CreateInstances<TResolved>(InstanceTypes); } #region Types collection manipulation /// <summary> /// Removes a type. /// </summary> /// <param name="value">The type to remove.</param> /// <exception cref="InvalidOperationException">the resolver does not support removing types, or /// the type is not a valid type for the resolver.</exception> public virtual void RemoveType(Type value) { EnsureSupportsRemove(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); l.UpgradeToWriteLock(); _instanceTypes.Remove(value); } } /// <summary> /// Removes a type. /// </summary> /// <typeparam name="T">The type to remove.</typeparam> /// <exception cref="InvalidOperationException">the resolver does not support removing types, or /// the type is not a valid type for the resolver.</exception> public void RemoveType<T>() where T : TResolved { RemoveType(typeof(T)); } /// <summary> /// Adds types. /// </summary> /// <param name="types">The types to add.</param> /// <remarks>The types are appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// a type is not a valid type for the resolver, or a type is already in the collection of types.</exception> protected void AddTypes(IEnumerable<Type> types) { EnsureSupportsAdd(); using (Resolution.Configuration) using (new WriteLock(_lock)) { foreach(var t in types) { EnsureCorrectType(t); if (_instanceTypes.Contains(t)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", t.FullName)); } _instanceTypes.Add(t); } } } /// <summary> /// Adds a type. /// </summary> /// <param name="value">The type to add.</param> /// <remarks>The type is appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public virtual void AddType(Type value) { EnsureSupportsAdd(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } l.UpgradeToWriteLock(); _instanceTypes.Add(value); } } /// <summary> /// Adds a type. /// </summary> /// <typeparam name="T">The type to add.</typeparam> /// <remarks>The type is appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public void AddType<T>() where T : TResolved { AddType(typeof(T)); } /// <summary> /// Clears the list of types /// </summary> /// <exception cref="InvalidOperationException">the resolver does not support clearing types.</exception> public virtual void Clear() { EnsureSupportsClear(); using (Resolution.Configuration) using (new WriteLock(_lock)) { _instanceTypes.Clear(); } } /// <summary> /// WARNING! Do not use this unless you know what you are doing, clear all types registered and instances /// created. Typically only used if a resolver is no longer used in an application and memory is to be GC'd /// </summary> internal void ResetCollections() { using (new WriteLock(_lock)) { _instanceTypes.Clear(); _sortedValues = null; _applicationInstances = null; } } /// <summary> /// Inserts a type at the specified index. /// </summary> /// <param name="index">The zero-based index at which the type should be inserted.</param> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception> public virtual void InsertType(int index, Type value) { EnsureSupportsInsert(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } l.UpgradeToWriteLock(); _instanceTypes.Insert(index, value); } } /// <summary> /// Inserts a type at the beginning of the list. /// </summary> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public virtual void InsertType(Type value) { InsertType(0, value); } /// <summary> /// Inserts a type at the specified index. /// </summary> /// <typeparam name="T">The type to insert.</typeparam> /// <param name="index">The zero-based index at which the type should be inserted.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception> public void InsertType<T>(int index) where T : TResolved { InsertType(index, typeof(T)); } /// <summary> /// Inserts a type at the beginning of the list. /// </summary> /// <typeparam name="T">The type to insert.</typeparam> public void InsertType<T>() where T : TResolved { InsertType(0, typeof(T)); } /// <summary> /// Inserts a type before a specified, already existing type. /// </summary> /// <param name="existingType">The existing type before which to insert.</param> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// one of the types is not a valid type for the resolver, or the existing type is not in the collection, /// or the new type is already in the collection of types.</exception> public virtual void InsertTypeBefore(Type existingType, Type value) { EnsureSupportsInsert(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(existingType); EnsureCorrectType(value); if (!_instanceTypes.Contains(existingType)) { throw new InvalidOperationException(string.Format( "Type {0} is not in the collection of types.", existingType.FullName)); } if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } int index = _instanceTypes.IndexOf(existingType); l.UpgradeToWriteLock(); _instanceTypes.Insert(index, value); } } /// <summary> /// Inserts a type before a specified, already existing type. /// </summary> /// <typeparam name="TExisting">The existing type before which to insert.</typeparam> /// <typeparam name="T">The type to insert.</typeparam> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// one of the types is not a valid type for the resolver, or the existing type is not in the collection, /// or the new type is already in the collection of types.</exception> public void InsertTypeBefore<TExisting, T>() where TExisting : TResolved where T : TResolved { InsertTypeBefore(typeof(TExisting), typeof(T)); } /// <summary> /// Returns a value indicating whether the specified type is already in the collection of types. /// </summary> /// <param name="value">The type to look for.</param> /// <returns>A value indicating whether the type is already in the collection of types.</returns> public virtual bool ContainsType(Type value) { using (new ReadLock(_lock)) { return _instanceTypes.Contains(value); } } /// <summary> /// Gets the types in the collection of types. /// </summary> /// <returns>The types in the collection of types.</returns> /// <remarks>Returns an enumeration, the list cannot be modified.</remarks> public virtual IEnumerable<Type> GetTypes() { Type[] types; using (new ReadLock(_lock)) { types = _instanceTypes.ToArray(); } return types; } /// <summary> /// Returns a value indicating whether the specified type is already in the collection of types. /// </summary> /// <typeparam name="T">The type to look for.</typeparam> /// <returns>A value indicating whether the type is already in the collection of types.</returns> public bool ContainsType<T>() where T : TResolved { return ContainsType(typeof(T)); } #endregion /// <summary> /// Returns a WriteLock to use when modifying collections /// </summary> /// <returns></returns> protected WriteLock GetWriteLock() { return new WriteLock(_lock); } #region Type utilities /// <summary> /// Ensures that a type is a valid type for the resolver. /// </summary> /// <param name="value">The type to test.</param> /// <exception cref="InvalidOperationException">the type is not a valid type for the resolver.</exception> protected virtual void EnsureCorrectType(Type value) { if (!TypeHelper.IsTypeAssignableFrom<TResolved>(value)) throw new InvalidOperationException(string.Format( "Type {0} is not an acceptable type for resolver {1}.", value.FullName, this.GetType().FullName)); } #endregion #region Types collection manipulation support /// <summary> /// Ensures that the resolver supports removing types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support removing types.</exception> protected void EnsureSupportsRemove() { if (!SupportsRemove) throw new InvalidOperationException("This resolver does not support removing types"); } /// <summary> /// Ensures that the resolver supports clearing types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support clearing types.</exception> protected void EnsureSupportsClear() { if (!SupportsClear) throw new InvalidOperationException("This resolver does not support clearing types"); } /// <summary> /// Ensures that the resolver supports adding types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support adding types.</exception> protected void EnsureSupportsAdd() { if (!SupportsAdd) throw new InvalidOperationException("This resolver does not support adding new types"); } /// <summary> /// Ensures that the resolver supports inserting types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support inserting types.</exception> protected void EnsureSupportsInsert() { if (!SupportsInsert) throw new InvalidOperationException("This resolver does not support inserting new types"); } /// <summary> /// Gets a value indicating whether the resolver supports adding types. /// </summary> protected virtual bool SupportsAdd { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports inserting types. /// </summary> protected virtual bool SupportsInsert { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports clearing types. /// </summary> protected virtual bool SupportsClear { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports removing types. /// </summary> protected virtual bool SupportsRemove { get { return true; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Resources; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using AzureFunctions.Common; using AzureFunctions.Contracts; using AzureFunctions.Models; using AzureFunctions.Trace; using Microsoft.ApplicationInsights; using Newtonsoft.Json.Linq; namespace AzureFunctions.Controllers { public class AzureFunctionsController : ApiController { private readonly ITemplatesManager _templatesManager; private readonly ISettings _settings; private readonly IDiagnosticsManager _diagnosticsManager; private readonly TelemetryClient _telemetryClient; private readonly IPassThroughRequestManager _passThroughRequestManager; private Dictionary<string, string> _languageMap = new Dictionary<string, string>() { { "ja", "ja-JP"}, { "ko", "ko-KR"}, { "sv", "sv-SE"}, { "cs", "cs-CZ"}, { "zh-hans", "zh-CN"}, { "zh-hant", "zh-TW"} }; public AzureFunctionsController(ITemplatesManager templatesManager, ISettings settings, IDiagnosticsManager diagnosticsManager, TelemetryClient telemetryClient, IPassThroughRequestManager passThroughRequestManager) { _telemetryClient = telemetryClient; _templatesManager = templatesManager; _settings = settings; _diagnosticsManager = diagnosticsManager; _passThroughRequestManager = passThroughRequestManager; } [HttpGet] public HttpResponseMessage ListTemplates([FromUri] string runtime) { runtime = GetClearRuntime(runtime); return Request.CreateResponse(HttpStatusCode.OK, _templatesManager.GetTemplates(runtime)); } [HttpGet] public async Task<HttpResponseMessage> GetBindingConfig([FromUri] string runtime) { runtime = GetClearRuntime(runtime); return Request.CreateResponse(HttpStatusCode.OK, await _templatesManager.GetBindingConfigAsync(runtime)); } [HttpGet] public HttpResponseMessage GetLatestRuntime() { return Request.CreateResponse(HttpStatusCode.OK, Constants.CurrentLatestRuntimeVersion); } [HttpGet] public HttpResponseMessage GetResources([FromUri] string name, [FromUri] string runtime) { runtime = GetClearRuntime(runtime); string portalFolder = ""; string sdkFolder = ""; string languageFolder = name; if (name != "en") { if (!_languageMap.TryGetValue(name, out languageFolder)) { languageFolder = name + "-" + name; } portalFolder = Path.Combine(languageFolder, "AzureFunctions\\ResourcesPortal"); sdkFolder = Path.Combine(languageFolder, "Resources"); } List<string> resxFiles = new List<string>(); var result = new JObject(); string templateResourcesPath; if (!string.IsNullOrEmpty(portalFolder) && !string.IsNullOrEmpty(sdkFolder)) { resxFiles.Add(Path.Combine(this._settings.ResourcesPortalPath.Replace(".Client", ""), portalFolder + "\\Resources.resx")); templateResourcesPath = Path.Combine(this._settings.TemplatesPath, runtime + "\\Resources\\" + sdkFolder + "\\Resources.resx"); if (!File.Exists(templateResourcesPath)) { templateResourcesPath = Path.Combine(this._settings.TemplatesPath, "default\\Resources\\" + sdkFolder + "\\Resources.resx"); } resxFiles.Add(templateResourcesPath); result["lang"] = ConvertResxToJObject(resxFiles); resxFiles.Clear(); } // Always add english strings resxFiles.Add(Path.Combine(this._settings.ResourcesPortalPath.Replace(".Client", ""), "Resources.resx")); templateResourcesPath = Path.Combine(this._settings.TemplatesPath, runtime + "\\Resources\\Resources.resx"); if (!File.Exists(templateResourcesPath)) { templateResourcesPath = Path.Combine(this._settings.TemplatesPath, "default\\Resources\\Resources.resx"); } resxFiles.Add(templateResourcesPath); result["en"] = ConvertResxToJObject(resxFiles); return Request.CreateResponse(HttpStatusCode.OK, result); } [Authorize] [HttpPost] public HttpResponseMessage ReportClientError([FromBody] ClientError clientError) { FunctionsTrace.Diagnostics.Error(new Exception(clientError.Message), TracingEvents.ClientError.Message, clientError.Message, clientError.StackTrace); return Request.CreateResponse(HttpStatusCode.Accepted); } [Authorize] [HttpPost] public async Task<HttpResponseMessage> Diagnose(string armId) { var diagnosticResult = await _diagnosticsManager.Diagnose(armId); diagnosticResult = diagnosticResult.Where(r => !r.IsDiagnosingSuccessful || r.SuccessResult.HasUserAction); return Request.CreateResponse(HttpStatusCode.OK, diagnosticResult); } // HACK: this is temporary until ANT68 [Authorize] [HttpGet] public async Task<HttpResponseMessage> GetRuntimeToken(string armId) { (var success, var runtimeTokenOrError) = await _diagnosticsManager.GetRuntimeToken(armId); return success ? Request.CreateResponse(HttpStatusCode.OK, runtimeTokenOrError) : Request.CreateErrorResponse(HttpStatusCode.InternalServerError, runtimeTokenOrError); } [HttpPost] public Task<HttpResponseMessage> PassThrough(RequestObject clientRequest) { return _passThroughRequestManager.HandleRequest(clientRequest); } [HttpPost] public async Task<HttpResponseMessage> TriggerFunctionAPIM(TriggerFunctionModel request) { var apimKey = Environment.GetEnvironmentVariable("APIMSubscriptionKey"); if(String.IsNullOrEmpty(apimKey)) { return Request.CreateResponse(HttpStatusCode.BadRequest, "No APIMSubscriptionKey set"); } using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ""); client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true"); var content = new StringContent(request.body, Encoding.UTF8, "application/json"); return await client.PostAsync(request.url, content); } } private JObject ConvertResxToJObject(List<string> resxFiles) { var jo = new JObject(); foreach (var file in resxFiles) { if (File.Exists(file)) { // Create a ResXResourceReader for the file items.resx. ResXResourceReader rsxr = new ResXResourceReader(file); // Iterate through the resources and display the contents to the console. foreach (DictionaryEntry d in rsxr) { jo[d.Key.ToString()] = d.Value.ToString(); } //Close the reader. rsxr.Close(); } } return jo; } private string GetClearRuntime(string runtime) { return runtime.Replace("~", ""); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Unmanaged; using Microsoft.Win32; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; /// <summary> /// Native utility methods. /// </summary> internal static class IgniteUtils { /** Environment variable: JAVA_HOME. */ private const string EnvJavaHome = "JAVA_HOME"; /** Lookup paths. */ private static readonly string[] JvmDllLookupPaths = {@"jre\bin\server", @"jre\bin\default"}; /** Registry lookup paths. */ private static readonly string[] JreRegistryKeys = { @"Software\JavaSoft\Java Runtime Environment", @"Software\Wow6432Node\JavaSoft\Java Runtime Environment" }; /** File: jvm.dll. */ internal const string FileJvmDll = "jvm.dll"; /** File: Ignite.Jni.dll. */ internal const string FileIgniteJniDll = "ignite.jni.dll"; /** Prefix for temp directory names. */ private const string DirIgniteTmp = "Ignite_"; /** Loaded. */ private static bool _loaded; /** Thread-local random. */ [ThreadStatic] private static Random _rnd; /// <summary> /// Initializes the <see cref="IgniteUtils"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static IgniteUtils() { TryCleanTempDirectories(); } /// <summary> /// Gets thread local random. /// </summary> /// <value>Thread local random.</value> public static Random ThreadLocalRandom { get { return _rnd ?? (_rnd = new Random()); } } /// <summary> /// Returns shuffled list copy. /// </summary> /// <returns>Shuffled list copy.</returns> public static IList<T> Shuffle<T>(IList<T> list) { int cnt = list.Count; if (cnt > 1) { List<T> res = new List<T>(list); Random rnd = ThreadLocalRandom; while (cnt > 1) { cnt--; int idx = rnd.Next(cnt + 1); T val = res[idx]; res[idx] = res[cnt]; res[cnt] = val; } return res; } return list; } /// <summary> /// Load JVM DLL if needed. /// </summary> /// <param name="configJvmDllPath">JVM DLL path from config.</param> public static void LoadDlls(string configJvmDllPath) { if (_loaded) return; // 1. Load JNI dll. LoadJvmDll(configJvmDllPath); // 2. Load GG JNI dll. UnmanagedUtils.Initialize(); _loaded = true; } /// <summary> /// Create new instance of specified class. /// </summary> /// <param name="typeName">Class name</param> /// <param name="props">Properties to set.</param> /// <returns>New Instance.</returns> public static T CreateInstance<T>(string typeName, IEnumerable<KeyValuePair<string, object>> props = null) { IgniteArgumentCheck.NotNullOrEmpty(typeName, "typeName"); var type = new TypeResolver().ResolveType(typeName); if (type == null) throw new IgniteException("Failed to create class instance [className=" + typeName + ']'); var res = (T) Activator.CreateInstance(type); if (props != null) SetProperties(res, props); return res; } /// <summary> /// Set properties on the object. /// </summary> /// <param name="target">Target object.</param> /// <param name="props">Properties.</param> private static void SetProperties(object target, IEnumerable<KeyValuePair<string, object>> props) { if (props == null) return; IgniteArgumentCheck.NotNull(target, "target"); Type typ = target.GetType(); foreach (KeyValuePair<string, object> prop in props) { PropertyInfo prop0 = typ.GetProperty(prop.Key, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (prop0 == null) throw new IgniteException("Property is not found [type=" + typ.Name + ", property=" + prop.Key + ']'); prop0.SetValue(target, prop.Value, null); } } /// <summary> /// Loads the JVM DLL. /// </summary> private static void LoadJvmDll(string configJvmDllPath) { var messages = new List<string>(); foreach (var dllPath in GetJvmDllPaths(configJvmDllPath)) { var errCode = LoadDll(dllPath.Value, FileJvmDll); if (errCode == 0) return; messages.Add(string.Format(CultureInfo.InvariantCulture, "[option={0}, path={1}, error={2}]", dllPath.Key, dllPath.Value, FormatWin32Error(errCode))); if (dllPath.Value == configJvmDllPath) break; // if configJvmDllPath is specified and is invalid - do not try other options } if (!messages.Any()) // not loaded and no messages - everything was null messages.Add(string.Format(CultureInfo.InvariantCulture, "Please specify IgniteConfiguration.JvmDllPath or {0}.", EnvJavaHome)); if (messages.Count == 1) throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0} ({1})", FileJvmDll, messages[0])); var combinedMessage = messages.Aggregate((x, y) => string.Format(CultureInfo.InvariantCulture, "{0}\n{1}", x, y)); throw new IgniteException(string.Format(CultureInfo.InvariantCulture, "Failed to load {0}:\n{1}", FileJvmDll, combinedMessage)); } /// <summary> /// Formats the Win32 error. /// </summary> private static string FormatWin32Error(int errorCode) { if (errorCode == NativeMethods.ERROR_BAD_EXE_FORMAT) { var mode = Environment.Is64BitProcess ? "x64" : "x86"; return string.Format("DLL could not be loaded (193: ERROR_BAD_EXE_FORMAT). " + "This is often caused by x64/x86 mismatch. " + "Current process runs in {0} mode, and DLL is not {0}.", mode); } return string.Format("{0}: {1}", errorCode, new Win32Exception(errorCode).Message); } /// <summary> /// Try loading DLLs first using file path, then using it's simple name. /// </summary> /// <param name="filePath"></param> /// <param name="simpleName"></param> /// <returns>Zero in case of success, error code in case of failure.</returns> private static int LoadDll(string filePath, string simpleName) { int res = 0; IntPtr ptr; if (filePath != null) { ptr = NativeMethods.LoadLibrary(filePath); if (ptr == IntPtr.Zero) res = Marshal.GetLastWin32Error(); else return res; } // Failed to load using file path, fallback to simple name. ptr = NativeMethods.LoadLibrary(simpleName); if (ptr == IntPtr.Zero) { // Preserve the first error code, if any. if (res == 0) res = Marshal.GetLastWin32Error(); } else res = 0; return res; } /// <summary> /// Gets the JVM DLL paths in order of lookup priority. /// </summary> private static IEnumerable<KeyValuePair<string, string>> GetJvmDllPaths(string configJvmDllPath) { if (!string.IsNullOrEmpty(configJvmDllPath)) yield return new KeyValuePair<string, string>("IgniteConfiguration.JvmDllPath", configJvmDllPath); var javaHomeDir = Environment.GetEnvironmentVariable(EnvJavaHome); if (!string.IsNullOrEmpty(javaHomeDir)) foreach (var path in JvmDllLookupPaths) yield return new KeyValuePair<string, string>(EnvJavaHome, Path.Combine(javaHomeDir, path, FileJvmDll)); // Get paths from the Windows Registry foreach (var regPath in JreRegistryKeys) { using (var jSubKey = Registry.LocalMachine.OpenSubKey(regPath)) { if (jSubKey == null) continue; var curVer = jSubKey.GetValue("CurrentVersion") as string; // Current version comes first var versions = new[] {curVer}.Concat(jSubKey.GetSubKeyNames().Where(x => x != curVer)); foreach (var ver in versions.Where(v => !string.IsNullOrEmpty(v))) { using (var verKey = jSubKey.OpenSubKey(ver)) { var dllPath = verKey == null ? null : verKey.GetValue("RuntimeLib") as string; if (dllPath != null) yield return new KeyValuePair<string, string>(verKey.Name, dllPath); } } } } } /// <summary> /// Unpacks an embedded resource into a temporary folder and returns the full path of resulting file. /// </summary> /// <param name="resourceName">Resource name.</param> /// <param name="fileName">Name of the resulting file.</param> /// <returns> /// Path to a temp file with an unpacked resource. /// </returns> public static string UnpackEmbeddedResource(string resourceName, string fileName) { var dllRes = Assembly.GetExecutingAssembly().GetManifestResourceNames() .Single(x => x.EndsWith(resourceName, StringComparison.OrdinalIgnoreCase)); return WriteResourceToTempFile(dllRes, fileName); } /// <summary> /// Writes the resource to temporary file. /// </summary> /// <param name="resource">The resource.</param> /// <param name="name">File name prefix</param> /// <returns>Path to the resulting temp file.</returns> private static string WriteResourceToTempFile(string resource, string name) { // Dll file name should not be changed, so we create a temp folder with random name instead. var file = Path.Combine(GetTempDirectoryName(), name); using (var src = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) using (var dest = File.OpenWrite(file)) { // ReSharper disable once PossibleNullReferenceException src.CopyTo(dest); return file; } } /// <summary> /// Tries to clean temporary directories created with <see cref="GetTempDirectoryName"/>. /// </summary> private static void TryCleanTempDirectories() { foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), DirIgniteTmp + "*")) { try { Directory.Delete(dir, true); } catch (IOException) { // Expected } catch (UnauthorizedAccessException) { // Expected } } } /// <summary> /// Creates a uniquely named, empty temporary directory on disk and returns the full path of that directory. /// </summary> /// <returns>The full path of the temporary directory.</returns> private static string GetTempDirectoryName() { while (true) { var dir = Path.Combine(Path.GetTempPath(), DirIgniteTmp + Path.GetRandomFileName()); try { return Directory.CreateDirectory(dir).FullName; } catch (IOException) { // Expected } catch (UnauthorizedAccessException) { // Expected } } } /// <summary> /// Convert unmanaged char array to string. /// </summary> /// <param name="chars">Char array.</param> /// <param name="charsLen">Char array length.</param> /// <returns></returns> public static unsafe string Utf8UnmanagedToString(sbyte* chars, int charsLen) { IntPtr ptr = new IntPtr(chars); if (ptr == IntPtr.Zero) return null; byte[] arr = new byte[charsLen]; Marshal.Copy(ptr, arr, 0, arr.Length); return Encoding.UTF8.GetString(arr); } /// <summary> /// Convert string to unmanaged byte array. /// </summary> /// <param name="str">String.</param> /// <returns>Unmanaged byte array.</returns> public static unsafe sbyte* StringToUtf8Unmanaged(string str) { var ptr = IntPtr.Zero; if (str != null) { byte[] strBytes = Encoding.UTF8.GetBytes(str); ptr = Marshal.AllocHGlobal(strBytes.Length + 1); Marshal.Copy(strBytes, 0, ptr, strBytes.Length); *((byte*)ptr.ToPointer() + strBytes.Length) = 0; // NULL-terminator. } return (sbyte*)ptr.ToPointer(); } /// <summary> /// Reads node collection from stream. /// </summary> /// <param name="reader">Reader.</param> /// <param name="pred">The predicate.</param> /// <returns> Nodes list or null. </returns> public static List<IClusterNode> ReadNodes(IBinaryRawReader reader, Func<ClusterNodeImpl, bool> pred = null) { var cnt = reader.ReadInt(); if (cnt < 0) return null; var res = new List<IClusterNode>(cnt); var ignite = ((BinaryReader)reader).Marshaller.Ignite; if (pred == null) { for (var i = 0; i < cnt; i++) res.Add(ignite.GetNode(reader.ReadGuid())); } else { for (var i = 0; i < cnt; i++) { var node = ignite.GetNode(reader.ReadGuid()); if (pred(node)) res.Add(node); } } return res; } /// <summary> /// Writes the node collection to a stream. /// </summary> /// <param name="writer">The writer.</param> /// <param name="nodes">The nodes.</param> public static void WriteNodes(IBinaryRawWriter writer, ICollection<IClusterNode> nodes) { Debug.Assert(writer != null); if (nodes != null) { writer.WriteInt(nodes.Count); foreach (var node in nodes) writer.WriteGuid(node.Id); } else writer.WriteInt(-1); } } }
// Copyright 2011, 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. // Author: api.anash@gmail.com (Anash P. Oommen) using Google.Api.Ads.Common.Lib; using Google.Api.Ads.Common.Logging; using Google.Api.Ads.Dfa.Lib; using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace Google.Api.Ads.Dfa.Lib { /// <summary> /// This listener adds or retrieves necessary Soap Headers to or from the /// Soap messages. /// </summary> public class SoapHeaderListener : SoapListener { /// <summary> /// The config class to be used with this class. /// </summary> private AppConfig config; /// <summary> /// Gets the config class to be used with this class. /// </summary> public AppConfig Config { get { return config; } } /// <summary> /// The singleton instance. /// </summary> protected static SoapHeaderListener instance = new SoapHeaderListener(); /// <summary> /// The soap namespace prefix. /// </summary> private const string SOAP_PREFIX = "soap"; /// <summary> /// The soap namespace url. /// </summary> private const string SOAP_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope/"; /// <summary> /// The wsse namespace prefix. /// </summary> private const string WSSE_PREFIX = "wsse"; /// <summary> /// The wsse namespace url. /// </summary> private const string WSSE_NAMESPACE = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; /// <summary> /// Protected constructor. /// </summary> protected SoapHeaderListener() { this.config = new DfaAppConfig(); } /// <summary> /// Gets the singleton instance. /// </summary> public static SoapListener Instance { get { return instance; } } /// <summary> /// Gets the soap header node. /// </summary> /// <param name="soapMessage">The soap message.</param> /// <param name="xmlnt">The xml nametable.</param> /// <param name="createIfMissing">True, if the header node should be created /// if missing.</param> /// <returns>The soap header node.</returns> XmlElement GetSoapHeaderNode(XmlDocument soapMessage, XmlNamespaceManager xmlnt, bool createIfMissing) { string headerXpath = string.Format("{0}:Envelope/{0}:Header", SOAP_PREFIX); string bodyXpath = string.Format("{0}:Envelope/{0}:Body", SOAP_PREFIX); XmlElement soapHeader = (XmlElement) soapMessage.SelectSingleNode(headerXpath, xmlnt); if (soapHeader == null && createIfMissing) { soapHeader = soapMessage.CreateElement(SOAP_PREFIX, "Header", SOAP_NAMESPACE); XmlElement soapBody = (XmlElement) soapMessage.SelectSingleNode(bodyXpath, xmlnt); if (soapBody != null) { soapMessage.DocumentElement.InsertBefore(soapHeader, soapBody); } } return soapHeader; } /// <summary> /// Adds the security header. /// </summary> /// <param name="soapHeader">The SOAP header.</param> /// <param name="token">The user token.</param> private void AddSecurityHeader(XmlElement soapHeader, UserToken token) { string securityXml = string.Join("\n", new string[] { "<" + WSSE_PREFIX + ":Security xmlns:" + SOAP_PREFIX + "='" + SOAP_NAMESPACE + "'", "xmlns:" + WSSE_PREFIX + "='" + WSSE_NAMESPACE + "'", SOAP_PREFIX + ":mustUnderstand='1'>", "<" + WSSE_PREFIX + ":UsernameToken>", "<" + WSSE_PREFIX + ":Username>" + token.Username + "</" + WSSE_PREFIX + ":Username>", "<" + WSSE_PREFIX + ":Password>" + token.Password + "</" + WSSE_PREFIX + ":Password>", "</" + WSSE_PREFIX + ":UsernameToken>", "</" + WSSE_PREFIX + ":Security>"}); XmlDocumentFragment securityHeader = soapHeader.OwnerDocument.CreateDocumentFragment(); securityHeader.InnerXml = securityXml; soapHeader.AppendChild(securityHeader); } /// <summary> /// Adds the request header. /// </summary> /// <param name="soapHeader">The SOAP header.</param> /// <param name="requestHeader">The request header.</param> private void AddRequestHeader(XmlElement soapHeader, RequestHeader requestHeader) { const string TNS_PREFIX = "tns"; string TNS_NAMESPACE = requestHeader.TargetNamespace; string requestHeaderXml = string.Join("\n", new string[] { "<" + TNS_PREFIX + ":RequestHeader xmlns:" + TNS_PREFIX + "='" + TNS_NAMESPACE + "'>", "<" + TNS_PREFIX + ":applicationName>" + requestHeader.ApplicationName + "</" + TNS_PREFIX + ":applicationName>", "</" + TNS_PREFIX + ":RequestHeader>" }); XmlDocumentFragment requestHeaderNode = soapHeader.OwnerDocument.CreateDocumentFragment(); requestHeaderNode.InnerXml = requestHeaderXml; soapHeader.AppendChild(requestHeaderNode); } /// <summary> /// Parses the response header. /// </summary> /// <param name="soapMessage">The SOAP message.</param> /// <param name="xmlnt">The xml name table.</param> /// <returns>The response header.</returns> private ResponseHeader ParseResponseHeader(XmlDocument soapMessage, XmlNamespaceManager xmlnt) { ResponseHeader responseHeader = null; XmlElement soapHeader = GetSoapHeaderNode(soapMessage, xmlnt, false); if (soapHeader != null) { responseHeader = new ResponseHeader(); XmlNodeList childNodes = soapHeader.SelectNodes("child::*"); foreach (XmlElement childNode in childNodes) { if (childNode.LocalName == "ResponseHeader") { XmlNodeList grandChildNodes = childNode.SelectNodes("child::*"); foreach (XmlElement grandChildNode in grandChildNodes) { switch (grandChildNode.LocalName) { case "requestId": responseHeader.RequestId = grandChildNode.InnerText; break; case "responseTime": responseHeader.ResponseTime = long.Parse(grandChildNode.InnerText); break; } } } } } return responseHeader; } /// <summary> /// Initializes the listener for handling an API call. /// </summary> public void InitForCall() { } /// <summary> /// Handles the message. /// </summary> /// <param name="soapMessage">The SOAP message.</param> /// <param name="service">The service.</param> /// <param name="direction">The direction.</param> public void HandleMessage(XmlDocument soapMessage, AdsClient service, SoapMessageDirection direction) { XmlNamespaceManager xmlnt = new XmlNamespaceManager(soapMessage.NameTable); xmlnt.AddNamespace(SOAP_PREFIX, SOAP_NAMESPACE); if (direction == SoapMessageDirection.OUT) { UserToken token = (UserToken) ContextStore.GetValue("Token"); RequestHeader requestHeader = (RequestHeader) ContextStore.GetValue("RequestHeader"); if (token != null || requestHeader != null) { XmlElement soapHeader = GetSoapHeaderNode(soapMessage, xmlnt, true); if (token != null) { AddSecurityHeader(soapHeader, token); } if (requestHeader != null) { AddRequestHeader(soapHeader, requestHeader); } } } else { ContextStore.AddKey("ResponseHeader", ParseResponseHeader(soapMessage, xmlnt)); } } /// <summary> /// Cleans up any resources after an API call. /// </summary> public void CleanupAfterCall() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; namespace ProjectEuler.Problems { class Problem58 { private int isPrime(long n) { if (n % 2 == 0 || n % 3 == 0) return 0; for (int i = 5; i < (long)Math.Sqrt(n) + 1; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return 0; } return 1; } public void Run() { DateTime start = DateTime.Now; int primes = 0; long size = 1; long arm1,arm2,arm3; double primes_rate = 1; do { size += 2; arm1 = (size * size) - (size - 1) * 3; arm2 = (size * size) - (size - 1) * 2; arm3 = (size * size) - (size - 1) * 1; primes += isPrime(arm1); primes += isPrime(arm2); primes += isPrime(arm3); primes_rate = primes / (size * 2.0 - 1); } while (primes_rate >= 0.1); Console.WriteLine("PrimesInSpiralArms(" + size.ToString() + ")= " + primes_rate.ToString()); Console.WriteLine((DateTime.Now - start).TotalMilliseconds); Console.ReadLine(); } } /******* Spiral building *******/ class Problem58_Overflow { List<List<int>> spiral; int size = 10001; SieveBig s; public Problem58_Overflow() { s = new SieveBig(51 * 50); //s = new SieveBig((new BigInteger(1000000)) * 535); } private void InitSpiral() { spiral = new List<List<int>>(); for (int i = 0; i < size; i++) { spiral.Add(new List<int>()); for (int j = 0; j < size; j++) { spiral[i].Add(0); } } int x = (size - 1) / 2; int y = x; spiral[x][y] = 1; FillSpiral(x, y, 2, "right"); } private void FillSpiral(int x, int y, int current, string direction) { int currentSize = spiral[0].Count; while (current <= currentSize * currentSize && x < currentSize && y < currentSize && x >= 0 && y >= 0) { if (direction == "right") { y = y + 1; if (y < currentSize) { spiral[x][y] = current; if (x - 1 > 0) { if (spiral[x - 1][y] == 0) { direction = "up"; } } } } else if (direction == "up") { x = x - 1; if (x >= 0) { spiral[x][y] = current; if (y - 1 > 0) { if (spiral[x][y - 1] == 0) { direction = "left"; } } } } else if (direction == "left") { y = y - 1; if (y >= 0) { spiral[x][y] = current; if (x + 1 < currentSize) { if (spiral[x + 1][y] == 0) { direction = "down"; } } } } else if (direction == "down") { x = x + 1; if (x < currentSize) { spiral[x][y] = current; if (y + 1 < currentSize) { if (spiral[x][y + 1] == 0) { direction = "right"; } } } } current++; } } private void PrintSpiral() { string blank = " "; for (int i = 0; i < (size * size).ToString().Length; i++) { blank += " "; } for (int i = 0; i < spiral.Count; i++) { for (int j = 0; j < spiral[i].Count; j++) { string to_print = spiral[i][j].ToString();; Console.Write((blank + to_print).Substring(to_print.Length - 1)); } Console.WriteLine(); } Console.WriteLine(); } private void GrowSpiral() { size += 2; for (int i = 0; i < spiral.Count; i++) { spiral[i].Insert(0, 0); spiral[i].Add(0); } List<int> newLine = new List<int>(); List<int> newLine2 = new List<int>(); for (int i = 0; i < size; i++) { newLine.Add(0); newLine2.Add(0); } spiral.Insert(0, newLine); spiral.Add(newLine2); FillSpiral(size - 2, size - 2, (size - 2) * (size - 2) + 1, "right"); } private int CountPrimes() { int count = 0; for (int i = 0; i < spiral.Count; i++) { if (s.isPrime(spiral[i][i])) { count++; } if (s.isPrime(spiral[i][size - i - 1])) { count++; } } return count; } public void Run() { InitSpiral(); int primes = CountPrimes(); double primes_ratio = primes / (size * 2.0 - 1); while (primes_ratio > 0.1) { GrowSpiral(); primes += s.isPrime(spiral[0][0]) ? 1 : 0; primes += s.isPrime(spiral[0][size - 1]) ? 1 : 0; primes += s.isPrime(spiral[size - 1][0]) ? 1 : 0; //primes += s.prime[spiral[size-1][size-1]] ? 1 : 0; // Always a Square Number primes_ratio = primes / (size * 2.0 - 1); } Console.WriteLine(primes.ToString() + "/" + (size * 2 - 1).ToString() + " = " + primes_ratio.ToString()); Console.ReadLine(); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using FluentAssertions; using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Tools.Test.Utilities; using System; using System.IO; using System.Linq; using Xunit; namespace Microsoft.DotNet.Cli.Sln.List.Tests { public class GivenDotnetSlnList : TestBase { private const string HelpText = @".NET List project(s) in a solution file Command Usage: dotnet sln <SLN_FILE> list [options] Arguments: <SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one. Options: -h, --help Show help information. "; private const string SlnCommandHelpText = @".NET modify solution file command Usage: dotnet sln [options] <SLN_FILE> [command] Arguments: <SLN_FILE> Solution file to operate on. If not specified, the command will search the current directory for one. Options: -h, --help Show help information. Commands: add <args> .NET Add project(s) to a solution file Command list .NET List project(s) in a solution file Command remove <args> .NET Remove project(s) from a solution file Command "; [Theory] [InlineData("--help")] [InlineData("-h")] public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln list {helpArg}"); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Theory] [InlineData("")] [InlineData("unknownCommandName")] public void WhenNoCommandIsPassedItPrintsError(string commandName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {commandName}"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Required command was not provided."); cmd.StdOut.Should().BeVisuallyEquivalentTo(SlnCommandHelpText); } [Fact] public void WhenTooManyArgumentsArePassedItPrintsError() { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput("sln one.sln two.sln three.sln list"); cmd.Should().Fail(); cmd.StdErr.Should().BeVisuallyEquivalentTo("Unrecognized command or argument 'two.sln'\r\nUnrecognized command or argument 'three.sln'"); } [Theory] [InlineData("idontexist.sln")] [InlineData("ihave?invalidcharacters.sln")] [InlineData("ihaveinv@lidcharacters.sln")] [InlineData("ihaveinvalid/characters")] [InlineData("ihaveinvalidchar\\acters")] public void WhenNonExistingSolutionIsPassedItPrintsErrorAndUsage(string solutionName) { var cmd = new DotnetCommand() .ExecuteWithCapturedOutput($"sln {solutionName} list"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Could not find solution or directory `{solutionName}`."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenInvalidSolutionIsPassedItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("sln InvalidSolution.sln list"); cmd.Should().Fail(); cmd.StdErr.Should().Be("Invalid solution `InvalidSolution.sln`. Expected file header not found."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenInvalidSolutionIsFoundItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("InvalidSolution") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionFullPath = Path.Combine(projectDirectory, "InvalidSolution.sln"); var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("sln list"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Invalid solution `{solutionFullPath}`. Expected file header not found."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithSlnAndCsprojFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var solutionDir = Path.Combine(projectDirectory, "App"); var cmd = new DotnetCommand() .WithWorkingDirectory(solutionDir) .ExecuteWithCapturedOutput("sln list"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Specified solution file {solutionDir + Path.DirectorySeparatorChar} does not exist, or there is no solution file in the directory."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenMoreThanOneSolutionExistsInTheDirectoryItPrintsErrorAndUsage() { var projectDirectory = TestAssets .Get("TestAppWithMultipleSlnFiles") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("sln list"); cmd.Should().Fail(); cmd.StdErr.Should().Be($"Found more than one solution file in {projectDirectory + Path.DirectorySeparatorChar}. Please specify which one to use."); cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText); } [Fact] public void WhenNoProjectReferencesArePresentInTheSolutionItPrintsANoProjectMessage() { var projectDirectory = TestAssets .Get("TestAppWithEmptySln") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("sln list"); cmd.Should().Pass(); cmd.StdOut.Should().Be("No projects found in the solution."); } [Fact] public void WhenProjectReferencesArePresentInTheSolutionItListsThem() { string OutputText = $@"Project reference(s) -------------------- {Path.Combine("App", "App.csproj")} {Path.Combine("Lib", "Lib.csproj")}"; var projectDirectory = TestAssets .Get("TestAppWithSlnAndExistingCsprojReferences") .CreateInstance() .WithSourceFiles() .Root .FullName; var cmd = new DotnetCommand() .WithWorkingDirectory(projectDirectory) .ExecuteWithCapturedOutput("sln list"); cmd.Should().Pass(); cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client.Cache { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Event; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Client.Cache.Query.Continuous; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Interop; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Compute; using NUnit.Framework; /// <summary> /// Tests for thin client continuous queries. /// </summary> public class ContinuousQueryTest : ClientTestBase { /** */ private const int MaxCursors = 20; /// <summary> /// Initializes a new instance of <see cref="ContinuousQueryTest"/>. /// </summary> public ContinuousQueryTest() : base(gridCount: 2, enableServerListLogging: true) { // No-op. } /// <summary> /// Executes after every test. /// </summary> [TearDown] public void TestTearDown() { Assert.IsEmpty(Client.GetActiveNotificationListeners()); } /// <summary> /// Basic continuous query test. /// /// - Start the query /// - Add cache entry, verify query event /// - Update cache entry, verify query event /// - Remove cache entry, verify query event /// </summary> [Test] public void TestContinuousQueryCallsLocalListenerWithCorrectEvent() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var events = new List<ICacheEntryEvent<int, int>>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(events.Add)); using (cache.QueryContinuous(qry)) { // Create. cache.Put(1, 1); TestUtils.WaitForTrueCondition(() => events.Count == 1); var evt = events.Single(); Assert.AreEqual(CacheEntryEventType.Created, evt.EventType); Assert.IsFalse(evt.HasOldValue); Assert.IsTrue(evt.HasValue); Assert.AreEqual(1, evt.Key); Assert.AreEqual(1, evt.Value); // Update. cache.Put(1, 2); TestUtils.WaitForTrueCondition(() => events.Count == 2); evt = events.Last(); Assert.AreEqual(CacheEntryEventType.Updated, evt.EventType); Assert.IsTrue(evt.HasOldValue); Assert.IsTrue(evt.HasValue); Assert.AreEqual(1, evt.Key); Assert.AreEqual(2, evt.Value); Assert.AreEqual(1, evt.OldValue); // Remove. cache.Remove(1); TestUtils.WaitForTrueCondition(() => events.Count == 3); evt = events.Last(); Assert.AreEqual(CacheEntryEventType.Removed, evt.EventType); Assert.IsTrue(evt.HasOldValue); Assert.IsTrue(evt.HasValue); Assert.AreEqual(1, evt.Key); Assert.AreEqual(2, evt.Value); Assert.AreEqual(2, evt.OldValue); } } /// <summary> /// Tests that default query settings have correct values. /// </summary> [Test] public void TestDefaultSettings() { var qry = new ContinuousQueryClient<int, int>(); Assert.AreEqual(ContinuousQueryClient.DefaultBufferSize, qry.BufferSize); Assert.AreEqual(TimeSpan.Zero, qry.TimeInterval); } /// <summary> /// Tests that Compute notifications and Continuous Query notifications work together correctly. /// Compute and Continuous Queries use the same server -> client notification mechanism, /// we ensure that there are no conflicts when both are used in parallel. /// /// - Start a new thread that runs Compute tasks in background /// - Start two continuous queries, with and without filter, using same thin client connection /// - Update cache and verify that continuous query listeners receive correct events /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestComputeWorksWhenContinuousQueryIsActive() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var receivedKeysAll = new ConcurrentBag<int>(); var receivedKeysOdd = new ConcurrentBag<int>(); var qry1 = new ContinuousQueryClient<int, int> { Listener = new DelegateListener<int, int>(e => receivedKeysOdd.Add(e.Key)), Filter = new OddKeyFilter() }; var qry2 = new ContinuousQueryClient<int, int> { Listener = new DelegateListener<int, int>(e => receivedKeysAll.Add(e.Key)), }; var cts = new CancellationTokenSource(); var computeRunnerTask = Task.Factory.StartNew(() => { while (!cts.IsCancellationRequested) { var res = Client.GetCompute().ExecuteJavaTask<int>( ComputeApiTest.EchoTask, ComputeApiTest.EchoTypeInt); Assert.AreEqual(1, res); } }, cts.Token); var keys = Enumerable.Range(1, 10000).ToArray(); using (cache.QueryContinuous(qry1)) using (cache.QueryContinuous(qry2)) { foreach (var key in keys) { cache[key] = key; } } cts.Cancel(); computeRunnerTask.Wait(); TestUtils.WaitForTrueCondition(() => receivedKeysAll.Count == keys.Length); Assert.AreEqual(keys.Length / 2, receivedKeysOdd.Count); CollectionAssert.AreEquivalent(keys, receivedKeysAll); CollectionAssert.AreEquivalent(keys.Where(k => k % 2 == 1), receivedKeysOdd); } /// <summary> /// Tests that continuous query with filter receives only matching events. /// /// - Start a continuous query with filter /// - Verify that filter receives all events /// - Verify that listener receives filtered events /// </summary> [Test] public void TestContinuousQueryWithFilterReceivesOnlyMatchingEvents() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); ICacheEntryEvent<int, int> lastEvt = null; var listener = new DelegateListener<int, int>(e => lastEvt = e); var qry = new ContinuousQueryClient<int,int>(listener) { Filter = new OddKeyFilter() }; using (cache.QueryContinuous(qry)) { cache.Put(0, 0); TestUtils.WaitForTrueCondition(() => OddKeyFilter.LastKey == 0); Assert.IsNull(lastEvt); cache.Put(5, 5); TestUtils.WaitForTrueCondition(() => OddKeyFilter.LastKey == 5); TestUtils.WaitForTrueCondition(() => lastEvt != null); Assert.IsNotNull(lastEvt); Assert.AreEqual(5, lastEvt.Key); cache.Put(8, 8); TestUtils.WaitForTrueCondition(() => OddKeyFilter.LastKey == 8); Assert.AreEqual(5, lastEvt.Key); } } /// <summary> /// Tests that continuous query with a Java filter receives only matching events. /// /// - Start a continuous query with a Java filter /// - Check that .NET listener receives filtered events /// </summary> [Test] public void TestContinuousQueryWithJavaFilterReceivesOnlyMatchingEvents() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var evts = new ConcurrentBag<int>(); var listener = new DelegateListener<int, int>(e => evts.Add(e.Key)); var qry = new ContinuousQueryClient<int, int>(listener) { Filter = new JavaObject("org.apache.ignite.platform.PlatformCacheEntryEvenKeyEventFilter", null) .ToCacheEntryEventFilter<int, int>() }; using (cache.QueryContinuous(qry)) { cache.PutAll(Enumerable.Range(1, 5).ToDictionary(x => x, x => x)); } TestUtils.WaitForTrueCondition(() => evts.Count == 2); CollectionAssert.AreEquivalent(new[] {2, 4}, evts); } /// <summary> /// Tests that server-side updates are sent to the client. /// /// - Start a thin client continuous query /// - Update cache from server node /// - Check that thin client receives events /// </summary> [Test] public void TestClientContinuousQueryReceivesEventsFromServerCache() { const int count = 10000; var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var receiveCount = 0; var listener = new DelegateListener<int, int>(e => { Interlocked.Increment(ref receiveCount); }); using (cache.QueryContinuous(new ContinuousQueryClient<int, int>(listener))) { var serverCache = Ignition.GetIgnite("1").GetCache<int, int>(cache.Name); for (var i = 0; i < count; i++) { serverCache.Put(i, i); } TestUtils.WaitForTrueCondition(() => receiveCount == count); } } /// <summary> /// Tests that when cache is in binary mode (<see cref="ICacheClient{TK,TV}.WithKeepBinary{K1,V1}"/>, /// continuous query listener and filter receive binary objects. /// /// - Get a cache in binary mode (WithKeepBinary) /// - Start a continuous query /// - Check that both filter and listener receive objects in binary form /// </summary> [Test] public void TestContinuousQueryWithKeepBinaryPassesBinaryObjectsToListenerAndFilter() { var cache = Client.GetOrCreateCache<int, Person>(TestUtils.TestName); var binCache = cache.WithKeepBinary<int, IBinaryObject>(); var evts = new ConcurrentBag<IBinaryObject>(); var qry = new ContinuousQueryClient<int, IBinaryObject> { Listener = new DelegateListener<int, IBinaryObject>(e => evts.Add(e.Value)), Filter = new EvenIdBinaryFilter() }; using (binCache.QueryContinuous(qry)) { cache[2] = new Person(2); cache[3] = new Person(3); TestUtils.WaitForTrueCondition(() => !evts.IsEmpty); } // Listener should receive one event with an even id. var binObj = evts.Single(); Assert.IsNotNull(binObj); Assert.AreEqual(2, binObj.GetField<int>("Id")); Assert.AreEqual("Person 2", binObj.GetField<string>("Name")); // Filter has received both events, last one was filtered out. binObj = EvenIdBinaryFilter.LastValue; Assert.IsNotNull(binObj); Assert.AreEqual(3, binObj.GetField<int>("Id")); Assert.AreEqual("Person 3", binObj.GetField<string>("Name")); } /// <summary> /// Tests that custom key / value objects can be used in Continuous Query filter and listener. /// /// - Create a cache with a custom class value (Person) /// - Run a continuous query with filter and listener /// </summary> [Test] public void TestContinuousQueryWithCustomObjects() { var cache = Client.GetOrCreateCache<int, Person>(TestUtils.TestName); var evts = new ConcurrentBag<Person>(); var qry = new ContinuousQueryClient<int, Person> { Listener = new DelegateListener<int, Person>(e => evts.Add(e.Value)), Filter = new EvenIdFilter() }; using (cache.QueryContinuous(qry)) { cache[2] = new Person(2); cache[3] = new Person(3); TestUtils.WaitForTrueCondition(() => !evts.IsEmpty); } // Listener should receive one event with an even id. var obj = evts.Single(); Assert.IsNotNull(obj); Assert.AreEqual(2, obj.Id); Assert.AreEqual("Person 2", obj.Name); // Filter has received both events, last one was filtered out. obj = EvenIdFilter.LastValue; Assert.IsNotNull(obj); Assert.AreEqual(3, obj.Id); Assert.AreEqual("Person 3", obj.Name); } /// <summary> /// Tests that exception in continuous query remote filter is logged and event is delivered anyway. /// /// - Run a continuous query with a filter that throws an exception /// - Verify that exception is logged /// - Verify that the client receives an event /// </summary> [Test] public void TestExceptionInFilterIsLoggedAndFilterIsIgnored() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var evts = new ConcurrentBag<int>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(e => evts.Add(e.Key))) { Filter = new ExceptionalFilter() }; using (cache.QueryContinuous(qry)) { cache[1] = 1; } Assert.AreEqual(1, cache[1]); // Assert: error is logged. var error = GetLoggers() .SelectMany(x => x.Entries) .Where(e => e.Level >= LogLevel.Warn) .Select(e => e.Message) .LastOrDefault(); Assert.AreEqual( "CacheEntryEventFilter failed: javax.cache.event.CacheEntryListenerException: " + ExceptionalFilter.Error, error); // Assert: continuous query event is delivered. Assert.AreEqual(new[] {1}, evts); } /// <summary> /// Tests that continuous query disconnected event (<see cref="IContinuousQueryHandleClient.Disconnected"/>) /// is raised when thin client connection is lost. /// /// - Start a continuous query /// - Disconnect the client /// - Verify that the Disconnected event is raised /// </summary> [Test] public void TestClientDisconnectRaisesDisconnectedEventOnQueryHandle() { ICacheEntryEvent<int, int> lastEvt = null; var qry = new ContinuousQueryClient<int,int>( new DelegateListener<int, int>(e => lastEvt = e)); var client = GetClient(); var cache = client.GetOrCreateCache<int, int>(TestUtils.TestName); var handle = cache.QueryContinuous(qry); ContinuousQueryClientDisconnectedEventArgs disconnectedEventArgs = null; handle.Disconnected += (sender, args) => { disconnectedEventArgs = args; // ReSharper disable once AccessToDisposedClosure (disposed state does not matter) Assert.AreEqual(handle, sender); }; cache[1] = 1; TestUtils.WaitForTrueCondition(() => lastEvt != null); client.Dispose(); // Assert: disconnected event has been raised. TestUtils.WaitForTrueCondition(() => disconnectedEventArgs != null); Assert.IsNotNull(disconnectedEventArgs.Exception); StringAssert.StartsWith("Cannot access a disposed object", disconnectedEventArgs.Exception.Message); // Multiple dispose is allowed. handle.Dispose(); handle.Dispose(); } /// <summary> /// Tests that continuous query disconnected event is not raised on a disposed handle. /// /// - Start a continuous query /// - Subscribe to the Disconnected event /// - Stop the continuous query /// - Stop the client /// - Check that the Disconnected event did not occur /// </summary> [Test] public void TestClientDisconnectDoesNotRaiseDisconnectedEventOnDisposedQueryHandle() { var qry = new ContinuousQueryClient<int,int>(new DelegateListener<int, int>()); var client = GetClient(); var cache = client.GetOrCreateCache<int, int>(TestUtils.TestName); ContinuousQueryClientDisconnectedEventArgs disconnectedEventArgs = null; using (var handle = cache.QueryContinuous(qry)) { handle.Disconnected += (sender, args) => disconnectedEventArgs = args; } client.Dispose(); // Assert: disconnected event has NOT been raised. Assert.IsNull(disconnectedEventArgs); } /// <summary> /// Tests that client does not receive updates for a stopped continuous query. /// /// - Start a continuous query with the TimeInterval set to 1 second and the BufferSize to 10 /// - Put 1 entry to the cache /// - Stop the continuous query /// - Check that the client does not receive any continuous query events after the query has been stopped /// </summary> [Test] public void TestDisposedQueryHandleDoesNotReceiveUpdates() { // Stop the query before the batch is sent out by time interval. var interval = TimeSpan.FromSeconds(1); TestBatches(1, 10, interval, (keys, res) => { }); Thread.Sleep(interval); // Check that socket has no dangling notifications. Assert.IsEmpty(Client.GetActiveNotificationListeners()); } /// <summary> /// Tests that <see cref="ClientConnectorConfiguration.MaxOpenCursorsPerConnection"/> controls /// maximum continuous query count. /// /// - Set MaxOpenCursorsPerConnection /// - Try to start more queries than that /// - Check that correct exception is returned /// </summary> [Test] public void TestContinuousQueryCountIsLimitedByMaxCursors() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var qry = new ContinuousQueryClient<int, int>( new DelegateListener<int, int>()); var queries = Enumerable.Range(1, MaxCursors).Select(_ => cache.QueryContinuous(qry)).ToList(); var ex = Assert.Throws<IgniteClientException>(() => cache.QueryContinuous(qry)); queries.ForEach(q => q.Dispose()); StringAssert.StartsWith("Too many open cursors", ex.Message); Assert.AreEqual(ClientStatusCode.TooManyCursors, ex.StatusCode); } /// <summary> /// Tests that multiple queries can be started from multiple threads. /// /// - Run multiple continuous queries from different threads using the same thin client connection /// - Versify that results are correct /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestMultipleQueriesMultithreaded() { var cache = Ignition.GetIgnite().GetOrCreateCache<int, int>(TestUtils.TestName); cache.Put(1, 0); var cts = new CancellationTokenSource(); var updaterThread = Task.Factory.StartNew(() => { for (long i = 0; i < long.MaxValue && !cts.IsCancellationRequested; i++) { cache.Put(1, (int) i); } }); var clientCache = Client.GetCache<int, int>(cache.Name); TestUtils.RunMultiThreaded(() => { var evt = new ManualResetEventSlim(); var qry = new ContinuousQueryClient<int, int> { Listener = new DelegateListener<int, int>(e => { Assert.AreEqual(1, e.Key); Assert.AreEqual(CacheEntryEventType.Updated, e.EventType); evt.Set(); }) }; for (var i = 0; i < 200; i++) { evt.Reset(); using (clientCache.QueryContinuous(qry)) { evt.Wait(); } } }, 16); cts.Cancel(); updaterThread.Wait(); } /// <summary> /// Tests that Listener presence is validated before starting the continuous query. /// </summary> [Test] public void TestContinuousQueryWithoutListenerThrowsException() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var ex = Assert.Throws<ArgumentNullException>(() => cache.QueryContinuous(new ContinuousQueryClient<int, int>())); Assert.AreEqual("continuousQuery.Listener", ex.ParamName); } /// <summary> /// Tests that when custom <see cref="ContinuousQueryClient{TK,TV}.BufferSize"/> is set, /// events are sent in batches, not 1 by 1. /// /// - Start a continuous query with the BufferSize set to 3 /// - Put 8 entries to the cache /// - Check that 2 batches of 3 entries has been received, and last 2 keys has not been received. /// </summary> [Test] public void TestCustomBufferSizeResultsInBatchedUpdates() { TestBatches(8, 3, TimeSpan.Zero, (keys, res) => { TestUtils.WaitForTrueCondition(() => res.Count == 2, () => res.Count.ToString()); var resOrdered = res.OrderBy(x => x.FirstOrDefault()).ToList(); CollectionAssert.AreEquivalent(keys.Take(3), resOrdered.First()); CollectionAssert.AreEquivalent(keys.Skip(3).Take(3), resOrdered.Last()); }); } /// <summary> /// Tests that when custom <see cref="ContinuousQueryClient{TK,TV}.TimeInterval"/> is set, /// and <see cref="ContinuousQueryClient{TK,TV}.BufferSize"/> is greater than 1, /// batches are sent out before buffer is full when the time interval passes. /// /// - Start a continuous query with the BufferSize set to 4 and TimeInterval set to 1 second /// - Put 2 entries to the cache /// - Wait and check that clint has received one batch of 2 entries /// </summary> [Test] public void TestCustomTimeIntervalCausesIncompleteBatches() { TestBatches(2, 4, TimeSpan.FromSeconds(1), (keys, res) => { TestUtils.WaitForTrueCondition(() => res.Count == 1, () => res.Count.ToString(), 2000); CollectionAssert.AreEquivalent(keys.Take(2), res.Single()); }); } /// <summary> /// Tests that <see cref="ContinuousQueryClient{TK,TV}.IncludeExpired"/> is false by default /// and expiration events are not delivered. /// /// - Create a cache with expiry policy /// - Start a continuous query with default settings /// - Check that Created events are delivered, but Expired events are not /// </summary> [Test] public void TestIncludeExpiredIsFalseByDefaultAndExpiredEventsAreSkipped() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName) .WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(100), null, null)); var events = new ConcurrentQueue<ICacheEntryEvent<int, int>>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(events.Enqueue)); Assert.IsFalse(qry.IncludeExpired); using (cache.QueryContinuous(qry)) { cache[1] = 2; TestUtils.WaitForTrueCondition(() => !cache.ContainsKey(1), 5000); cache[2] = 3; } Assert.AreEqual(2, events.Count); Assert.AreEqual(CacheEntryEventType.Created, events.First().EventType); Assert.AreEqual(CacheEntryEventType.Created, events.Last().EventType); } /// <summary> /// Tests that enabling <see cref="ContinuousQueryClient{TK,TV}.IncludeExpired"/> causes /// <see cref="CacheEntryEventType.Expired"/> events to be delivered. /// /// - Create a cache with expiry policy /// - Start a continuous query with <see cref="ContinuousQueryClient{TK,TV}.IncludeExpired"/> set to <c>true</c> /// - Check that Expired events are delivered /// </summary> [Test] public void TestExpiredEventsAreDeliveredWhenIncludeExpiredIsTrue() { var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName) .WithExpiryPolicy(new ExpiryPolicy(TimeSpan.FromMilliseconds(100), null, null)); var events = new ConcurrentQueue<ICacheEntryEvent<int, int>>(); var qry = new ContinuousQueryClient<int, int>(new DelegateListener<int, int>(events.Enqueue)) { IncludeExpired = true }; using (cache.QueryContinuous(qry)) { cache[1] = 2; TestUtils.WaitForTrueCondition(() => events.Count == 2, 5000); } Assert.AreEqual(2, events.Count); Assert.AreEqual(CacheEntryEventType.Created, events.First().EventType); Assert.AreEqual(CacheEntryEventType.Expired, events.Last().EventType); Assert.IsTrue(events.Last().HasValue); Assert.IsTrue(events.Last().HasOldValue); Assert.AreEqual(2, events.Last().Value); Assert.AreEqual(2, events.Last().OldValue); Assert.AreEqual(1, events.Last().Key); } /// <summary> /// Tests batching behavior. /// </summary> private void TestBatches(int keyCount, int bufferSize, TimeSpan interval, Action<List<int>, ConcurrentQueue<List<int>>> assert) { var res = new ConcurrentQueue<List<int>>(); var qry = new ContinuousQueryClient<int, int> { Listener = new DelegateBatchListener<int, int>(evts => res.Enqueue(evts.Select(e => e.Key).ToList())), BufferSize = bufferSize, TimeInterval = interval }; var cache = Client.GetOrCreateCache<int, int>(TestUtils.TestName); var server = Ignition.GetIgnite("1"); var serverCache = server.GetCache<int, int>(cache.Name); // Use primary keys for "remote" node to ensure batching. // Client is connected to another server node, so it will receive batches as expected. var keys = TestUtils.GetPrimaryKeys(server, cache.Name).Take(keyCount).ToList(); using (cache.QueryContinuous(qry)) { keys.ForEach(k => serverCache.Put(k, k)); assert(keys, res); } } /** <inheritdoc /> */ protected override IgniteConfiguration GetIgniteConfiguration() { return new IgniteConfiguration(base.GetIgniteConfiguration()) { ClientConnectorConfiguration = new ClientConnectorConfiguration { MaxOpenCursorsPerConnection = MaxCursors, ThinClientConfiguration = new ThinClientConfiguration { MaxActiveComputeTasksPerConnection = 100, } } }; } /** */ private class DelegateListener<TK, TV> : ICacheEntryEventListener<TK, TV> { /** */ private readonly Action<ICacheEntryEvent<TK, TV>> _action; /** */ public DelegateListener(Action<ICacheEntryEvent<TK, TV>> action = null) { _action = action ?? (_ => {}); } /** <inheritdoc /> */ public void OnEvent(IEnumerable<ICacheEntryEvent<TK, TV>> evts) { foreach (var evt in evts) { _action(evt); } } } /** */ private class DelegateBatchListener<TK, TV> : ICacheEntryEventListener<TK, TV> { /** */ private readonly Action<IEnumerable<ICacheEntryEvent<TK, TV>>> _action; /** */ public DelegateBatchListener(Action<IEnumerable<ICacheEntryEvent<TK, TV>>> action = null) { _action = action ?? (_ => {}); } /** <inheritdoc /> */ public void OnEvent(IEnumerable<ICacheEntryEvent<TK, TV>> evts) { _action(evts); } } /** */ private class OddKeyFilter : ICacheEntryEventFilter<int, int>, ICacheEntryFilter<int, int> { /** */ public static int LastKey; /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, int> evt) { LastKey = evt.Key; return evt.Key % 2 == 1; } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, int> entry) { LastKey = entry.Key; return entry.Key % 2 == 1; } } /** */ private class ExceptionalFilter : ICacheEntryEventFilter<int, int>, ICacheEntryFilter<int, int> { /** */ public const string Error = "Foo failed because of bar"; /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, int> evt) { throw new Exception(Error); } /** <inheritdoc /> */ public bool Invoke(ICacheEntry<int, int> entry) { throw new Exception(Error); } } /** */ private class EvenIdFilter : ICacheEntryEventFilter<int, Person> { /** */ public static Person LastValue { get; set; } /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, Person> evt) { LastValue = evt.Value; return evt.Value.Id % 2 == 0; } } /** */ private class EvenIdBinaryFilter : ICacheEntryEventFilter<int, IBinaryObject> { /** */ public static IBinaryObject LastValue { get; set; } /** <inheritdoc /> */ public bool Evaluate(ICacheEntryEvent<int, IBinaryObject> evt) { LastValue = evt.Value; return evt.Value.GetField<int>("Id") % 2 == 0; } } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.Logistics { /// <summary> /// Enumeration values for ElectronicsRepairCode (log.repaircomplete.electronics, Electronics, /// section 6.2.7) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public enum ElectronicsRepairCode : ushort { /// <summary> /// electronic warfare systems. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("electronic warfare systems.")] ElectronicWarfareSystems = 4500, /// <summary> /// detection systems. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("detection systems.")] DetectionSystems = 4600, /// <summary> /// radio frequency. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("radio frequency.")] RadioFrequency = 4610, /// <summary> /// microwave. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("microwave.")] Microwave = 4620, /// <summary> /// infrared. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("infrared.")] Infrared = 4630, /// <summary> /// laser. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("laser.")] Laser = 4640, /// <summary> /// range finders. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("range finders.")] RangeFinders = 4700, /// <summary> /// range-only radar. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("range-only radar.")] RangeOnlyRadar = 4710, /// <summary> /// laser range finder. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("laser range finder.")] LaserRangeFinder = 4720, /// <summary> /// electronic systems. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("electronic systems.")] ElectronicSystems = 4800, /// <summary> /// radio frequency. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("radio frequency.")] RadioFrequency_4810 = 4810, /// <summary> /// microwave. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("microwave.")] Microwave_4820 = 4820, /// <summary> /// infrared. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("infrared.")] Infrared_4830 = 4830, /// <summary> /// laser. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("laser.")] Laser_4840 = 4840, /// <summary> /// radios. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("radios.")] Radios = 5000, /// <summary> /// communication systems. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("communication systems.")] CommunicationSystems = 5010, /// <summary> /// intercoms. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("intercoms.")] Intercoms = 5100, /// <summary> /// encoders. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("encoders.")] Encoders = 5200, /// <summary> /// encryption devices. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("encryption devices.")] EncryptionDevices = 5250, /// <summary> /// decoders. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("decoders.")] Decoders = 5300, /// <summary> /// decryption devices. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("decryption devices.")] DecryptionDevices = 5350, /// <summary> /// computers. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("computers.")] Computers = 5500, /// <summary> /// navigation and control systems. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("navigation and control systems.")] NavigationAndControlSystems = 6000, /// <summary> /// fire control systems. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("fire control systems.")] FireControlSystems = 6500 } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TaskAwaiter.cs // // // Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter // and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; using System.Threading; using System.Threading.Tasks; using Internal.Threading.Tasks.Tracing; // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List<T>.Enumerator. namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct TaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task m_task; /// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param> internal TaskAwaiter(Task task) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public void GetResult() { ValidateEnd(m_task); } /// <summary> /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// </summary> /// <param name="task">The awaited task.</param> internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { // If either the end await bit is set or we're not completed successfully, // fall back to the slower path. HandleNonSuccessAndDebuggerNotification(task); } } /// <summary> /// Ensures the task is completed, triggers any necessary debugger breakpoints for completing /// the await on the task, and throws an exception if the task did not complete successfully. /// </summary> /// <param name="task">The awaited task.</param> private static void HandleNonSuccessAndDebuggerNotification(Task task) { // NOTE: The JIT refuses to inline ValidateEnd when it contains the contents // of HandleNonSuccessAndDebuggerNotification, hence the separation. // Synchronously wait for the task to complete. When used by the compiler, // the task will already be complete. This code exists only for direct GetResult use, // for cases where the same exception propagation semantics used by "await" are desired, // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken)); Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested task.NotifyDebuggerOfWaitCompletionIfNecessary(); // And throw an exception if the task is faulted or canceled. if (!task.IsRanToCompletion) ThrowForNonSuccess(task); } /// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary> private static void ThrowForNonSuccess(Task task) { Contract.Requires(task.IsCompleted, "Task must have been completed by now."); Contract.Requires(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) { // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: var oceEdi = task.GetCancellationExceptionDispatchInfo(); if (oceEdi != null) { oceEdi.Throw(); Contract.Assert(false, "Throw() should have thrown"); } throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: var edis = task.GetExceptionDispatchInfos(); if (edis.Count > 0) { edis[0].Throw(); Contract.Assert(false, "Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { Contract.Assert(false, "There should be exceptions if we're Faulted."); throw task.Exception; } } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException("continuation"); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TaskTrace.Enabled) { continuation = OutputWaitEtwEvents(task, continuation); } // Set the continuation onto the awaited task. task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } /// <summary> /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// </summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <returns>The action to use as the actual continuation.</returns> private static Action OutputWaitEtwEvents(Task task, Action continuation) { Contract.Requires(task != null, "Need a task to wait on"); Contract.Requires(continuation != null, "Need a continuation to invoke when the wait completes"); Contract.Assert(TaskTrace.Enabled, "Should only be used when ETW tracing is enabled"); // ETW event for Task Wait Begin var currentTaskAtBegin = Task.InternalCurrent; TaskTrace.TaskWaitBegin_Asynchronous( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id); // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). return () => { // ETW event for Task Wait End. if (TaskTrace.Enabled) { var currentTaskAtEnd = Task.InternalCurrent; TaskTrace.TaskWaitEnd( (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), task.Id); } // Invoke the original continuation provided to OnCompleted. continuation(); }; } } /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param> internal TaskAwaiter(Task<TResult> task) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct ConfiguredTaskAwaitable { /// <summary>The task being awaited.</summary> private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { Contract.Requires(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct ConfiguredTaskAwaitable<TResult> { /// <summary>The underlying awaitable on whose logic this awaitable relies.</summary> private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Text; using Encog.Engine.Network.Activation; using Encog.MathUtil.Randomize; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Neural.Flat; using Encog.Neural.Networks.Layers; using Encog.Neural.Networks.Structure; using Encog.Util; using Encog.Util.CSV; using Encog.Util.Simple; namespace Encog.Neural.Networks { /// <summary> /// This class implements a neural network. This class works in conjunction the /// Layer classes. Layers are added to the BasicNetwork to specify the structure /// of the neural network. /// The first layer added is the input layer, the final layer added is the output /// layer. Any layers added between these two layers are the hidden layers. /// The network structure is stored in the structure member. It is important to /// call: /// network.getStructure().finalizeStructure(); /// Once the neural network has been completely constructed. /// </summary> /// [Serializable] public class BasicNetwork : BasicML, IContainsFlat, IMLContext, IMLRegression, IMLEncodable, IMLResettable, IMLClassification, IMLError { /// <summary> /// Tag used for the connection limit. /// </summary> /// public const String TagLimit = "CONNECTION_LIMIT"; /// <summary> /// The default connection limit. /// </summary> /// public const double DefaultConnectionLimit = 0.0000000001d; /// <summary> /// The property for connection limit. /// </summary> /// public const String TagConnectionLimit = "connectionLimit"; /// <summary> /// The property for begin training. /// </summary> /// public const String TagBeginTraining = "beginTraining"; /// <summary> /// The property for context target offset. /// </summary> /// public const String TagContextTargetOffset = "contextTargetOffset"; /// <summary> /// The property for context target size. /// </summary> /// public const String TagContextTargetSize = "contextTargetSize"; /// <summary> /// The property for end training. /// </summary> /// public const String TagEndTraining = "endTraining"; /// <summary> /// The property for has context. /// </summary> /// public const String TagHasContext = "hasContext"; /// <summary> /// The property for layer counts. /// </summary> /// public const String TagLayerCounts = "layerCounts"; /// <summary> /// The property for layer feed counts. /// </summary> /// public const String TagLayerFeedCounts = "layerFeedCounts"; /// <summary> /// The property for layer index. /// </summary> /// public const String TagLayerIndex = "layerIndex"; /// <summary> /// The property for weight index. /// </summary> /// public const String TagWeightIndex = "weightIndex"; /// <summary> /// The property for bias activation. /// </summary> /// public const String TagBiasActivation = "biasActivation"; /// <summary> /// The property for layer context count. /// </summary> /// public const String TagLayerContextCount = "layerContextCount"; /// <summary> /// Holds the structure of the network. This keeps the network from having to /// constantly lookup layers and synapses. /// </summary> /// private readonly NeuralStructure _structure; /// <summary> /// Construct an empty neural network. /// </summary> /// public BasicNetwork() { _structure = new NeuralStructure(this); } /// <value>The layer count.</value> public int LayerCount { get { _structure.RequireFlat(); return _structure.Flat.LayerCounts.Length; } } /// <value>Get the structure of the neural network. The structure allows you /// to quickly obtain synapses and layers without traversing the /// network.</value> public NeuralStructure Structure { get { return _structure; } } /// <summary> /// Sets the bias activation for every layer that supports bias. Make sure /// that the network structure has been finalized before calling this method. /// </summary> public double BiasActivation { set { // first, see what mode we are on. If the network has not been // finalized, set the layers if (_structure.Flat == null) { foreach (ILayer layer in _structure.Layers) { if (layer.HasBias()) { layer.BiasActivation = value; } } } else { for (int i = 0; i < LayerCount; i++) { if (IsLayerBiased(i)) { SetLayerBiasActivation(i, value); } } } } } #region ContainsFlat Members /// <inheritdoc/> public FlatNetwork Flat { get { return Structure.Flat; } } #endregion #region MLClassification Members /// <inheritdoc/> public int Classify(IMLData input) { return Winner(input); } #endregion #region MLContext Members /// <summary> /// Clear any data from any context layers. /// </summary> /// public void ClearContext() { if (_structure.Flat != null) { _structure.Flat.ClearContext(); } } #endregion #region MLEncodable Members /// <inheritdoc/> public void DecodeFromArray(double[] encoded) { _structure.RequireFlat(); double[] weights = _structure.Flat.Weights; if (weights.Length != encoded.Length) { throw new NeuralNetworkError( "Size mismatch, encoded array should be of length " + weights.Length); } EngineArray.ArrayCopy(encoded, weights); } /// <inheritdoc/> public int EncodedArrayLength() { _structure.RequireFlat(); return _structure.Flat.EncodeLength; } /// <inheritdoc/> public void EncodeToArray(double[] encoded) { _structure.RequireFlat(); double[] weights = _structure.Flat.Weights; if (weights.Length != encoded.Length) { throw new NeuralNetworkError( "Size mismatch, encoded array should be of length " + weights.Length); } EngineArray.ArrayCopy(weights, encoded); } #endregion #region MLError Members /// <summary> /// Calculate the error for this neural network. /// </summary> /// /// <param name="data">The training set.</param> /// <returns>The error percentage.</returns> public double CalculateError(IMLDataSet data) { return EncogUtility.CalculateRegressionError(this, data); } #endregion #region MLRegression Members /// <summary> /// Compute the output for a given input to the neural network. /// </summary> /// /// <param name="input">The input to the neural network.</param> /// <returns>The output from the neural network.</returns> public IMLData Compute(IMLData input) { try { var output = new double[_structure.Flat.OutputCount]; _structure.Flat.Compute(input, output); return new BasicMLData(output, false); } catch (IndexOutOfRangeException ex) { throw new NeuralNetworkError( "Index exception: there was likely a mismatch between layer sizes, or the size of the input presented to the network.", ex); } } /// <inheritdoc/> public virtual int InputCount { get { _structure.RequireFlat(); return Structure.Flat.InputCount; } } /// <inheritdoc/> public virtual int OutputCount { get { _structure.RequireFlat(); return Structure.Flat.OutputCount; } } #endregion /// <summary> /// Determines the randomizer used for resets. This will normally return a /// Nguyen-Widrow randomizer with a range between -1 and 1. If the network /// does not have an input, output or hidden layers, then Nguyen-Widrow /// cannot be used and a simple range randomize between -1 and 1 will be /// used. Range randomizer is also used if the activation function is not /// TANH, Sigmoid, or the Elliott equivalents. /// </summary> private IRandomizer Randomizer { get { var useNwr = true; for (var i = 0; i < LayerCount; i++) { var af = GetActivation(i); if (af.GetType() != typeof(ActivationSigmoid) && af.GetType() != typeof(ActivationTANH) && af.GetType() != typeof(ActivationElliott) && af.GetType() != typeof(ActivationElliottSymmetric)) { useNwr = false; } } if (LayerCount < 3) { useNwr = false; } if (useNwr) { return new NguyenWidrowRandomizer(); } else { return new RangeRandomizer(-1, 1); } } } #region MLResettable Members /// <summary> /// Determines the randomizer used for resets. This will normally return a /// Nguyen-Widrow randomizer with a range between -1 and 1. If the network /// does not have an input, output or hidden layers, then Nguyen-Widrow /// cannot be used and a simple range randomize between -1 and 1 will be /// used. Range randomizer is also used if the activation function is not /// TANH, Sigmoid, or the Elliott equivalents. /// </summary> public void Reset() { Randomizer.Randomize(this); } /// <summary> /// Reset the weight matrix and the bias values. This will use a /// Nguyen-Widrow randomizer with a range between -1 and 1. If the network /// does not have an input, output or hidden layers, then Nguyen-Widrow /// cannot be used and a simple range randomize between -1 and 1 will be /// used. /// Use the specified seed. /// </summary> /// public void Reset(int seed) { Reset(); } #endregion /// <summary> /// Add a layer to the neural network. If there are no layers added this /// layer will become the input layer. This function automatically updates /// both the input and output layer references. /// </summary> /// /// <param name="layer">The layer to be added to the network.</param> public void AddLayer(ILayer layer) { layer.Network = this; _structure.Layers.Add(layer); } /// <summary> /// Add to a weight. /// </summary> /// /// <param name="fromLayer">The from layer.</param> /// <param name="fromNeuron">The from neuron.</param> /// <param name="toNeuron">The to neuron.</param> /// <param name="v">The value to add.</param> public void AddWeight(int fromLayer, int fromNeuron, int toNeuron, double v) { double old = GetWeight(fromLayer, fromNeuron, toNeuron); SetWeight(fromLayer, fromNeuron, toNeuron, old + v); } /// <summary> /// Calculate the total number of neurons in the network across all layers. /// </summary> /// /// <returns>The neuron count.</returns> public int CalculateNeuronCount() { int result = 0; foreach (ILayer layer in _structure.Layers) { result += layer.NeuronCount; } return result; } /// <summary> /// Return a clone of this neural network. Including structure, weights and /// bias values. This is a deep copy. /// </summary> /// /// <returns>A cloned copy of the neural network.</returns> public Object Clone() { var result = (BasicNetwork) ObjectCloner.DeepCopy(this); return result; } /// <summary> /// Compute the output for this network. /// </summary> /// /// <param name="input">The input.</param> /// <param name="output">The output.</param> public void Compute(double[] input, double[] output) { var input2 = new BasicMLData(input); IMLData output2 = Compute(input2); output2.CopyTo(output, 0, output2.Count); } /// <returns>The weights as a comma separated list.</returns> public String DumpWeights() { var result = new StringBuilder(); NumberList.ToList(CSVFormat.EgFormat, result, _structure.Flat.Weights); return result.ToString(); } /// <summary> /// Enable, or disable, a connection. /// </summary> /// /// <param name="fromLayer">The layer that contains the from neuron.</param> /// <param name="fromNeuron">The source neuron.</param> /// <param name="toNeuron">The target connection.</param> /// <param name="enable">True to enable, false to disable.</param> public void EnableConnection(int fromLayer, int fromNeuron, int toNeuron, bool enable) { double v = GetWeight(fromLayer, fromNeuron, toNeuron); if (enable) { if (!_structure.ConnectionLimited) { return; } if (Math.Abs(v) < _structure.ConnectionLimit) { SetWeight(fromLayer, fromNeuron, toNeuron, RangeRandomizer.Randomize(-1, 1)); } } else { if (!_structure.ConnectionLimited) { SetProperty(TagLimit, DefaultConnectionLimit); _structure.UpdateProperties(); } SetWeight(fromLayer, fromNeuron, toNeuron, 0); } } /// <summary> /// Compare the two neural networks. For them to be equal they must be of the /// same structure, and have the same matrix values. /// </summary> /// /// <param name="other">The other neural network.</param> /// <returns>True if the two networks are equal.</returns> public bool Equals(BasicNetwork other) { return Equals(other, EncogFramework.DefaultPrecision); } /// <summary> /// Determine if this neural network is equal to another. Equal neural /// networks have the same weight matrix and bias values, within a specified /// precision. /// </summary> /// /// <param name="other">The other neural network.</param> /// <param name="precision">The number of decimal places to compare to.</param> /// <returns>True if the two neural networks are equal.</returns> public bool Equals(BasicNetwork other, int precision) { return NetworkCODEC.Equals(this, other, precision); } /// <summary> /// Get the activation function for the specified layer. /// </summary> /// /// <param name="layer">The layer.</param> /// <returns>The activation function.</returns> public IActivationFunction GetActivation(int layer) { _structure.RequireFlat(); int layerNumber = LayerCount - layer - 1; return _structure.Flat.ActivationFunctions[layerNumber]; } /// <summary> /// Get the bias activation for the specified layer. /// </summary> /// /// <param name="l">The layer.</param> /// <returns>The bias activation.</returns> public double GetLayerBiasActivation(int l) { if (!IsLayerBiased(l)) { throw new NeuralNetworkError( "Error, the specified layer does not have a bias: " + l); } _structure.RequireFlat(); int layerNumber = LayerCount - l - 1; int layerOutputIndex = _structure.Flat.LayerIndex[layerNumber]; int count = _structure.Flat.LayerCounts[layerNumber]; return _structure.Flat.LayerOutput[layerOutputIndex + count - 1]; } /// <summary> /// Get the neuron count. /// </summary> /// /// <param name="l">The layer.</param> /// <returns>The neuron count.</returns> public int GetLayerNeuronCount(int l) { _structure.RequireFlat(); int layerNumber = LayerCount - l - 1; return _structure.Flat.LayerFeedCounts[layerNumber]; } /// <summary> /// Get the layer output for the specified neuron. /// </summary> /// /// <param name="layer">The layer.</param> /// <param name="neuronNumber">The neuron number.</param> /// <returns>The output from the last call to compute.</returns> public double GetLayerOutput(int layer, int neuronNumber) { _structure.RequireFlat(); int layerNumber = LayerCount - layer - 1; int index = _structure.Flat.LayerIndex[layerNumber] + neuronNumber; double[] output = _structure.Flat.LayerOutput; if (index >= output.Length) { throw new NeuralNetworkError("The layer index: " + index + " specifies an output index larger than the network has."); } return output[index]; } /// <summary> /// Get the total (including bias and context) neuron cont for a layer. /// </summary> /// /// <param name="l">The layer.</param> /// <returns>The count.</returns> public int GetLayerTotalNeuronCount(int l) { _structure.RequireFlat(); int layerNumber = LayerCount - l - 1; return _structure.Flat.LayerCounts[layerNumber]; } /// <summary> /// Get the weight between the two layers. /// </summary> /// /// <param name="fromLayer">The from layer.</param> /// <param name="fromNeuron">The from neuron.</param> /// <param name="toNeuron">The to neuron.</param> /// <returns>The weight value.</returns> public double GetWeight(int fromLayer, int fromNeuron, int toNeuron) { _structure.RequireFlat(); ValidateNeuron(fromLayer, fromNeuron); ValidateNeuron(fromLayer + 1, toNeuron); int fromLayerNumber = LayerCount - fromLayer - 1; int toLayerNumber = fromLayerNumber - 1; if (toLayerNumber < 0) { throw new NeuralNetworkError( "The specified layer is not connected to another layer: " + fromLayer); } int weightBaseIndex = _structure.Flat.WeightIndex[toLayerNumber]; int count = _structure.Flat.LayerCounts[fromLayerNumber]; int weightIndex = weightBaseIndex + fromNeuron + (toNeuron*count); return _structure.Flat.Weights[weightIndex]; } /// <summary> /// Generate a hash code. /// </summary> /// /// <returns>THe hash code.</returns> public override sealed int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Determine if the specified connection is enabled. /// </summary> /// /// <param name="layer">The layer to check.</param> /// <param name="fromNeuron">The source neuron.</param> /// <param name="toNeuron">THe target neuron.</param> /// <returns>True, if the connection is enabled, false otherwise.</returns> public bool IsConnected(int layer, int fromNeuron, int toNeuron) { /* * if (!this.structure.isConnectionLimited()) { return true; } final * double value = synapse.getMatrix().get(fromNeuron, toNeuron); * * return (Math.abs(value) > this.structure.getConnectionLimit()); */ return false; } /// <summary> /// Determine if the specified layer is biased. /// </summary> /// /// <param name="l">The layer number.</param> /// <returns>True, if the layer is biased.</returns> public bool IsLayerBiased(int l) { _structure.RequireFlat(); int layerNumber = LayerCount - l - 1; return _structure.Flat.LayerCounts[layerNumber] != _structure.Flat.LayerFeedCounts[layerNumber]; } /// <summary> /// Set the bias activation for the specified layer. /// </summary> /// /// <param name="l">The layer to use.</param> /// <param name="value_ren">The bias activation.</param> public void SetLayerBiasActivation(int l, double v) { if (!IsLayerBiased(l)) { throw new NeuralNetworkError( "Error, the specified layer does not have a bias: " + l); } _structure.RequireFlat(); int layerNumber = LayerCount - l - 1; int layerOutputIndex = _structure.Flat.LayerIndex[layerNumber]; int count = _structure.Flat.LayerCounts[layerNumber]; _structure.Flat.LayerOutput[layerOutputIndex + count - 1] = v; } /// <summary> /// Set the weight between the two specified neurons. /// </summary> /// /// <param name="fromLayer">The from layer.</param> /// <param name="fromNeuron">The from neuron.</param> /// <param name="toNeuron">The to neuron.</param> /// <param name="v">The to value.</param> public void SetWeight(int fromLayer, int fromNeuron, int toNeuron, double v) { _structure.RequireFlat(); int fromLayerNumber = LayerCount - fromLayer - 1; int toLayerNumber = fromLayerNumber - 1; if (toLayerNumber < 0) { throw new NeuralNetworkError( "The specified layer is not connected to another layer: " + fromLayer); } int weightBaseIndex = _structure.Flat.WeightIndex[toLayerNumber]; int count = _structure.Flat.LayerCounts[fromLayerNumber]; int weightIndex = weightBaseIndex + fromNeuron + (toNeuron*count); _structure.Flat.Weights[weightIndex] = v; } /// <summary> /// /// </summary> /// public override sealed String ToString() { var builder = new StringBuilder(); builder.Append("[BasicNetwork: Layers="); int layers = _structure.Flat==null ? _structure.Layers.Count : _structure.Flat.LayerCounts.Length; builder.Append(layers); builder.Append("]"); return builder.ToString(); } /// <summary> /// /// </summary> /// public override sealed void UpdateProperties() { _structure.UpdateProperties(); } /// <summary> /// Validate the the specified targetLayer and neuron are valid. /// </summary> /// /// <param name="targetLayer">The target layer.</param> /// <param name="neuron">The target neuron.</param> public void ValidateNeuron(int targetLayer, int neuron) { if ((targetLayer < 0) || (targetLayer >= LayerCount)) { throw new NeuralNetworkError("Invalid layer count: " + targetLayer); } if ((neuron < 0) || (neuron >= GetLayerTotalNeuronCount(targetLayer))) { throw new NeuralNetworkError("Invalid neuron number: " + neuron); } } /// <summary> /// Determine the winner for the specified input. This is the number of the /// winning neuron. /// </summary> /// /// <param name="input">The input patter to present to the neural network.</param> /// <returns>The winning neuron.</returns> public int Winner(IMLData input) { IMLData output = Compute(input); return EngineArray.MaxIndex(output); } } }
//---------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //---------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace Microsoft.IdentityModel.Clients.ActiveDirectory { internal enum WsTrustVersion { WsTrust13, WsTrust2005 } internal class WsTrustAddress { public Uri Uri { get; set; } public WsTrustVersion Version { get; set; } } internal class MexPolicy { public WsTrustVersion Version { get; set; } public string Id { get; set; } public UserAuthType AuthType { get; set; } public Uri Url { get; set; } } internal class MexParser { private const string WsTrustSoapTransport = "http://schemas.xmlsoap.org/soap/http"; public static async Task<WsTrustAddress> FetchWsTrustAddressFromMexAsync(string federationMetadataUrl, UserAuthType userAuthType, CallState callState) { XDocument mexDocument = await FetchMexAsync(federationMetadataUrl, callState); return ExtractWsTrustAddressFromMex(mexDocument, userAuthType, callState); } internal static async Task<XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState) { XDocument mexDocument; try { IHttpWebRequest request = NetworkPlugin.HttpWebRequestFactory.Create(federationMetadataUrl); request.Method = "GET"; request.ContentType = "application/soap+xml"; using (var response = await request.GetResponseSyncOrAsync(callState)) { mexDocument = XDocument.Load(response.GetResponseStream(), LoadOptions.None); } } catch (WebException ex) { throw new AdalServiceException(AdalError.AccessingWsMetadataExchangeFailed, ex); } catch (XmlException ex) { throw new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex); } return mexDocument; } internal static WsTrustAddress ExtractWsTrustAddressFromMex(XDocument mexDocument, UserAuthType userAuthType, CallState callState) { WsTrustAddress address = null; MexPolicy policy = null; try { Dictionary<string, MexPolicy> policies = ReadPolicies(mexDocument); Dictionary<string, MexPolicy> bindings = ReadPolicyBindings(mexDocument, policies); SetPolicyEndpointAddresses(mexDocument, bindings); Random random = new Random(); //try ws-trust 1.3 first policy = policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType && p.Version == WsTrustVersion.WsTrust13).OrderBy(p => random.Next()).FirstOrDefault() ?? policies.Values.Where(p => p.Url != null && p.AuthType == userAuthType).OrderBy(p => random.Next()).FirstOrDefault(); if (policy != null) { address = new WsTrustAddress(); address.Uri = policy.Url; address.Version = policy.Version; } else if (userAuthType == UserAuthType.IntegratedAuth) { throw new AdalException(AdalError.IntegratedAuthFailed, new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument)); } else { throw new AdalException(AdalError.WsTrustEndpointNotFoundInMetadataDocument); } } catch (XmlException ex) { throw new AdalException(AdalError.ParsingWsMetadataExchangeFailed, ex); } return address; } private static Dictionary<string, MexPolicy> ReadPolicies(XContainer mexDocument) { var policies = new Dictionary<string, MexPolicy>(); IEnumerable<XElement> policyElements = mexDocument.Elements().First().Elements(XmlNamespace.Wsp + "Policy"); foreach (XElement policy in policyElements) { XElement exactlyOnePolicy = policy.Elements(XmlNamespace.Wsp + "ExactlyOne").FirstOrDefault(); if (exactlyOnePolicy == null) { continue; } IEnumerable<XElement> all = exactlyOnePolicy.Descendants(XmlNamespace.Wsp + "All"); foreach (XElement element in all) { XNamespace securityPolicy = XmlNamespace.Sp; XElement auth = element.Elements(XmlNamespace.Http + "NegotiateAuthentication").FirstOrDefault(); if (auth != null) { AddPolicy(policies, policy, UserAuthType.IntegratedAuth, securityPolicy.Equals(XmlNamespace.Sp2005)); } auth = element.Elements(securityPolicy + "SignedEncryptedSupportingTokens").FirstOrDefault(); if (auth == null) { //switch to sp2005 securityPolicy = XmlNamespace.Sp2005; if ((auth = element.Elements(securityPolicy + "SignedSupportingTokens").FirstOrDefault()) == null) { continue; } } XElement wspPolicy = auth.Elements(XmlNamespace.Wsp + "Policy").FirstOrDefault(); if (wspPolicy == null) { continue; } XElement usernameToken = wspPolicy.Elements(securityPolicy + "UsernameToken").FirstOrDefault(); if (usernameToken == null) { continue; } XElement wspPolicy2 = usernameToken.Elements(XmlNamespace.Wsp + "Policy").FirstOrDefault(); if (wspPolicy2 == null) { continue; } XElement wssUsernameToken10 = wspPolicy2.Elements(securityPolicy + "WssUsernameToken10").FirstOrDefault(); if (wssUsernameToken10 != null) { AddPolicy(policies, policy, UserAuthType.UsernamePassword, securityPolicy.Equals(XmlNamespace.Sp2005)); } } } return policies; } private static Dictionary<string, MexPolicy> ReadPolicyBindings(XContainer mexDocument, IReadOnlyDictionary<string, MexPolicy> policies) { var bindings = new Dictionary<string, MexPolicy>(); IEnumerable<XElement> bindingElements = mexDocument.Elements().First().Elements(XmlNamespace.Wsdl + "binding"); foreach (XElement binding in bindingElements) { IEnumerable<XElement> policyReferences = binding.Elements(XmlNamespace.Wsp + "PolicyReference"); foreach (XElement policyReference in policyReferences) { XAttribute policyUri = policyReference.Attribute("URI"); if (policyUri == null || !policies.ContainsKey(policyUri.Value)) { continue; } XAttribute bindingName = binding.Attribute("name"); if (bindingName == null) { continue; } XElement bindingOperation = binding.Elements(XmlNamespace.Wsdl + "operation").FirstOrDefault(); if (bindingOperation == null) { continue; } XElement soapOperation = bindingOperation.Elements(XmlNamespace.Soap12 + "operation").FirstOrDefault(); if (soapOperation == null) { continue; } XAttribute soapAction = soapOperation.Attribute("soapAction"); if (soapAction == null || (string.Compare(XmlNamespace.Issue.ToString(), soapAction.Value, StringComparison.OrdinalIgnoreCase) != 0 && string.Compare(XmlNamespace.Issue2005.ToString(), soapAction.Value, StringComparison.OrdinalIgnoreCase) != 0)) { continue; } XElement soapBinding = binding.Elements(XmlNamespace.Soap12 + "binding").FirstOrDefault(); if (soapBinding == null) { continue; } XAttribute soapBindingTransport = soapBinding.Attribute("transport"); if (soapBindingTransport != null && string.Compare(WsTrustSoapTransport, soapBindingTransport.Value, StringComparison.OrdinalIgnoreCase) == 0) { bindings.Add(bindingName.Value, policies[policyUri.Value]); } } } return bindings; } private static void SetPolicyEndpointAddresses(XContainer mexDocument, IReadOnlyDictionary<string, MexPolicy> bindings) { XElement serviceElement = mexDocument.Elements().First().Elements(XmlNamespace.Wsdl + "service").First(); IEnumerable<XElement> portElements = serviceElement.Elements(XmlNamespace.Wsdl + "port"); foreach (XElement port in portElements) { XAttribute portBinding = port.Attribute("binding"); if (portBinding == null) { continue; } string portBindingName = portBinding.Value; string[] portBindingNameSegments = portBindingName.Split(new[] { ':' }, 2); if (portBindingNameSegments.Length < 2 || !bindings.ContainsKey(portBindingNameSegments[1])) { continue; } XElement endpointReference = port.Elements(XmlNamespace.Wsa10 + "EndpointReference").FirstOrDefault(); if (endpointReference == null) { continue; } XElement endpointAddress = endpointReference.Elements(XmlNamespace.Wsa10 + "Address").FirstOrDefault(); if (endpointAddress != null && Uri.IsWellFormedUriString(endpointAddress.Value, UriKind.Absolute)) { bindings[portBindingNameSegments[1]].Url = new Uri(endpointAddress.Value); } } } private static void AddPolicy(IDictionary<string, MexPolicy> policies, XElement policy, UserAuthType policyAuthType, bool isWsTrust2005) { XElement binding = policy.Descendants(XmlNamespace.Sp + "TransportBinding").FirstOrDefault() ?? policy.Descendants(XmlNamespace.Sp2005 + "TransportBinding").FirstOrDefault(); if (binding != null) { XAttribute id = policy.Attribute(XmlNamespace.Wsu + "Id"); WsTrustVersion version = WsTrustVersion.WsTrust13; if (isWsTrust2005) { version = WsTrustVersion.WsTrust2005; } if (id != null) { policies.Add("#" + id.Value, new MexPolicy { Id = id.Value, AuthType = policyAuthType, Version = version }); } } } } }
// ----------------------------------------------------------------------------- // Reminder Pattern Example for Rainer Hessmer's C# port of // Samek's Quantum Hierarchical State Machine. // // Author: David Shields (david@shields.net) // // References: // Practical Statecharts in C/C++; Quantum Programming for Embedded Systems // Author: Miro Samek, Ph.D. // http://www.quantum-leaps.com/book.htm // // Rainer Hessmer, Ph.D. (rainer@hessmer.org) // http://www.hessmer.org/dev/qhsm/ // ----------------------------------------------------------------------------- using System; using qf4net; namespace ReminderHsm { /// <summary> /// Reminder pattern example for Rainer Hessmer's C# port of HQSM. This code is adapted from /// Samek's reminder pattern example in section 5.2. /// /// </summary> public sealed class Reminder : QHsmQ { //communication with main form is via these events: public delegate void ReminderDisplayHandler(object sender, ReminderDisplayEventArgs e); public event ReminderDisplayHandler DisplayState; //name of state public event ReminderDisplayHandler DisplayPoll; //polling counter public event ReminderDisplayHandler DisplayProc; //processing counter public bool IsHandled { get{return isHandled;} set{isHandled = value;} }//IsHandled private bool isHandled; /// <summary> /// Determines how often DataReady events are posted /// </summary> public int Frequency { set {frequency = value;} } private int frequency = 3;//every Nth tick private int myPollCtr = 0; private int myProcCtr = 0; private QState Polling; private QState Processing; private QState Idle; private QState Busy; private QState Final; private QState DoPolling(IQEvent qevent) { switch (qevent.QSignal) { case (int)QSignals.Entry: MainForm.Instance.SetTimer(); OnDisplayState("Polling"); return null; case (int)QSignals.Init: InitializeState(Processing); return null; case (int)ReminderSignals.TimerTick: OnDisplayPoll(++myPollCtr); if ((myPollCtr & frequency) == 0) //using Samek's C-style technique { this.Enqueue(new ReminderEvent(ReminderSignals.DataReady)); } return null; case (int)ReminderSignals.Terminate: TransitionTo(Final); return null; case (int)QSignals.Exit: MainForm.Instance.KillTimer(); return null; } if (qevent.QSignal >= (int)QSignals.UserSig) { isHandled = false; } return this.TopState; } private QState DoProcessing(IQEvent qevent) { switch (qevent.QSignal) { case (int)QSignals.Entry: OnDisplayState("Processing"); return null; case (int)QSignals.Init: InitializeState(Idle); return null; } return Polling; } private QState DoIdle(IQEvent qevent) { switch (qevent.QSignal) { case (int)QSignals.Entry: OnDisplayState("Idle"); return null; case (int)ReminderSignals.DataReady: TransitionTo(Busy); return null; } return Processing; } private QState DoBusy(IQEvent qevent) { switch (qevent.QSignal) { case (int)QSignals.Entry: OnDisplayState("Busy"); return null; case (int)ReminderSignals.TimerTick: OnDisplayProc(++myProcCtr); if ((myPollCtr & 0x1) == 0) //using Samek's C-style technique { TransitionTo(Idle); } return null; } return Processing; } //UNDONE: revise this code private QState DoFinal(IQEvent qevent) { switch (qevent.QSignal) { case (int)QSignals.Entry: OnDisplayState("HSM terminated"); singleton = null; MainForm.Instance.Close(); System.Windows.Forms.Application.Exit(); return null; } return this.TopState; } private void OnDisplayState(string stateInfo) { if (DisplayState != null) { DisplayState(this, new ReminderDisplayEventArgs(stateInfo)); } }//OnDisplayState private void OnDisplayPoll(int pollCtr) { if (DisplayPoll != null) { DisplayPoll(this, new ReminderDisplayEventArgs(pollCtr.ToString())); } }//OnDisplayPoll private void OnDisplayProc(int procCtr) { if (DisplayProc != null) { DisplayProc(this, new ReminderDisplayEventArgs(procCtr.ToString())); } }//OnDisplayProc /// <summary> /// Is called inside of the function Init to give the deriving class a chance to /// initialize the state machine. /// </summary> protected override void InitializeStateMachine() { InitializeState(Polling); // initial transition }//init private Reminder() { Polling = new QState(this.DoPolling); Processing = new QState(this.DoProcessing); Idle = new QState(this.DoIdle); Busy = new QState(this.DoBusy); Final = new QState(this.DoFinal); }//ctor // //Thread-safe implementation of singleton as a property // private static volatile Reminder singleton = null; private static object sync = new object();//for static lock public static Reminder Instance { get { if (singleton == null) { lock (sync) { if (singleton == null) { singleton = new Reminder(); singleton.Init(); } } } return singleton; } }//Instance }//class Reminder public class ReminderDisplayEventArgs : EventArgs { private string s; public string Message { get { return s; } } public ReminderDisplayEventArgs(string message) { s = message;} } }//namespace
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Messages.Linden; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; using ChatSessionMember = Aurora.Framework.ChatSessionMember; namespace Aurora.Modules.Groups { public class GroupsMessagingModule : ISharedRegionModule, IGroupsMessagingModule { private readonly List<IScene> m_sceneList = new List<IScene>(); private bool m_debugEnabled = true; private IGroupsServicesConnector m_groupData; // Config Options private bool m_groupMessagingEnabled; private IGroupsModule m_groupsModule; private IMessageTransferModule m_msgTransferModule; #region IGroupsMessagingModule Members public void SendMessageToGroup(GridInstantMessage im, UUID groupID) { if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: {0} called", MethodBase.GetCurrentMethod().Name); // Copy Message GridInstantMessage msg = new GridInstantMessage { imSessionID = groupID, fromAgentName = im.fromAgentName, message = im.message, dialog = (byte) InstantMessageDialog.SessionSend, offline = 0, ParentEstateID = 0, Position = Vector3.Zero, RegionID = UUID.Zero }; ChatSession session = m_groupData.GetSession(im.imSessionID); msg.binaryBucket = Utils.StringToBytes(session.Name); msg.timestamp = (uint) Util.UnixTimeSinceEpoch(); msg.fromAgentID = im.fromAgentID; msg.fromGroup = true; Util.FireAndForget(SendInstantMessages, msg); } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) // Do not run this module by default. return; else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("MessagingModule", "Default") != Name)) { m_groupMessagingEnabled = false; return; } m_groupMessagingEnabled = groupsConfig.GetBoolean("MessagingEnabled", true); if (!m_groupMessagingEnabled) return; //MainConsole.Instance.Info("[GROUPS-MESSAGING]: Initializing GroupsMessagingModule"); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); } } public void AddRegion(IScene scene) { if (!m_groupMessagingEnabled) return; scene.RegisterModuleInterface<IGroupsMessagingModule>(this); } public void RegionLoaded(IScene scene) { if (!m_groupMessagingEnabled) return; m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>(); m_groupsModule = scene.RequestModuleInterface<IGroupsModule>(); // No groups module, no groups messaging if (m_groupData == null) { MainConsole.Instance.Error( "[GROUPS-MESSAGING]: Could not get IGroupsServicesConnector, GroupsMessagingModule is now disabled."); Close(); m_groupMessagingEnabled = false; return; } m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no groups messaging if (m_msgTransferModule == null) { MainConsole.Instance.Error("[GROUPS-MESSAGING]: Could not get MessageTransferModule"); Close(); m_groupMessagingEnabled = false; return; } m_sceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClosingClient += OnClosingClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; scene.EventManager.OnClientLogin += OnClientLogin; scene.EventManager.OnChatSessionRequest += OnChatSessionRequest; } public void RemoveRegion(IScene scene) { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: {0} called", MethodBase.GetCurrentMethod().Name); m_sceneList.Remove(scene); scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnClosingClient -= OnClosingClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; scene.EventManager.OnClientLogin -= OnClientLogin; scene.EventManager.OnChatSessionRequest -= OnChatSessionRequest; } public void Close() { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) MainConsole.Instance.Debug("[GROUPS-MESSAGING]: Shutting down GroupsMessagingModule module."); foreach (IScene scene in m_sceneList) { scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } m_sceneList.Clear(); m_groupData = null; m_msgTransferModule = null; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "GroupsMessagingModule"; } } public void PostInitialise() { // NoOp } #endregion private void SendInstantMessages(object message) { GridInstantMessage im = message as GridInstantMessage; ChatSession session = m_groupData.GetSession(im.imSessionID); if (session == null) return; List<UUID> agentsToSendTo = new List<UUID>(); foreach (ChatSessionMember member in session.Members) { if (member.HasBeenAdded) agentsToSendTo.Add(member.AvatarKey); else { IClientAPI client = GetActiveClient(member.AvatarKey); if (client != null) { client.Scene.RequestModuleInterface<IEventQueueService>().ChatterboxInvitation( session.SessionID , session.Name , im.fromAgentID , im.message , member.AvatarKey , im.fromAgentName , im.dialog , im.timestamp , im.offline == 1 , (int) im.ParentEstateID , im.Position , 1 , im.imSessionID , true , Utils.StringToBytes(session.Name) , client.Scene.RegionInfo.RegionHandle ); } else agentsToSendTo.Add(member.AvatarKey); //Forward it on, the other sim should take care of it } } m_msgTransferModule.SendInstantMessages(im, agentsToSendTo); } private void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID) { if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: {0} called", MethodBase.GetCurrentMethod().Name); IEventQueueService queue = remoteClient.Scene.RequestModuleInterface<IEventQueueService>(); if (queue != null) { queue.ChatterBoxSessionStartReply(groupName, groupID, remoteClient.AgentId, remoteClient.Scene.RegionInfo.RegionHandle); } } private void DebugGridInstantMessage(GridInstantMessage im) { // Don't log any normal IMs (privacy!) if (m_debugEnabled && im.dialog != (byte) InstantMessageDialog.MessageFromAgent) { MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: fromGroup({0})", im.fromGroup ? "True" : "False"); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: Dialog({0})", ((InstantMessageDialog) im.dialog).ToString()); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentID({0})", im.fromAgentID.ToString()); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentName({0})", im.fromAgentName); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: imSessionID({0})", im.imSessionID.ToString()); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: message({0})", im.message); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: offline({0})", im.offline.ToString()); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: toAgentID({0})", im.toAgentID.ToString()); MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: IM: binaryBucket({0})", Utils.BytesToHexString(im.binaryBucket, "BinaryBucket")); } } #region Client Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { if (m_debugEnabled) MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: Looking for local client {0}", agentID); IClientAPI child = null; // Try root avatar first foreach (IScene scene in m_sceneList) { IScenePresence user; if (scene.TryGetScenePresence(agentID, out user)) { if (!user.IsChildAgent) { if (m_debugEnabled) MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: Found root agent for client : {0}", user.ControllingClient.Name); return user.ControllingClient; } else { if (m_debugEnabled) MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: Found child agent for client : {0}", user.ControllingClient.Name); child = user.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none if (child == null) { if (m_debugEnabled) MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: Could not find local client for agent : {0}", agentID); } else { if (m_debugEnabled) MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: Returning child agent for client : {0}", child.Name); } return child; } #endregion #region SimGridEventHandlers public void EnsureGroupChatIsStarted(UUID groupID) { ChatSession session = m_groupData.GetSession(groupID); if (session == null) { GroupRecord record = m_groupData.GetGroupRecord(UUID.Zero, groupID, ""); UUID ownerID = record.FounderID; //Requires that the founder is still in the group List<ChatSessionMember> members = (from gmd in m_groupData.GetGroupMembers(ownerID, groupID) where (gmd.AgentPowers & (ulong) GroupPowers.JoinChat) == (ulong) GroupPowers.JoinChat select new ChatSessionMember { AvatarKey = gmd.AgentID }).ToList(); m_groupData.CreateSession(new ChatSession { Members = members, Name = record.GroupName, SessionID = groupID }); } } private void OnClientLogin(IClientAPI client) { if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name); } private void OnNewClient(IClientAPI client) { if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name); client.OnInstantMessage += OnInstantMessage; } private void OnClosingClient(IClientAPI client) { if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage unregistered for {0}", client.Name); client.OnInstantMessage -= OnInstantMessage; } private void OnGridInstantMessage(GridInstantMessage msg) { // The instant message module will only deliver messages of dialog types: // MessageFromAgent, StartTyping, StopTyping, MessageFromObject // // Any other message type will not be delivered to a client by the // Instant Message Module if (m_debugEnabled) { MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: {0} called", MethodBase.GetCurrentMethod().Name); DebugGridInstantMessage(msg); } // Incoming message from a group if (msg.fromGroup && ((msg.dialog == (byte) InstantMessageDialog.SessionSend) || (msg.dialog == (byte) InstantMessageDialog.SessionAdd) || (msg.dialog == (byte) InstantMessageDialog.SessionDrop) || (msg.dialog == 212) || (msg.dialog == 213))) { ProcessMessageFromGroupSession(msg); } } private void ProcessMessageFromGroupSession(GridInstantMessage msg) { if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID); UUID AgentID = msg.toAgentID; UUID GroupID = msg.imSessionID; switch (msg.dialog) { case (byte) InstantMessageDialog.SessionAdd: ChatSession chatSession = m_groupData.GetSession(msg.imSessionID); if (chatSession != null) { chatSession.Members.Add(new ChatSessionMember { AvatarKey = AgentID, CanVoiceChat = false, HasBeenAdded = true, IsModerator = GetIsModerator(AgentID, GroupID), MuteVoice = false, MuteText = false }); } break; case (byte) InstantMessageDialog.SessionDrop: case 212: DropMemberFromSession(GetActiveClient(AgentID), msg, false); break; case 213: //Special for muting/unmuting a user IClientAPI client = GetActiveClient(AgentID); IEventQueueService eq = client.Scene.RequestModuleInterface<IEventQueueService>(); ChatSessionMember thismember = m_groupData.FindMember(msg.imSessionID, AgentID); if (thismember == null) return; string[] brokenMessage = msg.message.Split(','); bool mutedText = false, mutedVoice = false; bool.TryParse(brokenMessage[0], out mutedText); bool.TryParse(brokenMessage[1], out mutedVoice); thismember.MuteText = mutedText; thismember.MuteVoice = mutedVoice; MuteUser(msg.imSessionID, eq, AgentID, thismember, false); break; case (byte) InstantMessageDialog.SessionSend: EnsureGroupChatIsStarted(msg.imSessionID); //Make sure one exists ChatSession session = m_groupData.GetSession(msg.imSessionID); if (session != null) { ChatSessionMember member = m_groupData.FindMember(msg.imSessionID, AgentID); if (member.AvatarKey == AgentID && !member.MuteText) { IClientAPI msgclient = GetActiveClient(msg.toAgentID); if (msgclient != null) { if (!member.HasBeenAdded) msgclient.Scene.RequestModuleInterface<IEventQueueService>().ChatterboxInvitation( session.SessionID , session.Name , msg.fromAgentID , msg.message , member.AvatarKey , msg.fromAgentName , msg.dialog , msg.timestamp , msg.offline == 1 , (int) msg.ParentEstateID , msg.Position , 1 , msg.imSessionID , true , Utils.StringToBytes(session.Name) , msgclient.Scene.RegionInfo.RegionHandle ); // Deliver locally, directly if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} locally", msgclient.Name); msgclient.SendInstantMessage(msg); } } } break; default: MainConsole.Instance.WarnFormat("[GROUPS-MESSAGING]: I don't know how to proccess a {0} message.", ((InstantMessageDialog) msg.dialog).ToString()); break; } } private string OnChatSessionRequest(UUID Agent, OSDMap rm) { string method = rm["method"].AsString(); UUID sessionid = UUID.Parse(rm["session-id"].AsString()); IClientAPI SP = GetActiveClient(Agent); IEventQueueService eq = SP.Scene.RequestModuleInterface<IEventQueueService>(); if (method == "accept invitation") { //They would like added to the group conversation List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> Us = new List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>(); List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> NotUsAgents = new List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>(); ChatSession session = m_groupData.GetSession(sessionid); if (session != null) { ChatSessionMember thismember = m_groupData.FindMember(sessionid, Agent); if (thismember == null) return ""; //No user with that session //Tell all the other members about the incoming member thismember.HasBeenAdded = true; foreach (ChatSessionMember sessionMember in session.Members) { ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block = new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock { AgentID = sessionMember.AvatarKey, CanVoiceChat = sessionMember.CanVoiceChat, IsModerator = sessionMember.IsModerator, MuteText = sessionMember.MuteText, MuteVoice = sessionMember.MuteVoice, Transition = "ENTER" }; if (Agent == sessionMember.AvatarKey) Us.Add(block); if (sessionMember.HasBeenAdded) // Don't add not joined yet agents. They don't want to be here. NotUsAgents.Add(block); } foreach (ChatSessionMember member in session.Members) { if (member.AvatarKey == thismember.AvatarKey) { //Tell 'us' about all the other agents in the group eq.ChatterBoxSessionAgentListUpdates(session.SessionID, NotUsAgents.ToArray(), member.AvatarKey, "ENTER", SP.Scene.RegionInfo.RegionHandle); } else { //Tell 'other' agents about the new agent ('us') IClientAPI otherAgent = GetActiveClient(member.AvatarKey); if (otherAgent != null) //Local, so we can send it directly eq.ChatterBoxSessionAgentListUpdates(session.SessionID, Us.ToArray(), member.AvatarKey, "ENTER", otherAgent.Scene.RegionInfo.RegionHandle); else { ISyncMessagePosterService amps = m_sceneList[0].RequestModuleInterface<ISyncMessagePosterService>(); if (amps != null) { OSDMap message = new OSDMap(); message["Method"] = "GroupSessionAgentUpdate"; message["AgentID"] = thismember.AvatarKey; message["Message"] = ChatterBoxSessionAgentListUpdates(session.SessionID, Us.ToArray(), "ENTER"); amps.Post(message, SP.Scene.RegionInfo.RegionHandle); } } } } return "Accepted"; } else return ""; //not this type of session } else if (method == "mute update") { //Check if the user is a moderator if (!GetIsModerator(Agent, sessionid)) return ""; OSDMap parameters = (OSDMap) rm["params"]; UUID AgentID = parameters["agent_id"].AsUUID(); OSDMap muteInfoMap = (OSDMap) parameters["mute_info"]; ChatSessionMember thismember = m_groupData.FindMember(sessionid, AgentID); if (muteInfoMap.ContainsKey("text")) thismember.MuteText = muteInfoMap["text"].AsBoolean(); if (muteInfoMap.ContainsKey("voice")) thismember.MuteVoice = muteInfoMap["voice"].AsBoolean(); MuteUser(sessionid, eq, AgentID, thismember, true); return "Accepted"; } else { MainConsole.Instance.Warn("ChatSessionRequest : " + method); return ""; } } private void MuteUser(UUID sessionid, IEventQueueService eq, UUID AgentID, ChatSessionMember thismember, bool forward) { ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block = new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock { AgentID = thismember.AvatarKey, CanVoiceChat = thismember.CanVoiceChat, IsModerator = thismember.IsModerator, MuteText = thismember.MuteText, MuteVoice = thismember.MuteVoice, Transition = "ENTER" }; // Send an update to the affected user IClientAPI affectedUser = GetActiveClient(thismember.AvatarKey); if (affectedUser != null) eq.ChatterBoxSessionAgentListUpdates(sessionid, new[] {block}, AgentID, "ENTER", affectedUser.Scene.RegionInfo.RegionHandle); else if (forward) SendMutedUserIM(thismember, sessionid); } private void SendMutedUserIM(ChatSessionMember member, UUID GroupID) { GridInstantMessage img = new GridInstantMessage { toAgentID = member.AvatarKey, fromGroup = true, imSessionID = GroupID, dialog = 213, //Special mute one message = member.MuteText + "," + member.MuteVoice }; m_msgTransferModule.SendInstantMessage(img); } #endregion #region ClientEvents private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { IScenePresence presence; if ((presence = remoteClient.Scene.GetScenePresence(remoteClient.AgentId)) == null || presence.IsChildAgent) return; //Must exist and not be a child if (m_debugEnabled) { MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: {0} called", MethodBase.GetCurrentMethod().Name); DebugGridInstantMessage(im); } // Start group IM session if ((im.dialog == (byte) InstantMessageDialog.SessionGroupStart)) { if (m_debugEnabled) MainConsole.Instance.InfoFormat("[GROUPS-MESSAGING]: imSessionID({0}) toAgentID({1})", im.imSessionID, im.toAgentID); UUID GroupID = im.imSessionID; UUID AgentID = im.fromAgentID; GroupRecord groupInfo = m_groupData.GetGroupRecord(AgentID, GroupID, null); if (groupInfo != null) { if (!m_groupsModule.GroupPermissionCheck(AgentID, GroupID, GroupPowers.JoinChat)) return; //They have to be able to join to create a group chat //Create the session. IEventQueueService queue = remoteClient.Scene.RequestModuleInterface<IEventQueueService>(); if (m_groupData.CreateSession(new ChatSession { Members = new List<ChatSessionMember>(), SessionID = GroupID, Name = groupInfo.GroupName })) { m_groupData.AddMemberToGroup(new ChatSessionMember { AvatarKey = AgentID, CanVoiceChat = false, IsModerator = GetIsModerator(AgentID, GroupID), MuteText = false, MuteVoice = false, HasBeenAdded = true }, GroupID); #if (!ISWIN) foreach (GroupMembersData gmd in m_groupData.GetGroupMembers(AgentID, GroupID)) { if (gmd.AgentID != AgentID) { if ((gmd.AgentPowers & (ulong) GroupPowers.JoinChat) == (ulong) GroupPowers.JoinChat) { m_groupData.AddMemberToGroup(new ChatSessionMember { AvatarKey = gmd.AgentID, CanVoiceChat = false, IsModerator = GetIsModerator(gmd.AgentID, GroupID), MuteText = false, MuteVoice = false, HasBeenAdded = false }, GroupID); } } } #else foreach (GroupMembersData gmd in m_groupData.GetGroupMembers(AgentID, GroupID).Where(gmd => gmd.AgentID != AgentID).Where(gmd => (gmd.AgentPowers & (ulong) GroupPowers.JoinChat) == (ulong) GroupPowers.JoinChat)) { m_groupData.AddMemberToGroup(new ChatSessionMember { AvatarKey = gmd.AgentID, CanVoiceChat = false, IsModerator = GetIsModerator(gmd.AgentID, GroupID), MuteText = false, MuteVoice = false, HasBeenAdded = false }, GroupID); } #endif //Tell us that it was made successfully ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID); } else { ChatSession thisSession = m_groupData.GetSession(GroupID); //A session already exists //Add us m_groupData.AddMemberToGroup(new ChatSessionMember { AvatarKey = AgentID, CanVoiceChat = false, IsModerator = GetIsModerator(AgentID, GroupID), MuteText = false, MuteVoice = false, HasBeenAdded = true }, GroupID); //Tell us that we entered successfully ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, GroupID); List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> Us = new List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>(); List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock> NotUsAgents = new List<ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock>(); foreach (ChatSessionMember sessionMember in thisSession.Members) { ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block = new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock { AgentID = sessionMember.AvatarKey, CanVoiceChat = sessionMember.CanVoiceChat, IsModerator = sessionMember.IsModerator, MuteText = sessionMember.MuteText, MuteVoice = sessionMember.MuteVoice, Transition = "ENTER" }; if (AgentID == sessionMember.AvatarKey) Us.Add(block); if (sessionMember.HasBeenAdded) // Don't add not joined yet agents. They don't want to be here. NotUsAgents.Add(block); } foreach (ChatSessionMember member in thisSession.Members) { if (member.AvatarKey == AgentID) { //Tell 'us' about all the other agents in the group queue.ChatterBoxSessionAgentListUpdates(GroupID, NotUsAgents.ToArray(), member.AvatarKey, "ENTER", remoteClient.Scene.RegionInfo.RegionHandle); } else { //Tell 'other' agents about the new agent ('us') IClientAPI otherAgent = GetActiveClient(member.AvatarKey); if (otherAgent != null) //Local, so we can send it directly queue.ChatterBoxSessionAgentListUpdates(GroupID, Us.ToArray(), member.AvatarKey, "ENTER", otherAgent.Scene.RegionInfo.RegionHandle); else { ISyncMessagePosterService amps = m_sceneList[0].RequestModuleInterface<ISyncMessagePosterService>(); if (amps != null) { OSDMap message = new OSDMap(); message["Method"] = "GroupSessionAgentUpdate"; message["AgentID"] = AgentID; message["Message"] = ChatterBoxSessionAgentListUpdates(GroupID, Us.ToArray(), "ENTER"); amps.Post(message, remoteClient.Scene.RegionInfo.RegionHandle); } } } } } //Tell us that we entered ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock ourblock = new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock { AgentID = AgentID, CanVoiceChat = true, IsModerator = true, MuteText = false, MuteVoice = false, Transition = "ENTER" }; queue.ChatterBoxSessionAgentListUpdates(GroupID, new[] {ourblock}, AgentID, "ENTER", remoteClient.Scene.RegionInfo.RegionHandle); } } // Send a message from locally connected client to a group else if ((im.dialog == (byte) InstantMessageDialog.SessionSend) && im.message != "") { UUID GroupID = im.imSessionID; UUID AgentID = im.fromAgentID; if (m_debugEnabled) MainConsole.Instance.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", GroupID, im.imSessionID.ToString()); ChatSessionMember memeber = m_groupData.FindMember(im.imSessionID, AgentID); if (memeber == null || memeber.MuteText) return; //Not in the chat or muted SendMessageToGroup(im, GroupID); } else if (im.dialog == (byte) InstantMessageDialog.SessionDrop) DropMemberFromSession(remoteClient, im, true); else if (im.dialog == 212) //Forwarded sessionDrop DropMemberFromSession(remoteClient, im, false); } private bool GetIsModerator(UUID AgentID, UUID GroupID) { return m_groupsModule.GroupPermissionCheck(AgentID, GroupID, GroupPowers.ModerateChat); } private OSD ChatterBoxSessionAgentListUpdates(UUID sessionID, ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock[] agentUpdatesBlock, string Transition) { OSDMap body = new OSDMap(); OSDMap agentUpdates = new OSDMap(); OSDMap infoDetail = new OSDMap(); OSDMap mutes = new OSDMap(); foreach (ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block in agentUpdatesBlock) { infoDetail = new OSDMap(); mutes = new OSDMap {{"text", OSD.FromBoolean(block.MuteText)}, {"voice", OSD.FromBoolean(block.MuteVoice)}}; infoDetail.Add("can_voice_chat", OSD.FromBoolean(block.CanVoiceChat)); infoDetail.Add("is_moderator", OSD.FromBoolean(block.IsModerator)); infoDetail.Add("mutes", mutes); OSDMap info = new OSDMap {{"info", infoDetail}}; if (Transition != string.Empty) info.Add("transition", OSD.FromString(Transition)); agentUpdates.Add(block.AgentID.ToString(), info); } body.Add("agent_updates", agentUpdates); body.Add("session_id", OSD.FromUUID(sessionID)); body.Add("updates", new OSD()); OSDMap chatterBoxSessionAgentListUpdates = new OSDMap { { "message", OSD.FromString("ChatterBoxSessionAgentListUpdates") }, {"body", body} }; return chatterBoxSessionAgentListUpdates; } /// <summary> /// Remove the member from this session /// </summary> /// <param name = "client"></param> /// <param name = "im"></param> public void DropMemberFromSession(IClientAPI client, GridInstantMessage im, bool forwardOn) { ChatSession session = m_groupData.GetSession(im.imSessionID); if (session == null) return; ChatSessionMember member = new ChatSessionMember {AvatarKey = UUID.Zero}; #if (!ISWIN) foreach (ChatSessionMember testmember in session.Members) { if (testmember.AvatarKey == im.fromAgentID) { member = testmember; } } #else foreach (ChatSessionMember testmember in session.Members.Where(testmember => testmember.AvatarKey == im.fromAgentID)) { member = testmember; } #endif if (member.AvatarKey != UUID.Zero) { member.HasBeenAdded = false; } if (GetMemeberCount(session) == 0) { m_groupData.RemoveSession(session.SessionID); //Noone is left! return; } ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock block = new ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock { AgentID = member.AvatarKey, CanVoiceChat = member.CanVoiceChat, IsModerator = member.IsModerator, MuteText = member.MuteText, MuteVoice = member.MuteVoice, Transition = "LEAVE" }; List<UUID> usersToForwardTo = new List<UUID>(); IEventQueueService eq = client.Scene.RequestModuleInterface<IEventQueueService>(); foreach (ChatSessionMember sessionMember in session.Members) { IClientAPI user = GetActiveClient(sessionMember.AvatarKey); if (user != null) eq.ChatterBoxSessionAgentListUpdates(session.SessionID, new[] {block}, sessionMember.AvatarKey, "LEAVE", user.Scene.RegionInfo.RegionHandle); else usersToForwardTo.Add(sessionMember.AvatarKey); } if (forwardOn) { im.dialog = 212; //Don't keep forwarding on other sims m_msgTransferModule.SendInstantMessages(im, usersToForwardTo); } } private int GetMemeberCount(ChatSession session) { #if (!ISWIN) int count = 0; foreach (ChatSessionMember member in session.Members) { if (member.HasBeenAdded) count++; } return count; #else return session.Members.Count(member => member.HasBeenAdded); #endif } #endregion } }
using System; namespace RecurrenceGenerator { #region Class-specific Enums /// <summary> /// The Regeneration type. /// </summary> public enum DailyRegenType { NotSet = -1, OnEveryXDays, OnEveryWeekday}; #endregion //Class-specific Enums public class DailyRecurrenceSettings : RecurrenceSettings { #region Constructors /// <summary> /// Get dates by Start date only. This is for no ending date values. /// </summary> /// <param name="startDate"></param> public DailyRecurrenceSettings(DateTime startDate) : base(startDate) { } /// <summary> /// Get dates by Start and End date boundries. /// </summary> /// <param name="startDate"></param> /// <param name="endDate"></param> public DailyRecurrenceSettings(DateTime startDate, DateTime endDate) : base(startDate, endDate) { } /// <summary> /// Get dates by Start date and number of occurrences. /// </summary> /// <param name="startDate"></param> /// <param name="numberOfOccurrences"></param> public DailyRecurrenceSettings(DateTime startDate, int numberOfOccurrences) : base(startDate, numberOfOccurrences) { } #endregion #region Private Fields DailyRegenType regenType = DailyRegenType.OnEveryWeekday; int regenEveryXDays = 1; bool getNextDateValue; DateTime nextDateValue; DateTime finalNextDateValue; #endregion #region Public GetValues /// <summary> /// Get day values. This overload is for every x-days. /// </summary> /// <param name="regenEveryXDays">Interval of days. Every x-days.</param> /// <returns>RecurrenceValues</returns> public RecurrenceValues GetValues(int regenEveryXDays) { this.regenEveryXDays = regenEveryXDays; regenType = DailyRegenType.OnEveryXDays; return GetValues(); } /// <summary> /// An overload to use to get either every weekday or just every x-days /// </summary> /// <param name="regenEveryXDays" type="int"> /// <para> /// Interval of days. Every x-days. /// </para> /// </param> /// <param name="regenType" type="BOCA.RecurrenceGenerator.DailyRegenType"> /// <para> /// Type of regeneration to perform. Every x-days or every weekday. /// </para> /// </param> /// <returns> /// A RecurrenceGenerator.RecurrenceValues value... /// </returns> public RecurrenceValues GetValues(int regenEveryXDays, DailyRegenType regenType) { this.regenEveryXDays = regenEveryXDays; this.regenType = regenType; return GetValues(); } #endregion //Public GetValues internal static RecurrenceInfo GetFriendlyRecurrenceInfo(string seriesInfo) { RecurrenceInfo info = new RecurrenceInfo(); EndDateType endType = EndDateType.NotDefined; DateTime endDateValue = DateTime.MinValue; int noOccurrences; // Exit if not a Daily seriesInfo type if (!seriesInfo.StartsWith("D")) return null; info.SetRecurrenceType(RecurrenceType.Daily); info.SetSeriesInfo(seriesInfo); // FORMATTING DEFINITIONS // Y = Yearly Designator // | 0 = Start Date (8 chars) // | | 1 = End Date (8 chars) // | | | 2 = Number of occurrences (4 chars) // | | | | 3 = Regeneration Type (1 char) // | | | | | 4 = End date type (1 char) // | | | | | | 5 = Regen Every x weeks // | | | | | | | // | | | | | | | // [0] [1-8] [9-16] [17-20] [21] [22] [23-25] // D 20071231 20171231 0000 1 1 000 string startDate = seriesInfo.Substring(1, 8); DateTime dtStartDate = new DateTime(int.Parse(startDate.Substring(0, 4)), int.Parse(startDate.Substring(4, 2)), int.Parse(startDate.Substring(6, 2))); string endDate = seriesInfo.Substring(9, 8); string occurrences = seriesInfo.Substring(17, 4); string dailyRegenType = seriesInfo.Substring(21, 1); string endDateType = seriesInfo.Substring(22, 1); int regenXDays = int.Parse(seriesInfo.Substring(23, 3)); endType = (EndDateType)(int.Parse(endDateType)); noOccurrences = int.Parse(occurrences); endType = (EndDateType)(int.Parse(endDateType)); noOccurrences = int.Parse(occurrences); // Get the EndDate before any modifications on it are performed if (endType == EndDateType.SpecificDate) endDateValue = new DateTime(int.Parse(endDate.Substring(0, 4)), int.Parse(endDate.Substring(4, 2)), int.Parse(endDate.Substring(6, 2))); info.SetEndDateType(endType); // Determine the Constructor by the type of End Date. // All constructors start with a Start date at a minimum. switch (endType) { case EndDateType.NumberOfOccurrences: info.SetStartDate(dtStartDate); info.SetNumberOfOccurrences(noOccurrences); break; case EndDateType.SpecificDate: info.SetStartDate(dtStartDate); info.SetEndDate(endDateValue); break; case EndDateType.NoEndDate: info.SetStartDate(dtStartDate); break; } info.SetDailyRegenType((DailyRegenType)(int.Parse(dailyRegenType))); // Determine the Type of dates to get, specific, custom, etc. switch (info.DailyRegenType) { case DailyRegenType.OnEveryXDays: info.SetDailyRegenEveryXDays(regenXDays); break; case DailyRegenType.OnEveryWeekday: // This is default. Nothing to set break; case DailyRegenType.NotSet: break; } return info; } #region Internal GetValues /// <summary> /// Get day values. Default is to get every weekday. This is called from the RecurrenceHelper staic methods only. /// </summary> /// <returns>RecurrenceValues</returns> internal override RecurrenceValues GetValues() { return GetRecurrenceValues(); } internal override RecurrenceValues GetValues(DateTime startDate, DateTime endDate) { base.StartDate = startDate; base.EndDate = endDate; // Change the end type to End Date as this original series info // may have been set to number of occurrences. base.endDateType = EndDateType.SpecificDate; return GetRecurrenceValues(); } internal override RecurrenceValues GetValues(DateTime startDate, int numberOfOccurrences) { base.NumberOfOccurrences = numberOfOccurrences; base.StartDate = startDate; // Change the end type to number of occurrences. // This must be set because the original starting Series Info may // be set to have an End Date type. base.endDateType = EndDateType.NumberOfOccurrences; return GetRecurrenceValues(); } RecurrenceValues GetRecurrenceValues() { RecurrenceValues values = null; switch (RegenType) { case DailyRegenType.OnEveryXDays: values = GetEveryXDaysValues(); break; case DailyRegenType.OnEveryWeekday: values = GetEveryWeekday(); break; } // Values will be null if just getting next date in series. No need // to fill the RecurrenceValues collection if all we need is the last date. if (values != null) { if (values.Values.Count > 0) { values.SetStartDate(values.Values[0]); // Get the end date if not open-ended if (base.TypeOfEndDate != EndDateType.NoEndDate) values.SetEndDate(values.Values[values.Values.Count - 1]); } // Set the Series information that's used to get the next date // values for no ending dates. values.SetSeriesInfo(GetSeriesInfo()); } return values; } #endregion //Internal GetValues #region Internal Procedures internal static string GetPatternDefinition(string seriesInfo) { string returnValue = string.Empty; returnValue = " DAILY FORMATTING DEFINITIONS\r\n" + " Y = Yearly Designator\r\n" + " | 0 = Start Date (8 chars)\r\n" + " | | 1 = End Date (8 chars)\r\n" + " | | | 2 = Number of occurrences (4 chars)\r\n" + " | | | | 3 = Regeneration Type (1 char)\r\n" + " | | | | | 4 = End date type (1 char)\r\n" + " | | | | | | 5 = Regen Every x weeks\r\n" + " | | | | | | |\r\n" + " | | | | | | |\r\n" + " [0] [1-8] [9-16] [17-20] [21] [22] [23-25]\r\n" + string.Format(" D {0} {1} {2} {3} {4} {5} \r\n", seriesInfo.Substring(1, 8), seriesInfo.Substring(9, 8), seriesInfo.Substring(17, 4), seriesInfo.Substring(21, 1), seriesInfo.Substring(22, 1), seriesInfo.Substring(23, 3)); return returnValue; } void SetValues(int regenEveryXDays) { this.regenEveryXDays = regenEveryXDays; regenType = DailyRegenType.OnEveryXDays; } internal override DateTime GetNextDate(DateTime currentDate) { getNextDateValue = true; nextDateValue = currentDate; // Run the date processing to set the last date value. GetValues(); return finalNextDateValue; } internal static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo) { return GetRecurrenceSettings(seriesInfo, -1, DateTime.MinValue); } internal static DailyRecurrenceSettings GetRecurrenceSettings(DateTime modifiedStartDate, string seriesInfo) { return GetRecurrenceSettings(seriesInfo, -1, modifiedStartDate, DateTime.MinValue); } internal static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo, int modifiedOccurrencesValue) { return GetRecurrenceSettings(seriesInfo, modifiedOccurrencesValue, DateTime.MinValue); } internal static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo, DateTime modifiedStartDate, int modifiedOccurrencesValue) { return GetRecurrenceSettings(seriesInfo, modifiedOccurrencesValue, modifiedStartDate, DateTime.MinValue); } internal static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo, DateTime modifiedEndDate) { return GetRecurrenceSettings(seriesInfo, -1, modifiedEndDate); } internal static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo, DateTime modifiedStartDate, DateTime modifiedEndDate) { return GetRecurrenceSettings(seriesInfo, -1, modifiedStartDate, modifiedEndDate); } static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo, int modifiedOccurrencesValue, DateTime modifiedStartDate, DateTime modifiedEndDate) { DailyRecurrenceSettings settings = null; RecurrenceInfo info = DailyRecurrenceSettings.GetFriendlyRecurrenceInfo(seriesInfo); // Check to see if this is to modify the SeriesInfo and run as endtype for occurrences if (modifiedOccurrencesValue != -1) { info.SetEndDateType(EndDateType.NumberOfOccurrences); info.SetNumberOfOccurrences(modifiedOccurrencesValue); } // Check to see if this is to modify the EndDate and run as endType for EndDate if (modifiedEndDate != DateTime.MinValue) { info.SetEndDateType(EndDateType.SpecificDate); info.SetEndDate(modifiedEndDate); } // Determine the Constructor by the type of End Date. // All constructors start with a Start date at a minimum. switch (info.EndDateType) { case EndDateType.NumberOfOccurrences: settings = new DailyRecurrenceSettings(modifiedStartDate, info.NumberOfOccurrences); break; case EndDateType.SpecificDate: settings = new DailyRecurrenceSettings(modifiedStartDate, info.EndDate.Value); break; case EndDateType.NoEndDate: settings = new DailyRecurrenceSettings(modifiedStartDate); break; } // Determine the Type of dates to get, specific, custom, etc. switch (info.DailyRegenType) { case DailyRegenType.OnEveryXDays: settings.SetValues(info.DailyRegenEveryXDays); break; case DailyRegenType.OnEveryWeekday: // This is default. Nothing to set break; case DailyRegenType.NotSet: break; } return settings; } static DailyRecurrenceSettings GetRecurrenceSettings(string seriesInfo, int modifiedOccurrencesValue, DateTime modifiedEndDate) { RecurrenceInfo info = DailyRecurrenceSettings.GetFriendlyRecurrenceInfo(seriesInfo); return GetRecurrenceSettings(seriesInfo, modifiedOccurrencesValue, info.StartDate, modifiedEndDate); } #endregion //Internal Procedures #region Private Procedures /// <summary> /// Get the Series information that's used to get dates at a later /// date. This is passed into the RecurrenceHelper to get date values. /// Most likely used for non-ending dates. /// </summary> /// <returns></returns> string GetSeriesInfo() { string info = string.Empty; string endDate = "ZZZZZZZZ"; // Default for no ending date. string occurrences = base.NumberOfOccurrences.ToString("0000"); string dailyRegenType = ((int)regenType).ToString("0"); string endDateType = ((int)base.TypeOfEndDate).ToString("0"); string regenXDays = regenEveryXDays.ToString("000"); // End Date may be null if no ending date. if (base.EndDate.HasValue) endDate = base.EndDate.Value.ToString("yyyyMMdd"); // FORMATTING DEFINITIONS // Y = Yearly Designator // | 0 = Start Date (8 chars) // | | 1 = End Date (8 chars) // | | | 2 = Number of occurrences (4 chars) // | | | | 3 = Regeneration Type (1 char) // | | | | | 4 = End date type (1 char) // | | | | | | 5 = Regen Every x weeks // | | | | | | | // | | | | | | | // | | | | | | | // | | | | | | | // | | | | | | | // | | | | | | | // | | | | | | | // | | | | | | | // [0] [1-8] [9-16] [17-20] [21] [22] [23-25] // D 20071231 20171231 0000 1 1 000 info = string.Format("D{0}{1}{2}{3}{4}{5}", base.StartDate.ToString("yyyyMMdd"), endDate, occurrences, dailyRegenType, endDateType, regenXDays); return info; } /// <summary> /// Get the values for just weekdays. /// </summary> /// <returns>RecurrenceValues</returns> RecurrenceValues GetEveryWeekday() { RecurrenceValues values; DateTime dt = base.StartDate; // Make sure the first date is a weekday if (dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday) dt = GetNextWeekday(dt); if (getNextDateValue) { do { finalNextDateValue = dt; if (finalNextDateValue > nextDateValue) break; dt = GetNextWeekday(dt); } while (dt <= nextDateValue.AddDays(3)); // Make sure it's past what may possibly be the next weekday. return null; } else { values = new RecurrenceValues(); switch (base.TypeOfEndDate) { case EndDateType.NoEndDate: throw new Exception("The ability to create recurring dates with no End date is not currently available."); case EndDateType.NumberOfOccurrences: for (int i = 0; i < base.NumberOfOccurrences; i++) { values.AddDateValue(dt); dt = GetNextWeekday(dt); } break; case EndDateType.SpecificDate: do { values.AddDateValue(dt); dt = GetNextWeekday(dt); } while (dt <= base.EndDate); break; default: throw new ArgumentNullException("TypeOfEndDate", "The TypeOfEndDate property has not been set."); } return values; } } /// <summary> /// Get the next Weekday value. This will increment the input date until it finds the next non-Saturday and non-Sunday dates. /// </summary> /// <param name="input"></param> /// <returns>DateTime</returns> DateTime GetNextWeekday(DateTime input) { do { input = input.AddDays(1); } while (input.DayOfWeek == DayOfWeek.Saturday || input.DayOfWeek == DayOfWeek.Sunday); return input; } /// <summary> /// Get dates for every x-days starting from the start date. /// </summary> /// <returns></returns> RecurrenceValues GetEveryXDaysValues() { RecurrenceValues values; DateTime dt = base.StartDate; if (getNextDateValue) { do { finalNextDateValue = dt; if (finalNextDateValue > nextDateValue) break; dt = dt.AddDays(RegenEveryXDays); } while (dt <= nextDateValue.AddDays(regenEveryXDays + 3)); // Make sure it's past what may possibly be the next weekday. return null; } else { values = new RecurrenceValues(); switch (base.TypeOfEndDate) { case EndDateType.NoEndDate: throw new Exception("The ability to create recurring dates with no End date is not currently available."); case EndDateType.NumberOfOccurrences: for (int i = 0; i < base.NumberOfOccurrences; i++) { values.AddDateValue(dt); dt = dt.AddDays(RegenEveryXDays); } break; case EndDateType.SpecificDate: do { values.AddDateValue(dt); dt = dt.AddDays(RegenEveryXDays); } while (dt <= base.EndDate); break; default: throw new ArgumentNullException("TypeOfEndDate", "The TypeOfEndDate property has not been set."); } return values; } } #endregion //Private Procedures #region Public Fields /// <summary> /// What is the interval to generate dates. This is used to skip days in the cycle. /// </summary> public int RegenEveryXDays { get { return regenEveryXDays; } } /// <summary> /// What is the regeneration type such as Specific day of month, custom date, etc. /// </summary> public DailyRegenType RegenType { get { return regenType; } } #endregion //Public Fields } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Diagnostics; using System.IO; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Security.Principal; using Microsoft.Win32; using WebsitePanel.Providers.OS; using WebsitePanel.Providers.Utils; using WebsitePanel.Server.Utils; using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.Administration; namespace WebsitePanel.Providers.SharePoint { public class Sps30Remote : MarshalByRefObject { public void ExtendVirtualServer(SharePointSite site, bool exclusiveNTLM) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); string siteUrl = "http://" + site.Name; // check input parameters if (String.IsNullOrEmpty(site.RootFolder) || !Directory.Exists(site.RootFolder)) throw new Exception("Could not create SharePoint site, because web site root folder does not exist. Open web site properties and click \"Update\" button to re-create site folder."); SPWebApplication app = SPWebApplication.Lookup(new Uri(siteUrl)); if (app != null) throw new Exception("SharePoint is already installed on this web site."); //SPFarm farm = SPFarm.Local; SPFarm farm = SPFarm.Local; SPWebApplicationBuilder builder = new SPWebApplicationBuilder(farm); builder.ApplicationPoolId = site.ApplicationPool; builder.DatabaseServer = site.DatabaseServer; builder.DatabaseName = site.DatabaseName; builder.DatabaseUsername = site.DatabaseUser; builder.DatabasePassword = site.DatabasePassword; builder.ServerComment = site.Name; builder.HostHeader = site.Name; builder.Port = 80; builder.RootDirectory = new DirectoryInfo(site.RootFolder); builder.DefaultZoneUri = new Uri(siteUrl); builder.UseNTLMExclusively = exclusiveNTLM; app = builder.Create(); app.Name = site.Name; app.Sites.Add(siteUrl, null, null, (uint)site.LocaleID, null, site.OwnerLogin, null, site.OwnerEmail); app.Update(); app.Provision(); wic.Undo(); } catch (Exception ex) { try { // try to delete app if it was created SPWebApplication app = SPWebApplication.Lookup(new Uri("http://" + site.Name)); if (app != null) app.Delete(); } catch { /* nop */ } throw new Exception("Error creating SharePoint site", ex); } } public void UnextendVirtualServer(string url, bool deleteContent) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); Uri uri = new Uri("http://" + url); SPWebApplication app = SPWebApplication.Lookup(uri); if (app == null) return; SPGlobalAdmin adm = new SPGlobalAdmin(); adm.UnextendVirtualServer(uri, false); //typeof(SPWebApplication).InvokeMember("UnprovisionIisWebSitesAsAdministrator", // BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, // null, null, new object[] { false, new string[] { url }, app.ApplicationPool }); //app.Unprovision(); app.Delete(); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not uninstall SharePoint from the web site", ex); } } public string BackupVirtualServer(string url, string fileName, bool zipBackup) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); string tempPath = Path.GetTempPath(); string bakFile = Path.Combine(tempPath, (zipBackup ? StringUtils.CleanIdentifier(url) + ".bsh" : StringUtils.CleanIdentifier(fileName))); SPWebApplication app = SPWebApplication.Lookup(new Uri("http://" + url)); if (app == null) throw new Exception("SharePoint is not installed on the web site"); // backup app.Sites.Backup("http://" + url, bakFile, true); // zip backup file if (zipBackup) { string zipFile = Path.Combine(tempPath, fileName); string zipRoot = Path.GetDirectoryName(bakFile); // zip files FileUtils.ZipFiles(zipFile, zipRoot, new string[] { Path.GetFileName(bakFile) }); // delete data files FileUtils.DeleteFile(bakFile); bakFile = zipFile; } wic.Undo(); return bakFile; } catch (Exception ex) { throw new Exception("Could not backup SharePoint site", ex); } } public void RestoreVirtualServer(string url, string fileName) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); SPWebApplication app = SPWebApplication.Lookup(new Uri("http://" + url)); if (app == null) throw new Exception("SharePoint is not installed on the web site"); string tempPath = Path.GetTempPath(); // unzip uploaded files if required string expandedFile = fileName; if (Path.GetExtension(fileName).ToLower() == ".zip") { // unpack file expandedFile = FileUtils.UnzipFiles(fileName, tempPath)[0]; // delete zip archive FileUtils.DeleteFile(fileName); } // delete site SPSiteAdministration site = new SPSiteAdministration("http://" + url); site.Delete(false); // restore from backup app.Sites.Restore("http://" + url, expandedFile, true); // delete expanded file FileUtils.DeleteFile(expandedFile); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not restore SharePoint site", ex); } } public string[] GetInstalledWebParts(string url) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); SPGlobalAdmin adm = new SPGlobalAdmin(); string lines = adm.EnumWPPacks(null, "http://" + url, false); List<string> list = new List<string>(); if(!String.IsNullOrEmpty(lines)) { string line = null; StringReader reader = new StringReader(lines); while ((line = reader.ReadLine()) != null) { line = line.Trim(); int commaIdx = line.IndexOf(","); if (!String.IsNullOrEmpty(line) && commaIdx != -1) list.Add(line.Substring(0, commaIdx)); } } wic.Undo(); return list.ToArray(); } catch (Exception ex) { throw new Exception("Error reading web parts packages", ex); } } public void InstallWebPartsPackage(string url, string fileName) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); string tempPath = Path.GetTempPath(); // unzip uploaded files if required string expandedFile = fileName; if (Path.GetExtension(fileName).ToLower() == ".zip") { // unpack file expandedFile = FileUtils.UnzipFiles(fileName, tempPath)[0]; // delete zip archive FileUtils.DeleteFile(fileName); } StringWriter errors = new StringWriter(); SPGlobalAdmin adm = new SPGlobalAdmin(); int result = adm.AddWPPack(expandedFile, null, 0, "http://" + url, false, true, errors); if (result > 1) throw new Exception("Error installing web parts package: " + errors.ToString()); // delete expanded file FileUtils.DeleteFile(expandedFile); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not install web parts package", ex); } } public void DeleteWebPartsPackage(string url, string packageName) { try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); StringWriter errors = new StringWriter(); SPGlobalAdmin adm = new SPGlobalAdmin(); int result = adm.RemoveWPPack(packageName, 0, "http://" + url, errors); if (result > 1) throw new Exception("Error uninstalling web parts package: " + errors.ToString()); wic.Undo(); } catch (Exception ex) { throw new Exception("Could not uninstall web parts package", ex); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ContainsSearchOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Contains is quite similar to the any/all operator above. Each partition searches a /// subset of elements for a match, and the first one to find a match signals to the rest /// of the partititons to stop searching. /// </summary> /// <typeparam name="TInput"></typeparam> internal sealed class ContainsSearchOperator<TInput> : UnaryQueryOperator<TInput, bool> { private readonly TInput _searchValue; // The value for which we are searching. private readonly IEqualityComparer<TInput> _comparer; // The comparer to use for equality tests. //--------------------------------------------------------------------------------------- // Constructs a new instance of the contains search operator. // // Arguments: // child - the child tree to enumerate. // searchValue - value we are searching for. // comparer - a comparison routine used to test equality. // internal ContainsSearchOperator(IEnumerable<TInput> child, TInput searchValue, IEqualityComparer<TInput> comparer) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); _searchValue = searchValue; if (comparer == null) { _comparer = EqualityComparer<TInput>.Default; } else { _comparer = comparer; } } //--------------------------------------------------------------------------------------- // Executes the entire query tree, and aggregates the individual partition results to // form an overall answer to the search operation. // internal bool Aggregate() { // Because the final reduction is typically much cheaper than the intermediate // reductions over the individual partitions, and because each parallel partition // could do a lot of work to produce a single output element, we prefer to turn off // pipelining, and process the final reductions serially. using (IEnumerator<bool> enumerator = GetEnumerator(ParallelMergeOptions.FullyBuffered, true)) { // Any value of true means the element was found. We needn't consult all partitions while (enumerator.MoveNext()) { if (enumerator.Current) { return true; } } } return false; } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<bool> Open(QuerySettings settings, bool preferStriping) { QueryResults<TInput> childQueryResults = Child.Open(settings, preferStriping); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInput, TKey> inputStream, IPartitionedStreamRecipient<bool> recipient, bool preferStriping, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; PartitionedStream<bool, int> outputStream = new PartitionedStream<bool, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Correct); // Create a shared cancelation variable Shared<bool> resultFoundFlag = new Shared<bool>(false); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ContainsSearchOperatorEnumerator<TKey>(inputStream[i], _searchValue, _comparer, i, resultFoundFlag, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<bool> AsSequentialQuery(CancellationToken token) { Debug.Fail("This method should never be called as it is an ending operator with LimitsParallelism=false."); throw new NotSupportedException(); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // This enumerator performs the search over its input data source. It also cancels peer // enumerators when an answer was found, and polls this cancelation flag to stop when // requested. // class ContainsSearchOperatorEnumerator<TKey> : QueryOperatorEnumerator<bool, int> { private readonly QueryOperatorEnumerator<TInput, TKey> _source; // The source data. private readonly TInput _searchValue; // The value for which we are searching. private readonly IEqualityComparer<TInput> _comparer; // The comparer to use for equality tests. private readonly int _partitionIndex; // This partition's unique index. private readonly Shared<bool> _resultFoundFlag; // Whether to cancel the operation. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new any/all search operator. // internal ContainsSearchOperatorEnumerator(QueryOperatorEnumerator<TInput, TKey> source, TInput searchValue, IEqualityComparer<TInput> comparer, int partitionIndex, Shared<bool> resultFoundFlag, CancellationToken cancellationToken) { Debug.Assert(source != null); Debug.Assert(comparer != null); Debug.Assert(resultFoundFlag != null); _source = source; _searchValue = searchValue; _comparer = comparer; _partitionIndex = partitionIndex; _resultFoundFlag = resultFoundFlag; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // This enumerates the entire input source to perform the search. If another peer // partition finds an answer before us, we will voluntarily return (propagating the // peer's result). // internal override bool MoveNext(ref bool currentElement, ref int currentKey) { Debug.Assert(_comparer != null); // Avoid enumerating if we've already found an answer. if (_resultFoundFlag.Value) return false; // We just scroll through the enumerator and accumulate the result. TInput element = default(TInput); TKey keyUnused = default(TKey); if (_source.MoveNext(ref element, ref keyUnused)) { currentElement = false; currentKey = _partitionIndex; // Continue walking the data so long as we haven't found an item that satisfies // the condition we are searching for. int i = 0; do { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); if (_resultFoundFlag.Value) { // If cancelation occurred, it's because a successful answer was found. return false; } if (_comparer.Equals(element, _searchValue)) { // We have found an item that satisfies the search. Cancel other // workers that are concurrently searching, and return. _resultFoundFlag.Value = true; currentElement = true; break; } } while (_source.MoveNext(ref element, ref keyUnused)); return true; } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); } } } }
///----------- ----------- ----------- ----------- ----------- ----------- ----------- /// <copyright file="DeflateStream.cs" company="Microsoft"> /// Copyright (c) Microsoft Corporation. All rights reserved. /// </copyright> /// ///----------- ----------- ----------- ----------- ----------- ----------- ----------- /// using System; using System.IO; using System.Diagnostics; using System.Threading; namespace Unity.IO.Compression { public class DeflateStream : Stream { internal const int DefaultBufferSize = 8192; internal delegate void AsyncWriteDelegate(byte[] array, int offset, int count, bool isAsync); //private const String OrigStackTrace_ExceptionDataKey = "ORIGINAL_STACK_TRACE"; private Stream _stream; private CompressionMode _mode; private bool _leaveOpen; private Inflater inflater; private IDeflater deflater; private byte[] buffer; private int asyncOperations; #if !NETFX_CORE private readonly AsyncCallback m_CallBack; private readonly AsyncWriteDelegate m_AsyncWriterDelegate; #endif private IFileFormatWriter formatWriter; private bool wroteHeader; private bool wroteBytes; private enum WorkerType : byte { Managed, Unknown }; public DeflateStream(Stream stream, CompressionMode mode) : this(stream, mode, false) { } public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) { if(stream == null ) throw new ArgumentNullException("stream"); if (CompressionMode.Compress != mode && CompressionMode.Decompress != mode) throw new ArgumentException(SR.GetString(SR.ArgumentOutOfRange_Enum), "mode"); _stream = stream; _mode = mode; _leaveOpen = leaveOpen; switch (_mode) { case CompressionMode.Decompress: if (!_stream.CanRead) { throw new ArgumentException(SR.GetString(SR.NotReadableStream), "stream"); } inflater = new Inflater(); #if !NETFX_CORE m_CallBack = new AsyncCallback(ReadCallback); #endif break; case CompressionMode.Compress: if (!_stream.CanWrite) { throw new ArgumentException(SR.GetString(SR.NotWriteableStream), "stream"); } deflater = CreateDeflater(); #if !NETFX_CORE m_AsyncWriterDelegate = new AsyncWriteDelegate(this.InternalWrite); m_CallBack = new AsyncCallback(WriteCallback); #endif break; } // switch (_mode) buffer = new byte[DefaultBufferSize]; } private static IDeflater CreateDeflater() { switch (GetDeflaterType()) { case WorkerType.Managed: return new DeflaterManaged(); default: // We do not expect this to ever be thrown. // But this is better practice than returning null. #if NETFX_CORE throw new Exception("Program entered an unexpected state."); #else throw new SystemException("Program entered an unexpected state."); #endif } } #if !SILVERLIGHT [System.Security.SecuritySafeCritical] #endif private static WorkerType GetDeflaterType() { return WorkerType.Managed; } internal void SetFileFormatReader(IFileFormatReader reader) { if (reader != null) { inflater.SetFileFormatReader(reader); } } internal void SetFileFormatWriter(IFileFormatWriter writer) { if (writer != null) { formatWriter = writer; } } public Stream BaseStream { get { return _stream; } } public override bool CanRead { get { if( _stream == null) { return false; } return (_mode == CompressionMode.Decompress && _stream.CanRead); } } public override bool CanWrite { get { if( _stream == null) { return false; } return (_mode == CompressionMode.Compress && _stream.CanWrite); } } public override bool CanSeek { get { return false; } } public override long Length { get { throw new NotSupportedException(SR.GetString(SR.NotSupported)); } } public override long Position { get { throw new NotSupportedException(SR.GetString(SR.NotSupported)); } set { throw new NotSupportedException(SR.GetString(SR.NotSupported)); } } public override void Flush() { EnsureNotDisposed(); return; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.GetString(SR.NotSupported)); } public override void SetLength(long value) { throw new NotSupportedException(SR.GetString(SR.NotSupported)); } public override int Read(byte[] array, int offset, int count) { EnsureDecompressionMode(); ValidateParameters(array, offset, count); EnsureNotDisposed(); int bytesRead; int currentOffset = offset; int remainingCount = count; while(true) { bytesRead = inflater.Inflate(array, currentOffset, remainingCount); currentOffset += bytesRead; remainingCount -= bytesRead; if( remainingCount == 0) { break; } if (inflater.Finished() ) { // if we finished decompressing, we can't have anything left in the outputwindow. Debug.Assert(inflater.AvailableOutput == 0, "We should have copied all stuff out!"); break; } Debug.Assert(inflater.NeedsInput(), "We can only run into this case if we are short of input"); int bytes = _stream.Read(buffer, 0, buffer.Length); if( bytes == 0) { break; //Do we want to throw an exception here? } inflater.SetInput(buffer, 0 , bytes); } return count - remainingCount; } private void ValidateParameters(byte[] array, int offset, int count) { if (array==null) throw new ArgumentNullException("array"); if (offset < 0) throw new ArgumentOutOfRangeException("offset"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (array.Length - offset < count) throw new ArgumentException(SR.GetString(SR.InvalidArgumentOffsetCount)); } private void EnsureNotDisposed() { if (_stream == null) throw new ObjectDisposedException(null, SR.GetString(SR.ObjectDisposed_StreamClosed)); } private void EnsureDecompressionMode() { if( _mode != CompressionMode.Decompress) throw new InvalidOperationException(SR.GetString(SR.CannotReadFromDeflateStream)); } private void EnsureCompressionMode() { if( _mode != CompressionMode.Compress) throw new InvalidOperationException(SR.GetString(SR.CannotWriteToDeflateStream)); } #if !NETFX_CORE public override IAsyncResult BeginRead(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) { EnsureDecompressionMode(); // We use this checking order for compat to earlier versions: if (asyncOperations != 0) throw new InvalidOperationException(SR.GetString(SR.InvalidBeginCall)); ValidateParameters(array, offset, count); EnsureNotDisposed(); Interlocked.Increment(ref asyncOperations); try { DeflateStreamAsyncResult userResult = new DeflateStreamAsyncResult( this, asyncState, asyncCallback, array, offset, count); userResult.isWrite = false; // Try to read decompressed data in output buffer int bytesRead = inflater.Inflate(array, offset, count); if( bytesRead != 0) { // If decompression output buffer is not empty, return immediately. // 'true' means we complete synchronously. userResult.InvokeCallback(true, (object) bytesRead); return userResult; } if (inflater.Finished() ) { // end of compression stream userResult.InvokeCallback(true, (object) 0); return userResult; } // If there is no data on the output buffer and we are not at // the end of the stream, we need to get more data from the base stream _stream.BeginRead(buffer, 0, buffer.Length, m_CallBack, userResult); userResult.m_CompletedSynchronously &= userResult.IsCompleted; return userResult; } catch { Interlocked.Decrement( ref asyncOperations); throw; } } // callback function for asynchrous reading on base stream private void ReadCallback(IAsyncResult baseStreamResult) { DeflateStreamAsyncResult outerResult = (DeflateStreamAsyncResult) baseStreamResult.AsyncState; outerResult.m_CompletedSynchronously &= baseStreamResult.CompletedSynchronously; int bytesRead = 0; try { EnsureNotDisposed(); bytesRead = _stream.EndRead(baseStreamResult); if (bytesRead <= 0 ) { // This indicates the base stream has received EOF outerResult.InvokeCallback((object) 0); return; } // Feed the data from base stream into decompression engine inflater.SetInput(buffer, 0 , bytesRead); bytesRead = inflater.Inflate(outerResult.buffer, outerResult.offset, outerResult.count); if (bytesRead == 0 && !inflater.Finished()) { // We could have read in head information and didn't get any data. // Read from the base stream again. // Need to solve recusion. _stream.BeginRead(buffer, 0, buffer.Length, m_CallBack, outerResult); } else { outerResult.InvokeCallback((object) bytesRead); } } catch (Exception exc) { // Defer throwing this until EndRead where we will likely have user code on the stack. outerResult.InvokeCallback(exc); return; } } public override int EndRead(IAsyncResult asyncResult) { EnsureDecompressionMode(); CheckEndXxxxLegalStateAndParams(asyncResult); // We checked that this will work in CheckEndXxxxLegalStateAndParams: DeflateStreamAsyncResult deflateStrmAsyncResult = (DeflateStreamAsyncResult) asyncResult; AwaitAsyncResultCompletion(deflateStrmAsyncResult); Exception previousException = deflateStrmAsyncResult.Result as Exception; if (previousException != null) { // Rethrowing will delete the stack trace. Let's help future debuggers: //previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace); throw previousException; } return (int) deflateStrmAsyncResult.Result; } #endif public override void Write(byte[] array, int offset, int count) { EnsureCompressionMode(); ValidateParameters(array, offset, count); EnsureNotDisposed(); InternalWrite(array, offset, count, false); } // isAsync always seems to be false. why do we have it? internal void InternalWrite(byte[] array, int offset, int count, bool isAsync) { DoMaintenance(array, offset, count); // Write compressed the bytes we already passed to the deflater: WriteDeflaterOutput(isAsync); // Pass new bytes through deflater and write them too: deflater.SetInput(array, offset, count); WriteDeflaterOutput(isAsync); } private void WriteDeflaterOutput(bool isAsync) { while (!deflater.NeedsInput()) { int compressedBytes = deflater.GetDeflateOutput(buffer); if (compressedBytes > 0) DoWrite(buffer, 0, compressedBytes, isAsync); } } private void DoWrite(byte[] array, int offset, int count, bool isAsync) { Debug.Assert(array != null); Debug.Assert(count != 0); #if !NETFX_CORE if (isAsync) { IAsyncResult result = _stream.BeginWrite(array, offset, count, null, null); _stream.EndWrite(result); } else #endif { _stream.Write(array, offset, count); } } // Perform deflate-mode maintenance required due to custom header and footer writers // (e.g. set by GZipStream): private void DoMaintenance(byte[] array, int offset, int count) { // If no bytes written, do nothing: if (count <= 0) return; // Note that stream contains more than zero data bytes: wroteBytes = true; // If no header/footer formatter present, nothing else to do: if (formatWriter == null) return; // If formatter has not yet written a header, do it now: if (!wroteHeader) { byte[] b = formatWriter.GetHeader(); _stream.Write(b, 0, b.Length); wroteHeader = true; } // Inform formatter of the data bytes written: formatWriter.UpdateWithBytesRead(array, offset, count); } // This is called by Dispose: private void PurgeBuffers(bool disposing) { if (!disposing) return; if (_stream == null) return; Flush(); if (_mode != CompressionMode.Compress) return; // Some deflaters (e.g. ZLib write more than zero bytes for zero bytes inpuits. // This round-trips and we should be ok with this, but our legacy managed deflater // always wrote zero output for zero input and upstack code (e.g. GZipStream) // took dependencies on it. Thus, make sure to only "flush" when we actually had // some input: if (wroteBytes) { // Compress any bytes left: WriteDeflaterOutput(false); // Pull out any bytes left inside deflater: bool finished; do { int compressedBytes; finished = deflater.Finish(buffer, out compressedBytes); if (compressedBytes > 0) DoWrite(buffer, 0, compressedBytes, false); } while (!finished); } // Write format footer: if (formatWriter != null && wroteHeader) { byte[] b = formatWriter.GetFooter(); _stream.Write(b, 0, b.Length); } } protected override void Dispose(bool disposing) { try { PurgeBuffers(disposing); } finally { // Close the underlying stream even if PurgeBuffers threw. // Stream.Close() may throw here (may or may not be due to the same error). // In this case, we still need to clean up internal resources, hence the inner finally blocks. try { if(disposing && !_leaveOpen && _stream != null) _stream.Dispose(); } finally { _stream = null; try { if (deflater != null) deflater.Dispose(); } finally { deflater = null; base.Dispose(disposing); } } // finally } // finally } // Dispose #if !NETFX_CORE public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) { EnsureCompressionMode(); // We use this checking order for compat to earlier versions: if (asyncOperations != 0 ) throw new InvalidOperationException(SR.GetString(SR.InvalidBeginCall)); ValidateParameters(array, offset, count); EnsureNotDisposed(); Interlocked.Increment(ref asyncOperations); try { DeflateStreamAsyncResult userResult = new DeflateStreamAsyncResult( this, asyncState, asyncCallback, array, offset, count); userResult.isWrite = true; m_AsyncWriterDelegate.BeginInvoke(array, offset, count, true, m_CallBack, userResult); userResult.m_CompletedSynchronously &= userResult.IsCompleted; return userResult; } catch { Interlocked.Decrement(ref asyncOperations); throw; } } // Callback function for asynchrous reading on base stream private void WriteCallback(IAsyncResult asyncResult) { DeflateStreamAsyncResult outerResult = (DeflateStreamAsyncResult) asyncResult.AsyncState; outerResult.m_CompletedSynchronously &= asyncResult.CompletedSynchronously; try { m_AsyncWriterDelegate.EndInvoke(asyncResult); } catch (Exception exc) { // Defer throwing this until EndWrite where there is user code on the stack: outerResult.InvokeCallback(exc); return; } outerResult.InvokeCallback(null); } public override void EndWrite(IAsyncResult asyncResult) { EnsureCompressionMode(); CheckEndXxxxLegalStateAndParams(asyncResult); // We checked that this will work in CheckEndXxxxLegalStateAndParams: DeflateStreamAsyncResult deflateStrmAsyncResult = (DeflateStreamAsyncResult) asyncResult; AwaitAsyncResultCompletion(deflateStrmAsyncResult); Exception previousException = deflateStrmAsyncResult.Result as Exception; if (previousException != null) { // Rethrowing will delete the stack trace. Let's help future debuggers: //previousException.Data.Add(OrigStackTrace_ExceptionDataKey, previousException.StackTrace); throw previousException; } } private void CheckEndXxxxLegalStateAndParams(IAsyncResult asyncResult) { if (asyncOperations != 1) throw new InvalidOperationException(SR.GetString(SR.InvalidEndCall)); if (asyncResult == null) throw new ArgumentNullException("asyncResult"); EnsureNotDisposed(); DeflateStreamAsyncResult myResult = asyncResult as DeflateStreamAsyncResult; // This should really be an ArgumentException, but we keep this for compat to previous versions: if (myResult == null) throw new ArgumentNullException("asyncResult"); } private void AwaitAsyncResultCompletion(DeflateStreamAsyncResult asyncResult) { try { if (!asyncResult.IsCompleted) asyncResult.AsyncWaitHandle.WaitOne(); } finally { Interlocked.Decrement(ref asyncOperations); asyncResult.Close(); // this will just close the wait handle } } #endif } // public class DeflateStream } // namespace Unity.IO.Compression
using System; using System.Collections.Generic; using System.Linq; using Cirrious.FluentLayouts.Touch; using CoreAnimation; using CoreFoundation; using CoreGraphics; using Foundation; using Toggl.Phoebe; using Toggl.Phoebe.Analytics; using Toggl.Phoebe.Data.DataObjects; using Toggl.Phoebe.Data.Models; using Toggl.Phoebe.Data.Utils; using Toggl.Phoebe.Data.Views; using Toggl.Ross.DataSources; using Toggl.Ross.Theme; using Toggl.Ross.Views; using UIKit; using XPlatUtils; namespace Toggl.Ross.ViewControllers { public class EditTimeEntryViewController : UIViewController { private enum LayoutVariant { Default, Description } class TGTableView : UITableView { public override UIView TableFooterView { get { return base.TableFooterView; } set { base.TableFooterView = value ?? new UIView (); } } } private LayoutVariant layoutVariant = LayoutVariant.Default; private readonly TimerNavigationController timerController; private NSLayoutConstraint[] trackedWrapperConstraints; private UIView wrapper; private StartStopView startStopView; private UIDatePicker datePicker; private ProjectClientTaskButton projectButton; private TextField descriptionTextField; private UIButton tagsButton; private LabelSwitchView billableSwitch; private UIButton deleteButton; private bool hideDatePicker = true; private readonly List<NSObject> notificationObjects = new List<NSObject> (); private readonly TimeEntryModel model; private readonly TimeEntryTagsView tagsView; private PropertyChangeTracker propertyTracker = new PropertyChangeTracker (); private bool descriptionChanging; private bool autoCommitScheduled; private int autoCommitId; private bool shouldRebindOnAppear; private UITableView autoCompletionTableView; private UIBarButtonItem autoCompletionDoneBarButtonItem; private Stack<UIBarButtonItem> barButtonItemsStack = new Stack<UIBarButtonItem> (); public EditTimeEntryViewController (TimeEntryModel model) { this.model = model; tagsView = new TimeEntryTagsView (model.Id); timerController = new TimerNavigationController (model); } protected override void Dispose (bool disposing) { base.Dispose (disposing); if (disposing) { if (tagsView != null) { tagsView.Updated -= OnTagsUpdated; } if (propertyTracker != null) { propertyTracker.Dispose (); propertyTracker = null; } } } private void ScheduleDescriptionChangeAutoCommit () { if (autoCommitScheduled) { return; } var commitId = ++autoCommitId; autoCommitScheduled = true; DispatchQueue.MainQueue.DispatchAfter (TimeSpan.FromSeconds (1), delegate { if (!autoCommitScheduled || commitId != autoCommitId) { return; } autoCommitScheduled = false; CommitDescriptionChanges (); }); } private void CancelDescriptionChangeAutoCommit () { autoCommitScheduled = false; } private void CommitDescriptionChanges () { if (descriptionChanging) { model.Description = descriptionTextField.Text; model.SaveAsync (); } descriptionChanging = false; CancelDescriptionChangeAutoCommit (); } private void DiscardDescriptionChanges () { descriptionChanging = false; CancelDescriptionChangeAutoCommit (); } private void OnTagsUpdated (object sender, EventArgs args) { RebindTags (); } private void ResetTrackedObservables () { if (propertyTracker == null) { return; } propertyTracker.MarkAllStale (); if (model != null) { propertyTracker.Add (model, HandleTimeEntryPropertyChanged); if (model.Project != null) { propertyTracker.Add (model.Project, HandleProjectPropertyChanged); if (model.Project.Client != null) { propertyTracker.Add (model.Project.Client, HandleClientPropertyChanged); } } if (model.Task != null) { propertyTracker.Add (model.Task, HandleTaskPropertyChanged); } } propertyTracker.ClearStale (); } private void HandleTimeEntryPropertyChanged (string prop) { if (prop == TimeEntryModel.PropertyProject || prop == TimeEntryModel.PropertyTask || prop == TimeEntryModel.PropertyStartTime || prop == TimeEntryModel.PropertyStopTime || prop == TimeEntryModel.PropertyState || prop == TimeEntryModel.PropertyIsBillable || prop == TimeEntryModel.PropertyDescription) { Rebind (); } } private void HandleProjectPropertyChanged (string prop) { if (prop == ProjectModel.PropertyClient || prop == ProjectModel.PropertyName || prop == ProjectModel.PropertyColor) { Rebind (); } } private void HandleClientPropertyChanged (string prop) { if (prop == ClientModel.PropertyName) { Rebind (); } } private void HandleTaskPropertyChanged (string prop) { if (prop == TaskModel.PropertyName) { Rebind (); } } private void BindStartStopView (StartStopView v) { v.StartTime = model.StartTime; v.StopTime = model.StopTime; } private void BindDatePicker (UIDatePicker v) { if (startStopView == null) { return; } var currentValue = v.Date.ToDateTime ().ToUtc (); switch (startStopView.Selected) { case TimeKind.Start: if (currentValue != model.StartTime) { v.SetDate (model.StartTime.ToNSDate (), !v.Hidden); } break; case TimeKind.Stop: if (currentValue != model.StopTime) { v.SetDate (model.StopTime.Value.ToNSDate (), !v.Hidden); } break; } } private void BindProjectButton (ProjectClientTaskButton v) { var projectName = "EditEntryProjectHint".Tr (); var projectColor = Color.White; var clientName = String.Empty; var taskName = String.Empty; if (model.Project != null) { projectName = model.Project.Name; projectColor = UIColor.Clear.FromHex (model.Project.GetHexColor ()); if (model.Project.Client != null) { clientName = model.Project.Client.Name; } if (model.Task != null) { taskName = model.Task.Name; } } v.ProjectColor = projectColor; v.ProjectName = projectName; v.ClientName = clientName; v.TaskName = taskName; } private void BindDescriptionField (TextField v) { if (!descriptionChanging && v.Text != model.Description) { v.Text = model.Description; } } private void BindTagsButton (UIButton v) { if (tagsView == null) { return; } // Construct tags attributed strings: NSMutableAttributedString text = null; foreach (var tag in tagsView.Data) { if (String.IsNullOrWhiteSpace (tag)) { continue; } var chip = NSAttributedString.CreateFrom (new NSTextAttachment () { Image = ServiceContainer.Resolve<TagChipCache> ().Get (tag, v), }); if (text == null) { text = new NSMutableAttributedString (chip); } else { text.Append (new NSAttributedString (" ", Style.EditTimeEntry.WithTags)); text.Append (chip); } } if (text == null) { v.SetAttributedTitle (new NSAttributedString ("EditEntryTagsHint".Tr (), Style.EditTimeEntry.NoTags), UIControlState.Normal); } else { v.SetAttributedTitle (text, UIControlState.Normal); } } private void BindBillableSwitch (LabelSwitchView v) { v.Hidden = model.Workspace == null || !model.Workspace.IsPremium; v.Switch.On = model.IsBillable; } private Source autocompletionTableViewSource; private void BindAutocompletionTableView (UITableView v) { autocompletionTableViewSource = new Source (this, v); autocompletionTableViewSource.Attach (); } private void BindAutoCompletionDoneBarButtonItem (UINavigationItem v) { autoCompletionDoneBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done); autoCompletionDoneBarButtonItem.Clicked += (object sender, EventArgs e) => { DescriptionSuggestionsMode = false; }; if (v.RightBarButtonItem != null) { barButtonItemsStack.Push (v.RightBarButtonItem); } v.SetRightBarButtonItem (autoCompletionDoneBarButtonItem, true); } private void UnBindAutoCompletionDoneBarButtonItem (UINavigationItem v) { if (v.RightBarButtonItem == autoCompletionDoneBarButtonItem) { v.SetRightBarButtonItem (null, true); if (barButtonItemsStack.Count > 0) { v.SetRightBarButtonItem (barButtonItemsStack.Pop (), true); } autoCompletionDoneBarButtonItem = null; } } private void BeginSuggestionMode() { DescriptionSuggestionsMode = true; } private class Source : GroupedDataViewSource<TimeEntryData, string, TimeEntryData> { private readonly static NSString EntryCellId = new NSString ("autocompletionCell"); private readonly EditTimeEntryViewController controller; private readonly SuggestionEntriesView dataView; public Source (EditTimeEntryViewController controller, UITableView tableView) : this (controller, tableView, new SuggestionEntriesView ()) { } private Source (EditTimeEntryViewController controller, UITableView tableView, SuggestionEntriesView dataView) : base (tableView, dataView) { this.dataView = dataView; this.dataView.Updated += (DataViewUpdated); this.controller = controller; tableView.RegisterClassForCellReuse (typeof (SuggestionTableViewCell), EntryCellId); } private void DataViewUpdated (object sender, EventArgs args) { if (sender == dataView && dataView.HasSuggestions) { controller.BeginSuggestionMode (); } } public void UpdateDescription (string descriptionString) { dataView.FilterByInfix (descriptionString); } protected override IEnumerable<string> GetSections () { return new List<string> () { "" }; } protected override IEnumerable<TimeEntryData> GetRows (string section) { return dataView.Data; } public override nfloat EstimatedHeight (UITableView tableView, NSIndexPath indexPath) { return 60f; } public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { return EstimatedHeight (tableView, indexPath); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = (SuggestionTableViewCell)tableView.DequeueReusableCell (EntryCellId, indexPath); cell.Bind ((TimeEntryModel)GetRow (indexPath)); return cell; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { tableView.DeselectRow (indexPath, false); TimeEntryModel selectedModel; selectedModel = (TimeEntryModel)GetRow (indexPath); controller.UpdateModel (selectedModel); } } private void Rebind () { ResetTrackedObservables (); var billableHidden = billableSwitch.Hidden; startStopView.Apply (BindStartStopView); datePicker.Apply (BindDatePicker); projectButton.Apply (BindProjectButton); descriptionTextField.Apply (BindDescriptionField); billableSwitch.Apply (BindBillableSwitch); if (billableHidden != billableSwitch.Hidden) { ResetWrapperConstraints (); } } private void ResetWrapperConstraints() { if (trackedWrapperConstraints != null) { wrapper.RemoveConstraints (trackedWrapperConstraints); trackedWrapperConstraints = null; } switch (layoutVariant) { case LayoutVariant.Default: trackedWrapperConstraints = VerticalLinearLayout (wrapper).ToLayoutConstraints (); break; case LayoutVariant.Description: trackedWrapperConstraints = new [] { descriptionTextField.AtTopOf (wrapper), descriptionTextField.AtLeftOf (wrapper), descriptionTextField.AtRightOf (wrapper), descriptionTextField.Height ().EqualTo (60.0f), autoCompletionTableView.AtTopOf (wrapper, 65.0f), autoCompletionTableView.AtLeftOf (wrapper), autoCompletionTableView.AtRightOf (wrapper), autoCompletionTableView.AtBottomOf (wrapper) } .ToLayoutConstraints (); break; } wrapper.AddConstraints (trackedWrapperConstraints); } private void RebindTags () { tagsButton.Apply (BindTagsButton); } public override void LoadView () { var scrollView = new UIScrollView ().Apply (Style.Screen); scrollView.Add (wrapper = new UIView () { TranslatesAutoresizingMaskIntoConstraints = false, }); wrapper.Add (startStopView = new StartStopView () { TranslatesAutoresizingMaskIntoConstraints = false, StartTime = model.StartTime, StopTime = model.StopTime, } .Apply (BindStartStopView)); startStopView.SelectedChanged += OnStartStopViewSelectedChanged; wrapper.Add (datePicker = new UIDatePicker () { TranslatesAutoresizingMaskIntoConstraints = false, Hidden = DatePickerHidden, Alpha = 0, } .Apply (Style.EditTimeEntry.DatePicker).Apply (BindDatePicker)); datePicker.ValueChanged += OnDatePickerValueChanged; wrapper.Add (projectButton = new ProjectClientTaskButton () { TranslatesAutoresizingMaskIntoConstraints = false, } .Apply (BindProjectButton)); projectButton.TouchUpInside += OnProjectButtonTouchUpInside; wrapper.Add (descriptionTextField = new TextField () { TranslatesAutoresizingMaskIntoConstraints = false, AttributedPlaceholder = new NSAttributedString ( "EditEntryDesciptionTimerHint".Tr (), foregroundColor: Color.Gray ), ShouldReturn = tf => tf.ResignFirstResponder (), } .Apply (Style.EditTimeEntry.DescriptionField).Apply (BindDescriptionField)); descriptionTextField.EditingChanged += OnDescriptionFieldEditingChanged; descriptionTextField.ShouldChangeCharacters = OnDescriptionFieldShouldChangeCharacters; descriptionTextField.EditingDidEnd += (s, e) => CommitDescriptionChanges (); descriptionTextField.ShouldBeginEditing += (s) => { ForceDimissDatePicker(); return true; }; descriptionTextField.ShouldEndEditing += s => { DescriptionSuggestionsMode = false; return true; }; wrapper.Add (tagsButton = new UIButton () { TranslatesAutoresizingMaskIntoConstraints = false, } .Apply (Style.EditTimeEntry.TagsButton).Apply (BindTagsButton)); tagsButton.TouchUpInside += OnTagsButtonTouchUpInside; wrapper.Add (billableSwitch = new LabelSwitchView () { TranslatesAutoresizingMaskIntoConstraints = false, Text = "EditEntryBillable".Tr (), } .Apply (Style.EditTimeEntry.BillableContainer).Apply (BindBillableSwitch)); billableSwitch.Label.Apply (Style.EditTimeEntry.BillableLabel); billableSwitch.Switch.ValueChanged += OnBillableSwitchValueChanged; wrapper.Add (autoCompletionTableView = new TGTableView() { TranslatesAutoresizingMaskIntoConstraints = false, EstimatedRowHeight = 60.0f, BackgroundColor = UIColor.Clear } .Apply (BindAutocompletionTableView)); wrapper.Add (deleteButton = new UIButton () { TranslatesAutoresizingMaskIntoConstraints = false, } .Apply (Style.EditTimeEntry.DeleteButton)); deleteButton.SetTitle ("EditEntryDelete".Tr (), UIControlState.Normal); deleteButton.TouchUpInside += OnDeleteButtonTouchUpInside; ResetWrapperConstraints (); scrollView.AddConstraints ( wrapper.AtTopOf (scrollView), wrapper.AtBottomOf (scrollView), wrapper.AtLeftOf (scrollView), wrapper.AtRightOf (scrollView), wrapper.WithSameWidth (scrollView), wrapper.Height ().GreaterThanOrEqualTo ().HeightOf (scrollView).Minus (64f), null ); View = scrollView; ResetTrackedObservables (); DescriptionSuggestionsMode = false; } public override void ViewDidLoad () { base.ViewDidLoad (); timerController.Attach (this); } private bool descriptionSuggestionsMode__; private bool DescriptionSuggestionsMode { get { return descriptionSuggestionsMode__; } set { if (value == descriptionSuggestionsMode__) { return; } UIScrollView scrlView = (UIScrollView)View; scrlView.ScrollEnabled = !value; if (value) { layoutVariant = LayoutVariant.Description; NavigationItem.Apply (BindAutoCompletionDoneBarButtonItem); } else { descriptionTextField.ResignFirstResponder (); layoutVariant = LayoutVariant.Default; NavigationItem.Apply (UnBindAutoCompletionDoneBarButtonItem); } ResetWrapperConstraints (); UIView.Animate (0.4f, delegate { SetEditingModeViewsHidden (value); wrapper.LayoutIfNeeded(); }); descriptionSuggestionsMode__ = value; } } private void SetEditingModeViewsHidden (bool editingMode) { billableSwitch.Alpha = tagsButton.Alpha = startStopView.Alpha = projectButton.Alpha = deleteButton.Alpha = editingMode ? 0 : 1; autoCompletionTableView.Alpha = 1 - tagsButton.Alpha; } private void OnDatePickerValueChanged (object sender, EventArgs e) { switch (startStopView.Selected) { case TimeKind.Start: model.StartTime = datePicker.Date.ToDateTime (); break; case TimeKind.Stop: model.StopTime = datePicker.Date.ToDateTime (); break; } model.SaveAsync (); } private void OnProjectButtonTouchUpInside (object sender, EventArgs e) { var controller = new ProjectSelectionViewController (model); NavigationController.PushViewController (controller, true); } public async void UpdateModel (TimeEntryModel updatedModel) { if (DescriptionSuggestionsMode) { descriptionTextField.Text = updatedModel.Description; } await model.MapMinorsFromModel (updatedModel); Rebind (); DescriptionSuggestionsMode = false; } bool shouldUpdateAutocompletionTableViewSource = false; NSTimer autocompletionModeTimeoutTimer; private bool OnDescriptionFieldShouldChangeCharacters (UITextField textField, NSRange range, string replacementString) { shouldUpdateAutocompletionTableViewSource = replacementString.Length > 0 && autocompletionTableViewSource != null; return true; } private void OnDescriptionFieldEditingChanged (object sender, EventArgs e) { autocompletionTableViewSource.UpdateDescription (descriptionTextField.Text); // Mark description as changed descriptionChanging = descriptionTextField.Text != model.Description; // Make sure that we're commiting 1 second after the user has stopped typing CancelDescriptionChangeAutoCommit (); if (descriptionChanging && !DescriptionSuggestionsMode) { ScheduleDescriptionChangeAutoCommit (); } if (shouldUpdateAutocompletionTableViewSource) { autocompletionTableViewSource.UpdateDescription (descriptionTextField.Text); } if (autocompletionModeTimeoutTimer != null) { autocompletionModeTimeoutTimer.Invalidate (); autocompletionModeTimeoutTimer = null; } if (descriptionTextField.Text.Length == 0) { autocompletionModeTimeoutTimer = NSTimer.CreateScheduledTimer (5.0f, delegate { DescriptionSuggestionsMode = false; }); } } private void OnTagsButtonTouchUpInside (object sender, EventArgs e) { var controller = new TagSelectionViewController (model); NavigationController.PushViewController (controller, true); } private void OnBillableSwitchValueChanged (object sender, EventArgs e) { model.IsBillable = billableSwitch.Switch.On; model.SaveAsync (); } private void OnDeleteButtonTouchUpInside (object sender, EventArgs e) { var alert = new UIAlertView ( "EditEntryConfirmTitle".Tr (), "EditEntryConfirmMessage".Tr (), null, "EditEntryConfirmCancel".Tr (), "EditEntryConfirmDelete".Tr ()); alert.Clicked += async (s, ev) => { if (ev.ButtonIndex == 1) { NavigationController.PopToRootViewController (true); await model.DeleteAsync (); } }; alert.Show (); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); timerController.Start (); ObserveNotification (UIKeyboard.WillHideNotification, (notif) => { OnKeyboardHeightChanged (0); }); ObserveNotification (UIKeyboard.WillShowNotification, (notif) => { var val = notif.UserInfo.ObjectForKey (UIKeyboard.FrameEndUserInfoKey) as NSValue; if (val != null) { OnKeyboardHeightChanged ((int)val.CGRectValue.Height); } }); ObserveNotification (UIKeyboard.WillChangeFrameNotification, (notif) => { var val = notif.UserInfo.ObjectForKey (UIKeyboard.FrameEndUserInfoKey) as NSValue; if (val != null) { OnKeyboardHeightChanged ((int)val.CGRectValue.Height); } }); if (tagsView != null) { tagsView.Updated += OnTagsUpdated; } RebindTags (); if (shouldRebindOnAppear) { Rebind (); } else { shouldRebindOnAppear = true; } } private void ObserveNotification (string name, Action<NSNotification> callback) { var obj = NSNotificationCenter.DefaultCenter.AddObserver (new NSString ( name), callback); if (obj != null) { notificationObjects.Add (obj); } } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Edit Time Entry"; } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); if (tagsView != null) { tagsView.Updated -= OnTagsUpdated; } NSNotificationCenter.DefaultCenter.RemoveObservers (notificationObjects); notificationObjects.Clear (); } public override void ViewDidDisappear (bool animated) { base.ViewDidDisappear (animated); timerController.Stop (); } private void OnKeyboardHeightChanged (int height) { var scrollView = (UIScrollView)View; var inset = scrollView.ContentInset; inset.Bottom = height; scrollView.ContentInset = inset; inset = scrollView.ScrollIndicatorInsets; inset.Bottom = height; scrollView.ScrollIndicatorInsets = inset; } private void OnStartStopViewSelectedChanged (object sender, EventArgs e) { datePicker.Apply (BindDatePicker); DatePickerHidden = startStopView.Selected == TimeKind.None; } private void ForceDimissDatePicker() { DatePickerHidden = true; startStopView.Selected = TimeKind.None; } private bool DatePickerHidden { get { return hideDatePicker; } set { if (hideDatePicker == value) { return; } hideDatePicker = value; if (hideDatePicker) { UIView.AnimateKeyframes ( 0.4, 0, 0, delegate { UIView.AddKeyframeWithRelativeStartTime (0, 0.4, delegate { datePicker.Alpha = 0; }); UIView.AddKeyframeWithRelativeStartTime (0.2, 0.8, delegate { ResetWrapperConstraints(); View.LayoutIfNeeded (); }); }, delegate { if (hideDatePicker) { datePicker.Hidden = true; } } ); } else { descriptionTextField.ResignFirstResponder (); datePicker.Hidden = false; UIView.AnimateKeyframes ( 0.4, 0, 0, delegate { UIView.AddKeyframeWithRelativeStartTime (0, 0.6, delegate { ResetWrapperConstraints(); View.LayoutIfNeeded (); }); UIView.AddKeyframeWithRelativeStartTime (0.4, 0.8, delegate { datePicker.Alpha = 1; }); }, delegate { } ); } } } private IEnumerable<FluentLayout> VerticalLinearLayout (UIView container) { UIView prev = null; var subviews = container.Subviews.Where (v => !v.Hidden && ! (v == datePicker && DatePickerHidden)).ToList (); foreach (var v in subviews) { var isLast = subviews [subviews.Count - 1] == v; if (prev == null) { yield return v.AtTopOf (container); } else if (isLast) { yield return v.Top ().GreaterThanOrEqualTo ().BottomOf (prev).Plus (5f); } else { yield return v.Below (prev, 5f); } yield return v.Height ().EqualTo (60f).SetPriority (UILayoutPriority.DefaultLow); yield return v.Height ().GreaterThanOrEqualTo (60f); yield return v.AtLeftOf (container); yield return v.AtRightOf (container); prev = v; } if (prev != null) { yield return prev.AtBottomOf (container); } } private class StartStopView : UIView { private readonly List<NSLayoutConstraint> trackedConstraints = new List<NSLayoutConstraint>(); private readonly UILabel startDateLabel; private readonly UILabel startTimeLabel; private readonly UIButton startDateTimeButton; private readonly UILabel stopDateLabel; private readonly UILabel stopTimeLabel; private readonly UIButton stopDateTimeButton; private readonly UIImageView arrowImageView; private LayoutVariant viewLayout = LayoutVariant.StartOnly; private bool stopTimeHidden = true; private DateTime startTime; private DateTime? stopTime; private TimeKind selectedTime; public StartStopView () { startDateTimeButton = new UIButton () { TranslatesAutoresizingMaskIntoConstraints = false, }; startDateTimeButton.TouchUpInside += OnStartDateTimeButtonTouchUpInside; arrowImageView = new UIImageView () { TranslatesAutoresizingMaskIntoConstraints = false, Image = Image.IconDurationArrow, }; stopDateTimeButton = new UIButton () { TranslatesAutoresizingMaskIntoConstraints = false, }; stopDateTimeButton.TouchUpInside += OnStopDateTimeButtonTouchUpInside; ConstructDateTimeView (startDateTimeButton, ref startDateLabel, ref startTimeLabel); ConstructDateTimeView (stopDateTimeButton, ref stopDateLabel, ref stopTimeLabel); Add (startDateTimeButton); StartTime = DateTime.Now - TimeSpan.FromHours (4); } private void OnStartDateTimeButtonTouchUpInside (object sender, EventArgs e) { Selected = Selected == TimeKind.Start ? TimeKind.None : TimeKind.Start; } private void OnStopDateTimeButtonTouchUpInside (object sender, EventArgs e) { Selected = Selected == TimeKind.Stop ? TimeKind.None : TimeKind.Stop; } public DateTime StartTime { get { return startTime; } set { if (startTime == value) { return; } startTime = value; var time = startTime.ToLocalTime (); startDateLabel.Text = time.ToLocalizedDateString (); startTimeLabel.Text = time.ToLocalizedTimeString (); } } public DateTime? StopTime { get { return stopTime; } set { if (stopTime == value) { return; } stopTime = value; if (stopTime.HasValue) { var time = stopTime.Value.ToLocalTime (); stopDateLabel.Text = time.ToLocalizedDateString (); stopTimeLabel.Text = time.ToLocalizedTimeString (); } SetStopTimeHidden (stopTime == null, animate: Superview != null); if (stopTime == null && Selected == TimeKind.Stop) { Selected = TimeKind.None; } } } public TimeKind Selected { get { return selectedTime; } set { if (selectedTime == value) { return; } selectedTime = value; if (selectedTime == TimeKind.Start) { startDateLabel.Apply (Style.EditTimeEntry.DateLabelActive); startTimeLabel.Apply (Style.EditTimeEntry.TimeLabelActive); } else { startDateLabel.Apply (Style.EditTimeEntry.DateLabel); startTimeLabel.Apply (Style.EditTimeEntry.TimeLabel); } if (selectedTime == TimeKind.Stop) { stopDateLabel.Apply (Style.EditTimeEntry.DateLabelActive); stopTimeLabel.Apply (Style.EditTimeEntry.TimeLabelActive); } else { stopDateLabel.Apply (Style.EditTimeEntry.DateLabel); stopTimeLabel.Apply (Style.EditTimeEntry.TimeLabel); } var handler = SelectedChanged; if (handler != null) { handler (this, EventArgs.Empty); } } } public event EventHandler SelectedChanged; private void SetStopTimeHidden (bool hidden, bool animate) { if (stopTimeHidden == hidden) { return; } stopTimeHidden = hidden; if (!animate) { ViewLayout = hidden ? LayoutVariant.StartOnly : LayoutVariant.BothCenterAll; } else if (hidden) { ViewLayout = LayoutVariant.BothCenterAll; stopDateTimeButton.Alpha = 1; arrowImageView.Alpha = 1; LayoutIfNeeded (); UIView.AnimateKeyframes ( 0.4, 0, UIViewKeyframeAnimationOptions.CalculationModeCubic | UIViewKeyframeAnimationOptions.BeginFromCurrentState, delegate { UIView.AddKeyframeWithRelativeStartTime (0, 1, delegate { ViewLayout = LayoutVariant.BothCenterStart; LayoutIfNeeded (); }); UIView.AddKeyframeWithRelativeStartTime (0, 0.8, delegate { stopDateTimeButton.Alpha = 0; arrowImageView.Alpha = 0; }); }, delegate { if (ViewLayout == LayoutVariant.BothCenterStart) { ViewLayout = LayoutVariant.StartOnly; LayoutIfNeeded (); } }); } else { ViewLayout = LayoutVariant.BothCenterStart; stopDateTimeButton.Alpha = 0; arrowImageView.Alpha = 0; LayoutIfNeeded (); UIView.AnimateKeyframes ( 0.4, 0, UIViewKeyframeAnimationOptions.CalculationModeCubic | UIViewKeyframeAnimationOptions.BeginFromCurrentState, delegate { UIView.AddKeyframeWithRelativeStartTime (0, 1, delegate { ViewLayout = LayoutVariant.BothCenterAll; LayoutIfNeeded (); }); UIView.AddKeyframeWithRelativeStartTime (0.2, 1, delegate { stopDateTimeButton.Alpha = 1; arrowImageView.Alpha = 1; }); }, delegate { }); } } private static void ConstructDateTimeView (UIView view, ref UILabel dateLabel, ref UILabel timeLabel) { view.Add (dateLabel = new UILabel ().Apply (Style.EditTimeEntry.DateLabel)); view.Add (timeLabel = new UILabel ().Apply (Style.EditTimeEntry.TimeLabel)); view.AddConstraints ( dateLabel.AtTopOf (view, 10f), dateLabel.AtLeftOf (view, 10f), dateLabel.AtRightOf (view, 10f), timeLabel.Below (dateLabel, 2f), timeLabel.AtBottomOf (view, 10f), timeLabel.AtLeftOf (view, 10f), timeLabel.AtRightOf (view, 10f) ); view.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints (); } public override void UpdateConstraints () { if (trackedConstraints.Count > 0) { RemoveConstraints (trackedConstraints.ToArray()); trackedConstraints.Clear (); } switch (viewLayout) { case LayoutVariant.StartOnly: arrowImageView.RemoveFromSuperview (); stopDateTimeButton.RemoveFromSuperview (); trackedConstraints.AddRange (new [] { startDateTimeButton.WithSameCenterX (this), startDateTimeButton.WithSameCenterY (this), startDateTimeButton.AtTopOf (this, 10f), startDateTimeButton.AtBottomOf (this, 10f) } .ToLayoutConstraints()); break; case LayoutVariant.BothCenterStart: AddSubview (arrowImageView); AddSubview (stopDateTimeButton); trackedConstraints.AddRange (new [] { startDateTimeButton.WithSameCenterX (this), startDateTimeButton.WithSameCenterY (this), startDateTimeButton.AtTopOf (this, 10f), startDateTimeButton.AtBottomOf (this, 10f), arrowImageView.WithSameCenterY (startDateTimeButton), arrowImageView.ToRightOf (startDateTimeButton, 10f), arrowImageView.ToLeftOf (stopDateTimeButton, 10f), stopDateTimeButton.AtTopOf (this, 10f), stopDateTimeButton.AtBottomOf (this, 10f) } .ToLayoutConstraints()); break; case LayoutVariant.BothCenterAll: default: AddSubview (arrowImageView); AddSubview (stopDateTimeButton); trackedConstraints.AddRange (new [] { startDateTimeButton.AtTopOf (this, 10f), startDateTimeButton.AtBottomOf (this, 10f), arrowImageView.WithSameCenterX (this), arrowImageView.WithSameCenterY (this), arrowImageView.ToRightOf (startDateTimeButton, 10f), arrowImageView.ToLeftOf (stopDateTimeButton, 10f), stopDateTimeButton.AtTopOf (this, 10f), stopDateTimeButton.AtBottomOf (this, 10f) } .ToLayoutConstraints()); break; } AddConstraints (trackedConstraints.ToArray ()); base.UpdateConstraints (); } private LayoutVariant ViewLayout { get { return viewLayout; } set { if (viewLayout == value) { return; } viewLayout = value; SetNeedsUpdateConstraints (); SetNeedsLayout (); } } private enum LayoutVariant { StartOnly, BothCenterStart, BothCenterAll } [Export ("requiresConstraintBasedLayout")] public static new bool RequiresConstraintBasedLayout () { return true; } } private enum TimeKind { None, Start, Stop } private class ProjectClientTaskButton : UIButton { private readonly List<NSLayoutConstraint> trackedConstraints = new List<NSLayoutConstraint>(); private readonly UIView container; private readonly UILabel projectLabel; private readonly UILabel clientLabel; private readonly UILabel taskLabel; public ProjectClientTaskButton () { Add (container = new UIView () { TranslatesAutoresizingMaskIntoConstraints = false, UserInteractionEnabled = false, }); var maskLayer = new CAGradientLayer () { AnchorPoint = CGPoint.Empty, StartPoint = new CGPoint (0.0f, 0.0f), EndPoint = new CGPoint (1.0f, 0.0f), Colors = new [] { UIColor.FromWhiteAlpha (1, 1).CGColor, UIColor.FromWhiteAlpha (1, 1).CGColor, UIColor.FromWhiteAlpha (1, 0).CGColor, }, Locations = new [] { NSNumber.FromFloat (0f), NSNumber.FromFloat (0.9f), NSNumber.FromFloat (1f), }, }; container.Layer.Mask = maskLayer; container.Add (projectLabel = new UILabel () { TranslatesAutoresizingMaskIntoConstraints = false, } .Apply (Style.EditTimeEntry.ProjectLabel)); container.Add (clientLabel = new UILabel () { TranslatesAutoresizingMaskIntoConstraints = false, } .Apply (Style.EditTimeEntry.ClientLabel)); container.Add (taskLabel = new UILabel () { TranslatesAutoresizingMaskIntoConstraints = false, } .Apply (Style.EditTimeEntry.TaskLabel)); } public override void UpdateConstraints () { if (trackedConstraints.Count > 0) { RemoveConstraints (trackedConstraints.ToArray()); trackedConstraints.Clear (); } trackedConstraints.AddRange (new FluentLayout[] { container.AtLeftOf (this, 15f), container.WithSameCenterY (this), projectLabel.AtTopOf (container), projectLabel.AtLeftOf (container), null } .ToLayoutConstraints()); if (!clientLabel.Hidden) { var baselineOffset = (float)Math.Floor (projectLabel.Font.Descender - clientLabel.Font.Descender); trackedConstraints.AddRange (new FluentLayout[] { clientLabel.AtTopOf (container, -baselineOffset), clientLabel.AtRightOf (container), clientLabel.ToRightOf (projectLabel, 5f), clientLabel.AtBottomOf (projectLabel, baselineOffset), null } .ToLayoutConstraints()); } else { trackedConstraints.AddRange (new FluentLayout[] { projectLabel.AtRightOf (container), null } .ToLayoutConstraints()); } if (!taskLabel.Hidden) { trackedConstraints.AddRange (new FluentLayout[] { taskLabel.Below (projectLabel, 3f), taskLabel.AtLeftOf (container), taskLabel.AtRightOf (container), taskLabel.AtBottomOf (container), null } .ToLayoutConstraints()); } else { trackedConstraints.AddRange (new FluentLayout[] { projectLabel.AtBottomOf (container), null } .ToLayoutConstraints()); } AddConstraints (trackedConstraints.ToArray ()); base.UpdateConstraints (); } public override void LayoutSubviews () { base.LayoutSubviews (); // Update fade mask position: var bounds = container.Frame; bounds.Width = Frame.Width - bounds.X; container.Layer.Mask.Bounds = bounds; } public string ProjectName { get { return projectLabel.Text; } set { projectLabel.Text = value; } } public string ClientName { get { return clientLabel.Text; } set { if (clientLabel.Text == value) { return; } var visibilityChanged = String.IsNullOrWhiteSpace (clientLabel.Text) != String.IsNullOrWhiteSpace (value); clientLabel.Text = value; if (visibilityChanged) { SetNeedsUpdateConstraints (); clientLabel.Hidden = String.IsNullOrWhiteSpace (value); } } } public string TaskName { get { return taskLabel.Text; } set { if (taskLabel.Text == value) { return; } var visibilityChanged = String.IsNullOrWhiteSpace (taskLabel.Text) != String.IsNullOrWhiteSpace (value); taskLabel.Text = value; if (visibilityChanged) { SetNeedsUpdateConstraints (); taskLabel.Hidden = String.IsNullOrWhiteSpace (value); } } } public UIColor ProjectColor { set { if (value == Color.White) { projectLabel.Apply (Style.EditTimeEntry.ProjectHintLabel); SetBackgroundImage (Color.White.ToImage (), UIControlState.Normal); SetBackgroundImage (Color.LightestGray.ToImage (), UIControlState.Highlighted); } else { projectLabel.Apply (Style.EditTimeEntry.ProjectLabel); SetBackgroundImage (value.ToImage (), UIControlState.Normal); SetBackgroundImage (null, UIControlState.Highlighted); } } } [Export ("requiresConstraintBasedLayout")] public static new bool RequiresConstraintBasedLayout () { return true; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial class AbstractSymbolDisplayService { protected abstract partial class AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.None, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_descriptionStyle = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword); private static readonly SymbolDisplayFormat s_globalNamespaceStyle = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); private readonly ISymbolDisplayService _displayService; private readonly SemanticModel _semanticModel; private readonly int _position; private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService; private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>(); protected readonly Workspace Workspace; protected readonly CancellationToken CancellationToken; protected AbstractSymbolDescriptionBuilder( ISymbolDisplayService displayService, SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) { _displayService = displayService; _anonymousTypeDisplayService = anonymousTypeDisplayService; this.Workspace = workspace; this.CancellationToken = cancellationToken; _semanticModel = semanticModel; _position = position; } protected abstract void AddExtensionPrefix(); protected abstract void AddAwaitablePrefix(); protected abstract void AddAwaitableExtensionPrefix(); protected abstract void AddDeprecatedPrefix(); protected abstract Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol); protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; } protected void AddPrefixTextForAwaitKeyword() { AddToGroup(SymbolDescriptionGroups.MainDescription, PlainText(FeaturesResources.PrefixTextForAwaitKeyword), Space()); } protected void AddTextForSystemVoid() { AddToGroup(SymbolDescriptionGroups.MainDescription, PlainText(FeaturesResources.TextForSystemVoid)); } protected SemanticModel GetSemanticModel(SyntaxTree tree) { if (_semanticModel.SyntaxTree == tree) { return _semanticModel; } var model = _semanticModel.GetOriginalSemanticModel(); if (model.Compilation.ContainsSyntaxTree(tree)) { return model.Compilation.GetSemanticModel(tree); } // it is from one of its p2p references foreach (var referencedCompilation in model.Compilation.GetReferencedCompilations()) { // find the reference that contains the given tree if (referencedCompilation.ContainsSyntaxTree(tree)) { return referencedCompilation.GetSemanticModel(tree); } } // the tree, a source symbol is defined in, doesn't exist in universe // how this can happen? Contract.Requires(false, "How?"); return null; } private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols) { await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false); AddOverloadCountPart(symbols); FixAllAnonymousTypes(symbols[0]); AddExceptions(symbols[0]); } private void AddExceptions(ISymbol symbol) { var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes; if (exceptionTypes.Any()) { var parts = new List<SymbolDisplayPart>(); parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions}")); foreach (var exceptionString in exceptionTypes) { parts.AddRange(LineBreak()); parts.AddRange(Space(count: 2)); parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel)); } AddToGroup(SymbolDescriptionGroups.Exceptions, parts); } } public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync( ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return this.BuildDescription(groups); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return this.BuildDescriptionSections(); } private async Task AddDescriptionPartAsync(ISymbol symbol) { if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute")) { AddDeprecatedPrefix(); } if (symbol is IDynamicTypeSymbol) { AddDescriptionForDynamicType(); } else if (symbol is IFieldSymbol) { await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false); } else if (symbol is ILocalSymbol) { await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false); } else if (symbol is IMethodSymbol) { AddDescriptionForMethod((IMethodSymbol)symbol); } else if (symbol is ILabelSymbol) { AddDescriptionForLabel((ILabelSymbol)symbol); } else if (symbol is INamedTypeSymbol) { AddDescriptionForNamedType((INamedTypeSymbol)symbol); } else if (symbol is INamespaceSymbol) { AddDescriptionForNamespace((INamespaceSymbol)symbol); } else if (symbol is IParameterSymbol) { await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false); } else if (symbol is IPropertySymbol) { AddDescriptionForProperty((IPropertySymbol)symbol); } else if (symbol is IRangeVariableSymbol) { AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol); } else if (symbol is ITypeParameterSymbol) { AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol); } else if (symbol is IAliasSymbol) { await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false); } else { AddDescriptionForArbitrarySymbol(symbol); } } private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups) { var finalParts = new List<SymbolDisplayPart>(); var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2); foreach (var group in orderedGroups) { if ((groups & group) == 0) { continue; } if (!finalParts.IsEmpty()) { var newLines = GetPrecedingNewLineCount(group); finalParts.AddRange(LineBreak(newLines)); } var parts = _groupMap[group]; finalParts.AddRange(parts); } return finalParts.AsImmutable(); } private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group) { switch (group) { case SymbolDescriptionGroups.MainDescription: // these parts are continuations of whatever text came before them return 0; case SymbolDescriptionGroups.Documentation: return 1; case SymbolDescriptionGroups.AnonymousTypes: return 0; case SymbolDescriptionGroups.Exceptions: case SymbolDescriptionGroups.TypeParameterMap: // Everything else is in a group on its own return 2; default: return Contract.FailWithReturn<int>("unknown part kind"); } } private IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>> BuildDescriptionSections() { return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutableOrEmpty()); } private void AddDescriptionForDynamicType() { AddToGroup(SymbolDescriptionGroups.MainDescription, Keyword("dynamic")); AddToGroup(SymbolDescriptionGroups.Documentation, PlainText(FeaturesResources.RepresentsAnObjectWhoseOperations)); } private void AddDescriptionForNamedType(INamedTypeSymbol symbol) { if (symbol.IsAwaitable(_semanticModel, _position)) { AddAwaitablePrefix(); } var token = _semanticModel.SyntaxTree.GetTouchingToken(_position, this.CancellationToken); if (token != default(SyntaxToken)) { var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>(); if (syntaxFactsService.IsAwaitKeyword(token)) { AddPrefixTextForAwaitKeyword(); if (symbol.SpecialType == SpecialType.System_Void) { AddTextForSystemVoid(); return; } } } if (symbol.TypeKind == TypeKind.Delegate) { var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol.OriginalDefinition, style)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle)); } if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol)) { var allTypeParameters = symbol.GetAllTypeParameters().ToList(); var allTypeArguments = symbol.GetAllTypeArguments().ToList(); AddTypeParameterMapPart(allTypeParameters, allTypeArguments); } } private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol) { var typeArguments = symbol.GetAllTypeArguments().ToList(); var typeParameters = symbol.GetAllTypeParameters().ToList(); for (int i = 0; i < typeArguments.Count; i++) { var typeArgument = typeArguments[i]; var typeParameter = typeParameters[i]; if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name) { continue; } return false; } return true; } private void AddDescriptionForNamespace(INamespaceSymbol symbol) { if (symbol.IsGlobalNamespace) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol, s_globalNamespaceStyle)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol, s_descriptionStyle)); } } private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol) { var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false); // Don't bother showing disambiguating text for enum members. The icon displayed // on Quick Info should be enough. if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum) { AddToGroup(SymbolDescriptionGroups.MainDescription, parts); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.Constant) : Description(FeaturesResources.Field), parts); } } private async Task<IEnumerable<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts; } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol) { var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.LocalConstant) : Description(FeaturesResources.LocalVariable), parts); } private async Task<IEnumerable<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts; } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private void AddDescriptionForLabel(ILabelSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.Label), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.RangeVariable), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForMethod(IMethodSymbol method) { // TODO : show duplicated member case // TODO : a way to check whether it is a member call off dynamic type? var awaitable = method.IsAwaitable(_semanticModel, _position); var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension; if (awaitable && extension) { AddAwaitableExtensionPrefix(); } else if (awaitable) { AddAwaitablePrefix(); } else if (extension) { AddExtensionPrefix(); } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat)); if (awaitable) { AddAwaitableUsageText(method, _semanticModel, _position); } } protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position); private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol) { IEnumerable<SymbolDisplayPart> initializerParts; if (symbol.IsOptional) { initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.Parameter), parts); return; } } AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.Parameter), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } protected virtual void AddDescriptionForProperty(IPropertySymbol symbol) { if (symbol.IsIndexer) { // TODO : show duplicated member case // TODO : a way to check whether it is a member call off dynamic type? AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); return; } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); } private void AddDescriptionForArbitrarySymbol(ISymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol)); } private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol) { Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref); AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol), Space(), PlainText(FeaturesResources.In), Space(), ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat)); } private void AddOverloadCountPart( ImmutableArray<ISymbol> symbolGroup) { var count = GetOverloadCount(symbolGroup); if (count >= 1) { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation("("), Punctuation("+"), Space(), PlainText(count.ToString()), Space(), count == 1 ? PlainText(FeaturesResources.Overload) : PlainText(FeaturesResources.Overloads), Punctuation(")")); } } private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup) { return symbolGroup.Select(s => s.OriginalDefinition) .Where(s => !s.Equals(symbolGroup.First().OriginalDefinition)) .Where(s => s is IMethodSymbol || s.IsIndexer()) .Count(); } protected void AddTypeParameterMapPart( List<ITypeParameterSymbol> typeParameters, List<ITypeSymbol> typeArguments) { var parts = new List<SymbolDisplayPart>(); var count = typeParameters.Count; for (int i = 0; i < count; i++) { parts.AddRange(TypeParameterName(typeParameters[i].Name)); parts.AddRange(Space()); parts.AddRange(PlainText(FeaturesResources.Is)); parts.AddRange(Space()); parts.AddRange(ToMinimalDisplayParts(typeArguments[i])); if (i < count - 1) { parts.AddRange(LineBreak()); } } AddToGroup(SymbolDescriptionGroups.TypeParameterMap, parts); } protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray) { AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray); } protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray) { var partsList = partsArray.Flatten().ToList(); if (partsList.Count > 0) { IList<SymbolDisplayPart> existingParts; if (!_groupMap.TryGetValue(group, out existingParts)) { existingParts = new List<SymbolDisplayPart>(); _groupMap.Add(group, existingParts); } existingParts.AddRange(partsList); } } private IEnumerable<SymbolDisplayPart> Description(string description) { return Punctuation("(") .Concat(PlainText(description)) .Concat(Punctuation(")")) .Concat(Space()); } protected IEnumerable<SymbolDisplayPart> Keyword(string text) { return Part(SymbolDisplayPartKind.Keyword, text); } protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1) { for (int i = 0; i < count; i++) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n"); } } protected IEnumerable<SymbolDisplayPart> PlainText(string text) { return Part(SymbolDisplayPartKind.Text, text); } protected IEnumerable<SymbolDisplayPart> Punctuation(string text) { return Part(SymbolDisplayPartKind.Punctuation, text); } protected IEnumerable<SymbolDisplayPart> Space(int count = 1) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count)); } protected IEnumerable<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { format = format ?? MinimallyQualifiedFormat; return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format); } protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { return _displayService.ToDisplayParts(symbol, format); } private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text) { yield return new SymbolDisplayPart(kind, symbol, text); } private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text) { return Part(kind, null, text); } private IEnumerable<SymbolDisplayPart> TypeParameterName(string text) { return Part(SymbolDisplayPartKind.TypeParameterName, text); } protected IEnumerable<SymbolDisplayPart> ConvertClassifications(SourceText text, IEnumerable<ClassifiedSpan> classifications) { var parts = new List<SymbolDisplayPart>(); ClassifiedSpan? lastSpan = null; foreach (var span in classifications) { // If there is space between this span and the last one, then add a space. if (lastSpan != null && lastSpan.Value.TextSpan.End != span.TextSpan.Start) { parts.AddRange(Space()); } var kind = GetClassificationKind(span.ClassificationType); if (kind != null) { parts.Add(new SymbolDisplayPart(kind.Value, null, text.ToString(span.TextSpan))); lastSpan = span; } } return parts; } private SymbolDisplayPartKind? GetClassificationKind(string type) { switch (type) { default: return null; case ClassificationTypeNames.Identifier: return SymbolDisplayPartKind.Text; case ClassificationTypeNames.Keyword: return SymbolDisplayPartKind.Keyword; case ClassificationTypeNames.NumericLiteral: return SymbolDisplayPartKind.NumericLiteral; case ClassificationTypeNames.StringLiteral: return SymbolDisplayPartKind.StringLiteral; case ClassificationTypeNames.WhiteSpace: return SymbolDisplayPartKind.Space; case ClassificationTypeNames.Operator: return SymbolDisplayPartKind.Operator; case ClassificationTypeNames.Punctuation: return SymbolDisplayPartKind.Punctuation; case ClassificationTypeNames.ClassName: return SymbolDisplayPartKind.ClassName; case ClassificationTypeNames.StructName: return SymbolDisplayPartKind.StructName; case ClassificationTypeNames.InterfaceName: return SymbolDisplayPartKind.InterfaceName; case ClassificationTypeNames.DelegateName: return SymbolDisplayPartKind.DelegateName; case ClassificationTypeNames.EnumName: return SymbolDisplayPartKind.EnumName; case ClassificationTypeNames.TypeParameterName: return SymbolDisplayPartKind.TypeParameterName; case ClassificationTypeNames.ModuleName: return SymbolDisplayPartKind.ModuleName; case ClassificationTypeNames.VerbatimStringLiteral: return SymbolDisplayPartKind.StringLiteral; } } } } }
#region File Description //----------------------------------------------------------------------------- // PrimitiveBatch.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Input; #endregion namespace XNA_Library { // PrimitiveBatch is a class that handles efficient rendering automatically for its // users, in a similar way to SpriteBatch. PrimitiveBatch can render lines, points, // and triangles to the screen. In this sample, it is used to draw a spacewars // retro scene. public class PrimitiveBatch : IDisposable { #region Constants and Fields // this constant controls how large the vertices buffer is. Larger buffers will // require flushing less often, which can increase performance. However, having // buffer that is unnecessarily large will waste memory. const int DefaultBufferSize = 500; // a block of vertices that calling AddVertex will fill. Flush will draw using // this array, and will determine how many primitives to draw from // positionInBuffer. VertexPositionColor[] vertices = new VertexPositionColor[DefaultBufferSize]; // keeps track of how many vertices have been added. this value increases until // we run out of space in the buffer, at which time Flush is automatically // called. int positionInBuffer = 0; // a basic effect, which contains the shaders that we will use to draw our // primitives. BasicEffect basicEffect; // the device that we will issue draw calls to. GraphicsDevice device; // this value is set by Begin, and is the type of primitives that we are // drawing. PrimitiveType primitiveType; // how many verts does each of these primitives take up? points are 1, // lines are 2, and triangles are 3. int numVertsPerPrimitive; // hasBegun is flipped to true once Begin is called, and is used to make // sure users don't call End before Begin is called. bool hasBegun = false; bool isDisposed = false; #endregion // the constructor creates a new PrimitiveBatch and sets up all of the internals // that PrimitiveBatch will need. public PrimitiveBatch(GraphicsDevice graphicsDevice) { if (graphicsDevice == null) { throw new ArgumentNullException("graphicsDevice"); } device = graphicsDevice; // set up a new basic effect, and enable vertex colors. basicEffect = new BasicEffect(graphicsDevice); basicEffect.VertexColorEnabled = true; // projection uses CreateOrthographicOffCenter to create 2d projection // matrix with 0,0 in the upper left. basicEffect.Projection = Matrix.CreateOrthographicOffCenter (0, graphicsDevice.Viewport.Width, graphicsDevice.Viewport.Height, 0, 0, 1); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && !isDisposed) { if (basicEffect != null) basicEffect.Dispose(); isDisposed = true; } } // Begin is called to tell the PrimitiveBatch what kind of primitives will be // drawn, and to prepare the graphics card to render those primitives. public void Begin(PrimitiveType primitiveType) { if (hasBegun) { throw new InvalidOperationException ("End must be called before Begin can be called again."); } // these three types reuse vertices, so we can't flush properly without more // complex logic. Since that's a bit too complicated for this sample, we'll // simply disallow them. if (primitiveType == PrimitiveType.LineStrip || primitiveType == PrimitiveType.TriangleStrip) { throw new NotSupportedException ("The specified primitiveType is not supported by PrimitiveBatch."); } this.primitiveType = primitiveType; // how many verts will each of these primitives require? this.numVertsPerPrimitive = NumVertsPerPrimitive(primitiveType); //tell our basic effect to begin. basicEffect.CurrentTechnique.Passes[0].Apply(); // flip the error checking boolean. It's now ok to call AddVertex, Flush, // and End. hasBegun = true; } // AddVertex is called to add another vertex to be rendered. To draw a point, // AddVertex must be called once. for lines, twice, and for triangles 3 times. // this function can only be called once begin has been called. // if there is not enough room in the vertices buffer, Flush is called // automatically. public void AddVertex(Vector2 vertex, Color color) { if (!hasBegun) { throw new InvalidOperationException ("Begin must be called before AddVertex can be called."); } // are we starting a new primitive? if so, and there will not be enough room // for a whole primitive, flush. bool newPrimitive = ((positionInBuffer % numVertsPerPrimitive) == 0); if (newPrimitive && (positionInBuffer + numVertsPerPrimitive) >= vertices.Length) { Flush(); } // once we know there's enough room, set the vertex in the buffer, // and increase position. vertices[positionInBuffer].Position = new Vector3(vertex, 0); vertices[positionInBuffer].Color = color; positionInBuffer++; } // End is called once all the primitives have been drawn using AddVertex. // it will call Flush to actually submit the draw call to the graphics card, and // then tell the basic effect to end. public void End() { if (!hasBegun) { throw new InvalidOperationException ("Begin must be called before End can be called."); } // Draw whatever the user wanted us to draw Flush(); hasBegun = false; } // Flush is called to issue the draw call to the graphics card. Once the draw // call is made, positionInBuffer is reset, so that AddVertex can start over // at the beginning. End will call this to draw the primitives that the user // requested, and AddVertex will call this if there is not enough room in the // buffer. private void Flush() { if (!hasBegun) { throw new InvalidOperationException ("Begin must be called before Flush can be called."); } // no work to do if (positionInBuffer == 0) { return; } // how many primitives will we draw? int primitiveCount = positionInBuffer / numVertsPerPrimitive; // submit the draw call to the graphics card device.DrawUserPrimitives<VertexPositionColor>(primitiveType, vertices, 0, primitiveCount); // now that we've drawn, it's ok to reset positionInBuffer back to zero, // and write over any vertices that may have been set previously. positionInBuffer = 0; } #region Helper functions // NumVertsPerPrimitive is a boring helper function that tells how many vertices // it will take to draw each kind of primitive. static private int NumVertsPerPrimitive(PrimitiveType primitive) { int numVertsPerPrimitive; switch (primitive) { case PrimitiveType.LineList: numVertsPerPrimitive = 2; break; case PrimitiveType.TriangleList: numVertsPerPrimitive = 3; break; default: throw new InvalidOperationException("primitive is not valid"); } return numVertsPerPrimitive; } #endregion } }
// 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.Text; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// A specialization of the ConsoleLogger that logs to a file instead of the console. /// The output in terms of what is written and how it looks is identical. For example you can /// log verbosely to a file using the FileLogger while simultaneously logging only high priority events /// to the console using a ConsoleLogger. /// </summary> /// <remarks> /// It's unfortunate that this is derived from ConsoleLogger, which is itself a facade; it makes things more /// complex -- for example, there is parameter parsing in this class, plus in BaseConsoleLogger. However we have /// to derive FileLogger from ConsoleLogger because it shipped that way in Whidbey. /// </remarks> public class FileLogger : ConsoleLogger { #region Constructors /// <summary> /// Default constructor. /// </summary> /// <owner>KieranMo</owner> public FileLogger() : base(LoggerVerbosity.Normal) { this.WriteHandler = new WriteHandler(Write); } #endregion /// <summary> /// Signs up the console file logger for all build events. /// This is the backward-compatible overload. /// </summary> /// <param name="eventSource">Available events.</param> public override void Initialize(IEventSource eventSource) { ErrorUtilities.VerifyThrowArgumentNull(eventSource, nameof(eventSource)); eventSource.BuildFinished += FileLoggerBuildFinished; InitializeFileLogger(eventSource, 1); } private void FileLoggerBuildFinished(object sender, BuildFinishedEventArgs e) { fileWriter?.Flush(); } /// <summary> /// Creates new file for logging /// </summary> private void InitializeFileLogger(IEventSource eventSource, int nodeCount) { // Prepend the default setting of "forcenoalign": no alignment is needed as we're // writing to a file string parameters = Parameters; if (parameters != null) { Parameters = "FORCENOALIGN;" + parameters; } else { Parameters = "FORCENOALIGN;"; } this.ParseFileLoggerParameters(); // Finally, ask the base console logger class to initialize. It may // want to make decisions based on our verbosity, so we do this last. base.Initialize(eventSource, nodeCount); try { fileWriter = new StreamWriter(logFileName, append, encoding); // We set AutoFlush = true because some tasks generate Unhandled Exceptions // on foreign threads and MSBuild does not properly Shutdown in this case. // With AutoFlush set, we try to log everything we can in case Shutdown is // not called. Hopefully in the future the MSBuild Engine will properly // handle this case. See VSWhidbey 586850 for more information. fileWriter.AutoFlush = true; } catch (Exception e) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(e)) throw; string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", logFileName, e.Message); fileWriter?.Close(); throw new LoggerException(message,e.InnerException,errorCode, helpKeyword); } } /// <summary> /// Multiproc aware initialization /// </summary> public override void Initialize(IEventSource eventSource, int nodeCount) { InitializeFileLogger(eventSource, nodeCount); } /// <summary> /// The handler for the write delegate of the console logger we are deriving from. /// </summary> /// <owner>KieranMo</owner> /// <param name="text">The text to write to the log</param> private void Write(string text) { try { fileWriter.Write(text); } catch (Exception ex) // Catching Exception, but rethrowing unless it's a well-known exception. { if (ExceptionHandling.NotExpectedException(ex)) throw; string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, "InvalidFileLoggerFile", logFileName, ex.Message); fileWriter?.Close(); throw new LoggerException(message, ex.InnerException, errorCode, helpKeyword); } } /// <summary> /// Shutdown method implementation of ILogger - we need to flush and close our logfile. /// </summary> /// <owner>KieranMo</owner> public override void Shutdown() { try { // Do, or do not, there is no try. } finally { // Keep FxCop happy by closing in a Finally. fileWriter?.Close(); } } /// <summary> /// Parses out the logger parameters from the Parameters string. /// </summary> /// <owner>KieranMo</owner> private void ParseFileLoggerParameters() { if (this.Parameters != null) { string[] parameterComponents = this.Parameters.Split(fileLoggerParameterDelimiters); for (int param = 0; param < parameterComponents.Length; param++) { if (parameterComponents[param].Length > 0) { string[] parameterAndValue = parameterComponents[param].Split(fileLoggerParameterValueSplitCharacter); if (parameterAndValue.Length > 1) { ApplyFileLoggerParameter(parameterAndValue[0], parameterAndValue[1]); } else { ApplyFileLoggerParameter(parameterAndValue[0], null); } } } } } /// <summary> /// Apply a parameter parsed by the file logger. /// </summary> /// <owner>KieranMo</owner> private void ApplyFileLoggerParameter(string parameterName, string parameterValue) { switch (parameterName.ToUpperInvariant()) { case "LOGFILE": this.logFileName = parameterValue; break; case "APPEND": this.append = true; break; case "ENCODING": try { this.encoding = Encoding.GetEncoding(parameterValue); } catch (ArgumentException ex) { // Can't change strings at this point, so for now we are using the exception string // verbatim, and supplying a error code directly. // This should move into the .resx later. throw new LoggerException(ex.Message, ex.InnerException, "MSB4128", null); } break; default: // We will not error for unrecognized parameters, since someone may wish to // extend this class and call this base method before theirs. break; } } #region Private member data /// <summary> /// logFileName is the name of the log file that we will generate /// the default value is msbuild.log /// </summary> /// <owner>KieranMo</owner> private string logFileName = "msbuild.log"; /// <summary> /// fileWriter is the stream that has been opened on our log file. /// </summary> /// <owner>KieranMo</owner> private StreamWriter fileWriter = null; /// <summary> /// Whether the logger should append to any existing file. /// Default is to overwrite. /// </summary> /// <owner>danmose</owner> private bool append = false; /// <summary> /// Encoding for the output. Defaults to ANSI. /// </summary> /// <owner>danmose</owner> private Encoding encoding = Encoding.Default; /// <summary> /// File logger parameters delimiters. /// </summary> private static readonly char[] fileLoggerParameterDelimiters = { ';' }; /// <summary> /// File logger parameter value split character. /// </summary> private static readonly char[] fileLoggerParameterValueSplitCharacter = { '=' }; #endregion } }
// Copyright (c) 2017 Jean Ressouche @SouchProd. All rights reserved. // https://github.com/souchprod/SouchProd.EntityFrameworkCore.Firebird // This code inherit from the .Net Foundation Entity Core repository (Apache licence) // and from the Pomelo Foundation Mysql provider repository (MIT licence). // Licensed under the MIT. See LICENSE in the project root for license information. using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Metadata { public class FbPropertyAnnotations : RelationalPropertyAnnotations, IFirebirdPropertyAnnotations { public FbPropertyAnnotations([NotNull] IProperty property) : base(property) { } protected FbPropertyAnnotations([NotNull] RelationalAnnotations annotations) : base(annotations) { } public virtual FirebirdValueGenerationStrategy? ValueGenerationStrategy { get { return GetFirebirdValueGenerationStrategy(fallbackToModel: true); } [param: CanBeNull] set { SetValueGenerationStrategy(value); } } public virtual FirebirdValueGenerationStrategy? GetFirebirdValueGenerationStrategy(bool fallbackToModel) { if (GetDefaultValue(false) != null || GetDefaultValueSql(false) != null || GetComputedColumnSql(false) != null) { return null; } var value = (FirebirdValueGenerationStrategy?)Annotations.Metadata[FbAnnotationNames.ValueGenerationStrategy]; if (value != null) { return value; } var relationalProperty = Property.Relational(); if (!fallbackToModel || Property.ValueGenerated != ValueGenerated.OnAdd || relationalProperty.DefaultValue != null || relationalProperty.DefaultValueSql != null || relationalProperty.ComputedColumnSql != null) { return null; } var modelStrategy = Property.DeclaringEntityType.Model.Firebird().ValueGenerationStrategy; if (modelStrategy == FirebirdValueGenerationStrategy.IdentityColumn && IsCompatibleIdentityColumn(Property.ClrType)) { return FirebirdValueGenerationStrategy.IdentityColumn; } if (modelStrategy == FirebirdValueGenerationStrategy.ComputedColumn && IsCompatibleIdentityColumn(Property.ClrType)) { return FirebirdValueGenerationStrategy.ComputedColumn; } return null; } protected virtual bool SetValueGenerationStrategy(FirebirdValueGenerationStrategy? value) { if (value != null) { var propertyType = Property.ClrType; if (value == FirebirdValueGenerationStrategy.IdentityColumn && !IsCompatibleIdentityColumn(propertyType)) { if (ShouldThrowOnInvalidConfiguration) { throw new ArgumentException( Property.Name + " " + Property.DeclaringEntityType.DisplayName() + " " + propertyType.ShortDisplayName()); } return false; } } if (!CanSetValueGenerationStrategy(value)) { return false; } if (!ShouldThrowOnConflict && ValueGenerationStrategy != value && value != null) { ClearAllServerGeneratedValues(); } return Annotations.SetAnnotation(FbAnnotationNames.ValueGenerationStrategy, value); } protected virtual bool CanSetValueGenerationStrategy(FirebirdValueGenerationStrategy? value) { if (GetFirebirdValueGenerationStrategy(fallbackToModel: false) == value) { return true; } if (!Annotations.CanSetAnnotation(FbAnnotationNames.ValueGenerationStrategy, value)) { return false; } if (ShouldThrowOnConflict) { if (GetDefaultValue(false) != null) { throw new InvalidOperationException( RelationalStrings.ConflictingColumnServerGeneration(nameof(ValueGenerationStrategy), Property.Name, nameof(DefaultValue))); } if (GetDefaultValueSql(false) != null) { throw new InvalidOperationException( RelationalStrings.ConflictingColumnServerGeneration(nameof(ValueGenerationStrategy), Property.Name, nameof(DefaultValueSql))); } if (GetComputedColumnSql(false) != null) { throw new InvalidOperationException( RelationalStrings.ConflictingColumnServerGeneration(nameof(ValueGenerationStrategy), Property.Name, nameof(ComputedColumnSql))); } } else if (value != null && (!CanSetDefaultValue(null) || !CanSetDefaultValueSql(null) || !CanSetComputedColumnSql(null))) { return false; } return true; } protected override object GetDefaultValue(bool fallback) { if (fallback && ValueGenerationStrategy != null) { return null; } return base.GetDefaultValue(fallback); } protected override bool CanSetDefaultValue(object value) { if (ShouldThrowOnConflict) { if (ValueGenerationStrategy != null) { throw new InvalidOperationException( RelationalStrings.ConflictingColumnServerGeneration(nameof(DefaultValue), Property.Name, nameof(ValueGenerationStrategy))); } } else if (value != null && !CanSetValueGenerationStrategy(null)) { return false; } return base.CanSetDefaultValue(value); } protected override string GetDefaultValueSql(bool fallback) { if (fallback && ValueGenerationStrategy != null) { return null; } return base.GetDefaultValueSql(fallback); } protected override bool CanSetDefaultValueSql(string value) { if (ShouldThrowOnConflict) { if (ValueGenerationStrategy != null) { throw new InvalidOperationException( RelationalStrings.ConflictingColumnServerGeneration(nameof(DefaultValueSql), Property.Name, nameof(ValueGenerationStrategy))); } } else if (value != null && !CanSetValueGenerationStrategy(null)) { return false; } return base.CanSetDefaultValueSql(value); } protected override string GetComputedColumnSql(bool fallback) { if (fallback && ValueGenerationStrategy != null) { return null; } return base.GetComputedColumnSql(fallback); } protected override bool CanSetComputedColumnSql(string value) { if (ShouldThrowOnConflict) { if (ValueGenerationStrategy != null) { throw new InvalidOperationException( RelationalStrings.ConflictingColumnServerGeneration(nameof(ComputedColumnSql), Property.Name, nameof(ValueGenerationStrategy))); } } else if (value != null && !CanSetValueGenerationStrategy(null)) { return false; } return base.CanSetComputedColumnSql(value); } protected override void ClearAllServerGeneratedValues() { SetValueGenerationStrategy(null); base.ClearAllServerGeneratedValues(); } private static bool IsCompatibleIdentityColumn(Type type) => type.IsInteger() || type == typeof(DateTime); } }
#if UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Collections; public class SerializedSetting<T> { private T m_rValue = default( T ); private bool m_bIsDefined = false; private SerializedProperty m_rSerializedProperty = null; public bool IsDefined { get { return m_bIsDefined; } } public bool HasMultipleDifferentValues { get { return m_bIsDefined == false && m_rSerializedProperty != null && m_rSerializedProperty.hasMultipleDifferentValues; } } public T Value { get { return m_bIsDefined ? m_rValue : this.GetSerializedValue( ); } set { m_rValue = value; m_bIsDefined = true; } } public SerializedSetting( SerializedObject a_rSerializedObject, string a_rPropertyPath ) { m_rSerializedProperty = a_rSerializedObject.FindProperty( a_rPropertyPath ); if( m_rSerializedProperty != null ) { m_rValue = this.GetSerializedValue( ); } else { this.NoSerializedPropertyAtGivenPathWarning( a_rPropertyPath ); } } public void Apply( ) { if( m_bIsDefined && m_rSerializedProperty != null ) { m_bIsDefined = false; switch( m_rSerializedProperty.propertyType ) { case SerializedPropertyType.Boolean: { m_rSerializedProperty.boolValue = (bool) System.Convert.ChangeType( m_rValue, typeof( bool ) ); } break; case SerializedPropertyType.ArraySize: case SerializedPropertyType.Integer: { m_rSerializedProperty.intValue = (int) System.Convert.ChangeType( m_rValue, typeof( int ) ); } break; case SerializedPropertyType.Float: { m_rSerializedProperty.floatValue = (float) System.Convert.ChangeType( m_rValue, typeof( float ) ); } break; case SerializedPropertyType.String: { m_rSerializedProperty.stringValue = (string) System.Convert.ChangeType( m_rValue, typeof( string ) ); } break; case SerializedPropertyType.Enum: { //m_rSerializedProperty.enumValueIndex = (int) System.Convert.ChangeType( m_rValue, typeof( int ) ); m_rSerializedProperty.intValue = (int) System.Convert.ChangeType( m_rValue, typeof( int ) ); } break; case SerializedPropertyType.Generic: case SerializedPropertyType.LayerMask: case SerializedPropertyType.ObjectReference: { //m_rSerializedProperty.objectReferenceValue = (Object) System.Convert.ChangeType( m_rValue, typeof( Object ) ); m_rSerializedProperty.objectReferenceValue = m_rValue as Object; } break; case SerializedPropertyType.Vector2: { // BugPatch : setting the property to the defaul value don't dirty this property even if the property has multiple value if(m_rSerializedProperty.hasMultipleDifferentValues) { // Set to an arbitrary different value before applying the new value m_rSerializedProperty.vector2Value = m_rSerializedProperty.vector2Value + Vector2.one; } m_rSerializedProperty.vector2Value = (Vector2) System.Convert.ChangeType( m_rValue, typeof( Vector2 ) ); } break; case SerializedPropertyType.Vector3: { m_rSerializedProperty.vector3Value = (Vector3) System.Convert.ChangeType( m_rValue, typeof( Vector3 ) ); } break; case SerializedPropertyType.Color: { m_rSerializedProperty.colorValue = (Color) System.Convert.ChangeType( m_rValue, typeof( Color ) ); } break; case SerializedPropertyType.Rect: { m_rSerializedProperty.rectValue = (Rect) System.Convert.ChangeType( m_rValue, typeof( Rect ) ); } break; case SerializedPropertyType.Bounds: { m_rSerializedProperty.boundsValue = (Bounds) System.Convert.ChangeType( m_rValue, typeof( Bounds ) ); } break; case SerializedPropertyType.AnimationCurve: { m_rSerializedProperty.animationCurveValue = (AnimationCurve) System.Convert.ChangeType( m_rValue, typeof( AnimationCurve ) ); } break; default: { m_bIsDefined = true; this.UnsupportedSerializedPropertyTypeError( ); } break; } } else if( m_rSerializedProperty == null ) { this.NoSerializedPropertyAtGivenPathWarning( ); } } public void Revert( ) { m_bIsDefined = false; m_rValue = GetSerializedValue( ); } private T GetSerializedValue( ) { if( m_rSerializedProperty == null || m_rSerializedProperty.hasMultipleDifferentValues ) { return default( T ); } else { switch( m_rSerializedProperty.propertyType ) { case SerializedPropertyType.Boolean: { return (T) System.Convert.ChangeType( m_rSerializedProperty.boolValue, typeof( T ) ); } //break; case SerializedPropertyType.ArraySize: case SerializedPropertyType.Integer: { return (T) System.Convert.ChangeType( m_rSerializedProperty.intValue, typeof( T ) ); } //break; case SerializedPropertyType.Float: { return (T) System.Convert.ChangeType( m_rSerializedProperty.floatValue, typeof( T ) ); } //break; case SerializedPropertyType.String: { return (T) System.Convert.ChangeType( m_rSerializedProperty.stringValue, typeof( T ) ); } //break; case SerializedPropertyType.Enum: { return (T) System.Enum.ToObject( typeof( T ), m_rSerializedProperty.intValue ); //return (T) System.Enum.ToObject( typeof( T ), m_rSerializedProperty.enumValueIndex ); //return (T) System.Convert.ChangeType( m_rSerializedProperty.enumValueIndex, typeof( T ) ); } //break; case SerializedPropertyType.LayerMask: case SerializedPropertyType.ObjectReference: case SerializedPropertyType.Generic: { return (T) System.Convert.ChangeType( m_rSerializedProperty.objectReferenceValue, typeof( T ) ); } //break; case SerializedPropertyType.Vector2: { return (T) System.Convert.ChangeType( m_rSerializedProperty.vector2Value, typeof( T ) ); } //break; case SerializedPropertyType.Vector3: { return (T) System.Convert.ChangeType( m_rSerializedProperty.vector3Value, typeof( T ) ); } //break; case SerializedPropertyType.Color: { return (T) System.Convert.ChangeType( m_rSerializedProperty.colorValue, typeof( T ) ); } //break; case SerializedPropertyType.Rect: { return (T) System.Convert.ChangeType( m_rSerializedProperty.rectValue, typeof( T ) ); } //break; case SerializedPropertyType.Bounds: { return (T) System.Convert.ChangeType( m_rSerializedProperty.boundsValue, typeof( T ) ); } //break; case SerializedPropertyType.AnimationCurve: { return (T) System.Convert.ChangeType( m_rSerializedProperty.animationCurveValue, typeof( T ) ); } //break; default: { this.UnsupportedSerializedPropertyTypeError( ); return default( T ); } //break; } } } private void UnsupportedSerializedPropertyTypeError( ) { Debug.LogError( "Unsupported/undocumented serialized property of type \"" + m_rSerializedProperty.type + "\" ("+ m_rSerializedProperty.propertyType.ToString( ) + ")" ); } private void NoSerializedPropertyAtGivenPathWarning( string a_rPropertyPath = null ) { Debug.LogWarning( "No serialized property at given path" + ( a_rPropertyPath != null ? ( " \"" + a_rPropertyPath + "\"" ) : null ) ); } } #endif
using System.IO; namespace Lucene.Net.Search.Payloads { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using Similarity = Lucene.Net.Search.Similarities.Similarity; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using SpanScorer = Lucene.Net.Search.Spans.SpanScorer; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using SpanWeight = Lucene.Net.Search.Spans.SpanWeight; using Term = Lucene.Net.Index.Term; using TermSpans = Lucene.Net.Search.Spans.TermSpans; /// <summary> /// This class is very similar to /// <see cref="Lucene.Net.Search.Spans.SpanTermQuery"/> except that it factors /// in the value of the payload located at each of the positions where the /// <see cref="Lucene.Net.Index.Term"/> occurs. /// <para/> /// NOTE: In order to take advantage of this with the default scoring implementation /// (<see cref="Similarities.DefaultSimilarity"/>), you must override <see cref="Similarities.DefaultSimilarity.ScorePayload(int, int, int, BytesRef)"/>, /// which returns 1 by default. /// <para/> /// Payload scores are aggregated using a pluggable <see cref="PayloadFunction"/>. </summary> /// <seealso cref="Lucene.Net.Search.Similarities.Similarity.SimScorer.ComputePayloadFactor(int, int, int, BytesRef)"/> public class PayloadTermQuery : SpanTermQuery { protected PayloadFunction m_function; private bool includeSpanScore; public PayloadTermQuery(Term term, PayloadFunction function) : this(term, function, true) { } public PayloadTermQuery(Term term, PayloadFunction function, bool includeSpanScore) : base(term) { this.m_function = function; this.includeSpanScore = includeSpanScore; } public override Weight CreateWeight(IndexSearcher searcher) { return new PayloadTermWeight(this, this, searcher); } protected class PayloadTermWeight : SpanWeight { private readonly PayloadTermQuery outerInstance; public PayloadTermWeight(PayloadTermQuery outerInstance, PayloadTermQuery query, IndexSearcher searcher) : base(query, searcher) { this.outerInstance = outerInstance; } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { return new PayloadTermSpanScorer(this, (TermSpans)m_query.GetSpans(context, acceptDocs, m_termContexts), this, m_similarity.GetSimScorer(m_stats, context)); } protected class PayloadTermSpanScorer : SpanScorer { private readonly PayloadTermQuery.PayloadTermWeight outerInstance; protected BytesRef m_payload; protected internal float m_payloadScore; protected internal int m_payloadsSeen; internal readonly TermSpans termSpans; public PayloadTermSpanScorer(PayloadTermQuery.PayloadTermWeight outerInstance, TermSpans spans, Weight weight, Similarity.SimScorer docScorer) : base(spans, weight, docScorer) { this.outerInstance = outerInstance; termSpans = spans; } protected override bool SetFreqCurrentDoc() { if (!m_more) { return false; } m_doc = m_spans.Doc; m_freq = 0.0f; m_numMatches = 0; m_payloadScore = 0; m_payloadsSeen = 0; while (m_more && m_doc == m_spans.Doc) { int matchLength = m_spans.End - m_spans.Start; m_freq += m_docScorer.ComputeSlopFactor(matchLength); m_numMatches++; ProcessPayload(outerInstance.m_similarity); m_more = m_spans.Next(); // this moves positions to the next match in this // document } return m_more || (m_freq != 0); } protected internal virtual void ProcessPayload(Similarity similarity) { if (termSpans.IsPayloadAvailable) { DocsAndPositionsEnum postings = termSpans.Postings; m_payload = postings.GetPayload(); if (m_payload != null) { m_payloadScore = outerInstance.outerInstance.m_function.CurrentScore(m_doc, outerInstance.outerInstance.Term.Field, m_spans.Start, m_spans.End, m_payloadsSeen, m_payloadScore, m_docScorer.ComputePayloadFactor(m_doc, m_spans.Start, m_spans.End, m_payload)); } else { m_payloadScore = outerInstance.outerInstance.m_function.CurrentScore(m_doc, outerInstance.outerInstance.Term.Field, m_spans.Start, m_spans.End, m_payloadsSeen, m_payloadScore, 1F); } m_payloadsSeen++; } else { // zero out the payload? } } /// /// <returns> <see cref="GetSpanScore()"/> * <see cref="GetPayloadScore()"/> </returns> /// <exception cref="IOException"> if there is a low-level I/O error </exception> public override float GetScore() { return outerInstance.outerInstance.includeSpanScore ? GetSpanScore() * GetPayloadScore() : GetPayloadScore(); } /// <summary> /// Returns the <see cref="SpanScorer"/> score only. /// <para/> /// Should not be overridden without good cause! /// </summary> /// <returns> the score for just the Span part w/o the payload </returns> /// <exception cref="IOException"> if there is a low-level I/O error /// </exception> /// <seealso cref="GetScore()"/> protected internal virtual float GetSpanScore() { return base.GetScore(); } /// <summary> /// The score for the payload /// </summary> /// <returns> The score, as calculated by /// <see cref="PayloadFunction.DocScore(int, string, int, float)"/> </returns> protected internal virtual float GetPayloadScore() { return outerInstance.outerInstance.m_function.DocScore(m_doc, outerInstance.outerInstance.Term.Field, m_payloadsSeen, m_payloadScore); } } public override Explanation Explain(AtomicReaderContext context, int doc) { PayloadTermSpanScorer scorer = (PayloadTermSpanScorer)GetScorer(context, (context.AtomicReader).LiveDocs); if (scorer != null) { int newDoc = scorer.Advance(doc); if (newDoc == doc) { float freq = scorer.SloppyFreq; Similarity.SimScorer docScorer = m_similarity.GetSimScorer(m_stats, context); Explanation expl = new Explanation(); expl.Description = "weight(" + Query + " in " + doc + ") [" + m_similarity.GetType().Name + "], result of:"; Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "phraseFreq=" + freq)); expl.AddDetail(scoreExplanation); expl.Value = scoreExplanation.Value; // now the payloads part // QUESTION: Is there a way to avoid this skipTo call? We need to know // whether to load the payload or not // GSI: I suppose we could toString the payload, but I don't think that // would be a good idea string field = ((SpanQuery)Query).Field; Explanation payloadExpl = outerInstance.m_function.Explain(doc, field, scorer.m_payloadsSeen, scorer.m_payloadScore); payloadExpl.Value = scorer.GetPayloadScore(); // combined ComplexExplanation result = new ComplexExplanation(); if (outerInstance.includeSpanScore) { result.AddDetail(expl); result.AddDetail(payloadExpl); result.Value = expl.Value * payloadExpl.Value; result.Description = "btq, product of:"; } else { result.AddDetail(payloadExpl); result.Value = payloadExpl.Value; result.Description = "btq(includeSpanScore=false), result of:"; } result.Match = true; // LUCENE-1303 return result; } } return new ComplexExplanation(false, 0.0f, "no matching term"); } } public override int GetHashCode() { const int prime = 31; int result = base.GetHashCode(); result = prime * result + ((m_function == null) ? 0 : m_function.GetHashCode()); result = prime * result + (includeSpanScore ? 1231 : 1237); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!base.Equals(obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } PayloadTermQuery other = (PayloadTermQuery)obj; if (m_function == null) { if (other.m_function != null) { return false; } } else if (!m_function.Equals(other.m_function)) { return false; } if (includeSpanScore != other.includeSpanScore) { return false; } return true; } } }
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; // <auto-generated /> namespace Southwind{ /// <summary> /// Strongly-typed collection for the SalesByCategory class. /// </summary> [Serializable] public partial class SalesByCategoryCollection : ReadOnlyList<SalesByCategory, SalesByCategoryCollection> { public SalesByCategoryCollection() {} } /// <summary> /// This is Read-only wrapper class for the sales by category view. /// </summary> [Serializable] public partial class SalesByCategory : ReadOnlyRecord<SalesByCategory>, 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("sales by category", TableType.View, DataService.GetInstance("Southwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema); colvarCategoryID.ColumnName = "CategoryID"; colvarCategoryID.DataType = DbType.Int32; colvarCategoryID.MaxLength = 10; colvarCategoryID.AutoIncrement = false; colvarCategoryID.IsNullable = false; colvarCategoryID.IsPrimaryKey = false; colvarCategoryID.IsForeignKey = false; colvarCategoryID.IsReadOnly = false; schema.Columns.Add(colvarCategoryID); TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarProductName = new TableSchema.TableColumn(schema); colvarProductName.ColumnName = "ProductName"; colvarProductName.DataType = DbType.String; colvarProductName.MaxLength = 40; colvarProductName.AutoIncrement = false; colvarProductName.IsNullable = false; colvarProductName.IsPrimaryKey = false; colvarProductName.IsForeignKey = false; colvarProductName.IsReadOnly = false; schema.Columns.Add(colvarProductName); TableSchema.TableColumn colvarProductSales = new TableSchema.TableColumn(schema); colvarProductSales.ColumnName = "ProductSales"; colvarProductSales.DataType = DbType.Decimal; colvarProductSales.MaxLength = 0; colvarProductSales.AutoIncrement = false; colvarProductSales.IsNullable = true; colvarProductSales.IsPrimaryKey = false; colvarProductSales.IsForeignKey = false; colvarProductSales.IsReadOnly = false; schema.Columns.Add(colvarProductSales); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Southwind"].AddSchema("sales by category",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public SalesByCategory() { SetSQLProps(); SetDefaults(); MarkNew(); } public SalesByCategory(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public SalesByCategory(object keyID) { SetSQLProps(); LoadByKey(keyID); } public SalesByCategory(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("CategoryID")] [Bindable(true)] public int CategoryID { get { return GetColumnValue<int>("CategoryID"); } set { SetColumnValue("CategoryID", value); } } [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>("CategoryName"); } set { SetColumnValue("CategoryName", value); } } [XmlAttribute("ProductName")] [Bindable(true)] public string ProductName { get { return GetColumnValue<string>("ProductName"); } set { SetColumnValue("ProductName", value); } } [XmlAttribute("ProductSales")] [Bindable(true)] public decimal? ProductSales { get { return GetColumnValue<decimal?>("ProductSales"); } set { SetColumnValue("ProductSales", value); } } #endregion #region Columns Struct public struct Columns { public static string CategoryID = @"CategoryID"; public static string CategoryName = @"CategoryName"; public static string ProductName = @"ProductName"; public static string ProductSales = @"ProductSales"; } #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 } }
using UnityEngine; using System.Collections.Generic; /// <summary> /// Adaptation of the standard MouseOrbit script to use the finger drag gesture to rotate the current object using /// the fingers/mouse around a target object /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/Camera/Orbit" )] public class TBOrbit : MonoBehaviour { public enum PanMode { Disabled, OneFinger, TwoFingers } /// <summary> /// The object to orbit around /// </summary> public Transform target; /// <summary> /// Initial camera distance to target /// </summary> public float initialDistance = 10.0f; /// <summary> /// Minimum distance between camera and target /// </summary> public float minDistance = 1.0f; /// <summary> /// Maximum distance between camera and target /// </summary> public float maxDistance = 30.0f; /// <summary> /// Affects horizontal rotation speed (in degrees per cm) /// </summary> public float yawSensitivity = 45.0f; /// <summary> /// Affects vertical rotation speed (in degrees per cm) /// </summary> public float pitchSensitivity = 45.0f; /// <summary> /// Keep yaw angle value between minYaw and maxYaw? /// </summary> public bool clampYawAngle = false; public float minYaw = -75; public float maxYaw = 75; /// <summary> /// Keep pitch angle value between minPitch and maxPitch? /// </summary> public bool clampPitchAngle = true; public float minPitch = -20; public float maxPitch = 80; /// <summary> /// Allow the user to affect the orbit distance using the pinch zoom gesture /// </summary> public bool allowPinchZoom = true; /// <summary> /// Affects pinch zoom speed /// </summary> public float pinchZoomSensitivity = 5.0f; /// <summary> /// Use smooth camera motions? /// </summary> public bool smoothMotion = true; public float smoothZoomSpeed = 5.0f; public float smoothOrbitSpeed = 10.0f; /// <summary> /// Two-Finger camera panning. /// Panning will apply an offset to the pivot/camera target point /// </summary> public bool allowPanning = false; public bool invertPanningDirections = false; public float panningSensitivity = 1.0f; public Transform panningPlane; // reference transform used to apply the panning translation (using panningPlane.right and panningPlane.up vectors) public bool smoothPanning = true; public float smoothPanningSpeed = 12.0f; // collision test public LayerMask collisionLayerMask; float distance = 10.0f; float yaw = 0; float pitch = 0; float idealDistance = 0; float idealYaw = 0; float idealPitch = 0; Vector3 idealPanOffset = Vector3.zero; Vector3 panOffset = Vector3.zero; PinchRecognizer pinchRecognizer; public float Distance { get { return distance; } } public float IdealDistance { get { return idealDistance; } set { idealDistance = Mathf.Clamp( value, minDistance, maxDistance ); } } public float Yaw { get { return yaw; } } public float IdealYaw { get { return idealYaw; } set { idealYaw = clampYawAngle ? ClampAngle( value, minYaw, maxYaw ) : value; } } public float Pitch { get { return pitch; } } public float IdealPitch { get { return idealPitch; } set { idealPitch = clampPitchAngle ? ClampAngle( value, minPitch, maxPitch ) : value; } } public Vector3 IdealPanOffset { get { return idealPanOffset; } set { idealPanOffset = value; } } public Vector3 PanOffset { get { return panOffset; } } void InstallGestureRecognizers() { List<GestureRecognizer> recogniers = new List<GestureRecognizer>( GetComponents<GestureRecognizer>() ); DragRecognizer drag = recogniers.Find( r => r.EventMessageName == "OnDrag" ) as DragRecognizer; DragRecognizer twoFingerDrag = recogniers.Find( r => r.EventMessageName == "OnTwoFingerDrag" ) as DragRecognizer; PinchRecognizer pinch = recogniers.Find( r => r.EventMessageName == "OnPinch" ) as PinchRecognizer; // check if we need to automatically add a screenraycaster if( OnlyRotateWhenDragStartsOnObject ) { ScreenRaycaster raycaster = gameObject.GetComponent<ScreenRaycaster>(); if( !raycaster ) raycaster = gameObject.AddComponent<ScreenRaycaster>(); } if( !drag ) { drag = gameObject.AddComponent<DragRecognizer>(); drag.RequiredFingerCount = 1; drag.IsExclusive = true; drag.MaxSimultaneousGestures = 1; drag.SendMessageToSelection = GestureRecognizer.SelectionType.None; } if( !pinch ) pinch = gameObject.AddComponent<PinchRecognizer>(); if( !twoFingerDrag ) { twoFingerDrag = gameObject.AddComponent<DragRecognizer>(); twoFingerDrag.RequiredFingerCount = 2; twoFingerDrag.IsExclusive = true; twoFingerDrag.MaxSimultaneousGestures = 1; twoFingerDrag.ApplySameDirectionConstraint = true; twoFingerDrag.EventMessageName = "OnTwoFingerDrag"; } } void Start() { InstallGestureRecognizers(); if( !panningPlane ) panningPlane = this.transform; Vector3 angles = transform.eulerAngles; distance = IdealDistance = initialDistance; yaw = IdealYaw = angles.y; pitch = IdealPitch = angles.x; // Make the rigid body not change rotation if( rigidbody ) rigidbody.freezeRotation = true; Apply(); } #region Gesture Event Messages float nextDragTime = 0; public bool OnlyRotateWhenDragStartsOnObject = false; void OnDrag( DragGesture gesture ) { // don't rotate unless the drag started on our target object if( OnlyRotateWhenDragStartsOnObject ) { if( gesture.Phase == ContinuousGesturePhase.Started ) { if( !gesture.Recognizer.Raycaster ) { Debug.LogWarning( "The drag recognizer on " + gesture.Recognizer.name + " has no ScreenRaycaster component set. This will prevent OnlyRotateWhenDragStartsOnObject flag from working." ); OnlyRotateWhenDragStartsOnObject = false; return; } if( target && !target.collider ) { Debug.LogWarning( "The target object has no collider set. OnlyRotateWhenDragStartsOnObject won't work." ); OnlyRotateWhenDragStartsOnObject = false; return; } } if( !target || gesture.StartSelection != target.gameObject ) return; } // wait for drag cooldown timer to wear off // used to avoid dragging right after a pinch or pan, when lifting off one finger but the other one is still on screen if( Time.time < nextDragTime ) return; if( target ) { IdealYaw += gesture.DeltaMove.x.Centimeters() * yawSensitivity; IdealPitch -= gesture.DeltaMove.y.Centimeters() * pitchSensitivity; } } void OnPinch( PinchGesture gesture ) { if( allowPinchZoom ) { IdealDistance -= gesture.Delta.Centimeters() * pinchZoomSensitivity; nextDragTime = Time.time + 0.25f; } } void OnTwoFingerDrag( DragGesture gesture ) { if( allowPanning ) { Vector3 move = -panningSensitivity * ( panningPlane.right * gesture.DeltaMove.x.Centimeters() + panningPlane.up * gesture.DeltaMove.y.Centimeters() ); if( invertPanningDirections ) IdealPanOffset -= move; else IdealPanOffset += move; nextDragTime = Time.time + 0.25f; } } #endregion void Apply() { if( smoothMotion ) { distance = Mathf.Lerp( distance, IdealDistance, Time.deltaTime * smoothZoomSpeed ); yaw = Mathf.Lerp( yaw, IdealYaw, Time.deltaTime * smoothOrbitSpeed ); pitch = Mathf.LerpAngle( pitch, IdealPitch, Time.deltaTime * smoothOrbitSpeed ); } else { distance = IdealDistance; yaw = IdealYaw; pitch = IdealPitch; } if( smoothPanning ) panOffset = Vector3.Lerp( panOffset, idealPanOffset, Time.deltaTime * smoothPanningSpeed ); else panOffset = idealPanOffset; transform.rotation = Quaternion.Euler( pitch, yaw, 0 ); Vector3 lookAtPos = ( target.position + panOffset ); Vector3 desiredPos = lookAtPos - distance * transform.forward; if( collisionLayerMask != 0 ) { Vector3 dir = desiredPos - lookAtPos; // from target to camera float dist = dir.magnitude; dir.Normalize(); RaycastHit hit; if( Physics.Raycast( lookAtPos, dir, out hit, dist, collisionLayerMask ) ) { desiredPos = hit.point - dir * 0.1f; distance = hit.distance; } } transform.position = desiredPos; } void LateUpdate() { Apply(); } static float ClampAngle( float angle, float min, float max ) { if( angle < -360 ) angle += 360; if( angle > 360 ) angle -= 360; return Mathf.Clamp( angle, min, max ); } // recenter the camera public void ResetPanning() { IdealPanOffset = Vector3.zero; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Net.Sockets { public partial class SocketAsyncEventArgs : EventArgs, IDisposable { // AcceptSocket property variables. internal Socket _acceptSocket; private Socket _connectSocket; // Buffer,Offset,Count property variables. internal byte[] _buffer; internal int _count; internal int _offset; // BufferList property variables. private IList<ArraySegment<byte>> _bufferList; private List<ArraySegment<byte>> _bufferListInternal; // BytesTransferred property variables. private int _bytesTransferred; // Completed event property variables. private event EventHandler<SocketAsyncEventArgs> _completed; private bool _completedChanged; // DisconnectReuseSocket propery variables. private bool _disconnectReuseSocket; // LastOperation property variables. private SocketAsyncOperation _completedOperation; // ReceiveMessageFromPacketInfo property variables. private IPPacketInformation _receiveMessageFromPacketInfo; // RemoteEndPoint property variables. private EndPoint _remoteEndPoint; // SendPacketsSendSize property variable. internal int _sendPacketsSendSize; // SendPacketsElements property variables. internal SendPacketsElement[] _sendPacketsElements; // SendPacketsFlags property variable. internal TransmitFileOptions _sendPacketsFlags; // SocketError property variables. private SocketError _socketError; private Exception _connectByNameError; // SocketFlags property variables. internal SocketFlags _socketFlags; // UserToken property variables. private object _userToken; // Internal buffer for AcceptEx when Buffer not supplied. internal byte[] _acceptBuffer; internal int _acceptAddressBufferCount; // Internal SocketAddress buffer. internal Internals.SocketAddress _socketAddress; // Misc state variables. private ExecutionContext _context; private static readonly ContextCallback s_executionCallback = ExecutionCallback; private Socket _currentSocket; private bool _disposeCalled; // Controls thread safety via Interlocked. private const int Configuring = -1; private const int Free = 0; private const int InProgress = 1; private const int Disposed = 2; private int _operating; private MultipleConnectAsync _multipleConnect; public SocketAsyncEventArgs() { InitializeInternals(); } public Socket AcceptSocket { get { return _acceptSocket; } set { _acceptSocket = value; } } public Socket ConnectSocket { get { return _connectSocket; } } public byte[] Buffer { get { return _buffer; } } public int Offset { get { return _offset; } } public int Count { get { return _count; } } // SendPacketsFlags property. public TransmitFileOptions SendPacketsFlags { get { return _sendPacketsFlags; } set { _sendPacketsFlags = value; } } // NOTE: this property is mutually exclusive with Buffer. // Setting this property with an existing non-null Buffer will throw. public IList<ArraySegment<byte>> BufferList { get { return _bufferList; } set { StartConfiguring(); try { if (value != null) { if (_buffer != null) { // Can't have both set throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(Buffer))); } // Copy the user-provided list into our internal buffer list, // so that we are not affected by subsequent changes to the list. // We reuse the existing list so that we can avoid reallocation when possible. int bufferCount = value.Count; if (_bufferListInternal == null) { _bufferListInternal = new List<ArraySegment<byte>>(bufferCount); } else { _bufferListInternal.Clear(); } for (int i = 0; i < bufferCount; i++) { ArraySegment<byte> buffer = value[i]; RangeValidationHelpers.ValidateSegment(buffer); _bufferListInternal.Add(buffer); } } else { _bufferListInternal?.Clear(); } _bufferList = value; SetupMultipleBuffers(); } finally { Complete(); } } } public int BytesTransferred { get { return _bytesTransferred; } } public event EventHandler<SocketAsyncEventArgs> Completed { add { _completed += value; _completedChanged = true; } remove { _completed -= value; _completedChanged = true; } } protected virtual void OnCompleted(SocketAsyncEventArgs e) { EventHandler<SocketAsyncEventArgs> handler = _completed; if (handler != null) { handler(e._currentSocket, e); } } // DisconnectResuseSocket property. public bool DisconnectReuseSocket { get { return _disconnectReuseSocket; } set { _disconnectReuseSocket = value; } } public SocketAsyncOperation LastOperation { get { return _completedOperation; } } public IPPacketInformation ReceiveMessageFromPacketInfo { get { return _receiveMessageFromPacketInfo; } } public EndPoint RemoteEndPoint { get { return _remoteEndPoint; } set { _remoteEndPoint = value; } } public SendPacketsElement[] SendPacketsElements { get { return _sendPacketsElements; } set { StartConfiguring(); try { _sendPacketsElements = value; SetupSendPacketsElements(); } finally { Complete(); } } } public int SendPacketsSendSize { get { return _sendPacketsSendSize; } set { _sendPacketsSendSize = value; } } public SocketError SocketError { get { return _socketError; } set { _socketError = value; } } public Exception ConnectByNameError { get { return _connectByNameError; } } public SocketFlags SocketFlags { get { return _socketFlags; } set { _socketFlags = value; } } public object UserToken { get { return _userToken; } set { _userToken = value; } } public void SetBuffer(byte[] buffer, int offset, int count) { SetBufferInternal(buffer, offset, count); } public void SetBuffer(int offset, int count) { SetBufferInternal(_buffer, offset, count); } internal bool HasMultipleBuffers { get { return _bufferList != null; } } private void SetBufferInternal(byte[] buffer, int offset, int count) { StartConfiguring(); try { if (buffer == null) { // Clear out existing buffer. _buffer = null; _offset = 0; _count = 0; } else { // Can't have both Buffer and BufferList. if (_bufferList != null) { throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, nameof(BufferList))); } // Offset and count can't be negative and the // combination must be in bounds of the array. if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException(nameof(count)); } _buffer = buffer; _offset = offset; _count = count; } // Pin new or unpin old buffer if necessary. SetupSingleBuffer(); } finally { Complete(); } } internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags) { _socketError = socketError; _connectByNameError = null; _bytesTransferred = bytesTransferred; _socketFlags = flags; } internal void SetResults(Exception exception, int bytesTransferred, SocketFlags flags) { _connectByNameError = exception; _bytesTransferred = bytesTransferred; _socketFlags = flags; if (exception == null) { _socketError = SocketError.Success; } else { SocketException socketException = exception as SocketException; if (socketException != null) { _socketError = socketException.SocketErrorCode; } else { _socketError = SocketError.SocketError; } } } private static void ExecutionCallback(object state) { var thisRef = (SocketAsyncEventArgs)state; thisRef.OnCompleted(thisRef); } // Marks this object as no longer "in-use". Will also execute a Dispose deferred // because I/O was in progress. internal void Complete() { // Mark as not in-use. _operating = Free; // Check for deferred Dispose(). // The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress. // The _disposeCalled variable is not managed in a thread-safe manner on purpose for performance. if (_disposeCalled) { Dispose(); } } // Dispose call to implement IDisposable. public void Dispose() { // Remember that Dispose was called. _disposeCalled = true; // Check if this object is in-use for an async socket operation. if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free) { // Either already disposed or will be disposed when current operation completes. return; } // OK to dispose now. FreeInternals(); // Don't bother finalizing later. GC.SuppressFinalize(this); } ~SocketAsyncEventArgs() { if (!Environment.HasShutdownStarted) { FreeInternals(); } } // NOTE: Use a try/finally to make sure Complete is called when you're done private void StartConfiguring() { int status = Interlocked.CompareExchange(ref _operating, Configuring, Free); if (status != Free) { ThrowForNonFreeStatus(status); } } private void ThrowForNonFreeStatus(int status) { Debug.Assert(status == InProgress || status == Configuring || status == Disposed, $"Unexpected status: {status}"); if (status == Disposed) { throw new ObjectDisposedException(GetType().FullName); } else { throw new InvalidOperationException(SR.net_socketopinprogress); } } // Prepares for a native async socket call. // This method performs the tasks common to all socket operations. internal void StartOperationCommon(Socket socket) { // Change status to "in-use". int status = Interlocked.CompareExchange(ref _operating, InProgress, Free); if (status != Free) { ThrowForNonFreeStatus(status); } // Prepare execution context for callback. // If event delegates have changed or socket has changed // then discard any existing context. if (_completedChanged || socket != _currentSocket) { _completedChanged = false; _currentSocket = socket; _context = null; } // Capture execution context if none already. if (_context == null) { _context = ExecutionContext.Capture(); } } internal void StartOperationAccept() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Accept; // AcceptEx needs a single buffer that's the size of two native sockaddr buffers with 16 // extra bytes each. It can also take additional buffer space in front of those special // sockaddr structures that can be filled in with initial data coming in on a connection. _acceptAddressBufferCount = 2 * (Socket.GetAddressSize(_currentSocket._rightEndPoint) + 16); // If our caller specified a buffer (willing to get received data with the Accept) then // it needs to be large enough for the two special sockaddr buffers that AcceptEx requires. // Throw if that buffer is not large enough. bool userSuppliedBuffer = _buffer != null; if (userSuppliedBuffer) { // Caller specified a buffer - see if it is large enough if (_count < _acceptAddressBufferCount) { throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, nameof(Count))); } // Buffer is already pinned if necessary. } else { // Caller didn't specify a buffer so use an internal one. // See if current internal one is big enough, otherwise create a new one. if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount) { _acceptBuffer = new byte[_acceptAddressBufferCount]; } } InnerStartOperationAccept(userSuppliedBuffer); } internal void StartOperationConnect() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Connect; _multipleConnect = null; _connectSocket = null; InnerStartOperationConnect(); } internal void StartOperationWrapperConnect(MultipleConnectAsync args) { _completedOperation = SocketAsyncOperation.Connect; _multipleConnect = args; _connectSocket = null; } internal void CancelConnectAsync() { if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect) { if (_multipleConnect != null) { // If a multiple connect is in progress, abort it. _multipleConnect.Cancel(); } else { // Otherwise we're doing a normal ConnectAsync - cancel it by closing the socket. // _currentSocket will only be null if _multipleConnect was set, so we don't have to check. if (_currentSocket == null) { NetEventSource.Fail(this, "CurrentSocket and MultipleConnect both null!"); } _currentSocket.Dispose(); } } } internal void StartOperationDisconnect() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Disconnect; InnerStartOperationDisconnect(); } internal void StartOperationReceive() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Receive; InnerStartOperationReceive(); } internal void StartOperationReceiveFrom() { // Remember the operation type. _completedOperation = SocketAsyncOperation.ReceiveFrom; InnerStartOperationReceiveFrom(); } internal void StartOperationReceiveMessageFrom() { // Remember the operation type. _completedOperation = SocketAsyncOperation.ReceiveMessageFrom; InnerStartOperationReceiveMessageFrom(); } internal void StartOperationSend() { // Remember the operation type. _completedOperation = SocketAsyncOperation.Send; InnerStartOperationSend(); } internal void StartOperationSendPackets() { // Remember the operation type. _completedOperation = SocketAsyncOperation.SendPackets; InnerStartOperationSendPackets(); } internal void StartOperationSendTo() { // Remember the operation type. _completedOperation = SocketAsyncOperation.SendTo; InnerStartOperationSendTo(); } internal void UpdatePerfCounters(int size, bool sendOp) { if (sendOp) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesSent, size); if (_currentSocket.Transport == TransportType.Udp) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsSent); } } else { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, size); if (_currentSocket.Transport == TransportType.Udp) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived); } } } internal void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags) { SetResults(socketError, bytesTransferred, flags); // This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified; // the attempt socket will be closed anyways, so not updating the state is OK. _currentSocket?.UpdateStatusAfterSocketError(socketError); Complete(); } internal void FinishConnectByNameSyncFailure(Exception exception, int bytesTransferred, SocketFlags flags) { SetResults(exception, bytesTransferred, flags); _currentSocket?.UpdateStatusAfterSocketError(_socketError); Complete(); } internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags) { SetResults(socketError, bytesTransferred, flags); // This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified; // the attempt socket will be closed anyways, so not updating the state is OK. _currentSocket?.UpdateStatusAfterSocketError(socketError); Complete(); if (_context == null) { OnCompleted(this); } else { ExecutionContext.Run(_context, s_executionCallback, this); } } internal void FinishOperationAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags) { SetResults(exception, bytesTransferred, flags); _currentSocket?.UpdateStatusAfterSocketError(_socketError); Complete(); if (_context == null) { OnCompleted(this); } else { ExecutionContext.Run(_context, s_executionCallback, this); } } internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags) { SetResults(SocketError.Success, bytesTransferred, flags); _currentSocket = connectSocket; _connectSocket = connectSocket; // Complete the operation and raise the event. Complete(); if (_context == null) { OnCompleted(this); } else { ExecutionContext.Run(_context, s_executionCallback, this); } } internal void FinishOperationSyncSuccess(int bytesTransferred, SocketFlags flags) { SetResults(SocketError.Success, bytesTransferred, flags); if (NetEventSource.IsEnabled || Socket.s_perfCountersEnabled) { LogBytesTransferred(bytesTransferred, _completedOperation); } SocketError socketError = SocketError.Success; switch (_completedOperation) { case SocketAsyncOperation.Accept: // Get the endpoint. Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint); socketError = FinishOperationAccept(remoteSocketAddress); if (socketError == SocketError.Success) { _acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress)); if (NetEventSource.IsEnabled) NetEventSource.Accepted(_acceptSocket, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint); } else { SetResults(socketError, bytesTransferred, flags); _acceptSocket = null; _currentSocket.UpdateStatusAfterSocketError(socketError); } break; case SocketAsyncOperation.Connect: socketError = FinishOperationConnect(); if (socketError == SocketError.Success) { if (NetEventSource.IsEnabled) NetEventSource.Connected(_currentSocket, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint); // Mark socket connected. _currentSocket.SetToConnected(); _connectSocket = _currentSocket; } else { SetResults(socketError, bytesTransferred, flags); _currentSocket.UpdateStatusAfterSocketError(socketError); } break; case SocketAsyncOperation.Disconnect: _currentSocket.SetToDisconnected(); _currentSocket._remoteEndPoint = null; break; case SocketAsyncOperation.ReceiveFrom: // Deal with incoming address. _socketAddress.InternalSize = GetSocketAddressSize(); Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint); if (!socketAddressOriginal.Equals(_socketAddress)) { try { _remoteEndPoint = _remoteEndPoint.Create(_socketAddress); } catch { } } break; case SocketAsyncOperation.ReceiveMessageFrom: // Deal with incoming address. _socketAddress.InternalSize = GetSocketAddressSize(); socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint); if (!socketAddressOriginal.Equals(_socketAddress)) { try { _remoteEndPoint = _remoteEndPoint.Create(_socketAddress); } catch { } } FinishOperationReceiveMessageFrom(); break; case SocketAsyncOperation.SendPackets: FinishOperationSendPackets(); break; } Complete(); } private void LogBytesTransferred(int bytesTransferred, SocketAsyncOperation operation) { if (bytesTransferred > 0) { if (NetEventSource.IsEnabled) { LogBuffer(bytesTransferred); } if (Socket.s_perfCountersEnabled) { bool sendOp = false; switch (operation) { case SocketAsyncOperation.Connect: case SocketAsyncOperation.Send: case SocketAsyncOperation.SendPackets: case SocketAsyncOperation.SendTo: sendOp = true; break; } UpdatePerfCounters(bytesTransferred, sendOp); } } } internal void FinishOperationAsyncSuccess(int bytesTransferred, SocketFlags flags) { FinishOperationSyncSuccess(bytesTransferred, flags); // Raise completion event. if (_context == null) { OnCompleted(this); } else { ExecutionContext.Run(_context, s_executionCallback, this); } } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Text.RegularExpressions; using System.Windows.Forms; using XenAPI; using XenAdmin.Actions.Wlb; using XenAdmin.Core; using XenAdmin.Wlb; using XenAdmin.Controls; namespace XenAdmin.Dialogs.Wlb { public partial class WlbReportSubscriptionDialog : XenAdmin.Dialogs.XenDialogBase { #region Variables private Pool _pool; private string _reportDisplayName; private Dictionary<string, string> _rpParams; private WlbReportSubscription _subscription; private string _subId = String.Empty; ToolTip InvalidParamToolTip = new ToolTip(); // Due to localization, changed email regex from @"^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)*[A-Z0-9-]+$" // to match anything with an @ sign in the middle private static readonly Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase); private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); #endregion #region Constructors // Create new subscription public WlbReportSubscriptionDialog(string reportDisplayName, Dictionary<string, string> reportParams, Pool pool) : base(pool.Connection) { _rpParams = reportParams; _subscription = null; _reportDisplayName = reportDisplayName; _pool = pool; init(); } // Edit existing subscription public WlbReportSubscriptionDialog(string reportDisplayName, WlbReportSubscription subscription, Pool pool) : base(pool.Connection) { _subId = subscription.Id; _rpParams = subscription.ReportParameters; _subscription = subscription; _reportDisplayName = reportDisplayName; _pool = pool; init(); } #endregion #region Private Methods private void init() { InitializeComponent(); InitializeControls(); // Initialize InvalidParamToolTip InvalidParamToolTip.IsBalloon = true; InvalidParamToolTip.ToolTipIcon = ToolTipIcon.Warning; InvalidParamToolTip.ToolTipTitle = Messages.INVALID_PARAMETER; if (null != _subscription) { LoadSubscription(); } } private void InitializeControls() { this.Text = String.Concat(this.Text, this._reportDisplayName); this.rpParamComboBox.SelectedIndex = 0; this.rpRenderComboBox.SelectedIndex = 0; this.schedDeliverComboBox.DataSource = new BindingSource(BuildDaysOfWeek(), null); this.schedDeliverComboBox.ValueMember = "key"; this.schedDeliverComboBox.DisplayMember = "value"; ; this.schedDeliverComboBox.SelectedIndex = 1; this.dateTimePickerSchedEnd.Value = DateTime.Now.AddMonths(1); this.dateTimePickerSchedStart.Value = DateTime.Now; } private Dictionary<int, string> BuildDaysOfWeek() { Dictionary<int, string> days = new Dictionary<int, string>(); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.All, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.All)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Weekends, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Weekends)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Sunday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Sunday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Monday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Monday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Tuesday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Tuesday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Wednesday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Wednesday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Thursday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Thursday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Friday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Friday)); days.Add((int)WlbScheduledTask.WlbTaskDaysOfWeek.Saturday, GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek.Saturday)); return days; } private string GetLocalizedDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek daysOfWeek) { return WlbScheduledTask.DaysOfWeekL10N(daysOfWeek); } private void LoadSubscription() { // subscription name this.subNameTextBox.Text = this._subscription.Description; // report data range int days = 0; if (this._subscription.ReportParameters != null) { int.TryParse(this._subscription.ReportParameters["Start"], out days); } this.rpParamComboBox.SelectedIndex = (days-1)/-7 -1; // email info this.emailToTextBox.Text = this._subscription.EmailTo; this.emailCcTextBox.Text = this._subscription.EmailCc; this.emailBccTextBox.Text = this._subscription.EmailBcc; this.emailReplyTextBox.Text = this._subscription.EmailReplyTo; this.emailSubjectTextBox.Text = this._subscription.EmailSubject; this.emailCommentRichTextBox.Text = this._subscription.EmailComment; this.rpRenderComboBox.SelectedIndex = (int)this._subscription.ReportRenderFormat; // convert utc days of week and utc execute time to local days of week and local execute time DateTime localExecuteTime; WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek; WlbScheduledTask.GetLocalTaskTimes(this._subscription.DaysOfWeek, this._subscription.ExecuteTimeOfDay, out localDaysOfWeek, out localExecuteTime); // subscription run time this.dateTimePickerSubscriptionRunTime.Value = localExecuteTime; // subscription delivery day this.schedDeliverComboBox.SelectedValue = (int)localDaysOfWeek; // subscription enable start and end dates if (this._subscription.DisableDate != DateTime.MinValue) { this.dateTimePickerSchedEnd.Value = this._subscription.DisableDate.ToLocalTime(); } if (this._subscription.EnableDate != DateTime.MinValue) { this.dateTimePickerSchedStart.Value = this._subscription.EnableDate.ToLocalTime(); } } #endregion //Private Methods #region DateTimePicker and ComboBox Event Handler private void rpParamComboBox_SelectedIndexChanged(object sender, EventArgs e) { switch (this.rpParamComboBox.SelectedIndex) { case 0: this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-7); break; case 1: this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-14); break; case 2: this.dateTimePickerSchedStart.Value = DateTime.Now.AddDays(-21); break; case 3: this.dateTimePickerSchedStart.Value = DateTime.Now.AddMonths(-1); break; } this.dateTimePickerSchedEnd.Value = DateTime.Now; } private void dateTimePickerSchedEnd_ValueChanged(object sender, EventArgs e) { if (this.dateTimePickerSchedEnd.Value < this.dateTimePickerSchedStart.Value) { this.dateTimePickerSchedStart.Value = this.dateTimePickerSchedEnd.Value; } } private void dateTimePickerSchedStart_ValueChanged(object sender, EventArgs e) { if (this.dateTimePickerSchedStart.Value > this.dateTimePickerSchedEnd.Value) { this.dateTimePickerSchedEnd.Value = this.dateTimePickerSchedStart.Value; } } #endregion //DateTimePicker and ComboBox Event Handler #region Validators private bool ValidToSave() { foreach (Control ctl in this.tableLayoutPanelSubscriptionName.Controls) { if (!IsValidControl(ctl)) { HelpersGUI.ShowBalloonMessage(ctl, Messages.INVALID_PARAMETER, InvalidParamToolTip); return false; } } foreach (Control ctl in this.tableLayoutPanelDeliveryOptions.Controls) { if (!IsValidControl(ctl)) { HelpersGUI.ShowBalloonMessage(ctl, Messages.INVALID_PARAMETER, InvalidParamToolTip); return false; } } return true; } private bool IsValidControl(Control ctl) { if (String.Compare(this.subNameTextBox.Name, ctl.Name) == 0) { return !String.IsNullOrEmpty(ctl.Text); } else if (String.Compare(this.emailToTextBox.Name, ctl.Name) == 0 || String.Compare(this.emailReplyTextBox.Name, ctl.Name) == 0) { return IsValidEmail(ctl.Text); } else if (String.Compare(this.emailBccTextBox.Name, ctl.Name) == 0 || String.Compare(this.emailCcTextBox.Name, ctl.Name) == 0) { if (!String.IsNullOrEmpty(ctl.Text)) { return IsValidEmail(ctl.Text); } } return true; } private static bool IsValidEmail(string emailAddress) { foreach (string address in emailAddress.Split(new char[] { ';' })) { if (!emailRegex.IsMatch(address)) { return false; } } return true; } #endregion #region Button Click Event Handler private void saveButton_Click(object sender, EventArgs e) { if (!ValidToSave()) { this.DialogResult = DialogResult.None; } else { SaveSubscription(); InvalidParamToolTip.Dispose(); } } private void cancelButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; InvalidParamToolTip.Dispose(); } #endregion #region Private Methods private string GetLoggedInAsText() { if (_pool.Connection == null) { // Shouldn't happen return String.Empty; } Session session = _pool.Connection.Session; if (session == null) { return String.Empty; } return session.UserFriendlyName(); } private void SaveSubscription() { if (this._subscription == null) { _subscription = new WlbReportSubscription(String.Empty); _subscription.SubscriberName = GetLoggedInAsText(); _subscription.Created = DateTime.UtcNow; } _subscription.Name = this.subNameTextBox.Text; _subscription.Description = this.subNameTextBox.Text; DateTime utcExecuteTime; WlbScheduledTask.WlbTaskDaysOfWeek utcDaysOfWeek; WlbScheduledTask.GetUTCTaskTimes((WlbScheduledTask.WlbTaskDaysOfWeek)this.schedDeliverComboBox.SelectedValue, this.dateTimePickerSubscriptionRunTime.Value, out utcDaysOfWeek, out utcExecuteTime); _subscription.ExecuteTimeOfDay = utcExecuteTime; _subscription.DaysOfWeek = utcDaysOfWeek; if (_subscription.DaysOfWeek != WlbScheduledTask.WlbTaskDaysOfWeek.All) { _subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Weekly; } else { _subscription.TriggerType = (int)WlbScheduledTask.WlbTaskTriggerType.Daily; } _subscription.Enabled = true; _subscription.EnableDate = this.dateTimePickerSchedStart.Value == DateTime.MinValue ? DateTime.UtcNow : this.dateTimePickerSchedStart.Value.ToUniversalTime(); _subscription.DisableDate = this.dateTimePickerSchedEnd.Value == DateTime.MinValue ? DateTime.UtcNow.AddMonths(1) : this.dateTimePickerSchedEnd.Value.ToUniversalTime(); _subscription.LastTouched = DateTime.UtcNow; _subscription.LastTouchedBy = GetLoggedInAsText(); // store email info _subscription.EmailTo = this.emailToTextBox.Text.Trim(); _subscription.EmailCc = this.emailCcTextBox.Text.Trim(); _subscription.EmailBcc = this.emailBccTextBox.Text.Trim(); _subscription.EmailReplyTo = this.emailReplyTextBox.Text.Trim(); _subscription.EmailSubject = this.emailSubjectTextBox.Text.Trim(); _subscription.EmailComment = this.emailCommentRichTextBox.Text; // store reoprt Info //sub.ReportId = ; _subscription.ReportRenderFormat = this.rpRenderComboBox.SelectedIndex; Dictionary<string, string> rps = new Dictionary<string, string>(); foreach(string key in this._rpParams.Keys) { if (String.Compare(key, WlbReportSubscription.REPORT_NAME, true) == 0) _subscription.ReportName = this._rpParams[WlbReportSubscription.REPORT_NAME]; else { //Get start date range if (String.Compare(key, "start", true) == 0) { rps.Add(key, ((this.rpParamComboBox.SelectedIndex + 1) * (-7)+1).ToString()); } else { rps.Add(key, _rpParams[key]); } } } _subscription.ReportParameters = rps; SendWlbConfigurationAction action = new SendWlbConfigurationAction(this._pool, _subscription.ToDictionary(), SendWlbConfigurationKind.SetReportSubscription); using (var dialog = new ActionProgressDialog(action, ProgressBarStyle.Blocks)) { dialog.ShowCancel = true; dialog.ShowDialog(this); } if (action.Succeeded) { DialogResult = DialogResult.OK; this.Close(); } else if(!action.Cancelled) { using (var dlg = new ThreeButtonDialog( new ThreeButtonDialog.Details( SystemIcons.Error, String.Format(Messages.WLB_SUBSCRIPTION_ERROR, _subscription.Description), Messages.XENCENTER))) { dlg.ShowDialog(this); } //log.ErrorFormat("There was an error calling SendWlbConfigurationAction to SetReportSubscription {0}, Action Result: {1}.", _subscription.Description, action.Result); DialogResult = DialogResult.None; } } #endregion //Button Click Event Handler } }
// <copyright file="Executable.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security.Permissions; using System.Text; using Microsoft.Win32; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Firefox.Internal { /// <summary> /// Represents the executable file for Firefox. /// </summary> internal class Executable { private readonly string binaryInDefaultLocationForPlatform; private string binaryLocation; /// <summary> /// Initializes a new instance of the <see cref="Executable"/> class. /// </summary> /// <param name="userSpecifiedBinaryPath">The path and file name to the Firefox executable.</param> public Executable(string userSpecifiedBinaryPath) { if (!string.IsNullOrEmpty(userSpecifiedBinaryPath)) { // It should exist and be a file. if (File.Exists(userSpecifiedBinaryPath)) { this.binaryLocation = userSpecifiedBinaryPath; return; } throw new WebDriverException( "Specified firefox binary location does not exist or is not a real file: " + userSpecifiedBinaryPath); } else { this.binaryInDefaultLocationForPlatform = LocateFirefoxBinaryFromPlatform(); } if (this.binaryInDefaultLocationForPlatform != null && File.Exists(this.binaryInDefaultLocationForPlatform)) { this.binaryLocation = this.binaryInDefaultLocationForPlatform; return; } throw new WebDriverException("Cannot find Firefox binary in PATH or default install locations. " + "Make sure Firefox is installed. OS appears to be: " + Platform.CurrentPlatform.ToString()); } /// <summary> /// Gets the full path to the executable. /// </summary> public string ExecutablePath { get { return this.binaryLocation; } } /// <summary> /// Sets the library path for the Firefox executable environment. /// </summary> /// <param name="builder">The <see cref="Process"/> used to execute the binary.</param> [SecurityPermission(SecurityAction.Demand)] public void SetLibraryPath(Process builder) { string propertyName = GetLibraryPathPropertyName(); StringBuilder libraryPath = new StringBuilder(); // If we have an env var set for the path, use it. string env = GetEnvironmentVariable(propertyName, null); if (env != null) { libraryPath.Append(env).Append(Path.PathSeparator); } // Check our extra env vars for the same var, and use it too. if (builder.StartInfo.EnvironmentVariables.ContainsKey(propertyName)) { libraryPath.Append(builder.StartInfo.EnvironmentVariables[propertyName]).Append(Path.PathSeparator); } // Last, add the contents of the specified system property, defaulting to the binary's path. // On Snow Leopard, beware of problems the sqlite library string firefoxLibraryPath = Path.GetFullPath(this.binaryLocation); if (Platform.CurrentPlatform.IsPlatformType(PlatformType.Mac) && Platform.CurrentPlatform.MinorVersion > 5) { libraryPath.Append(Path.PathSeparator); } else { // Insert the Firefox library path and the path separator at the beginning // of the path. libraryPath.Insert(0, Path.PathSeparator).Insert(0, firefoxLibraryPath); } // Add the library path to the builder. if (builder.StartInfo.EnvironmentVariables.ContainsKey(propertyName)) { builder.StartInfo.EnvironmentVariables[propertyName] = libraryPath.ToString(); } else { builder.StartInfo.EnvironmentVariables.Add(propertyName, libraryPath.ToString()); } } /// <summary> /// Locates the Firefox binary by platform. /// </summary> /// <returns>The full path to the binary.</returns> [SecurityPermission(SecurityAction.Demand)] private static string LocateFirefoxBinaryFromPlatform() { string binary = string.Empty; if (Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { #if !NETCOREAPP2_0 && !NETSTANDARD2_0 // NOTE: This code is legacy, and will be removed. It will not be // fixed for the .NET Core case. // Look first in HKEY_LOCAL_MACHINE, then in HKEY_CURRENT_USER // if it's not found there. If it's still not found, look in // the default install location (C:\Program Files\Mozilla Firefox). string firefoxRegistryKey = @"SOFTWARE\Mozilla\Mozilla Firefox"; RegistryKey mozillaKey = Registry.LocalMachine.OpenSubKey(firefoxRegistryKey); if (mozillaKey == null) { mozillaKey = Registry.CurrentUser.OpenSubKey(firefoxRegistryKey); } if (mozillaKey != null) { binary = GetExecutablePathUsingRegistry(mozillaKey); } else { #endif // NOTE: Can't use Environment.SpecialFolder.ProgramFilesX86, because .NET 3.5 // doesn't have that member of the enum. string[] windowsDefaultInstallLocations = new string[] { Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Mozilla Firefox"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + " (x86)", "Mozilla Firefox") }; binary = GetExecutablePathUsingDefaultInstallLocations(windowsDefaultInstallLocations, "Firefox.exe"); #if !NETCOREAPP2_0 && !NETSTANDARD2_0 } #endif } else { string[] macDefaultInstallLocations = new string[] { "/Applications/Firefox.app/Contents/MacOS", string.Format(CultureInfo.InvariantCulture, "/Users/{0}/Applications/Firefox.app/Contents/MacOS", Environment.UserName) }; binary = GetExecutablePathUsingDefaultInstallLocations(macDefaultInstallLocations, "firefox-bin"); if (string.IsNullOrEmpty(binary)) { // Use "which firefox" for non-Windows OS, and non-Mac OS where // Firefox is installed in a non-default location. using (Process proc = new Process()) { proc.StartInfo.FileName = "which"; proc.StartInfo.Arguments = "firefox"; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.Start(); proc.WaitForExit(); binary = proc.StandardOutput.ReadToEnd().Trim(); } } } if (binary != null && File.Exists(binary)) { return binary; } // Didn't find binary in any of the default install locations, so look // at directories on the user's PATH environment variable. return FindBinary(new string[] { "firefox3", "firefox" }); } #if !NETCOREAPP2_0 && !NETSTANDARD2_0 private static string GetExecutablePathUsingRegistry(RegistryKey mozillaKey) { // NOTE: This code is legacy, and will be removed. It will not be // fixed for the .NET Core case. string currentVersion = (string)mozillaKey.GetValue("CurrentVersion"); if (string.IsNullOrEmpty(currentVersion)) { throw new WebDriverException("Unable to determine the current version of FireFox using the registry, please make sure you have installed FireFox correctly"); } RegistryKey currentMain = mozillaKey.OpenSubKey(string.Format(CultureInfo.InvariantCulture, @"{0}\Main", currentVersion)); if (currentMain == null) { throw new WebDriverException( "Unable to determine the current version of FireFox using the registry, please make sure you have installed FireFox correctly"); } string path = (string)currentMain.GetValue("PathToExe"); if (!File.Exists(path)) { throw new WebDriverException( "FireFox executable listed in the registry does not exist, please make sure you have installed FireFox correctly"); } return path; } #endif private static string GetExecutablePathUsingDefaultInstallLocations(string[] defaultInstallLocations, string exeName) { foreach (string defaultInstallLocation in defaultInstallLocations) { string fullPath = Path.Combine(defaultInstallLocation, exeName); if (File.Exists(fullPath)) { return fullPath; } } return null; } /// <summary> /// Retrieves an environment variable /// </summary> /// <param name="name">Name of the variable.</param> /// <param name="defaultValue">Default value of the variable.</param> /// <returns>The value of the variable. If no variable with that name is set, returns the default.</returns> private static string GetEnvironmentVariable(string name, string defaultValue) { string value = Environment.GetEnvironmentVariable(name); if (string.IsNullOrEmpty(value)) { value = defaultValue; } return value; } /// <summary> /// Retrieves the platform specific environment property name which contains the library path. /// </summary> /// <returns>The platform specific environment property name which contains the library path.</returns> private static string GetLibraryPathPropertyName() { string libraryPropertyPathName = "LD_LIBRARY_PATH"; if (Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { libraryPropertyPathName = "PATH"; } else if (Platform.CurrentPlatform.IsPlatformType(PlatformType.Mac)) { libraryPropertyPathName = "DYLD_LIBRARY_PATH"; } return libraryPropertyPathName; } /// <summary> /// Walk a PATH to locate binaries with a specified name. Binaries will be searched for in the /// order they are provided. /// </summary> /// <param name="binaryNames">The binary names to search for.</param> /// <returns>The first binary found matching that name.</returns> private static string FindBinary(string[] binaryNames) { foreach (string binaryName in binaryNames) { string exe = binaryName; if (Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { exe += ".exe"; } string path = FileUtilities.FindFile(exe); if (!string.IsNullOrEmpty(path)) { return Path.Combine(path, exe); } } return null; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories.Core { /// <summary> /// Operations for managing data slices. /// </summary> internal partial class DataSliceOperations : IServiceOperations<DataFactoryManagementClient>, IDataSliceOperations { /// <summary> /// Initializes a new instance of the DataSliceOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataSliceOperations(DataFactoryManagementClient client) { this._client = client; } private DataFactoryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient. /// </summary> public DataFactoryManagementClient Client { get { return this._client; } } /// <summary> /// Gets the first page of data slice instances with the link to the /// next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='parameters'> /// Required. Parameters specifying how to list data slices of the /// table. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data slices operation response. /// </returns> public async Task<DataSliceListResponse> ListAsync(string resourceGroupName, string dataFactoryName, string tableName, DataSliceListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (tableName != null && tableName.Length > 260) { throw new ArgumentOutOfRangeException("tableName"); } if (Regex.IsMatch(tableName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("tableName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.DataSliceRangeEndTime == null) { throw new ArgumentNullException("parameters.DataSliceRangeEndTime"); } if (parameters.DataSliceRangeStartTime == null) { throw new ArgumentNullException("parameters.DataSliceRangeStartTime"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/tables/"; url = url + Uri.EscapeDataString(tableName); url = url + "/slices"; List<string> queryParameters = new List<string>(); queryParameters.Add("start=" + Uri.EscapeDataString(parameters.DataSliceRangeStartTime)); queryParameters.Add("end=" + Uri.EscapeDataString(parameters.DataSliceRangeEndTime)); queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataSliceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataSlice dataSliceInstance = new DataSlice(); result.DataSlices.Add(dataSliceInstance); JToken startValue = valueValue["start"]; if (startValue != null && startValue.Type != JTokenType.Null) { DateTime startInstance = ((DateTime)startValue); dataSliceInstance.Start = startInstance; } JToken endValue = valueValue["end"]; if (endValue != null && endValue.Type != JTokenType.Null) { DateTime endInstance = ((DateTime)endValue); dataSliceInstance.End = endInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); dataSliceInstance.State = stateInstance; } JToken substateValue = valueValue["substate"]; if (substateValue != null && substateValue.Type != JTokenType.Null) { string substateInstance = ((string)substateValue); dataSliceInstance.Substate = substateInstance; } JToken latencyStatusValue = valueValue["latencyStatus"]; if (latencyStatusValue != null && latencyStatusValue.Type != JTokenType.Null) { string latencyStatusInstance = ((string)latencyStatusValue); dataSliceInstance.LatencyStatus = latencyStatusInstance; } JToken retryCountValue = valueValue["retryCount"]; if (retryCountValue != null && retryCountValue.Type != JTokenType.Null) { int retryCountInstance = ((int)retryCountValue); dataSliceInstance.RetryCount = retryCountInstance; } JToken longRetryCountValue = valueValue["longRetryCount"]; if (longRetryCountValue != null && longRetryCountValue.Type != JTokenType.Null) { int longRetryCountInstance = ((int)longRetryCountValue); dataSliceInstance.LongRetryCount = longRetryCountInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the next page of data slice instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next data slices page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List data slices operation response. /// </returns> public async Task<DataSliceListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result DataSliceListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DataSliceListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { DataSlice dataSliceInstance = new DataSlice(); result.DataSlices.Add(dataSliceInstance); JToken startValue = valueValue["start"]; if (startValue != null && startValue.Type != JTokenType.Null) { DateTime startInstance = ((DateTime)startValue); dataSliceInstance.Start = startInstance; } JToken endValue = valueValue["end"]; if (endValue != null && endValue.Type != JTokenType.Null) { DateTime endInstance = ((DateTime)endValue); dataSliceInstance.End = endInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); dataSliceInstance.State = stateInstance; } JToken substateValue = valueValue["substate"]; if (substateValue != null && substateValue.Type != JTokenType.Null) { string substateInstance = ((string)substateValue); dataSliceInstance.Substate = substateInstance; } JToken latencyStatusValue = valueValue["latencyStatus"]; if (latencyStatusValue != null && latencyStatusValue.Type != JTokenType.Null) { string latencyStatusInstance = ((string)latencyStatusValue); dataSliceInstance.LatencyStatus = latencyStatusInstance; } JToken retryCountValue = valueValue["retryCount"]; if (retryCountValue != null && retryCountValue.Type != JTokenType.Null) { int retryCountInstance = ((int)retryCountValue); dataSliceInstance.RetryCount = retryCountInstance; } JToken longRetryCountValue = valueValue["longRetryCount"]; if (longRetryCountValue != null && longRetryCountValue.Type != JTokenType.Null) { int longRetryCountInstance = ((int)longRetryCountValue); dataSliceInstance.LongRetryCount = longRetryCountInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Sets status of data slices over a time range for a specific table. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. A unique data factory instance name. /// </param> /// <param name='tableName'> /// Required. A unique table instance name. /// </param> /// <param name='parameters'> /// Required. The parameters required to set status of data slices. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> SetStatusAsync(string resourceGroupName, string dataFactoryName, string tableName, DataSliceSetStatusParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (tableName == null) { throw new ArgumentNullException("tableName"); } if (tableName != null && tableName.Length > 260) { throw new ArgumentOutOfRangeException("tableName"); } if (Regex.IsMatch(tableName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("tableName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("dataFactoryName", dataFactoryName); tracingParameters.Add("tableName", tableName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "SetStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/tables/"; url = url + Uri.EscapeDataString(tableName); url = url + "/slices/setstatus"; List<string> queryParameters = new List<string>(); if (parameters.DataSliceRangeStartTime != null) { queryParameters.Add("start=" + Uri.EscapeDataString(parameters.DataSliceRangeStartTime)); } if (parameters.DataSliceRangeEndTime != null) { queryParameters.Add("end=" + Uri.EscapeDataString(parameters.DataSliceRangeEndTime)); } queryParameters.Add("api-version=2015-07-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject dataSliceSetStatusParametersValue = new JObject(); requestDoc = dataSliceSetStatusParametersValue; if (parameters.SliceState != null) { dataSliceSetStatusParametersValue["SliceState"] = parameters.SliceState; } if (parameters.UpdateType != null) { dataSliceSetStatusParametersValue["UpdateType"] = parameters.UpdateType; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Runtime.InteropServices; namespace Sparrow.Sdl2 { public static partial class Sdl { /// <summary> /// Event type codes returned within <see cref='Event'/> /// </summary> /// <seealso cref="Event"/> public enum EventType : uint { FirstEvent = 0, /* Application events */ Quit = 0x100, /* Window events */ WindowEvent = 0x200, SysWmEvent, /* Keyboard events */ KeyDown = 0x300, KeyUp, TextEditing, TextInput, /* Mouse events */ MouseMotion = 0x400, MouseButtonDown, MouseButtonUp, MouseWheel, /* Joystick events */ JoyAxisMotion = 0x600, JoyBallMotion, JoyHatMotion, JoyButtonDown, JoyButtonUp, JoyDeviceAdded, JoyDeviceRemoved, /* Game controller events */ ControllerAxisMotion = 0x650, ControllerButtonDown, ControllerButtonUp, ControllerDeviceAdded, ControllerDeviceRemoved, ControllerDeviceRemapped, /* Touch events */ FingerDown = 0x700, FingerUp, FingerMotion, /* Gesture events */ DollarGesture = 0x800, DollarRecord, MultiGesture, /* Clipboard events */ ClipboardUpdate = 0x900, /* Drag and drop events */ DropFile = 0x1000, /* Only available in 2.0.4 or higher */ DropText, DropBegin, DropComplete, /* Audio hotplug events */ /* Only available in SDL 2.0.4 or higher */ AudioDeviceAdded = 0x1100, AudioDeviceRemoved, /* Render events */ /* Only available in SDL 2.0.2 or higher */ RenderTargetsReset = 0x2000, /* Only available in SDL 2.0.4 or higher */ RenderDeviceReset, /* Events SDL_USEREVENT through SDL_LASTEVENT are for * your use, and should be allocated with * SDL_RegisterEvents() */ UserEvent = 0x8000, /* The last event, used for bouding arrays. */ LastEvent = 0xFFFF } public enum MouseWheelDirection : uint { Normal, Flipped } [Flags] public enum MouseButton : byte { Left = 1 << 0, Middle = 1 << 1, Right = 1 << 2, X1 = 1 << 3, X2 = 1 << 4, } public enum ButtonState : byte { Pressed = 1, Released = 0, } [StructLayout(LayoutKind.Sequential)] public struct KeySymbol { public Scancode scancode; public Keycode keycode; public KeyModifier modifers; /* UInt16 */ public uint unicode; /* Deprecated */ } /// <summary> /// The event returned when quit is requested /// </summary> /// <seealso cref="PollEvent()"/> [StructLayout(LayoutKind.Sequential)] public struct QuitEvent { public EventType type; public uint timestamp; } [StructLayout(LayoutKind.Sequential)] public struct KeyboardEvent { public EventType type; public uint timestamp; public uint windowId; public ButtonState state; public byte repeat; /* non-zero if this is a repeat */ private byte padding2; private byte padding3; public KeySymbol keySymbol; } [StructLayout(LayoutKind.Sequential)] public struct MouseMotionEvent { public EventType type; public uint timestamp; public uint windowId; public uint which; public MouseButton state; private byte padding1; private byte padding2; private byte padding3; public int x; public int y; public int xrel; public int yrel; } [StructLayout(LayoutKind.Sequential)] public struct MouseButtonEvent { public EventType type; public uint timestamp; public uint windowId; public uint which; public MouseButton button; public ButtonState state; public byte clicks; /* click count */ private byte padding1; public int x; public int y; } [StructLayout(LayoutKind.Sequential)] public struct MouseWheelEvent { public EventType type; public uint timestamp; public uint windowId; public uint which; public int x; /* amount scrolled horizontally */ public int y; /* amount scrolled vertically */ public MouseWheelDirection direction; /* Set to one of the SDL_MOUSEWHEEL_* defines */ } [StructLayout(LayoutKind.Sequential)] public struct ControllerAxisEvent { public EventType type; public uint timestamp; public int which; /* SDL_JoystickID */ public byte axis; private byte padding1; private byte padding2; private byte padding3; public short axisValue; /* value, lolC# */ private ushort padding4; } [StructLayout(LayoutKind.Sequential)] public struct ControllerDeviceEvent { public EventType type; public uint timestamp; public int which; } [StructLayout(LayoutKind.Sequential)] public struct ControllerButtonEvent { public EventType type; public uint timestamp; public int which; /* SDL_JoystickID */ public byte button; public byte state; private byte padding1; private byte padding2; } [StructLayout(LayoutKind.Sequential)] public struct CommonEvent { public EventType type; public uint timestamp; } /// <summary> /// The full event structure returned and used by <see cref='PollEvent()'/> /// </summary> /// <seealso cref="PollEvent()"/> [StructLayout(LayoutKind.Explicit, Size=56)] public struct Event { [FieldOffset(0)] public CommonEvent common; /* [FieldOffset(0)] public WindowEvent window; */ [FieldOffset(0)] public KeyboardEvent key; /* [FieldOffset(0)] public TextEditingEvent edit; [FieldOffset(0)] public TextInputEvent text; */ [FieldOffset(0)] public MouseMotionEvent motion; [FieldOffset(0)] public MouseButtonEvent button; [FieldOffset(0)] public MouseWheelEvent wheel; /* [FieldOffset(0)] public JoyAxisEvent jaxis; [FieldOffset(0)] public JoyBallEvent jball; [FieldOffset(0)] public JoyHatEvent jhat; [FieldOffset(0)] public JoyButtonEvent jbutton; [FieldOffset(0)] public JoyDeviceEvent jdevice; */ [FieldOffset(0)] public ControllerAxisEvent caxis; [FieldOffset(0)] public ControllerButtonEvent cbutton; [FieldOffset(0)] public ControllerDeviceEvent cdevice; [FieldOffset(0)] public QuitEvent quit; /* [FieldOffset(0)] public UserEvent user; [FieldOffset(0)] public SysWMEvent syswm; [FieldOffset(0)] public TouchFingerEvent tfinger; [FieldOffset(0)] public MultiGestureEvent mgesture; [FieldOffset(0)] public DollarGestureEvent dgesture; [FieldOffset(0)] public DropEvent drop; */ } /// <summary> /// Poll for currently pending events. /// </summary> /// <param name="@event">the <see cref='Event'/> structure to be filled with the next event from the queue, or null</param> /// <returns>Returns 1 if there is a pending event or 0 if there are none available.</returns> /// <remarks> /// If event is not null, the next event is removed from the queue and stored in the <see cref='Event'/> structure pointed to by event. /// If event is null, it simply returns 1 if there is an event in the queue, but will not remove it. /// As this function implicitly calls <see cref='PumpEvents()'/>, you can only call this function in the thread that set the video mode. /// <see cref='PollEvents()'/> is the favored way of receiving system events since it can be done from the main loop and does not suspend the main loop while waiting on an event to be posted. /// </remarks> /// <seealso cref="GetEventFilter()"/> /// <seealso cref="PeepEvents()"/> /// <seealso cref="PushEvent()"/> /// <seealso cref="SetEventFilter()"/> /// <seealso cref="WaitEvent()"/> /// <seealso cref="WaitEventTimeout()"/> [DllImport(DllName, EntryPoint = "SDL_PollEvent")] public static extern uint PollEvent(out Event @event); } }
// 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.Data.Common; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace System.Data.SqlClient { internal class TdsParserStateObjectNative : TdsParserStateObject { private SNIHandle _sessionHandle = null; // the SNI handle we're to work on private SNIPacket _sniPacket = null; // Will have to re-vamp this for MARS internal SNIPacket _sniAsyncAttnPacket = null; // Packet to use to send Attn private readonly WritePacketCache _writePacketCache = new WritePacketCache(); // Store write packets that are ready to be re-used public TdsParserStateObjectNative(TdsParser parser) : base(parser) { } private GCHandle _gcHandle; // keeps this object alive until we're closed. private readonly Dictionary<IntPtr, SNIPacket> _pendingWritePackets = new Dictionary<IntPtr, SNIPacket>(); // Stores write packets that have been sent to SNI, but have not yet finished writing (i.e. we are waiting for SNI's callback) internal TdsParserStateObjectNative(TdsParser parser, TdsParserStateObject physicalConnection, bool async) : base(parser, physicalConnection, async) { } internal SNIHandle Handle => _sessionHandle; internal override uint Status => _sessionHandle != null ? _sessionHandle.Status : TdsEnums.SNI_UNINITIALIZED; internal override SessionHandle SessionHandle => SessionHandle.FromNativeHandle(_sessionHandle); protected override void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async) { Debug.Assert(physicalConnection is TdsParserStateObjectNative, "Expected a stateObject of type " + this.GetType()); TdsParserStateObjectNative nativeSNIObject = physicalConnection as TdsParserStateObjectNative; SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async); _sessionHandle = new SNIHandle(myInfo, nativeSNIObject.Handle); } private SNINativeMethodWrapper.ConsumerInfo CreateConsumerInfo(bool async) { SNINativeMethodWrapper.ConsumerInfo myInfo = new SNINativeMethodWrapper.ConsumerInfo(); Debug.Assert(_outBuff.Length == _inBuff.Length, "Unexpected unequal buffers."); myInfo.defaultBufferSize = _outBuff.Length; // Obtain packet size from outBuff size. if (async) { myInfo.readDelegate = SNILoadHandle.SingletonInstance.ReadAsyncCallbackDispatcher; myInfo.writeDelegate = SNILoadHandle.SingletonInstance.WriteAsyncCallbackDispatcher; _gcHandle = GCHandle.Alloc(this, GCHandleType.Normal); myInfo.key = (IntPtr)_gcHandle; } return myInfo; } internal override void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool fParallel, bool isIntegratedSecurity) { // We assume that the loadSSPILibrary has been called already. now allocate proper length of buffer spnBuffer = null; if (isIntegratedSecurity) { // now allocate proper length of buffer spnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength]; } SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async); // Translate to SNI timeout values (Int32 milliseconds) long timeout; if (long.MaxValue == timerExpire) { timeout = int.MaxValue; } else { timeout = ADP.TimerRemainingMilliseconds(timerExpire); if (timeout > int.MaxValue) { timeout = int.MaxValue; } else if (0 > timeout) { timeout = 0; } } _sessionHandle = new SNIHandle(myInfo, serverName, spnBuffer, ignoreSniOpenTimeout, checked((int)timeout), out instanceName, flushCache, !async, fParallel); } protected override uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize) { Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer"); return SNINativeMethodWrapper.SNIPacketGetData(packet.NativePointer, _inBuff, ref dataSize); } protected override bool CheckPacket(PacketHandle packet, TaskCompletionSource<object> source) { Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer"); IntPtr ptr = packet.NativePointer; return IntPtr.Zero == ptr || IntPtr.Zero != ptr && source != null; } public void ReadAsyncCallback(IntPtr key, IntPtr packet, uint error) => ReadAsyncCallback(key, packet, error); public void WriteAsyncCallback(IntPtr key, IntPtr packet, uint sniError) => WriteAsyncCallback(key, packet, sniError); protected override void RemovePacketFromPendingList(PacketHandle ptr) { Debug.Assert(ptr.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer"); IntPtr pointer = ptr.NativePointer; SNIPacket recoveredPacket; lock (_writePacketLockObject) { if (_pendingWritePackets.TryGetValue(pointer, out recoveredPacket)) { _pendingWritePackets.Remove(pointer); _writePacketCache.Add(recoveredPacket); } #if DEBUG else { Debug.Fail("Removing a packet from the pending list that was never added to it"); } #endif } } internal override void Dispose() { SafeHandle packetHandle = _sniPacket; SafeHandle sessionHandle = _sessionHandle; SafeHandle asyncAttnPacket = _sniAsyncAttnPacket; _sniPacket = null; _sessionHandle = null; _sniAsyncAttnPacket = null; DisposeCounters(); if (null != sessionHandle || null != packetHandle) { packetHandle?.Dispose(); asyncAttnPacket?.Dispose(); if (sessionHandle != null) { sessionHandle.Dispose(); DecrementPendingCallbacks(true); // Will dispose of GC handle. } } DisposePacketCache(); } protected override void FreeGcHandle(int remaining, bool release) { if ((0 == remaining || release) && _gcHandle.IsAllocated) { _gcHandle.Free(); } } internal override bool IsFailedHandle() => _sessionHandle.Status != TdsEnums.SNI_SUCCESS; internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error) { SNIHandle handle = Handle; if (handle == null) { throw ADP.ClosedConnectionError(); } IntPtr readPacketPtr = IntPtr.Zero; error = SNINativeMethodWrapper.SNIReadSyncOverAsync(handle, ref readPacketPtr, GetTimeoutRemaining()); return PacketHandle.FromNativePointer(readPacketPtr); } protected override PacketHandle EmptyReadPacket => PacketHandle.FromNativePointer(default); internal override bool IsPacketEmpty(PacketHandle readPacket) { Debug.Assert(readPacket.Type == PacketHandle.NativePointerType || readPacket.Type == 0, "unexpected packet type when requiring NativePointer"); return IntPtr.Zero == readPacket.NativePointer; } internal override void ReleasePacket(PacketHandle syncReadPacket) { Debug.Assert(syncReadPacket.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer"); SNINativeMethodWrapper.SNIPacketRelease(syncReadPacket.NativePointer); } internal override uint CheckConnection() { SNIHandle handle = Handle; return handle == null ? TdsEnums.SNI_SUCCESS : SNINativeMethodWrapper.SNICheckConnection(handle); } internal override PacketHandle ReadAsync(SessionHandle handle, out uint error) { Debug.Assert(handle.Type == SessionHandle.NativeHandleType, "unexpected handle type when requiring NativePointer"); IntPtr readPacketPtr = IntPtr.Zero; error = SNINativeMethodWrapper.SNIReadAsync(handle.NativeHandle, ref readPacketPtr); return PacketHandle.FromNativePointer(readPacketPtr); } internal override PacketHandle CreateAndSetAttentionPacket() { SNIHandle handle = Handle; SNIPacket attnPacket = new SNIPacket(handle); _sniAsyncAttnPacket = attnPacket; SetPacketData(PacketHandle.FromNativePacket(attnPacket), SQL.AttentionHeader, TdsEnums.HEADER_LEN); return PacketHandle.FromNativePacket(attnPacket); } internal override uint WritePacket(PacketHandle packet, bool sync) { Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket"); return SNINativeMethodWrapper.SNIWritePacket(Handle, packet.NativePacket, sync); } internal override PacketHandle AddPacketToPendingList(PacketHandle packetToAdd) { Debug.Assert(packetToAdd.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket"); SNIPacket packet = packetToAdd.NativePacket; Debug.Assert(packet == _sniPacket, "Adding a packet other than the current packet to the pending list"); _sniPacket = null; IntPtr pointer = packet.DangerousGetHandle(); lock (_writePacketLockObject) { _pendingWritePackets.Add(pointer, packet); } return PacketHandle.FromNativePointer(pointer); } internal override bool IsValidPacket(PacketHandle packetPointer) { Debug.Assert(packetPointer.Type == PacketHandle.NativePointerType || packetPointer.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePointer"); return ( (packetPointer.Type == PacketHandle.NativePointerType && packetPointer.NativePointer != IntPtr.Zero) || (packetPointer.Type == PacketHandle.NativePacketType && packetPointer.NativePacket != null) ); } internal override PacketHandle GetResetWritePacket(int dataSize) { if (_sniPacket != null) { SNINativeMethodWrapper.SNIPacketReset(Handle, SNINativeMethodWrapper.IOType.WRITE, _sniPacket, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI); } else { lock (_writePacketLockObject) { _sniPacket = _writePacketCache.Take(Handle); } } return PacketHandle.FromNativePacket(_sniPacket); } internal override void ClearAllWritePackets() { if (_sniPacket != null) { _sniPacket.Dispose(); _sniPacket = null; } lock (_writePacketLockObject) { Debug.Assert(_pendingWritePackets.Count == 0 && _asyncWriteCount == 0, "Should not clear all write packets if there are packets pending"); _writePacketCache.Clear(); } } internal override void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed) { Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket"); SNINativeMethodWrapper.SNIPacketSetData(packet.NativePacket, buffer, bytesUsed); } internal override uint SniGetConnectionId(ref Guid clientConnectionId) => SNINativeMethodWrapper.SniGetConnectionId(Handle, ref clientConnectionId); internal override uint DisabeSsl() => SNINativeMethodWrapper.SNIRemoveProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV); internal override uint EnableMars(ref uint info) => SNINativeMethodWrapper.SNIAddProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SMUX_PROV, ref info); internal override uint EnableSsl(ref uint info) { // Add SSL (Encryption) SNI provider. return SNINativeMethodWrapper.SNIAddProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV, ref info); } internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) => SNINativeMethodWrapper.SNISetInfo(Handle, SNINativeMethodWrapper.QTypes.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize); internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer) => SNINativeMethodWrapper.SNISecGenClientContext(Handle, receivedBuff, receivedLength, sendBuff, ref sendLength, _sniSpnBuffer); internal override uint WaitForSSLHandShakeToComplete() => SNINativeMethodWrapper.SNIWaitForSSLHandshakeToComplete(Handle, GetTimeoutRemaining()); internal override void DisposePacketCache() { lock (_writePacketLockObject) { _writePacketCache.Dispose(); // Do not set _writePacketCache to null, just in case a WriteAsyncCallback completes after this point } } internal sealed class WritePacketCache : IDisposable { private bool _disposed; private readonly Stack<SNIPacket> _packets; public WritePacketCache() { _disposed = false; _packets = new Stack<SNIPacket>(); } public SNIPacket Take(SNIHandle sniHandle) { SNIPacket packet; if (_packets.Count > 0) { // Success - reset the packet packet = _packets.Pop(); SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI); } else { // Failed to take a packet - create a new one packet = new SNIPacket(sniHandle); } return packet; } public void Add(SNIPacket packet) { if (!_disposed) { _packets.Push(packet); } else { // If we're disposed, then get rid of any packets added to us packet.Dispose(); } } public void Clear() { while (_packets.Count > 0) { _packets.Pop().Dispose(); } } public void Dispose() { if (!_disposed) { _disposed = true; Clear(); } } } } }
using System; using System.Diagnostics; using System.Collections; using System.Runtime.InteropServices; using System.ComponentModel; namespace Defrag { public class IOWrapper { const uint FILE_SHARE_READ = 0x00000001; const uint FILE_SHARE_WRITE = 0x00000002; const uint FILE_SHARE_DELETE = 0x00000004; const uint OPEN_EXISTING = 3; const uint GENERIC_READ = (0x80000000); const uint GENERIC_WRITE = (0x40000000); const uint FILE_FLAG_NO_BUFFERING = 0x20000000; const uint FILE_READ_ATTRIBUTES = (0x0080); const uint FILE_WRITE_ATTRIBUTES = 0x0100; const uint ERROR_INSUFFICIENT_BUFFER = 122; [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateFile( string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] static extern int CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", SetLastError = true)] static extern bool DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, [Out] IntPtr lpOutBuffer, uint nOutBufferSize, ref uint lpBytesReturned, IntPtr lpOverlapped); static private IntPtr OpenVolume(string DeviceName) { IntPtr hDevice; hDevice = CreateFile( @"\\.\" + DeviceName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if ((int)hDevice == -1) { throw new Win32Exception(); } return hDevice; } static private IntPtr OpenFile(string path) { IntPtr hFile; hFile = CreateFile( path, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); if ((int)hFile == -1) { throw new Win32Exception(); } return hFile; } /// <summary> /// Get cluster usage for a device /// </summary> /// <param name="DeviceName">use "c:"</param> /// <returns>a bitarray for each cluster</returns> static public BitArray GetVolumeMap(string DeviceName) { IntPtr pAlloc = IntPtr.Zero; IntPtr hDevice = IntPtr.Zero; try { hDevice = OpenVolume(DeviceName); Int64 i64 = 0; GCHandle handle = GCHandle.Alloc(i64, GCHandleType.Pinned); IntPtr p = handle.AddrOfPinnedObject(); // alloc off more than enough for my machine // 64 megs == 67108864 bytes == 536870912 bits == cluster count // NTFS 4k clusters == 2147483648 k of storage == 2097152 megs == 2048 gig disk storage uint q = 1024 * 1024 * 64; // 1024 bytes == 1k * 1024 == 1 meg * 64 == 64 megs uint size = 0; pAlloc = Marshal.AllocHGlobal((int)q); IntPtr pDest = pAlloc; bool fResult = DeviceIoControl( hDevice, FSConstants.FSCTL_GET_VOLUME_BITMAP, p, (uint)Marshal.SizeOf(i64), pDest, q, ref size, IntPtr.Zero); if (!fResult) { throw new Win32Exception(); } handle.Free(); /* object returned was... typedef struct { LARGE_INTEGER StartingLcn; LARGE_INTEGER BitmapSize; BYTE Buffer[1]; } VOLUME_BITMAP_BUFFER, *PVOLUME_BITMAP_BUFFER; */ Int64 StartingLcn = (Int64)Marshal.PtrToStructure(pDest, typeof(Int64)); Debug.Assert(StartingLcn == 0); pDest = (IntPtr)((Int64)pDest + 8); Int64 BitmapSize = (Int64)Marshal.PtrToStructure(pDest, typeof(Int64)); Int32 byteSize = (int)(BitmapSize / 8); byteSize++; // round up - even with no remainder IntPtr BitmapBegin = (IntPtr)((Int64)pDest + 8); byte[] byteArr = new byte[byteSize]; Marshal.Copy(BitmapBegin, byteArr, 0, (Int32)byteSize); BitArray retVal = new BitArray(byteArr); retVal.Length = (int)BitmapSize; // truncate to exact cluster count return retVal; } finally { CloseHandle(hDevice); hDevice = IntPtr.Zero; Marshal.FreeHGlobal(pAlloc); pAlloc = IntPtr.Zero; } } /// <summary> /// returns a 2*number of extents array - /// the vcn and the lcn as pairs /// </summary> /// <param name="path">file to get the map for ex: "c:\windows\explorer.exe" </param> /// <returns>An array of [virtual cluster, physical cluster]</returns> static public Array GetFileMap(string path) { IntPtr hFile = IntPtr.Zero; IntPtr pAlloc = IntPtr.Zero; try { hFile = OpenFile(path); Int64 i64 = 0; GCHandle handle = GCHandle.Alloc(i64, GCHandleType.Pinned); IntPtr p = handle.AddrOfPinnedObject(); uint q = 1024 * 1024 * 64; // 1024 bytes == 1k * 1024 == 1 meg * 64 == 64 megs uint size = 0; pAlloc = Marshal.AllocHGlobal((int)q); IntPtr pDest = pAlloc; bool fResult = DeviceIoControl( hFile, FSConstants.FSCTL_GET_RETRIEVAL_POINTERS, p, (uint)Marshal.SizeOf(i64), pDest, q, ref size, IntPtr.Zero); if (!fResult) { throw new Win32Exception(); } handle.Free(); /* returned back one of... typedef struct RETRIEVAL_POINTERS_BUFFER { DWORD ExtentCount; LARGE_INTEGER StartingVcn; struct { LARGE_INTEGER NextVcn; LARGE_INTEGER Lcn; } Extents[1]; } RETRIEVAL_POINTERS_BUFFER, *PRETRIEVAL_POINTERS_BUFFER; */ Int32 ExtentCount = (Int32)Marshal.PtrToStructure(pDest, typeof(Int32)); pDest = (IntPtr)((Int64)pDest + 4); Int64 StartingVcn = (Int64)Marshal.PtrToStructure(pDest, typeof(Int64)); Debug.Assert(StartingVcn == 0); pDest = (IntPtr)((Int64)pDest + 8); // now pDest points at an array of pairs of Int64s. Array retVal = Array.CreateInstance(typeof(UInt64), new int[2] { ExtentCount, 2 }); for (int i = 0; i < ExtentCount; i++) { for (int j = 0; j < 2; j++) { UInt64 v = (UInt64)Marshal.PtrToStructure(pDest, typeof(UInt64)); v = (v >> 32) | (v & 0xffffffff) << 32; retVal.SetValue(v, new int[2] { i, j }); pDest = (IntPtr)((Int64)pDest + 8); } } return retVal; } finally { CloseHandle(hFile); hFile = IntPtr.Zero; Marshal.FreeHGlobal(pAlloc); pAlloc = IntPtr.Zero; } } /// <summary> /// input structure for use in MoveFile /// </summary> private struct MoveFileData { public IntPtr hFile; public Int64 StartingVCN; public Int64 StartingLCN; public Int32 ClusterCount; } /// <summary> /// move a virtual cluster for a file to a logical cluster on disk, repeat for count clusters /// </summary> /// <param name="deviceName">device to move on"c:"</param> /// <param name="path">file to muck with "c:\windows\explorer.exe"</param> /// <param name="VCN">cluster number in file to move</param> /// <param name="LCN">cluster on disk to move to</param> /// <param name="count">for how many clusters</param> static public void MoveFile(string deviceName, string path, Int64 VCN, Int64 LCN, Int32 count) { IntPtr hVol = IntPtr.Zero; IntPtr hFile = IntPtr.Zero; try { hVol = OpenVolume(deviceName); hFile = OpenFile(path); MoveFileData mfd = new MoveFileData(); mfd.hFile = hFile; mfd.StartingVCN = VCN; mfd.StartingLCN = LCN; mfd.ClusterCount = count; GCHandle handle = GCHandle.Alloc(mfd, GCHandleType.Pinned); IntPtr p = handle.AddrOfPinnedObject(); uint bufSize = (uint)Marshal.SizeOf(mfd); uint size = 0; bool fResult = DeviceIoControl( hVol, FSConstants.FSCTL_MOVE_FILE, p, bufSize, IntPtr.Zero, // no output data from this FSCTL 0, ref size, IntPtr.Zero); handle.Free(); if (!fResult) { throw new Win32Exception(); } } finally { CloseHandle(hVol); CloseHandle(hFile); } } } /// <summary> /// constants lifted from winioctl.h from platform sdk /// </summary> internal class FSConstants { const uint FILE_DEVICE_FILE_SYSTEM = 0x00000009; const uint METHOD_NEITHER = 3; const uint METHOD_BUFFERED = 0; const uint FILE_ANY_ACCESS = 0; const uint FILE_SPECIAL_ACCESS = FILE_ANY_ACCESS; public static uint FSCTL_GET_VOLUME_BITMAP = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 27, METHOD_NEITHER, FILE_ANY_ACCESS); public static uint FSCTL_GET_RETRIEVAL_POINTERS = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 28, METHOD_NEITHER, FILE_ANY_ACCESS); public static uint FSCTL_MOVE_FILE = CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 29, METHOD_BUFFERED, FILE_SPECIAL_ACCESS); static uint CTL_CODE(uint DeviceType, uint Function, uint Method, uint Access) { return ((DeviceType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Xunit; public static unsafe class DateTimeTests { [Fact] public static void TestConstructors() { DateTime dt = new DateTime(2012, 6, 11); ValidateYearMonthDay(dt, 2012, 6, 11); dt = new DateTime(2012, 12, 31, 13, 50, 10); ValidateYearMonthDay(dt, 2012, 12, 31, 13, 50, 10); dt = new DateTime(1973, 10, 6, 14, 30, 0, 500); ValidateYearMonthDay(dt, 1973, 10, 6, 14, 30, 0, 500); dt = new DateTime(1986, 8, 15, 10, 20, 5, DateTimeKind.Local); ValidateYearMonthDay(dt, 1986, 8, 15, 10, 20, 5); } [Fact] public static void TestDateTimeLimits() { DateTime dt = DateTime.MaxValue; ValidateYearMonthDay(dt, 9999, 12, 31); dt = DateTime.MinValue; ValidateYearMonthDay(dt, 1, 1, 1); } [Fact] public static void TestLeapYears() { Assert.Equal(true, DateTime.IsLeapYear(2004)); Assert.Equal(false, DateTime.IsLeapYear(2005)); } [Fact] public static void TestAddition() { DateTime dt = new DateTime(1986, 8, 15, 10, 20, 5, 70); Assert.Equal(17, dt.AddDays(2).Day); Assert.Equal(13, dt.AddDays(-2).Day); Assert.Equal(10, dt.AddMonths(2).Month); Assert.Equal(6, dt.AddMonths(-2).Month); Assert.Equal(1996, dt.AddYears(10).Year); Assert.Equal(1976, dt.AddYears(-10).Year); Assert.Equal(13, dt.AddHours(3).Hour); Assert.Equal(7, dt.AddHours(-3).Hour); Assert.Equal(25, dt.AddMinutes(5).Minute); Assert.Equal(15, dt.AddMinutes(-5).Minute); Assert.Equal(35, dt.AddSeconds(30).Second); Assert.Equal(2, dt.AddSeconds(-3).Second); Assert.Equal(80, dt.AddMilliseconds(10).Millisecond); Assert.Equal(60, dt.AddMilliseconds(-10).Millisecond); } [Fact] public static void TestDayOfWeek() { DateTime dt = new DateTime(2012, 6, 18); Assert.Equal(DayOfWeek.Monday, dt.DayOfWeek); } [Fact] public static void TestTimeSpan() { DateTime dt = new DateTime(2012, 6, 18, 10, 5, 1, 0); TimeSpan ts = dt.TimeOfDay; DateTime newDate = dt.Subtract(ts); Assert.Equal(new DateTime(2012, 6, 18, 0, 0, 0, 0).Ticks, newDate.Ticks); Assert.Equal(dt.Ticks, newDate.Add(ts).Ticks); } [Fact] public static void TestToday() { DateTime today = DateTime.Today; DateTime now = DateTime.Now; ValidateYearMonthDay(today, now.Year, now.Month, now.Day); today = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, DateTimeKind.Utc); Assert.Equal(DateTimeKind.Utc, today.Kind); Assert.Equal(false, today.IsDaylightSavingTime()); } [Fact] public static void TestCoversion() { DateTime today = DateTime.Today; long dateTimeRaw = today.ToBinary(); Assert.Equal(today, DateTime.FromBinary(dateTimeRaw)); dateTimeRaw = today.ToFileTime(); Assert.Equal(today, DateTime.FromFileTime(dateTimeRaw)); dateTimeRaw = today.ToFileTimeUtc(); Assert.Equal(today, DateTime.FromFileTimeUtc(dateTimeRaw).ToLocalTime()); } [Fact] public static void TestOperators() { System.DateTime date1 = new System.DateTime(1996, 6, 3, 22, 15, 0); System.DateTime date2 = new System.DateTime(1996, 12, 6, 13, 2, 0); System.DateTime date3 = new System.DateTime(1996, 10, 12, 8, 42, 0); // diff1 gets 185 days, 14 hours, and 47 minutes. System.TimeSpan diff1 = date2.Subtract(date1); Assert.Equal(new TimeSpan(185, 14, 47, 0), diff1); // date4 gets 4/9/1996 5:55:00 PM. System.DateTime date4 = date3.Subtract(diff1); Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date4); // diff2 gets 55 days 4 hours and 20 minutes. System.TimeSpan diff2 = date2 - date3; Assert.Equal(new TimeSpan(55, 4, 20, 0), diff2); // date5 gets 4/9/1996 5:55:00 PM. System.DateTime date5 = date1 - diff2; Assert.Equal(new DateTime(1996, 4, 9, 17, 55, 0), date5); } [Fact] public static void TestParsingDateTimeWithTimeDesignator() { DateTime result; Assert.True(DateTime.TryParse("4/21 5am", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(4, result.Month); Assert.Equal(21, result.Day); Assert.Equal(5, result.Hour); Assert.True(DateTime.TryParse("4/21 5pm", new CultureInfo("en-US"), DateTimeStyles.None, out result)); Assert.Equal(4, result.Month); Assert.Equal(21, result.Day); Assert.Equal(17, result.Hour); } public class MyFormater : IFormatProvider { public object GetFormat(Type formatType) { if (typeof(IFormatProvider) == formatType) { return this; } else { return null; } } } [Fact] public static void TestParseWithAdjustToUniversal() { var formater = new MyFormater(); var dateBefore = DateTime.Now.ToString(); var dateAfter = DateTime.ParseExact(dateBefore, "G", formater, DateTimeStyles.AdjustToUniversal); Assert.Equal(dateBefore, dateAfter.ToString()); } [Fact] public static void TestFormatParse() { DateTime dt = new DateTime(2012, 12, 21, 10, 8, 6); CultureInfo ci = new CultureInfo("ja-JP"); string s = string.Format(ci, "{0}", dt); Assert.Equal(dt, DateTime.Parse(s, ci)); } [Fact] public static void TestParse1() { DateTime src = DateTime.MaxValue; String s = src.ToString(); DateTime in_1 = DateTime.Parse(s); String actual = in_1.ToString(); Assert.Equal(s, actual); } [Fact] public static void TestParse2() { DateTime src = DateTime.MaxValue; String s = src.ToString(); DateTime in_1 = DateTime.Parse(s, null); String actual = in_1.ToString(); Assert.Equal(s, actual); } [Fact] public static void TestParse3() { DateTime src = DateTime.MaxValue; String s = src.ToString(); DateTime in_1 = DateTime.Parse(s, null, DateTimeStyles.None); String actual = in_1.ToString(); Assert.Equal(s, actual); } [Fact] public static void TestParseExact3() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1 = DateTime.ParseExact(s, "g", null); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestParseExact4() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1 = DateTime.ParseExact(s, "g", null, DateTimeStyles.None); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestParseExact4a() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); String[] formats = { "g" }; DateTime in_1 = DateTime.ParseExact(s, formats, null, DateTimeStyles.None); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParse2() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1; bool b = DateTime.TryParse(s, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParse4() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1; bool b = DateTime.TryParse(s, null, DateTimeStyles.None, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParseExact() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); DateTime in_1; bool b = DateTime.TryParseExact(s, "g", null, DateTimeStyles.None, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestTryParseExactA() { DateTime src = DateTime.MaxValue; String s = src.ToString("g"); String[] formats = { "g" }; DateTime in_1; bool b = DateTime.TryParseExact(s, formats, null, DateTimeStyles.None, out in_1); Assert.True(b); String actual = in_1.ToString("g"); Assert.Equal(s, actual); } [Fact] public static void TestGetDateTimeFormats() { char[] allStandardFormats = { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y', }; DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); List<string> july28Formats = new List<string>(); foreach (char format in allStandardFormats) { string[] dates = july28.GetDateTimeFormats(format); Assert.True(dates.Length > 0); DateTime parsedDate; Assert.True(DateTime.TryParseExact(dates[0], format.ToString(), CultureInfo.CurrentCulture, DateTimeStyles.None, out parsedDate)); july28Formats.AddRange(dates); } List<string> actualJuly28Formats = july28.GetDateTimeFormats().ToList(); Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t)); actualJuly28Formats = july28.GetDateTimeFormats(CultureInfo.CurrentCulture).ToList(); Assert.Equal(july28Formats.OrderBy(t => t), actualJuly28Formats.OrderBy(t => t)); } [Theory] [InlineData("fi-FI")] [InlineData("nb-NO")] [InlineData("nb-SJ")] [InlineData("sr-Cyrl-XK")] [InlineData("sr-Latn-ME")] [InlineData("sr-Latn-RS")] [InlineData("sr-Latn-XK")] public static void TestSpecialCulturesParsing(string cultureName) { // Test DateTime parsing with cultures which has the date separator and time separator are same CultureInfo ci; try { ci = new CultureInfo(cultureName); } catch (CultureNotFoundException) { // ignore un-supported culture in current platform return; } DateTime date = new DateTime(2015, 11, 20, 11, 49, 50); string dateString = date.ToString(ci.DateTimeFormat.ShortDatePattern, ci); DateTime parsedDate; Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); if (ci.DateTimeFormat.ShortDatePattern.Contains("yyyy")) { Assert.Equal(date.Date, parsedDate); } else { // When the date separator and time separator are the same, DateTime.TryParse cannot // tell the difference between a short date like dd.MM.yy and a short time // like HH.mm.ss. So it assumes that if it gets 03.04.11, that must be a time // and uses the current date to construct the date time. DateTime now = DateTime.Now; Assert.Equal(new DateTime(now.Year, now.Month, now.Day, date.Day, date.Month, date.Year % 100), parsedDate); } dateString = date.ToString(ci.DateTimeFormat.LongDatePattern, ci); Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date.Date, parsedDate); dateString = date.ToString(ci.DateTimeFormat.FullDateTimePattern, ci); Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date, parsedDate); dateString = date.ToString(ci.DateTimeFormat.LongTimePattern, ci); Assert.True(DateTime.TryParse(dateString, ci, DateTimeStyles.None, out parsedDate)); Assert.Equal(date.TimeOfDay, parsedDate.TimeOfDay); } [Fact] public static void TestGetDateTimeFormats_FormatSpecifier_InvalidFormat() { DateTime july28 = new DateTime(2009, 7, 28, 5, 23, 15); Assert.Throws<FormatException>(() => july28.GetDateTimeFormats('x')); } internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day) { Assert.Equal(dt.Year, year); Assert.Equal(dt.Month, month); Assert.Equal(dt.Day, day); } internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second) { ValidateYearMonthDay(dt, year, month, day); Assert.Equal(dt.Hour, hour); Assert.Equal(dt.Minute, minute); Assert.Equal(dt.Second, second); } internal static void ValidateYearMonthDay(DateTime dt, int year, int month, int day, int hour, int minute, int second, int millisecond) { ValidateYearMonthDay(dt, year, month, day, hour, minute, second); Assert.Equal(dt.Millisecond, millisecond); } }
// Copyright 2012 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Annotations; using NodaTime.Text; using NodaTime.Utility; using System; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace NodaTime { /// <summary> /// A mutable builder class for <see cref="Period"/> values. Each property can /// be set independently, and then a Period can be created from the result /// using the <see cref="Build"/> method. /// </summary> /// <threadsafety> /// This type is not thread-safe without extra synchronization, but has no /// thread affinity. /// </threadsafety> [Mutable] public sealed class PeriodBuilder : IXmlSerializable { #region Properties /// <summary> /// Gets or sets the number of years within the period. /// </summary> /// <value>The number of years within the period.</value> public int Years { get; set; } /// <summary> /// Gets or sets the number of months within the period. /// </summary> /// <value>The number of months within the period.</value> public int Months { get; set; } /// <summary> /// Gets or sets the number of weeks within the period. /// </summary> /// <value>The number of weeks within the period.</value> public int Weeks { get; set; } /// <summary> /// Gets or sets the number of days within the period. /// </summary> /// <value>The number of days within the period.</value> public int Days { get; set; } /// <summary> /// Gets or sets the number of hours within the period. /// </summary> /// <value>The number of hours within the period.</value> public long Hours { get; set; } /// <summary> /// Gets or sets the number of minutes within the period. /// </summary> /// <value>The number of minutes within the period.</value> public long Minutes { get; set; } /// <summary> /// Gets or sets the number of seconds within the period. /// </summary> /// <value>The number of seconds within the period.</value> public long Seconds { get; set; } /// <summary> /// Gets or sets the number of milliseconds within the period. /// </summary> /// <value>The number of milliseconds within the period.</value> public long Milliseconds { get; set; } /// <summary> /// Gets or sets the number of ticks within the period. /// </summary> /// <value>The number of ticks within the period.</value> public long Ticks { get; set; } /// <summary> /// Gets or sets the number of nanoseconds within the period. /// </summary> /// <value>The number of nanoseconds within the period.</value> public long Nanoseconds { get; set; } #endregion /// <summary> /// Creates a new period builder with an initially zero period. /// </summary> public PeriodBuilder() { } /// <summary> /// Creates a new period builder with the values from an existing /// period. Calling this constructor instead of <see cref="Period.ToBuilder"/> /// allows object initializers to be used. /// </summary> /// <param name="period">An existing period to copy values from.</param> public PeriodBuilder(Period period) { Preconditions.CheckNotNull(period, nameof(period)); Years = period.Years; Months = period.Months; Weeks = period.Weeks; Days = period.Days; Hours = period.Hours; Minutes = period.Minutes; Seconds = period.Seconds; Milliseconds = period.Milliseconds; Ticks = period.Ticks; Nanoseconds = period.Nanoseconds; } /// <summary> /// Gets or sets the value of a single unit. /// </summary> /// <remarks> /// <para> /// The type of this indexer is <see cref="System.Int64"/> for uniformity, but any date unit (year, month, week, day) will only ever have a value /// in the range of <see cref="System.Int32"/>. /// </para> /// <para> /// For the <see cref="PeriodUnits.Nanoseconds"/> unit, the value is converted to <c>Int64</c> when reading from the indexer, causing it to /// fail if the value is out of range (around 250 years). To access the values of very large numbers of nanoseconds, use the <see cref="Nanoseconds"/> /// property directly. /// </para> /// </remarks> /// <param name="unit">A single value within the <see cref="PeriodUnits"/> enumeration.</param> /// <value>The value of the given unit within this period builder, or zero if the unit is unset.</value> /// <exception cref="ArgumentOutOfRangeException"><paramref name="unit"/> is not a single unit, or a value is provided for a date unit which is outside the range of <see cref="System.Int32"/>.</exception> public long this[PeriodUnits unit] { get => unit switch { PeriodUnits.Years => Years, PeriodUnits.Months => Months, PeriodUnits.Weeks => Weeks, PeriodUnits.Days => Days, PeriodUnits.Hours => Hours, PeriodUnits.Minutes => Minutes, PeriodUnits.Seconds => Seconds, PeriodUnits.Milliseconds => Milliseconds, PeriodUnits.Ticks => Ticks, PeriodUnits.Nanoseconds => Nanoseconds, _ => throw new ArgumentOutOfRangeException(nameof(unit), "Indexer for PeriodBuilder only takes a single unit") }; set { if ((unit & PeriodUnits.AllDateUnits) != 0) { Preconditions.CheckArgumentRange(nameof(value), value, int.MinValue, int.MaxValue); } switch (unit) { case PeriodUnits.Years: Years = (int) value; return; case PeriodUnits.Months: Months = (int) value; return; case PeriodUnits.Weeks: Weeks = (int) value; return; case PeriodUnits.Days: Days = (int) value; return; case PeriodUnits.Hours: Hours = value; return; case PeriodUnits.Minutes: Minutes = value; return; case PeriodUnits.Seconds: Seconds = value; return; case PeriodUnits.Milliseconds: Milliseconds = value; return; case PeriodUnits.Ticks: Ticks = value; return; case PeriodUnits.Nanoseconds: Nanoseconds = value; return; default: throw new ArgumentOutOfRangeException(nameof(unit), "Indexer for PeriodBuilder only takes a single unit"); } } } /// <summary> /// Builds a period from the properties in this builder. /// </summary> /// <returns>A period containing the values from this builder.</returns> public Period Build() => new Period(Years, Months, Weeks, Days, Hours, Minutes, Seconds, Milliseconds, Ticks, Nanoseconds); /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that /// <inheritdoc /> void IXmlSerializable.ReadXml(XmlReader reader) { string text = reader.ReadElementContentAsString(); Period period = PeriodPattern.Roundtrip.Parse(text).Value; Years = period.Years; Months = period.Months; Weeks = period.Weeks; Days = period.Days; Hours = period.Hours; Minutes = period.Minutes; Seconds = period.Seconds; Milliseconds = period.Milliseconds; Ticks = period.Ticks; Nanoseconds = period.Nanoseconds; } /// <inheritdoc /> void IXmlSerializable.WriteXml(XmlWriter writer) { writer.WriteString(PeriodPattern.Roundtrip.Format(Build())); } } }
namespace NEventStore.Persistence.Sql.SqlDialects { using System; using System.Data; using System.Reflection; using System.Transactions; using NEventStore.Persistence.Sql; public class OracleNativeDialect : CommonSqlDialect { private Action<IConnectionFactory, IDbConnection, IDbStatement, byte[]> _addPayloadParamater; public override string AppendSnapshotToCommit { get { return OracleNativeStatements.AppendSnapshotToCommit; } } public override string CheckpointNumber { get { return MakeOracleParameter(base.CheckpointNumber); } } public override string FromCheckpointNumber { get { return MakeOracleParameter(base.FromCheckpointNumber); } } public override string ToCheckpointNumber { get { return MakeOracleParameter(base.ToCheckpointNumber); } } public override string CommitId { get { return MakeOracleParameter(base.CommitId); } } public override string CommitSequence { get { return MakeOracleParameter(base.CommitSequence); } } public override string CommitStamp { get { return MakeOracleParameter(base.CommitStamp); } } public override string CommitStampEnd { get { return MakeOracleParameter(base.CommitStampEnd); } } public override string CommitStampStart { get { return MakeOracleParameter(CommitStampStart); } } public override string DuplicateCommit { get { return OracleNativeStatements.DuplicateCommit; } } public override string GetSnapshot { get { return OracleNativeStatements.GetSnapshot; } } public override string GetCommitsFromStartingRevision { get { return LimitedQuery(OracleNativeStatements.GetCommitsFromStartingRevision); } } public override string GetCommitsFromInstant { get { return OraclePaging(OracleNativeStatements.GetCommitsFromInstant); } } public override string GetCommitsFromCheckpoint { get { return OraclePaging(OracleNativeStatements.GetCommitsSinceCheckpoint); } } public override string GetCommitsFromToCheckpoint { get { return OraclePaging(OracleNativeStatements.GetCommitsSinceToCheckpoint); } } public override string GetCommitsFromBucketAndCheckpoint { get { return OraclePaging(OracleNativeStatements.GetCommitsFromBucketAndCheckpoint); } } public override string GetCommitsFromToBucketAndCheckpoint { get { return OraclePaging(OracleNativeStatements.GetCommitsFromToBucketAndCheckpoint); } } public override string GetStreamsRequiringSnapshots { get { return LimitedQuery(OracleNativeStatements.GetStreamsRequiringSnapshots); } } public override string InitializeStorage { get { return OracleNativeStatements.InitializeStorage; } } public override string Limit { get { return MakeOracleParameter(base.Limit); } } public override string PersistCommit { get { return OracleNativeStatements.PersistCommit; } } public override string PurgeStorage { get { return OracleNativeStatements.PurgeStorage; } } public override string DeleteStream { get { return OracleNativeStatements.DeleteStream; } } public override string Drop { get { return OracleNativeStatements.DropTables; } } public override string Skip { get { return MakeOracleParameter(base.Skip); } } public override string BucketId { get { return MakeOracleParameter(base.BucketId); } } public override string StreamId { get { return MakeOracleParameter(base.StreamId); } } public override string StreamIdOriginal { get { return MakeOracleParameter(base.StreamIdOriginal); } } public override string Threshold { get { return MakeOracleParameter(base.Threshold); } } public override string Payload { get { return MakeOracleParameter(base.Payload); } } public override string StreamRevision { get { return MakeOracleParameter(base.StreamRevision); } } public override string MaxStreamRevision { get { return MakeOracleParameter(base.MaxStreamRevision); } } public override IDbStatement BuildStatement(TransactionScope scope, IDbConnection connection, IDbTransaction transaction) { return new OracleDbStatement(this, scope, connection, transaction); } public override object CoalesceParameterValue(object value) { if (value is Guid) { value = ((Guid)value).ToByteArray(); } return value; } private static string ExtractOrderBy(ref string query) { int orderByIndex = query.IndexOf("ORDER BY", StringComparison.Ordinal); string result = query.Substring(orderByIndex).Replace(";", String.Empty); query = query.Substring(0, orderByIndex); return result; } public override bool IsDuplicate(Exception exception) { return exception.Message.Contains("ORA-00001"); } public override NextPageDelegate NextPageDelegate { get { return (q, r) => { }; } } public override void AddPayloadParamater(IConnectionFactory connectionFactory, IDbConnection connection, IDbStatement cmd, byte[] payload) { if (_addPayloadParamater == null) { string dbProviderAssemblyName = connectionFactory.GetDbProviderFactoryType().Assembly.GetName().Name; const string oracleManagedDataAcccessAssemblyName = "Oracle.ManagedDataAccess"; const string oracleDataAcccessAssemblyName = "Oracle.DataAccess"; if (dbProviderAssemblyName.Equals(oracleManagedDataAcccessAssemblyName, StringComparison.Ordinal)) { _addPayloadParamater = CreateOraAddPayloadAction(oracleManagedDataAcccessAssemblyName); } else if (dbProviderAssemblyName.Equals(oracleDataAcccessAssemblyName, StringComparison.Ordinal)) { _addPayloadParamater = CreateOraAddPayloadAction(oracleDataAcccessAssemblyName); } else { _addPayloadParamater = (connectionFactory2, connection2, cmd2, payload2) => base.AddPayloadParamater(connectionFactory2, connection2, cmd2, payload2); } } _addPayloadParamater(connectionFactory, connection, cmd, payload); } private Action<IConnectionFactory, IDbConnection, IDbStatement, byte[]> CreateOraAddPayloadAction( string assemblyName) { Assembly assembly = Assembly.Load(assemblyName); var oracleParamaterType = assembly.GetType(assemblyName + ".Client.OracleParameter", true); var oracleParamaterValueProperty = oracleParamaterType.GetProperty("Value"); var oracleBlobType = assembly.GetType(assemblyName + ".Types.OracleBlob", true); var oracleBlobWriteMethod = oracleBlobType.GetMethod("Write", new[] { typeof(Byte[]), typeof(int), typeof(int) }); Type oracleParamapterType = assembly.GetType(assemblyName + ".Client.OracleDbType", true); FieldInfo blobField = oracleParamapterType.GetField("Blob"); var blobDbType = blobField.GetValue(null); return (_, connection2, cmd2, payload2) => { object payloadParam = Activator.CreateInstance(oracleParamaterType, new[] { Payload, blobDbType }); ((OracleDbStatement)cmd2).AddParameter(Payload, payloadParam); object oracleConnection = ((ConnectionScope)connection2).Current; object oracleBlob = Activator.CreateInstance(oracleBlobType, new[] { oracleConnection }); oracleBlobWriteMethod.Invoke(oracleBlob, new object[] { payload2, 0, payload2.Length }); oracleParamaterValueProperty.SetValue(payloadParam, oracleBlob, null); }; } private static string LimitedQuery(string query) { query = RemovePaging(query); if (query.EndsWith(";")) { query = query.TrimEnd(new[] { ';' }); } string value = OracleNativeStatements.LimitedQueryFormat.FormatWith(query); return value; } private static string MakeOracleParameter(string parameterName) { return parameterName.Replace('@', ':'); } private static string OraclePaging(string query) { query = RemovePaging(query); string orderBy = ExtractOrderBy(ref query); int fromIndex = query.IndexOf("FROM ", StringComparison.Ordinal); string from = query.Substring(fromIndex); string select = query.Substring(0, fromIndex); string value = OracleNativeStatements.PagedQueryFormat.FormatWith(select, orderBy, from); return value; } private static string RemovePaging(string query) { return query .Replace("\n LIMIT @Limit OFFSET @Skip;", ";") .Replace("\n LIMIT @Limit;", ";") .Replace("WHERE ROWNUM <= :Limit;", ";") .Replace("\r\nWHERE ROWNUM <= (:Skip + 1) AND ROWNUM > :Skip", ";"); } } }