context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Rhino.Mocks; using VersionOne.Bugzilla.BugzillaAPI; using VersionOne.ServiceHost.BugzillaServices; using VersionOne.ServiceHost.Core.Configuration; using VersionOne.ServiceHost.Core.Logging; using VersionOne.ServiceHost.Tests.WorkitemServices.Bugzilla; using VersionOne.ServiceHost.WorkitemServices; namespace VersionOne.Integration.Bugzilla.Tests { [TestClass] public class BugzillaReaderUpdaterTester { private const string userName = "fred"; private const string password = "12345"; private const string expectedUrl = "http://localhost/v1.cgi"; private const string expectedUserId = "123"; private const string expectedFilterId = "filtid"; private const int productId = 333; private const string productName = "Expected Name"; private const string v1ProjectId = "Scope:1234"; private const string v1PriorityId = "WorkitemPriority:1"; private const string expectedPriority = "Normal"; private const string assignTo = "[email protected]"; [TestMethod, Ignore] public void GetBugsNoUrl() { // This test wasn't working when we picked up work on the RESTful client in Sept/Oct of 2016. // Not sure why it was left in a failing state. We were pressed for time (surprise... surprise) and // for the near term have left this test in a failing state. Need to look closer at its intent // and make things right. GetBugs(GetStockConfig()); } [TestMethod, Ignore] public void GetBugsWithUrl() { // This test wasn't working when we picked up work on the RESTful client in Sept/Oct of 2016. // Not sure why it was left in a failing state. We were pressed for time (surprise... surprise) and // for the near term have left this test in a failing state. Need to look closer at its intent // and make things right. BugzillaServiceConfiguration config = GetStockConfig(); config.UrlTemplateToIssue = "http://localhost/show_bug.cgi?id=#key#"; config.UrlTitleToIssue = "Bugz"; GetBugs(config); } private void GetBugs(BugzillaServiceConfiguration config) { BugzillaMocks mocks = new BugzillaMocks(); List<Bug> expectedBugs = CreateSomeBogusRemoteBugs(5); List<int> expectedIds = new List<int>(); // Product expectedProduct = Product.Create(new GetProductResult(productId, productName, "Expected Descr")); // User expectedOwner = User.Create(new GetUserResult(ownerId, "Fred", "FredsLogin")); foreach (Bug bug in expectedBugs) { expectedIds.Add(int.Parse(bug.ID)); } // SetupResult.For(mocks.ClientFactory.CreateNew(config.Url, mocks.Logger)).Return(mocks.Client); Expect.Call(mocks.Client.Login()).Return(expectedUserId); for (int i = 0; i < expectedBugs.Count; i++) { Bug bug = expectedBugs[i]; Expect.Call(mocks.Client.GetBug(int.Parse(bug.ID))).Return(bug); Expect.Call(mocks.Client.Search(expectedFilterId)).Return(new List<int>{1,2,3,4,5}); //Expect.Call(mocks.Client.GetProduct(bug.ProductID)).Return(expectedProduct); //Expect.Call(mocks.Client.GetUser(bug.AssignedToID)).Return(expectedOwner); } mocks.Repository.ReplayAll(); BugzillaReaderUpdater reader = new BugzillaReaderUpdater(config, mocks.ClientFactory, mocks.Logger); List<Defect> returnedBugs = reader.GetBugs(); Assert.AreEqual(expectedBugs.Count, returnedBugs.Count, "Did not get back the right number of defects."); foreach (Defect defect in returnedBugs) { Assert.AreEqual(defect.ProjectId, v1ProjectId); Assert.AreEqual(defect.Owners, assignTo); Assert.AreEqual(defect.Priority, v1PriorityId); if (! string.IsNullOrEmpty(config.UrlTemplateToIssue) && ! string.IsNullOrEmpty(config.UrlTitleToIssue)) { Assert.AreEqual(config.UrlTemplateToIssue.Replace("#key#", defect.ExternalId), defect.ExternalLink.Url); Assert.AreEqual(config.UrlTitleToIssue, defect.ExternalLink.Title); } } mocks.Repository.VerifyAll(); } [TestMethod] public void DefectCreated() { BugzillaServiceConfiguration config = GetStockConfig(); config.OnCreateFieldName = "cf_V1Status"; config.OnCreateFieldValue = "Open"; OnDefectCreated(config); } [TestMethod] public void DefectCreatedWithLink() { BugzillaServiceConfiguration config = GetStockConfig(); config.OnCreateFieldName = "cf_V1Status"; config.OnCreateFieldValue = "Open"; config.DefectLinkFieldName = "cf_LinkToV1Defect"; OnDefectCreated(config); } [TestMethod] public void DefectCreatedReassign() { BugzillaServiceConfiguration config = GetStockConfig(); config.OnCreateReassignValue = "fred"; OnDefectCreated(config); } [TestMethod] public void DefectCreatedResolve() { BugzillaServiceConfiguration config = GetStockConfig(); config.OnCreateResolveValue = "fixed"; OnDefectCreated(config); } private void OnDefectCreated(BugzillaServiceConfiguration config) { BugzillaMocks mocks = new BugzillaMocks(); Defect defect = GetStockBug(); int expectedExternalId = 1234; string expectedDefectLinkValue = "http://localhost/VersionOne.Web/assetdetail.v1?Oid=Defect:1000"; defect.ExternalId = expectedExternalId.ToString(); WorkitemCreationResult workitemCreationResult = new WorkitemCreationResult(defect); workitemCreationResult.Messages.Add("Message1"); workitemCreationResult.Permalink = expectedDefectLinkValue; SetupResult.For(mocks.ClientFactory.CreateNew()).Return(mocks.Client); Expect.Call(mocks.Client.Login()).Return(expectedUserId); Expect.Call(mocks.Client.Logout); Expect.Call(mocks.Client.AcceptBug(Arg<int>.Is.Anything, Arg<string>.Is.Anything)).Return(true); if (!string.IsNullOrEmpty(config.OnCreateFieldName)) { Expect.Call(mocks.Client.UpdateBug(expectedExternalId, config.OnCreateFieldName, config.OnCreateFieldValue)).Return(true); } if (!string.IsNullOrEmpty(config.DefectLinkFieldName)) { Expect.Call(mocks.Client.UpdateBug(expectedExternalId, config.DefectLinkFieldName, expectedDefectLinkValue)).Return(true); } if (!string.IsNullOrEmpty(config.OnCreateReassignValue)) { Expect.Call(mocks.Client.ReassignBug(expectedExternalId, config.OnCreateReassignValue)).Return(true); } mocks.Repository.ReplayAll(); BugzillaReaderUpdater updater = new BugzillaReaderUpdater(config, mocks.ClientFactory, mocks.Logger); updater.OnDefectCreated(workitemCreationResult); mocks.Repository.VerifyAll(); } private static List<Bug> CreateSomeBogusRemoteBugs(int size) { List<Bug> result = new List<Bug>(); Random random = new Random(1); for (int index = 0; index < size; index++) { // var bug = new Bug(); // bug.ID = $"{index + 1}"; // bug.AssignedTo = assignTo; // bug.Component = $"{random.Next()}"; // bug.Description = Guid.NewGuid().ToString(); // bug.Name = Guid.NewGuid().ToString(); // bug.ProductId = productId; // bug.Priority = expectedPriority; // result.Add(bug); } return result; } private BugzillaServiceConfiguration GetStockConfig() { BugzillaServiceConfiguration config = new BugzillaServiceConfiguration(); config.UserName = userName; config.Password = password; config.Url = expectedUrl; config.OpenIssueFilterId = expectedFilterId; MappingInfo zillaProject = new MappingInfo(productId.ToString(), productName); MappingInfo v1Project = new MappingInfo(v1ProjectId, null); config.ProjectMappings.Add(zillaProject, v1Project); MappingInfo zillaPriority = new MappingInfo(null, expectedPriority); MappingInfo v1Priority = new MappingInfo(v1PriorityId, null); config.PriorityMappings.Add(zillaPriority, v1Priority); return config; } private static Defect GetStockBug() { return new Defect("Summary", "Description", "Project", "johndoe"); } } [TestClass] public class Given_A_Defect_Was_Created_In_VersionOne { [TestClass] public class When_Updating_Bugzilla { private BugzillaReaderUpdater _bugzillaReaderUpdater; private IBugzillaClient _bugZillaClient; [TestInitialize()] public void Setup() { _bugZillaClient = MockRepository.GenerateMock<IBugzillaClient>(); _bugZillaClient.Stub(client => client.Login()).Return("123"); _bugZillaClient.Stub(client => client.AcceptBug(Arg<int>.Is.Anything, Arg<string>.Is.Anything)).Return(true); var bugZillaClientFactory = MockRepository.GenerateMock<IBugzillaClientFactory>(); bugZillaClientFactory.Stub(factory => factory.CreateNew()).Return(_bugZillaClient); var logger = MockRepository.GenerateMock<ILogger>(); var config = new BugzillaServiceConfiguration(); var bugZillaBugStatusToSet = "IN_PROGRESS"; config.OnCreateResolveValue = bugZillaBugStatusToSet; _bugzillaReaderUpdater = new BugzillaReaderUpdater(config, bugZillaClientFactory, logger); var versionOneDefect = new Defect(string.Empty, String.Empty, String.Empty, string.Empty); var bugId = "1"; versionOneDefect.ExternalId = bugId; var versionOneWorkitemCreationResult = new WorkitemCreationResult(versionOneDefect); _bugzillaReaderUpdater.OnDefectCreated(versionOneWorkitemCreationResult); } [TestMethod] public void The_Bugzilla_Client_Accepts_The_Bug() { var expectedBugId = 1; var expectedStatus = "IN_PROGRESS"; _bugZillaClient.AssertWasCalled(client => client.AcceptBug(expectedBugId, expectedStatus)); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Orleans.ApplicationParts; using Orleans.Hosting; using Orleans.Runtime.Configuration; using Orleans.Runtime.Providers; using Orleans.Runtime.TestHooks; using Orleans.Configuration; using Orleans.Logging; using Orleans.Messaging; using Orleans.Runtime; using Orleans.Runtime.MembershipService; using Orleans.Statistics; using Orleans.TestingHost.Utils; namespace Orleans.TestingHost { /// <summary> /// Utility for creating silos given a name and collection of configuration sources. /// </summary> public class TestClusterHostFactory { /// <summary> /// Creates an returns a new silo. /// </summary> /// <param name="hostName">The silo name if it is not already specified in the configuration.</param> /// <param name="configurationSources">The configuration.</param> /// <returns>A new silo.</returns> public static ISiloHost CreateSiloHost(string hostName, IEnumerable<IConfigurationSource> configurationSources) { var configBuilder = new ConfigurationBuilder(); foreach (var source in configurationSources) { configBuilder.Add(source); } var configuration = configBuilder.Build(); string siloName = configuration[nameof(TestSiloSpecificOptions.SiloName)] ?? hostName; var hostBuilder = new SiloHostBuilder() .Configure<ClusterOptions>(configuration) .Configure<SiloOptions>(options => options.SiloName = siloName) .ConfigureHostConfiguration(cb => { // TODO: Instead of passing the sources individually, just chain the pre-built configuration once we upgrade to Microsoft.Extensions.Configuration 2.1 foreach (var source in configBuilder.Sources) { cb.Add(source); } }); hostBuilder.Properties["Configuration"] = configuration; ConfigureAppServices(configuration, hostBuilder); hostBuilder.ConfigureServices((context, services) => { services.AddSingleton<TestHooksHostEnvironmentStatistics>(); services.AddFromExisting<IHostEnvironmentStatistics, TestHooksHostEnvironmentStatistics>(); services.AddSingleton<TestHooksSystemTarget>(); ConfigureListeningPorts(context, services); TryConfigureTestClusterMembership(context, services); TryConfigureFileLogging(configuration, services, siloName); if (Debugger.IsAttached) { // Test is running inside debugger - Make timeout ~= infinite services.Configure<SiloMessagingOptions>(op => op.ResponseTimeout = TimeSpan.FromMilliseconds(1000000)); } }); hostBuilder.GetApplicationPartManager().ConfigureDefaults(); var host = hostBuilder.Build(); InitializeTestHooksSystemTarget(host); return host; } public static IClusterClient CreateClusterClient(string hostName, IEnumerable<IConfigurationSource> configurationSources) { var configBuilder = new ConfigurationBuilder(); foreach (var source in configurationSources) { configBuilder.Add(source); } var configuration = configBuilder.Build(); var builder = new ClientBuilder(); builder.Properties["Configuration"] = configuration; builder.Configure<ClusterOptions>(configuration); builder.ConfigureServices(services => { TryConfigureTestClusterMembership(configuration, services); TryConfigureFileLogging(configuration, services, hostName); }); ConfigureAppServices(configuration, builder); builder.GetApplicationPartManager().ConfigureDefaults(); return builder.Build(); } public static string SerializeConfigurationSources(IList<IConfigurationSource> sources) { var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented, }; return JsonConvert.SerializeObject(sources, settings); } public static IList<IConfigurationSource> DeserializeConfigurationSources(string serializedSources) { var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented, }; return JsonConvert.DeserializeObject<IList<IConfigurationSource>>(serializedSources, settings); } private static void ConfigureListeningPorts(HostBuilderContext context, IServiceCollection services) { int siloPort = int.Parse(context.Configuration[nameof(TestSiloSpecificOptions.SiloPort)]); int gatewayPort = int.Parse(context.Configuration[nameof(TestSiloSpecificOptions.GatewayPort)]); services.Configure<EndpointOptions>(options => { options.AdvertisedIPAddress = IPAddress.Loopback; options.SiloPort = siloPort; options.GatewayPort = gatewayPort; options.SiloListeningEndpoint = new IPEndPoint(IPAddress.Loopback, siloPort); if (gatewayPort != 0) { options.GatewayListeningEndpoint = new IPEndPoint(IPAddress.Loopback, gatewayPort); } }); } private static void ConfigureAppServices(IConfiguration configuration, ISiloHostBuilder hostBuilder) { var builderConfiguratorTypes = configuration.GetSection(nameof(TestClusterOptions.SiloBuilderConfiguratorTypes))?.Get<string[]>(); if (builderConfiguratorTypes == null) return; foreach (var builderConfiguratorType in builderConfiguratorTypes) { if (!string.IsNullOrWhiteSpace(builderConfiguratorType)) { var builderConfigurator = (ISiloBuilderConfigurator)Activator.CreateInstance(Type.GetType(builderConfiguratorType, true)); builderConfigurator.Configure(hostBuilder); } } } private static void ConfigureAppServices(IConfiguration configuration, IClientBuilder clientBuilder) { var builderConfiguratorTypes = configuration.GetSection(nameof(TestClusterOptions.ClientBuilderConfiguratorTypes))?.Get<string[]>(); if (builderConfiguratorTypes == null) return; foreach (var builderConfiguratorType in builderConfiguratorTypes) { if (!string.IsNullOrWhiteSpace(builderConfiguratorType)) { var builderConfigurator = (IClientBuilderConfigurator)Activator.CreateInstance(Type.GetType(builderConfiguratorType, true)); builderConfigurator.Configure(configuration, clientBuilder); } } } private static void TryConfigureTestClusterMembership(HostBuilderContext context, IServiceCollection services) { bool.TryParse(context.Configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership); // Configure test cluster membership if requested and if no membership table implementation has been registered. // If the test involves a custom membership oracle and no membership table, special care will be required if (useTestClusterMembership && services.All(svc => svc.ServiceType != typeof(IMembershipTable))) { var primarySiloEndPoint = new IPEndPoint(IPAddress.Loopback, int.Parse(context.Configuration[nameof(TestSiloSpecificOptions.PrimarySiloPort)])); services.Configure<DevelopmentClusterMembershipOptions>(options => options.PrimarySiloEndpoint = primarySiloEndPoint); services .AddSingleton<SystemTargetBasedMembershipTable>() .AddFromExisting<IMembershipTable, SystemTargetBasedMembershipTable>(); } } private static void TryConfigureTestClusterMembership(IConfiguration configuration, IServiceCollection services) { bool.TryParse(configuration[nameof(TestClusterOptions.UseTestClusterMembership)], out bool useTestClusterMembership); if (useTestClusterMembership && services.All(svc => svc.ServiceType != typeof(IGatewayListProvider))) { Action<StaticGatewayListProviderOptions> configureOptions = options => { int baseGatewayPort = int.Parse(configuration[nameof(TestClusterOptions.BaseGatewayPort)]); int initialSilosCount = int.Parse(configuration[nameof(TestClusterOptions.InitialSilosCount)]); options.Gateways = Enumerable.Range(baseGatewayPort, initialSilosCount) .Select(port => new IPEndPoint(IPAddress.Loopback, port).ToGatewayUri()) .ToList(); }; if (configureOptions != null) { services.Configure(configureOptions); } services.AddSingleton<IGatewayListProvider, StaticGatewayListProvider>() .ConfigureFormatter<StaticGatewayListProviderOptions>(); } } private static void TryConfigureFileLogging(IConfiguration configuration, IServiceCollection services, string name) { bool.TryParse(configuration[nameof(TestClusterOptions.ConfigureFileLogging)], out bool configureFileLogging); if (configureFileLogging) { var fileName = TestingUtils.CreateTraceFileName(name, configuration[nameof(TestClusterOptions.ClusterId)]); services.AddLogging(loggingBuilder => loggingBuilder.AddFile(fileName)); } } private static void InitializeTestHooksSystemTarget(ISiloHost host) { var testHook = host.Services.GetRequiredService<TestHooksSystemTarget>(); var providerRuntime = host.Services.GetRequiredService<SiloProviderRuntime>(); providerRuntime.RegisterSystemTarget(testHook); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Xaml.Xaml File: OrderGrid.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Xaml { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Ecng.Collections; using Ecng.Common; using Ecng.ComponentModel; using Ecng.Xaml; using StockSharp.Algo; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// The table showing orders (<see cref="Order"/>). /// </summary> public partial class OrderGrid { /// <summary> /// The command for the order registration. /// </summary> public static RoutedCommand RegisterOrderCommand = new RoutedCommand(); /// <summary> /// The command for the order re-registration. /// </summary> public static RoutedCommand ReRegisterOrderCommand = new RoutedCommand(); /// <summary> /// The command for the cancel of selected orders. /// </summary> public static RoutedCommand CancelOrderCommand = new RoutedCommand(); /// <summary> /// The command for the copying of the error text. /// </summary> public static RoutedCommand CopyErrorCommand = new RoutedCommand(); private class OrderItem : NotifiableObject { private Order _order; public Order Order { get { return _order; } set { if (_order == value) return; if (_order != null) _order.PropertyChanged -= OrderOnPropertyChanged; _order = value; if (_order != null) _order.PropertyChanged += OrderOnPropertyChanged; NotifyChanged(nameof(Order)); } } private string _comment; public string Comment { get { return _comment; } set { _comment = value; NotifyChanged(nameof(Comment)); } } private string _condition; public string Condition { get { return _condition; } set { _condition = value; NotifyChanged(nameof(Condition)); } } public string OrderId { get { var order = Order; if (order == null) return null; return order.Id.To<string>() ?? order.StringId; } } public int OrderState { get { var order = Order; if (order == null) return -1; switch (order.State) { case OrderStates.None: return 0; case OrderStates.Pending: return 1; case OrderStates.Failed: return 2; case OrderStates.Active: return 3; case OrderStates.Done: return order.IsMatched() ? 4 : 5; default: throw new InvalidOperationException(LocalizedStrings.Str1596Params.Put(order.State, order)); } } } public long OrderTif { get { var order = Order; if (order == null) return -1; var tif = order.TimeInForce; var expiryDate = order.ExpiryDate; switch (tif) { case null: case TimeInForce.PutInQueue: return expiryDate?.Ticks ?? long.MaxValue; case TimeInForce.MatchOrCancel: return 0; case TimeInForce.CancelBalance: return 1; default: throw new ArgumentOutOfRangeException(); } } } private void OrderOnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(Order.Id) || e.PropertyName == nameof(Order.StringId)) NotifyChanged(nameof(OrderId)); if (e.PropertyName == nameof(Order.Balance) || e.PropertyName == nameof(Order.State)) NotifyChanged(nameof(OrderState)); if (e.PropertyName == nameof(Order.TimeInForce) || e.PropertyName == nameof(Order.ExpiryDate)) NotifyChanged(nameof(OrderTif)); } } private readonly ConvertibleObservableCollection<Order, OrderItem> _orders; /// <summary> /// Initializes a new instance of the <see cref="OrderGrid"/>. /// </summary> public OrderGrid() { InitializeComponent(); var itemsSource = new ObservableCollectionEx<OrderItem>(); ItemsSource = itemsSource; _orders = new ConvertibleObservableCollection<Order, OrderItem>(new ThreadSafeObservableCollection<OrderItem>(itemsSource), order => new OrderItem { Order = order, Condition = FormatCondition(order.Condition), }) { MaxCount = 100000 }; ContextMenu.Items.Add(new Separator()); ContextMenu.Items.Add(new MenuItem { Header = LocalizedStrings.Str1566, Command = RegisterOrderCommand, CommandTarget = this}); } /// <summary> /// The maximum number of orders to display. The -1 value means unlimited amount. The default is 100000. /// </summary> public int MaxCount { get { return _orders.MaxCount; } set { _orders.MaxCount = value; } } /// <summary> /// The list of orders that have been added to the table. /// </summary> public IListEx<Order> Orders => _orders; /// <summary> /// To add a description of the registration error to the table. /// </summary> /// <param name="fail">Error.</param> public void AddRegistrationFail(OrderFail fail) { if (fail == null) throw new ArgumentNullException(nameof(fail)); var item = _orders.TryGet(fail.Order); if (item != null) item.Comment = fail.Error.Message; } /// <summary> /// The selected order. /// </summary> public Order SelectedOrder => SelectedOrders.FirstOrDefault(); /// <summary> /// Selected orders. /// </summary> public IEnumerable<Order> SelectedOrders { get { return SelectedItems.Cast<OrderItem>().Select(i => i.Order); } } /// <summary> /// The order registration event. /// </summary> public event Action OrderRegistering; /// <summary> /// The order re-registration event. /// </summary> public event Action<Order> OrderReRegistering; /// <summary> /// The selected orders cancel event. /// </summary> public event Action<IEnumerable<Order>> OrderCanceling; /// <summary> /// The method is called when a new order added. /// </summary> /// <param name="order">Order.</param> protected virtual void OnOrderAdded(Order order) { } private void ExecutedRegisterOrderCommand(object sender, ExecutedRoutedEventArgs e) { OrderRegistering.SafeInvoke(); } private void CanExecuteRegisterOrderCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = OrderRegistering != null; } private void ExecutedReRegisterOrder(object sender, ExecutedRoutedEventArgs e) { OrderReRegistering.SafeInvoke(SelectedOrder); } private void CanExecuteReRegisterOrder(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = OrderReRegistering != null && SelectedOrder != null && SelectedOrder.State == OrderStates.Active; } private void ExecutedCancelOrder(object sender, ExecutedRoutedEventArgs e) { OrderCanceling.SafeInvoke(SelectedOrders); } private void CanExecuteCancelOrder(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = OrderCanceling != null && SelectedOrders.Any(o => o.State == OrderStates.Active); } internal static string FormatCondition(OrderCondition condition) { return condition == null ? string.Empty : condition.Parameters.Select(p => "{Key} = {Value}".PutEx(p)).Join(Environment.NewLine); } private void ExecutedCopyErrorCommand(object sender, ExecutedRoutedEventArgs e) { e.Parameter.CopyToClipboard(); e.Handled = true; } } class OrderStateConverter : IMultiValueConverter { object IMultiValueConverter.Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var state = (OrderStates)values[0]; var order = (Order)values[1]; switch (state) { case OrderStates.None: return "--"; case OrderStates.Pending: return LocalizedStrings.Str538; case OrderStates.Failed: return LocalizedStrings.Str152; case OrderStates.Active: return LocalizedStrings.Str238; case OrderStates.Done: return order.IsMatched() ? LocalizedStrings.Str1328 : LocalizedStrings.Str1329; default: throw new ArgumentOutOfRangeException(nameof(values), state, LocalizedStrings.Str1597Params.Put(order)); } } object[] IMultiValueConverter.ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } class OrderTimeInForceConverter : IMultiValueConverter { object IMultiValueConverter.Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var tif = (TimeInForce?)values[0]; var expiryDate = (DateTimeOffset?)values[1]; switch (tif) { case null: case TimeInForce.PutInQueue: { if (expiryDate == null || expiryDate.Value.IsGtc()) return "GTC"; else if (expiryDate.Value.IsToday()) return "GTD"; else return expiryDate.Value.LocalDateTime.ToString("d"); } case TimeInForce.MatchOrCancel: return "FOK"; case TimeInForce.CancelBalance: return "IOC"; default: throw new ArgumentOutOfRangeException(); } } object[] IMultiValueConverter.ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } class OrderConditionConverter : IValueConverter { object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture) { return OrderGrid.FormatCondition((OrderCondition)value); } object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org/?p=license&r=2.4. // **************************************************************** using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using NUnit.Core; using NUnit.Util; namespace NUnit.UiKit { /// <summary> /// ColorProgressBar provides a custom progress bar with the /// ability to control the color of the bar and to render itself /// in either solid or segmented style. The bar can be updated /// on the fly and has code to avoid repainting the entire bar /// when that occurs. /// </summary> public class ColorProgressBar : System.Windows.Forms.Control { #region Instance Variables /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// The current progress value /// </summary> private int val = 0; /// <summary> /// The minimum value allowed /// </summary> private int min = 0; /// <summary> /// The maximum value allowed /// </summary> private int max = 100; /// <summary> /// Amount to advance for each step /// </summary> private int step = 1; /// <summary> /// Last segment displayed when displaying asynchronously rather /// than through OnPaint calls. /// </summary> private int lastSegmentCount=0; /// <summary> /// The brush to use in painting the progress bar /// </summary> private Brush foreBrush = null; /// <summary> /// The brush to use in painting the background of the bar /// </summary> private Brush backBrush = null; /// <summary> /// Indicates whether to draw the bar in segments or not /// </summary> private bool segmented = false; #endregion #region Constructors & Disposer public ColorProgressBar() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); SetStyle(ControlStyles.ResizeRedraw, true); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } this.ReleaseBrushes(); } base.Dispose( disposing ); } #endregion #region Properties [Category("Behavior")] public int Minimum { get { return this.min; } set { if (value <= Maximum) { if (this.min != value) { this.min = value; this.PaintBar(); } } else { throw new ArgumentOutOfRangeException("Minimum", value ,"Minimum must be <= Maximum."); } } } [Category("Behavior")] public int Maximum { get { return this.max; } set { if (value >= Minimum) { if (this.max != value) { this.max = value; this.PaintBar(); } } else { throw new ArgumentOutOfRangeException("Maximum", value ,"Maximum must be >= Minimum."); } } } [Category("Behavior")] public int Step { get { return this.step; } set { if (value <= Maximum && value >= Minimum) { this.step = value; } else { throw new ArgumentOutOfRangeException("Step", value ,"Must fall between Minimum and Maximum inclusive."); } } } [Browsable(false)] private float PercentValue { get { if (0 != Maximum - Minimum) // NRG 05/28/03: Prevent divide by zero return((float)this.val / ((float)Maximum - (float)Minimum)); else return(0); } } [Category("Behavior")] public int Value { get { return this.val; } set { if(value == this.val) return; else if(value <= Maximum && value >= Minimum) { this.val = value; this.PaintBar(); } else { throw new ArgumentOutOfRangeException("Value", value ,"Must fall between Minimum and Maximum inclusive."); } } } [Category("Appearance")] public bool Segmented { get { return segmented; } set { segmented = value; } } #endregion #region Methods protected override void OnCreateControl() { } public void PerformStep() { int newValue = Value + Step; if( newValue > Maximum ) newValue = Maximum; Value = newValue; } protected override void OnBackColorChanged(System.EventArgs e) { base.OnBackColorChanged(e); this.Refresh(); } protected override void OnForeColorChanged(System.EventArgs e) { base.OnForeColorChanged(e); this.Refresh(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); this.lastSegmentCount=0; this.ReleaseBrushes(); PaintBar(e.Graphics); ControlPaint.DrawBorder3D( e.Graphics ,this.ClientRectangle ,Border3DStyle.SunkenOuter); //e.Graphics.Flush(); } private void ReleaseBrushes() { if(foreBrush != null) { foreBrush.Dispose(); backBrush.Dispose(); foreBrush=null; backBrush=null; } } private void AcquireBrushes() { if(foreBrush == null) { foreBrush = new SolidBrush(this.ForeColor); backBrush = new SolidBrush(this.BackColor); } } private void PaintBar() { using(Graphics g = this.CreateGraphics()) { this.PaintBar(g); } } private void PaintBar(Graphics g) { Rectangle theBar = Rectangle.Inflate(ClientRectangle, -2, -2); int maxRight = theBar.Right-1; this.AcquireBrushes(); if ( segmented ) { int segmentWidth = (int)((float)ClientRectangle.Height * 0.66f); int maxSegmentCount = ( theBar.Width + segmentWidth ) / segmentWidth; //int maxRight = Bar.Right; int newSegmentCount = (int)System.Math.Ceiling(PercentValue*maxSegmentCount); if(newSegmentCount > lastSegmentCount) { theBar.X += lastSegmentCount*segmentWidth; while (lastSegmentCount < newSegmentCount ) { theBar.Width = System.Math.Min( maxRight - theBar.X, segmentWidth - 2 ); g.FillRectangle( foreBrush, theBar ); theBar.X += segmentWidth; lastSegmentCount++; } } else if(newSegmentCount < lastSegmentCount) { theBar.X += newSegmentCount * segmentWidth; theBar.Width = maxRight - theBar.X; g.FillRectangle(backBrush, theBar); lastSegmentCount = newSegmentCount; } } else { //g.FillRectangle( backBrush, theBar ); theBar.Width = theBar.Width * val / max; g.FillRectangle( foreBrush, theBar ); } if(Value == Minimum || Value == Maximum) this.ReleaseBrushes(); } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // ProgressBar // this.CausesValidation = false; this.Enabled = false; this.ForeColor = System.Drawing.SystemColors.Highlight; this.Name = "ProgressBar"; this.Size = new System.Drawing.Size(432, 24); } #endregion } public class TestProgressBar : ColorProgressBar, TestObserver { private static Color SuccessColor = Color.Lime; private static Color FailureColor = Color.Red; private static Color IgnoredColor = Color.Yellow; public TestProgressBar() { Initialize( 100 ); } private void Initialize( int testCount ) { ForeColor = SuccessColor; Value = 0; Maximum = testCount; } private void OnRunStarting( object Sender, TestEventArgs e ) { Initialize( e.TestCount ); } private void OnLoadComplete( object sender, TestEventArgs e ) { Initialize( e.TestCount ); } private void OnUnloadComplete( object sender, TestEventArgs e ) { Initialize( 100 ); } private void OnTestFinished( object sender, TestEventArgs e ) { PerformStep(); switch (e.Result.RunState) { case RunState.Executed: if (e.Result.IsFailure) ForeColor = FailureColor; break; case RunState.Ignored: if (ForeColor == SuccessColor) ForeColor = IgnoredColor; break; default: break; } } private void OnTestException(object sender, TestEventArgs e) { ForeColor = FailureColor; } #region TestObserver Members public void Subscribe(ITestEvents events) { events.TestLoaded += new TestEventHandler( OnLoadComplete ); events.TestReloaded += new TestEventHandler( OnLoadComplete ); events.TestUnloaded += new TestEventHandler( OnUnloadComplete ); events.RunStarting += new TestEventHandler( OnRunStarting ); events.TestFinished += new TestEventHandler( OnTestFinished ); events.TestException += new TestEventHandler(OnTestException); } #endregion } }
#if UNITY_EDITOR || UNITY_STANDALONE using System; using System.Runtime.InteropServices; namespace FFmpeg.AutoGen { public unsafe partial struct AVDictionary { } public unsafe partial struct AVBuffer { } public unsafe partial struct AVBufferPool { } public unsafe partial struct AVFilterContext { } public unsafe partial struct AVFilterLink { } public unsafe partial struct AVFilterPad { } public unsafe partial struct AVFilterFormats { } public unsafe partial struct AVFilter { public sbyte* @name; public sbyte* @description; public AVFilterPad* @inputs; public AVFilterPad* @outputs; public AVClass* @priv_class; public int @flags; public IntPtr @init; public IntPtr @init_dict; public IntPtr @uninit; public IntPtr @query_formats; public int @priv_size; public AVFilter* @next; public IntPtr @process_command; public IntPtr @init_opaque; } public unsafe partial struct AVFilterInternal { } public unsafe partial struct AVFilterContext { public AVClass* @av_class; public AVFilter* @filter; public sbyte* @name; public AVFilterPad* @input_pads; public AVFilterLink** @inputs; public uint @nb_inputs; public AVFilterPad* @output_pads; public AVFilterLink** @outputs; public uint @nb_outputs; public void* @priv; public AVFilterGraph* @graph; public int @thread_type; public AVFilterInternal* @internal; public AVFilterCommand* @command_queue; public sbyte* @enable_str; public void* @enable; public double* @var_values; public int @is_disabled; } public unsafe partial struct AVFilterCommand { } public unsafe partial struct AVFilterGraph { } public unsafe partial struct AVFilterLink { public AVFilterContext* @src; public AVFilterPad* @srcpad; public AVFilterContext* @dst; public AVFilterPad* @dstpad; public AVMediaType @type; public int @w; public int @h; public AVRational @sample_aspect_ratio; public ulong @channel_layout; public int @sample_rate; public int @format; public AVRational @time_base; public AVFilterFormats* @in_formats; public AVFilterFormats* @out_formats; public AVFilterFormats* @in_samplerates; public AVFilterFormats* @out_samplerates; public AVFilterChannelLayouts* @in_channel_layouts; public AVFilterChannelLayouts* @out_channel_layouts; public int @request_samples; public init_state @init_state; public AVFilterGraph* @graph; public long @current_pts; public long @current_pts_us; public int @age_index; public AVRational @frame_rate; public AVFrame* @partial_buf; public int @partial_buf_size; public int @min_samples; public int @max_samples; public int @status; public int @channels; public uint @flags; public long @frame_count; public void* @video_frame_pool; public int @frame_wanted_in; public int @frame_wanted_out; } public unsafe partial struct AVFilterChannelLayouts { } public unsafe partial struct AVFilterGraphInternal { } public unsafe partial struct AVFilterGraph { public AVClass* @av_class; public AVFilterContext** @filters; public uint @nb_filters; public sbyte* @scale_sws_opts; public sbyte* @resample_lavr_opts; public int @thread_type; public int @nb_threads; public AVFilterGraphInternal* @internal; public void* @opaque; public IntPtr @execute; public sbyte* @aresample_swr_opts; public AVFilterLink** @sink_links; public int @sink_links_count; public uint @disable_auto_convert; } public unsafe partial struct AVFilterInOut { public sbyte* @name; public AVFilterContext* @filter_ctx; public int @pad_idx; public AVFilterInOut* @next; } public unsafe partial struct AVBuffer { } public unsafe partial struct AVBufferPool { } public unsafe partial struct AVBPrint { } public unsafe partial struct AVDictionary { } public unsafe partial struct AVCodecInternal { } public unsafe partial struct AVCodecDefault { } public unsafe partial struct MpegEncContext { } public unsafe partial struct ReSampleContext { } public unsafe partial struct AVResampleContext { } public unsafe partial struct AVFilterPad { } public unsafe partial struct AVFilterFormats { } public unsafe partial struct AVFilterInternal { } public unsafe partial struct AVFilterGraphInternal { } public unsafe partial struct AVDictionary { } public unsafe partial struct AVBuffer { } public unsafe partial struct AVBufferPool { } public unsafe partial struct AVFilterPad { } public unsafe partial struct AVFilterFormats { } public unsafe partial struct AVFilterInternal { } public unsafe partial struct AVFilterGraphInternal { } public unsafe partial struct AVBufferSinkParams { public AVPixelFormat* @pixel_fmts; } public unsafe partial struct AVABufferSinkParams { public AVSampleFormat* @sample_fmts; public long* @channel_layouts; public int* @channel_counts; public int @all_channel_counts; public int* @sample_rates; } public enum init_state : int { @AVLINK_UNINIT = 0, @AVLINK_STARTINIT = 1, @AVLINK_INIT = 2, } public enum avfilter_graph_config : int { @AVFILTER_AUTO_CONVERT_ALL = 0, @AVFILTER_AUTO_CONVERT_NONE = -1, } public enum av_buffersrc_get_nb_failed_requests : int { @AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT = 1, @AV_BUFFERSRC_FLAG_PUSH = 4, @AV_BUFFERSRC_FLAG_KEEP_REF = 8, } public unsafe static partial class ffmpeg { public const int LIBAVFILTER_VERSION_MAJOR = 6; public const int LIBAVFILTER_VERSION_MINOR = 31; public const int LIBAVFILTER_VERSION_MICRO = 100; public const bool FF_API_OLD_FILTER_OPTS = (LIBAVFILTER_VERSION_MAJOR<7); public const bool FF_API_OLD_FILTER_OPTS_ERROR = (LIBAVFILTER_VERSION_MAJOR<7); public const bool FF_API_AVFILTER_OPEN = (LIBAVFILTER_VERSION_MAJOR<7); public const bool FF_API_AVFILTER_INIT_FILTER = (LIBAVFILTER_VERSION_MAJOR<7); public const bool FF_API_OLD_FILTER_REGISTER = (LIBAVFILTER_VERSION_MAJOR<7); public const bool FF_API_NOCONST_GET_NAME = (LIBAVFILTER_VERSION_MAJOR<7); public const int AVFILTER_FLAG_DYNAMIC_INPUTS = (1<<0); public const int AVFILTER_FLAG_DYNAMIC_OUTPUTS = (1<<1); public const int AVFILTER_FLAG_SLICE_THREADS = (1<<2); public const int AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC = (1<<16); public const int AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL = (1<<17); public const int AVFILTER_FLAG_SUPPORT_TIMELINE = (AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC|AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL); public const int AVFILTER_THREAD_SLICE = (1<<0); public const int AVFILTER_CMD_FLAG_ONE = 1; public const int AVFILTER_CMD_FLAG_FAST = 2; public const int AV_BUFFERSINK_FLAG_PEEK = 1; public const int AV_BUFFERSINK_FLAG_NO_REQUEST = 2; private const string libavfilter = "avfilter-6"; [DllImport(libavfilter, EntryPoint = "avfilter_version", CallingConvention = CallingConvention.Cdecl)] public static extern uint avfilter_version(); [DllImport(libavfilter, EntryPoint = "avfilter_configuration", CallingConvention = CallingConvention.Cdecl)] public static extern string avfilter_configuration(); [DllImport(libavfilter, EntryPoint = "avfilter_license", CallingConvention = CallingConvention.Cdecl)] public static extern string avfilter_license(); [DllImport(libavfilter, EntryPoint = "avfilter_pad_count", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_pad_count(AVFilterPad* @pads); [DllImport(libavfilter, EntryPoint = "avfilter_pad_get_name", CallingConvention = CallingConvention.Cdecl)] public static extern string avfilter_pad_get_name(AVFilterPad* @pads, int @pad_idx); [DllImport(libavfilter, EntryPoint = "avfilter_pad_get_type", CallingConvention = CallingConvention.Cdecl)] public static extern AVMediaType avfilter_pad_get_type(AVFilterPad* @pads, int @pad_idx); [DllImport(libavfilter, EntryPoint = "avfilter_link", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_link(AVFilterContext* @src, uint @srcpad, AVFilterContext* @dst, uint @dstpad); [DllImport(libavfilter, EntryPoint = "avfilter_link_free", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_link_free(AVFilterLink** @link); [DllImport(libavfilter, EntryPoint = "avfilter_link_get_channels", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_link_get_channels(AVFilterLink* @link); [DllImport(libavfilter, EntryPoint = "avfilter_link_set_closed", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_link_set_closed(AVFilterLink* @link, int @closed); [DllImport(libavfilter, EntryPoint = "avfilter_config_links", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_config_links(AVFilterContext* @filter); [DllImport(libavfilter, EntryPoint = "avfilter_process_command", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_process_command(AVFilterContext* @filter, [MarshalAs(UnmanagedType.LPStr)] string @cmd, [MarshalAs(UnmanagedType.LPStr)] string @arg, IntPtr @res, int @res_len, int @flags); [DllImport(libavfilter, EntryPoint = "avfilter_register_all", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_register_all(); [DllImport(libavfilter, EntryPoint = "avfilter_uninit", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_uninit(); [DllImport(libavfilter, EntryPoint = "avfilter_register", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_register(AVFilter* @filter); [DllImport(libavfilter, EntryPoint = "avfilter_get_by_name", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilter* avfilter_get_by_name([MarshalAs(UnmanagedType.LPStr)] string @name); [DllImport(libavfilter, EntryPoint = "avfilter_next", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilter* avfilter_next(AVFilter* @prev); [DllImport(libavfilter, EntryPoint = "av_filter_next", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilter** av_filter_next(AVFilter** @filter); [DllImport(libavfilter, EntryPoint = "avfilter_open", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_open(AVFilterContext** @filter_ctx, AVFilter* @filter, [MarshalAs(UnmanagedType.LPStr)] string @inst_name); [DllImport(libavfilter, EntryPoint = "avfilter_init_filter", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_init_filter(AVFilterContext* @filter, [MarshalAs(UnmanagedType.LPStr)] string @args, void* @opaque); [DllImport(libavfilter, EntryPoint = "avfilter_init_str", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_init_str(AVFilterContext* @ctx, [MarshalAs(UnmanagedType.LPStr)] string @args); [DllImport(libavfilter, EntryPoint = "avfilter_init_dict", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_init_dict(AVFilterContext* @ctx, AVDictionary** @options); [DllImport(libavfilter, EntryPoint = "avfilter_free", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_free(AVFilterContext* @filter); [DllImport(libavfilter, EntryPoint = "avfilter_insert_filter", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_insert_filter(AVFilterLink* @link, AVFilterContext* @filt, uint @filt_srcpad_idx, uint @filt_dstpad_idx); [DllImport(libavfilter, EntryPoint = "avfilter_get_class", CallingConvention = CallingConvention.Cdecl)] public static extern AVClass* avfilter_get_class(); [DllImport(libavfilter, EntryPoint = "avfilter_graph_alloc", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilterGraph* avfilter_graph_alloc(); [DllImport(libavfilter, EntryPoint = "avfilter_graph_alloc_filter", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilterContext* avfilter_graph_alloc_filter(AVFilterGraph* @graph, AVFilter* @filter, [MarshalAs(UnmanagedType.LPStr)] string @name); [DllImport(libavfilter, EntryPoint = "avfilter_graph_get_filter", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilterContext* avfilter_graph_get_filter(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @name); [DllImport(libavfilter, EntryPoint = "avfilter_graph_add_filter", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_add_filter(AVFilterGraph* @graphctx, AVFilterContext* @filter); [DllImport(libavfilter, EntryPoint = "avfilter_graph_create_filter", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_create_filter(AVFilterContext** @filt_ctx, AVFilter* @filt, [MarshalAs(UnmanagedType.LPStr)] string @name, [MarshalAs(UnmanagedType.LPStr)] string @args, void* @opaque, AVFilterGraph* @graph_ctx); [DllImport(libavfilter, EntryPoint = "avfilter_graph_set_auto_convert", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_graph_set_auto_convert(AVFilterGraph* @graph, uint @flags); [DllImport(libavfilter, EntryPoint = "avfilter_graph_config", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_config(AVFilterGraph* @graphctx, void* @log_ctx); [DllImport(libavfilter, EntryPoint = "avfilter_graph_free", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_graph_free(AVFilterGraph** @graph); [DllImport(libavfilter, EntryPoint = "avfilter_inout_alloc", CallingConvention = CallingConvention.Cdecl)] public static extern AVFilterInOut* avfilter_inout_alloc(); [DllImport(libavfilter, EntryPoint = "avfilter_inout_free", CallingConvention = CallingConvention.Cdecl)] public static extern void avfilter_inout_free(AVFilterInOut** @inout); [DllImport(libavfilter, EntryPoint = "avfilter_graph_parse", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_parse(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @filters, AVFilterInOut* @inputs, AVFilterInOut* @outputs, void* @log_ctx); [DllImport(libavfilter, EntryPoint = "avfilter_graph_parse_ptr", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_parse_ptr(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @filters, AVFilterInOut** @inputs, AVFilterInOut** @outputs, void* @log_ctx); [DllImport(libavfilter, EntryPoint = "avfilter_graph_parse2", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_parse2(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @filters, AVFilterInOut** @inputs, AVFilterInOut** @outputs); [DllImport(libavfilter, EntryPoint = "avfilter_graph_send_command", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_send_command(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @target, [MarshalAs(UnmanagedType.LPStr)] string @cmd, [MarshalAs(UnmanagedType.LPStr)] string @arg, IntPtr @res, int @res_len, int @flags); [DllImport(libavfilter, EntryPoint = "avfilter_graph_queue_command", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_queue_command(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @target, [MarshalAs(UnmanagedType.LPStr)] string @cmd, [MarshalAs(UnmanagedType.LPStr)] string @arg, int @flags, double @ts); [DllImport(libavfilter, EntryPoint = "avfilter_graph_dump", CallingConvention = CallingConvention.Cdecl)] public static extern sbyte* avfilter_graph_dump(AVFilterGraph* @graph, [MarshalAs(UnmanagedType.LPStr)] string @options); [DllImport(libavfilter, EntryPoint = "avfilter_graph_request_oldest", CallingConvention = CallingConvention.Cdecl)] public static extern int avfilter_graph_request_oldest(AVFilterGraph* @graph); [DllImport(libavfilter, EntryPoint = "av_buffersrc_get_nb_failed_requests", CallingConvention = CallingConvention.Cdecl)] public static extern uint av_buffersrc_get_nb_failed_requests(AVFilterContext* @buffer_src); [DllImport(libavfilter, EntryPoint = "av_buffersrc_write_frame", CallingConvention = CallingConvention.Cdecl)] public static extern int av_buffersrc_write_frame(AVFilterContext* @ctx, AVFrame* @frame); [DllImport(libavfilter, EntryPoint = "av_buffersrc_add_frame", CallingConvention = CallingConvention.Cdecl)] public static extern int av_buffersrc_add_frame(AVFilterContext* @ctx, AVFrame* @frame); [DllImport(libavfilter, EntryPoint = "av_buffersrc_add_frame_flags", CallingConvention = CallingConvention.Cdecl)] public static extern int av_buffersrc_add_frame_flags(AVFilterContext* @buffer_src, AVFrame* @frame, int @flags); [DllImport(libavfilter, EntryPoint = "av_buffersink_get_frame_flags", CallingConvention = CallingConvention.Cdecl)] public static extern int av_buffersink_get_frame_flags(AVFilterContext* @ctx, AVFrame* @frame, int @flags); [DllImport(libavfilter, EntryPoint = "av_buffersink_params_alloc", CallingConvention = CallingConvention.Cdecl)] public static extern AVBufferSinkParams* av_buffersink_params_alloc(); [DllImport(libavfilter, EntryPoint = "av_abuffersink_params_alloc", CallingConvention = CallingConvention.Cdecl)] public static extern AVABufferSinkParams* av_abuffersink_params_alloc(); [DllImport(libavfilter, EntryPoint = "av_buffersink_set_frame_size", CallingConvention = CallingConvention.Cdecl)] public static extern void av_buffersink_set_frame_size(AVFilterContext* @ctx, uint @frame_size); [DllImport(libavfilter, EntryPoint = "av_buffersink_get_frame_rate", CallingConvention = CallingConvention.Cdecl)] public static extern AVRational av_buffersink_get_frame_rate(AVFilterContext* @ctx); [DllImport(libavfilter, EntryPoint = "av_buffersink_get_frame", CallingConvention = CallingConvention.Cdecl)] public static extern int av_buffersink_get_frame(AVFilterContext* @ctx, AVFrame* @frame); [DllImport(libavfilter, EntryPoint = "av_buffersink_get_samples", CallingConvention = CallingConvention.Cdecl)] public static extern int av_buffersink_get_samples(AVFilterContext* @ctx, AVFrame* @frame, int @nb_samples); } } #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. /*============================================================ ** ** ** ** ** ** Purpose: Implements a dynamically sized List as an array, ** and provides many convenience methods for treating ** an array as an IList. ** ** ===========================================================*/ using System; using System.Runtime; using System.Security; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections { // Implements a variable-size List that uses an array of objects to store the // elements. A ArrayList has a capacity, which is the allocated length // of the internal array. As elements are added to a ArrayList, the capacity // of the ArrayList is automatically increased as required by reallocating the // internal array. // [FriendAccessAllowed] [DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))] [DebuggerDisplay("Count = {Count}")] [Serializable] internal class ArrayList : IList, ICloneable { private Object[] _items; [ContractPublicPropertyName("Count")] private int _size; private int _version; [NonSerialized] private Object _syncRoot; private const int _defaultCapacity = 4; private static readonly Object[] emptyArray = EmptyArray<Object>.Value; // Constructs a ArrayList. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to _defaultCapacity, and then increased in multiples of two as required. public ArrayList() { _items = emptyArray; } // Constructs a ArrayList with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public ArrayList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(capacity))); Contract.EndContractBlock(); if (capacity == 0) _items = emptyArray; else _items = new Object[capacity]; } // Constructs a ArrayList, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public ArrayList(ICollection c) { if (c == null) throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection")); Contract.EndContractBlock(); int count = c.Count; if (count == 0) { _items = emptyArray; } else { _items = new Object[count]; AddRange(c); } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public virtual int Capacity { get { Contract.Ensures(Contract.Result<int>() >= Count); return _items.Length; } set { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity")); } Contract.Ensures(Capacity >= 0); Contract.EndContractBlock(); // We don't want to update the version number when we change the capacity. // Some existing applications have dependency on this. if (value != _items.Length) { if (value > 0) { Object[] newItems = new Object[value]; if (_size > 0) { Array.Copy(_items, 0, newItems, 0, _size); } _items = newItems; } else { _items = new Object[_defaultCapacity]; } } } } // Read-only property describing how many elements are in the List. public virtual int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } public virtual bool IsFixedSize { get { return false; } } // Is this ArrayList read-only? public virtual bool IsReadOnly { get { return false; } } // Is this ArrayList synchronized (thread-safe)? public virtual bool IsSynchronized { get { return false; } } // Synchronization root for this object. public virtual Object SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Sets or Gets the element at the given index. // public virtual Object this[int index] { get { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); return _items[index]; } set { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); _items[index] = value; _version++; } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public virtual int Add(Object value) { Contract.Ensures(Contract.Result<int>() >= 0); if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size] = value; _version++; return _size++; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public virtual void AddRange(ICollection c) { InsertRange(_size, c); } // Clears the contents of ArrayList. public virtual void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Clones this ArrayList, doing a shallow copy. (A copy is made of all // Object references in the ArrayList, but the Objects pointed to // are not cloned). public virtual Object Clone() { Contract.Ensures(Contract.Result<Object>() != null); ArrayList la = new ArrayList(_size); la._size = _size; la._version = _version; Array.Copy(_items, 0, la._items, 0, _size); return la; } // Contains returns true if the specified element is in the ArrayList. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public virtual bool Contains(Object item) { if (item == null) { for (int i = 0; i < _size; i++) if (_items[i] == null) return true; return false; } else { for (int i = 0; i < _size; i++) if ((_items[i] != null) && (_items[i].Equals(item))) return true; return false; } } // Copies this ArrayList into array, which must be of a // compatible array type. // public virtual void CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Ensures that the capacity of this list is at least the given minimum // value. If the currect capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public virtual IEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<IEnumerator>() != null); return new ArrayListEnumeratorSimple(this); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public virtual int IndexOf(Object value) { Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf((Array)_items, value, 0, _size); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public virtual void Insert(int index, Object value) { // Note that insertions at the end are legal. if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_ArrayListInsert")); //Contract.Ensures(Count == Contract.OldValue(Count) + 1); Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = value; _size++; _version++; } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the ArrayList's size. // public virtual void InsertRange(int index, ICollection c) { if (c == null) throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection")); if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); //Contract.Ensures(Count == Contract.OldValue(Count) + c.Count); Contract.EndContractBlock(); int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); // shift existing items if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } Object[] itemsToInsert = new Object[count]; c.CopyTo(itemsToInsert, 0); itemsToInsert.CopyTo(_items, index); _size += count; _version++; } } // Returns a read-only IList wrapper for the given IList. // [FriendAccessAllowed] public static IList ReadOnly(IList list) { if (list == null) throw new ArgumentNullException(nameof(list)); Contract.Ensures(Contract.Result<IList>() != null); Contract.EndContractBlock(); return new ReadOnlyList(list); } // Removes the element at the given index. The size of the list is // decreased by one. // public virtual void Remove(Object obj) { Contract.Ensures(Count >= 0); int index = IndexOf(obj); BCLDebug.Correctness(index >= 0 || !(obj is Int32), "You passed an Int32 to Remove that wasn't in the ArrayList." + Environment.NewLine + "Did you mean RemoveAt? int: " + obj + " Count: " + Count); if (index >= 0) RemoveAt(index); } // Removes the element at the given index. The size of the list is // decreased by one. // public virtual void RemoveAt(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.Ensures(Count >= 0); //Contract.Ensures(Count == Contract.OldValue(Count) - 1); Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = null; _version++; } // ToArray returns a new array of a particular type containing the contents // of the ArrayList. This requires copying the ArrayList and potentially // downcasting all elements. This copy may fail and is an O(n) operation. // Internally, this implementation calls Array.Copy. // public virtual Array ToArray(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); Contract.Ensures(Contract.Result<Array>() != null); Contract.EndContractBlock(); Array array = Array.UnsafeCreateInstance(type, _size); Array.Copy(_items, 0, array, 0, _size); return array; } [Serializable] private class ReadOnlyList : IList { private IList _list; internal ReadOnlyList(IList l) { _list = l; } public virtual int Count { get { return _list.Count; } } public virtual bool IsReadOnly { get { return true; } } public virtual bool IsFixedSize { get { return true; } } public virtual bool IsSynchronized { get { return _list.IsSynchronized; } } public virtual Object this[int index] { get { return _list[index]; } set { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); } } public virtual Object SyncRoot { get { return _list.SyncRoot; } } public virtual int Add(Object obj) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); } public virtual void Clear() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); } public virtual bool Contains(Object obj) { return _list.Contains(obj); } public virtual void CopyTo(Array array, int index) { _list.CopyTo(array, index); } public virtual IEnumerator GetEnumerator() { return _list.GetEnumerator(); } public virtual int IndexOf(Object value) { return _list.IndexOf(value); } public virtual void Insert(int index, Object obj) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); } public virtual void Remove(Object value) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); } public virtual void RemoveAt(int index) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection")); } } [Serializable] private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable { private ArrayList list; private int index; private int version; private Object currentElement; [NonSerialized] private bool isArrayList; // this object is used to indicate enumeration has not started or has terminated private static Object dummyObject = new Object(); internal ArrayListEnumeratorSimple(ArrayList list) { this.list = list; index = -1; version = list._version; isArrayList = (list.GetType() == typeof(ArrayList)); currentElement = dummyObject; } public Object Clone() { return MemberwiseClone(); } public bool MoveNext() { if (version != list._version) { throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); } if (isArrayList) { // avoid calling virtual methods if we are operating on ArrayList to improve performance if (index < list._size - 1) { currentElement = list._items[++index]; return true; } else { currentElement = dummyObject; index = list._size; return false; } } else { if (index < list.Count - 1) { currentElement = list[++index]; return true; } else { index = list.Count; currentElement = dummyObject; return false; } } } public Object Current { get { object temp = currentElement; if (dummyObject == temp) { // check if enumeration has not started or has terminated if (index == -1) { throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); } else { throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); } } return temp; } } public void Reset() { if (version != list._version) { throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); } currentElement = dummyObject; index = -1; } } internal class ArrayListDebugView { private ArrayList arrayList; } } }
// 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.Diagnostics; using Microsoft.Research.AbstractDomains.Expressions; using Microsoft.Research.DataStructures; using Microsoft.Research.CodeAnalysis; namespace Microsoft.Research.AbstractDomains.Numerical { /// <summary> /// We keep a bounded disjunction of abstract domains /// </summary> public class BoundedDisjunction<Variable, Expression> : INumericalAbstractDomain<Variable, Expression> { #region Private state private readonly int MaxDisjuncts = 8; // TODO Want to make it a command line option private INumericalAbstractDomain<Variable, Expression>[] disjuncts; private INumericalAbstractDomain<Variable, Expression> FirstDisjunct { get { return disjuncts[0]; } } #endregion #region Constructor public BoundedDisjunction(INumericalAbstractDomain<Variable, Expression> initial) { disjuncts = new INumericalAbstractDomain<Variable, Expression>[1]; disjuncts[0] = initial; } private BoundedDisjunction(INumericalAbstractDomain<Variable, Expression>[] domains) { if (domains.Length <= MaxDisjuncts) { disjuncts = domains; } else { disjuncts = new INumericalAbstractDomain<Variable, Expression>[1] { SmashTogether(domains) }; } } #endregion #region INumericalAbstractDomain<Variable, Expression>Members public DisInterval BoundsFor(Expression v) { var result = FirstDisjunct.BoundsFor(v); for (int i = 1; i < disjuncts.Length; i++) { result = (DisInterval)result.Join(disjuncts[i].BoundsFor(v)); } return result; } public DisInterval BoundsFor(Variable v) { var result = FirstDisjunct.BoundsFor(v); for (int i = 1; i < disjuncts.Length; i++) { result = (DisInterval)result.Join(disjuncts[i].BoundsFor(v)); } return result; } public List<Pair<Variable, Int32>> IntConstants { get { return new List<Pair<Variable, Int32>>(); } } public IEnumerable<Expression> LowerBoundsFor(Expression v, bool strict) { yield break; //not implemented } public IEnumerable<Expression> UpperBoundsFor(Expression v, bool strict) { yield break; //not implemented } public IEnumerable<Expression> LowerBoundsFor(Variable v, bool strict) { yield break; //not implemented } public IEnumerable<Expression> UpperBoundsFor(Variable v, bool strict) { yield break; //not implemented } public IEnumerable<Variable> EqualitiesFor(Variable v) { yield break; //not implemented } public void AssumeInDisInterval(Variable x, DisInterval value) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].AssumeInDisInterval(x, value); } } public void AssumeDomainSpecificFact(DomainSpecificFact fact) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].AssumeDomainSpecificFact(fact); } } public INumericalAbstractDomain<Variable, Expression> TestTrueGeqZero(Expression exp) { var result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = disjuncts[i].TestTrueGeqZero(exp); } return new BoundedDisjunction<Variable, Expression>(result); } public INumericalAbstractDomain<Variable, Expression> TestTrueLessThan(Expression exp1, Expression exp2) { var result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = disjuncts[i].TestTrueLessThan(exp1, exp2); } return new BoundedDisjunction<Variable, Expression>(result); } public INumericalAbstractDomain<Variable, Expression> TestTrueLessEqualThan(Expression exp1, Expression exp2) { var result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = disjuncts[i].TestTrueLessEqualThan(exp1, exp2); } return new BoundedDisjunction<Variable, Expression>(result); } public INumericalAbstractDomain<Variable, Expression> TestTrueEqual(Expression exp1, Expression exp2) { var result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = disjuncts[i].TestTrueEqual(exp1, exp2); } return new BoundedDisjunction<Variable, Expression>(result); } public INumericalAbstractDomain<Variable, Expression> RemoveRedundanciesWith(INumericalAbstractDomain<Variable, Expression> oracle) { var result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = disjuncts[i].RemoveRedundanciesWith(oracle); } return new BoundedDisjunction<Variable, Expression>(result); } public FlatAbstractDomain<bool> CheckIfGreaterEqualThanZero(Expression exp) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfGreaterEqualThanZero(exp)); } return result; } public FlatAbstractDomain<bool> CheckIfLessThan(Expression e1, Expression e2) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessThan(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfLessThan_Un(Expression e1, Expression e2) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessThan_Un(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfLessThan(Variable v1, Variable v2) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessThan(v1, v2)); } return result; } public FlatAbstractDomain<bool> CheckIfLessEqualThan(Expression e1, Expression e2) { var result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessEqualThan(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfLessThanIncomplete(Expression e1, Expression e2) { var result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessThanIncomplete(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfLessEqualThan_Un(Expression e1, Expression e2) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessEqualThan_Un(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfEqual(Expression e1, Expression e2) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfEqual(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfEqualIncomplete(Expression e1, Expression e2) { return this.CheckIfEqual(e1, e2); } public FlatAbstractDomain<bool> CheckIfEqualThan(Expression e1, Expression e2) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfEqual(e1, e2)); } return result; } public FlatAbstractDomain<bool> CheckIfLessEqualThan(Variable v1, Variable v2) { var result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfLessEqualThan(v1, v2)); } return result; } public FlatAbstractDomain<bool> CheckIfNonZero(Expression e) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfNonZero(e)); } return result; } #endregion #region IAbstractDomain Members public bool IsBottom { get { for (int i = 0; i < disjuncts.Length; i++) { if (!disjuncts[i].IsBottom) { return false; } } return true; } } public bool IsTop { get { for (int i = 0; i < disjuncts.Length; i++) { if (disjuncts[i].IsTop) { INumericalAbstractDomain<Variable, Expression>[] newDisjunct = new INumericalAbstractDomain<Variable, Expression>[1]; newDisjunct[0] = disjuncts[i]; disjuncts = newDisjunct; return true; } } return false; } } public bool LessEqual(IAbstractDomain a) { bool r; if (AbstractDomainsHelper.TryTrivialLessEqual(this, a, out r)) { return r; } INumericalAbstractDomain<Variable, Expression> leftSmashed = SmashTogether(this, true); INumericalAbstractDomain<Variable, Expression> rightSmashed = SmashTogether(a, true); return leftSmashed.LessEqual(rightSmashed); } static private INumericalAbstractDomain<Variable, Expression> SmashTogether(IAbstractDomain boundedDisjunction, bool p) { INumericalAbstractDomain<Variable, Expression> asNumericalDomain = (INumericalAbstractDomain<Variable, Expression>)boundedDisjunction; Debug.Assert(boundedDisjunction != null); if (p) { // It is a BoundedDisjunction<Variable, Expression> asDisjunction = asNumericalDomain as BoundedDisjunction<Variable, Expression>; Debug.Assert(asDisjunction != null); return SmashTogether(asDisjunction.disjuncts); } else { return asNumericalDomain; } } private static INumericalAbstractDomain<Variable, Expression> SmashTogether(INumericalAbstractDomain<Variable, Expression>[] asDisjunction) { IAbstractDomain result = asDisjunction[0]; for (int i = 1; i < asDisjunction.Length; i++) { result = result.Join(asDisjunction[i]); } return (INumericalAbstractDomain<Variable, Expression>)result; } public IAbstractDomain Bottom { get { return new BoundedDisjunction<Variable, Expression>((INumericalAbstractDomain<Variable, Expression>)this.FirstDisjunct.Bottom); } } public IAbstractDomain Top { get { return new BoundedDisjunction<Variable, Expression>((INumericalAbstractDomain<Variable, Expression>)this.FirstDisjunct.Top); } } public IAbstractDomain Join(IAbstractDomain a) { IAbstractDomain result; if (AbstractDomainsHelper.TryTrivialJoin(this, a, out result)) { return result; } BoundedDisjunction<Variable, Expression> asDisjunctionDomain = a as BoundedDisjunction<Variable, Expression>; Debug.Assert(asDisjunctionDomain != null); INumericalAbstractDomain<Variable, Expression>[] joinDisjuncts = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length + asDisjunctionDomain.disjuncts.Length]; // Copy both the domains for (int i = 0; i < disjuncts.Length; i++) { joinDisjuncts[i] = disjuncts[i]; } for (int i = 0; i < asDisjunctionDomain.disjuncts.Length; i++) { joinDisjuncts[disjuncts.Length + i] = asDisjunctionDomain.disjuncts[i]; } return new BoundedDisjunction<Variable, Expression>(joinDisjuncts); } public IAbstractDomain Meet(IAbstractDomain a) { IAbstractDomain result; if (AbstractDomainsHelper.TryTrivialMeet(this, a, out result)) { return result; } BoundedDisjunction<Variable, Expression> asDisjunctionDomain = a as BoundedDisjunction<Variable, Expression>; Debug.Assert(asDisjunctionDomain != null); INumericalAbstractDomain<Variable, Expression> left = SmashTogether(disjuncts); INumericalAbstractDomain<Variable, Expression> right = SmashTogether(asDisjunctionDomain.disjuncts); return new BoundedDisjunction<Variable, Expression>((INumericalAbstractDomain<Variable, Expression>)left.Meet(right)); } public IAbstractDomain Widening(IAbstractDomain prev) { IAbstractDomain result; if (AbstractDomainsHelper.TryTrivialJoin(this, prev, out result)) { return result; } BoundedDisjunction<Variable, Expression> asDisjunctionDomain = prev as BoundedDisjunction<Variable, Expression>; Debug.Assert(asDisjunctionDomain != null); INumericalAbstractDomain<Variable, Expression> left = SmashTogether(disjuncts); INumericalAbstractDomain<Variable, Expression> right = SmashTogether(asDisjunctionDomain.disjuncts); return new BoundedDisjunction<Variable, Expression>((INumericalAbstractDomain<Variable, Expression>)left.Widening(right)); } #endregion #region ICloneable Members public object Clone() { INumericalAbstractDomain<Variable, Expression>[] cloned = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { cloned[i] = (INumericalAbstractDomain<Variable, Expression>)disjuncts[i].Clone(); } return new BoundedDisjunction<Variable, Expression>(cloned); } #endregion #region IPureExpressionAssignments<Expression> Members public List<Variable> Variables { get { var result = new Set<Variable>(); for (int i = 0; i < disjuncts.Length; i++) { result.AddRange(disjuncts[i].Variables); } return result.ToList(); } } public void AddVariable(Variable var) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].AddVariable(var); } } public void Assign(Expression x, Expression exp) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].Assign(x, exp); } } public void Assign(Expression x, Expression exp, INumericalAbstractDomainQuery<Variable, Expression> preState) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].Assign(x, exp, preState); } } public void ProjectVariable(Variable var) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].ProjectVariable(var); } } public void RemoveVariable(Variable var) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].RemoveVariable(var); } } public void RenameVariable(Variable OldName, Variable NewName) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].RenameVariable(OldName, NewName); } } #endregion #region IPureExpressionTest<Expression> Members public IAbstractDomainForEnvironments<Variable, Expression> TestTrue(Expression guard) { INumericalAbstractDomain<Variable, Expression>[] result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = (INumericalAbstractDomain<Variable, Expression>)disjuncts[i].TestTrue(guard); } return Reduce(result); } public IAbstractDomainForEnvironments<Variable, Expression> TestFalse(Expression guard) { INumericalAbstractDomain<Variable, Expression>[] result = new INumericalAbstractDomain<Variable, Expression>[disjuncts.Length]; for (int i = 0; i < disjuncts.Length; i++) { result[i] = (INumericalAbstractDomain<Variable, Expression>)disjuncts[i].TestFalse(guard); } return Reduce(result); } public FlatAbstractDomain<bool> CheckIfHolds(Expression exp) { FlatAbstractDomain<bool> result = CheckOutcome.Bottom; for (int i = 0; i < disjuncts.Length; i++) { result = result.Join(disjuncts[i].CheckIfHolds(exp)); } return result; } #endregion #region IAssignInParallel<Expression> Members public void AssignInParallel(Dictionary<Variable, FList<Variable>> sourcesToTargets, Converter<Variable, Expression> convert) { for (int i = 0; i < disjuncts.Length; i++) { disjuncts[i].AssignInParallel(sourcesToTargets, convert); } } #endregion #region To public T To<T>(IFactory<T> factory) { if (this.IsBottom) return factory.Constant(false); if (this.IsTop) return factory.Constant(true); T result = factory.IdentityForOr; for (int i = 0; i < disjuncts.Length; i++) { T atom = disjuncts[i].To(factory); result = factory.Or(result, atom); } return result; } #endregion public string Statistics { get { return string.Empty; } } public override string ToString() { if (this.IsTop) { return "Top"; } else if (disjuncts.Length == 1) { return this.FirstDisjunct.ToString(); } else { return "Bounded disjunction with " + disjuncts.Length + " disjuncts"; } } public string ToString(Expression exp) { return "< missing expression decoder >"; } /// <summary> /// For the moment the reduction just get rid of the bottom elements /// </summary> private BoundedDisjunction<Variable, Expression> Reduce(INumericalAbstractDomain<Variable, Expression>[] domains) { bool[] isBottom = new bool[domains.Length]; int countBottom = 0; for (int i = 0; i < domains.Length; i++) { if (domains[i].IsBottom) { isBottom[i] = true; countBottom++; } } if (countBottom == 0 || countBottom == domains.Length) { return new BoundedDisjunction<Variable, Expression>(domains); } else { INumericalAbstractDomain<Variable, Expression>[] tmp = new INumericalAbstractDomain<Variable, Expression>[domains.Length - countBottom]; for (int i = 0, k = 0; i < domains.Length; i++) { if (!isBottom[i]) { tmp[k] = domains[i]; k++; } } return new BoundedDisjunction<Variable, Expression>(tmp); } } #region Floating point types public void SetFloatType(Variable v, ConcreteFloat f) { // does nothing } public FlatAbstractDomain<ConcreteFloat> GetFloatType(Variable v) { return FloatTypes<Variable, Expression>.Unknown; } #endregion #region INumericalAbstractDomainQuery<Variable,Expression> Members public Variable ToVariable(Expression exp) { return default(Variable); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections.Generic; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class Sys { private const int MountPointFormatBufferSizeInBytes = 32; /// <summary> /// Internal FileSystem names and magic numbers taken from man(2) statfs /// </summary> /// <remarks> /// These value names MUST be kept in sync with those in GetDriveType below /// </remarks> internal enum UnixFileSystemTypes : long { adfs = 0xadf5, affs = 0xADFF, befs = 0x42465331, bfs = 0x1BADFACE, cifs = 0xFF534D42, coda = 0x73757245, coherent = 0x012FF7B7, cramfs = 0x28cd3d45, devfs = 0x1373, efs = 0x00414A53, ext = 0x137D, ext2_old = 0xEF51, ext2 = 0xEF53, ext3 = 0xEF53, ext4 = 0xEF53, hfs = 0x4244, hpfs = 0xF995E849, hugetlbfs = 0x958458f6, isofs = 0x9660, jffs2 = 0x72b6, jfs = 0x3153464a, minix_old = 0x137F, /* orig. minix */ minix = 0x138F, /* 30 char minix */ minix2 = 0x2468, /* minix V2 */ minix2v2 = 0x2478, /* minix V2, 30 char names */ msdos = 0x4d44, ncpfs = 0x564c, nfs = 0x6969, ntfs = 0x5346544e, openprom = 0x9fa1, overlay = 0x794c7630, overlayfs = 0x794c764f, proc = 0x9fa0, qnx4 = 0x002f, reiserfs = 0x52654973, romfs = 0x7275, smb = 0x517B, sysv2 = 0x012FF7B6, sysv4 = 0x012FF7B5, tmpfs = 0x01021994, udf = 0x15013346, ufs = 0x00011954, usbdevice = 0x9fa2, vxfs = 0xa501FCF5, xenix = 0x012FF7B4, xfs = 0x58465342, xiafs = 0x012FD16D, } [StructLayout(LayoutKind.Sequential)] internal struct MountPointInformation { internal ulong AvailableFreeSpace; internal ulong TotalFreeSpace; internal ulong TotalSize; } [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetSpaceInfoForMountPoint", SetLastError = true)] internal static extern int GetSpaceInfoForMountPoint([MarshalAs(UnmanagedType.LPStr)]string name, out MountPointInformation mpi); [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetFormatInfoForMountPoint", SetLastError = true)] private static extern unsafe int GetFormatInfoForMountPoint( [MarshalAs(UnmanagedType.LPStr)]string name, byte* formatNameBuffer, int bufferLength, long* formatType); internal static int GetFormatInfoForMountPoint(string name, out string format) { DriveType temp; return GetFormatInfoForMountPoint(name, out format, out temp); } internal static int GetFormatInfoForMountPoint(string name, out DriveType type) { string temp; return GetFormatInfoForMountPoint(name, out temp, out type); } private static int GetFormatInfoForMountPoint(string name, out string format, out DriveType type) { unsafe { byte* formatBuffer = stackalloc byte[MountPointFormatBufferSizeInBytes]; // format names should be small long numericFormat; int result = GetFormatInfoForMountPoint(name, formatBuffer, MountPointFormatBufferSizeInBytes, &numericFormat); if (result == 0) { // Check if we have a numeric answer or string format = numericFormat != -1 ? Enum.GetName(typeof(UnixFileSystemTypes), numericFormat) : Marshal.PtrToStringAnsi((IntPtr)formatBuffer); type = GetDriveType(format); } else { format = string.Empty; type = DriveType.Unknown; } return result; } } /// <summary>Categorizes a file system name into a drive type.</summary> /// <param name="fileSystemName">The name to categorize.</param> /// <returns>The recognized drive type.</returns> private static DriveType GetDriveType(string fileSystemName) { // This list is based primarily on "man fs", "man mount", "mntent.h", "/proc/filesystems", // and "wiki.debian.org/FileSystem". It can be extended over time as we // find additional file systems that should be recognized as a particular drive type. switch (fileSystemName) { case "iso": case "isofs": case "iso9660": case "fuseiso": case "fuseiso9660": case "umview-mod-umfuseiso9660": return DriveType.CDRom; case "adfs": case "affs": case "apfs": case "befs": case "bfs": case "btrfs": case "drvfs": case "ecryptfs": case "efs": case "ext": case "ext2": case "ext2_old": case "ext3": case "ext4": case "ext4dev": case "fat": case "fuseblk": case "fuseext2": case "fusefat": case "hfs": case "hfsplus": case "hpfs": case "jbd": case "jbd2": case "jfs": case "jffs": case "jffs2": case "lxfs": case "minix": case "minix_old": case "minix2": case "minix2v2": case "msdos": case "ocfs2": case "omfs": case "openprom": case "overlay": case "overlayfs": case "ntfs": case "qnx4": case "reiserfs": case "squashfs": case "swap": case "sysv": case "ubifs": case "udf": case "ufs": case "umsdos": case "umview-mod-umfuseext2": case "xenix": case "xfs": case "xiafs": case "xmount": case "zfs-fuse": return DriveType.Fixed; case "9p": case "autofs": case "autofs4": case "beaglefs": case "cifs": case "coda": case "coherent": case "curlftpfs": case "davfs2": case "dlm": case "flickrfs": case "fusedav": case "fusesmb": case "gfs2": case "glusterfs-client": case "gmailfs": case "kafs": case "ltspfs": case "ncpfs": case "nfs": case "nfs4": case "obexfs": case "s3ql": case "smb": case "smbfs": case "sshfs": case "sysfs": case "sysv2": case "sysv4": case "vxfs": case "wikipediafs": return DriveType.Network; case "anon_inodefs": case "aptfs": case "avfs": case "bdev": case "binfmt_misc": case "cgroup": case "configfs": case "cramfs": case "cryptkeeper": case "cpuset": case "debugfs": case "devfs": case "devpts": case "devtmpfs": case "encfs": case "fuse": case "fuse.gvfsd-fuse": case "fusectl": case "hugetlbfs": case "libpam-encfs": case "ibpam-mount": case "mtpfs": case "mythtvfs": case "mqueue": case "pipefs": case "plptools": case "proc": case "pstore": case "pytagsfs": case "ramfs": case "rofs": case "romfs": case "rootfs": case "securityfs": case "sockfs": case "tmpfs": return DriveType.Ram; case "gphotofs": case "usbfs": case "usbdevice": case "vfat": return DriveType.Removable; // Categorize as "Unknown" everything else not explicitly // recognized as a particular drive type. default: return DriveType.Unknown; } } } }
using System; using System.Collections.Generic; using System.Text; using Orleans.Serialization.Invocation; namespace Orleans.Runtime { [WellKnownId(101)] internal sealed class Message { public const int LENGTH_HEADER_SIZE = 8; public const int LENGTH_META_HEADER = 4; [NonSerialized] private string _targetHistory; [NonSerialized] private int _retryCount; // Cache values of TargetAddess and SendingAddress as they are used very frequently [NonSerialized] private ActivationAddress _targetAddress; [NonSerialized] private ActivationAddress _sendingAddress; // For statistical measuring of time spent in queues. [NonSerialized] private CoarseStopwatch _timeInterval; [NonSerialized] public readonly CoarseStopwatch _timeSinceCreation = CoarseStopwatch.StartNew(); public object BodyObject { get; set; } public Categories _category; public Directions? _direction; public bool _isReadOnly; public bool _isAlwaysInterleave; public bool _isUnordered; public int _forwardCount; public CorrelationId _id; public CorrelationId _callChainId; public Dictionary<string, object> _requestContextData; public SiloAddress _targetSilo; public GrainId _targetGrain; public ActivationId _targetActivation; public ushort _interfaceVersion; public GrainInterfaceType _interfaceType; public SiloAddress _sendingSilo; public GrainId _sendingGrain; public ActivationId _sendingActivation; public TimeSpan? _timeToLive; public List<ActivationAddress> _cacheInvalidationHeader; public ResponseTypes _result; public RejectionTypes _rejectionType; public string _rejectionInfo; [GenerateSerializer] public enum Categories : byte { Ping, System, Application, } [GenerateSerializer] public enum Directions : byte { Request, Response, OneWay } [GenerateSerializer] public enum ResponseTypes : byte { Success, Error, Rejection, Status } [GenerateSerializer] public enum RejectionTypes : byte { Transient, Overloaded, DuplicateRequest, Unrecoverable, GatewayTooBusy, CacheInvalidation } public Directions Direction { get => _direction ?? default; set => _direction = value; } public bool HasDirection => _direction.HasValue; public bool IsFullyAddressed => TargetSilo is object && !TargetGrain.IsDefault && !TargetActivation.IsDefault; public ActivationAddress TargetAddress { get { if (_targetAddress is { } result) return result; if (!TargetGrain.IsDefault) { return _targetAddress = ActivationAddress.GetAddress(TargetSilo, TargetGrain, TargetActivation); } return null; } set { TargetGrain = value.Grain; TargetActivation = value.Activation; TargetSilo = value.Silo; _targetAddress = value; } } public ActivationAddress SendingAddress { get => _sendingAddress ??= ActivationAddress.GetAddress(SendingSilo, SendingGrain, SendingActivation); set { SendingGrain = value.Grain; SendingActivation = value.Activation; SendingSilo = value.Silo; _sendingAddress = value; } } public bool IsExpired { get { if (!TimeToLive.HasValue) { return false; } return TimeToLive <= TimeSpan.Zero; } } public string TargetHistory { get => _targetHistory; set => _targetHistory = value; } public int RetryCount { get => _retryCount; set => _retryCount = value; } public bool HasCacheInvalidationHeader => CacheInvalidationHeader is { Count: > 0 }; public TimeSpan Elapsed => _timeInterval.Elapsed; public Categories Category { get => _category; set => _category = value; } public bool IsReadOnly { get => _isReadOnly; set => _isReadOnly = value; } public bool IsAlwaysInterleave { get => _isAlwaysInterleave; set => _isAlwaysInterleave = value; } public bool IsUnordered { get => _isUnordered; set => _isUnordered = value; } public CorrelationId Id { get => _id; set => _id = value; } public int ForwardCount { get => _forwardCount; set => _forwardCount = value; } public SiloAddress TargetSilo { get => _targetSilo; set { _targetSilo = value; _targetAddress = null; } } public GrainId TargetGrain { get => _targetGrain; set { _targetGrain = value; _targetAddress = null; } } public ActivationId TargetActivation { get => _targetActivation; set { _targetActivation = value; _targetAddress = null; } } public SiloAddress SendingSilo { get => _sendingSilo; set { _sendingSilo = value; _sendingAddress = null; } } public GrainId SendingGrain { get => _sendingGrain; set { _sendingGrain = value; _sendingAddress = null; } } public ActivationId SendingActivation { get => _sendingActivation; set { _sendingActivation = value; _sendingAddress = null; } } public ushort InterfaceVersion { get => _interfaceVersion; set => _interfaceVersion = value; } public ResponseTypes Result { get => _result; set => _result = value; } public TimeSpan? TimeToLive { get => _timeToLive - _timeSinceCreation.Elapsed; set => _timeToLive = value; } public List<ActivationAddress> CacheInvalidationHeader { get => _cacheInvalidationHeader; set => _cacheInvalidationHeader = value; } public RejectionTypes RejectionType { get => _rejectionType; set => _rejectionType = value; } public string RejectionInfo { get => _rejectionInfo ?? ""; set => _rejectionInfo = value; } public Dictionary<string, object> RequestContextData { get => _requestContextData; set => _requestContextData = value; } public CorrelationId CallChainId { get => _callChainId; set => _callChainId = value; } public GrainInterfaceType InterfaceType { get => _interfaceType; set => _interfaceType = value; } public bool IsExpirableMessage(bool dropExpiredMessages) { if (!dropExpiredMessages) return false; GrainId id = TargetGrain; if (id.IsDefault) return false; // don't set expiration for one way, system target and system grain messages. return Direction != Directions.OneWay && !id.IsSystemTarget(); } internal void AddToCacheInvalidationHeader(ActivationAddress address) { var list = new List<ActivationAddress>(); if (CacheInvalidationHeader != null) { list.AddRange(CacheInvalidationHeader); } list.Add(address); CacheInvalidationHeader = list; } public void ClearTargetAddress() { _targetAddress = null; } // For testing and logging/tracing public string ToLongString() { var sb = new StringBuilder(); AppendIfExists(Headers.CACHE_INVALIDATION_HEADER, sb, (m) => m.CacheInvalidationHeader); AppendIfExists(Headers.CATEGORY, sb, (m) => m.Category); AppendIfExists(Headers.DIRECTION, sb, (m) => m.Direction); AppendIfExists(Headers.TIME_TO_LIVE, sb, (m) => m.TimeToLive); AppendIfExists(Headers.FORWARD_COUNT, sb, (m) => m.ForwardCount); AppendIfExists(Headers.CORRELATION_ID, sb, (m) => m.Id); AppendIfExists(Headers.ALWAYS_INTERLEAVE, sb, (m) => m.IsAlwaysInterleave); AppendIfExists(Headers.READ_ONLY, sb, (m) => m.IsReadOnly); AppendIfExists(Headers.IS_UNORDERED, sb, (m) => m.IsUnordered); AppendIfExists(Headers.REJECTION_INFO, sb, (m) => m.RejectionInfo); AppendIfExists(Headers.REJECTION_TYPE, sb, (m) => m.RejectionType); AppendIfExists(Headers.REQUEST_CONTEXT, sb, (m) => m.RequestContextData); AppendIfExists(Headers.RESULT, sb, (m) => m.Result); AppendIfExists(Headers.SENDING_ACTIVATION, sb, (m) => m.SendingActivation); AppendIfExists(Headers.SENDING_GRAIN, sb, (m) => m.SendingGrain); AppendIfExists(Headers.SENDING_SILO, sb, (m) => m.SendingSilo); AppendIfExists(Headers.TARGET_ACTIVATION, sb, (m) => m.TargetActivation); AppendIfExists(Headers.TARGET_GRAIN, sb, (m) => m.TargetGrain); AppendIfExists(Headers.CALL_CHAIN_ID, sb, (m) => m.CallChainId); AppendIfExists(Headers.TARGET_SILO, sb, (m) => m.TargetSilo); return sb.ToString(); } private void AppendIfExists(Headers header, StringBuilder sb, Func<Message, object> valueProvider) { // used only under log3 level if ((GetHeadersMask() & header) != Headers.NONE) { sb.AppendFormat("{0}={1};", header, valueProvider(this)); sb.AppendLine(); } } public override string ToString() { var response = ""; if (Direction == Directions.Response) { switch (Result) { case ResponseTypes.Error: response = "Error "; break; case ResponseTypes.Rejection: response = string.Format("{0} Rejection (info: {1}) ", RejectionType, RejectionInfo); break; case ResponseTypes.Status: response = "Status "; break; default: break; } } return $"{(IsReadOnly ? "ReadOnly" : "")}" + $"{(IsAlwaysInterleave ? " IsAlwaysInterleave" : "")}" + $" {response}{Direction}" + $" {$"[{SendingSilo} {SendingGrain} {SendingActivation}]"}->{$"[{TargetSilo} {TargetGrain} {TargetActivation}]"}" + $"{(BodyObject is { } request ? $" {request}" : string.Empty)}" + $" #{Id}{(ForwardCount > 0 ? "[ForwardCount=" + ForwardCount + "]" : "")}"; } public string GetTargetHistory() { var history = new StringBuilder(); history.Append("<"); if (TargetSilo != null) { history.Append(TargetSilo).Append(":"); } if (!TargetGrain.IsDefault) { history.Append(TargetGrain).Append(":"); } if (!TargetActivation.IsDefault) { history.Append(TargetActivation); } history.Append(">"); if (!string.IsNullOrEmpty(TargetHistory)) { history.Append(" ").Append(TargetHistory); } return history.ToString(); } public void Start() { _timeInterval = CoarseStopwatch.StartNew(); } public void Stop() { _timeInterval.Stop(); } public void Restart() { _timeInterval.Restart(); } public static Message CreatePromptExceptionResponse(Message request, Exception exception) { return new Message { Category = request.Category, Direction = Message.Directions.Response, Result = Message.ResponseTypes.Error, BodyObject = Response.FromException(exception) }; } [Flags] public enum Headers { NONE = 0, ALWAYS_INTERLEAVE = 1 << 0, CACHE_INVALIDATION_HEADER = 1 << 1, CATEGORY = 1 << 2, CORRELATION_ID = 1 << 3, DEBUG_CONTEXT = 1 << 4, // No longer used DIRECTION = 1 << 5, TIME_TO_LIVE = 1 << 6, FORWARD_COUNT = 1 << 7, NEW_GRAIN_TYPE = 1 << 8, GENERIC_GRAIN_TYPE = 1 << 9, RESULT = 1 << 10, REJECTION_INFO = 1 << 11, REJECTION_TYPE = 1 << 12, READ_ONLY = 1 << 13, RESEND_COUNT = 1 << 14, // Support removed. Value retained for backwards compatibility. SENDING_ACTIVATION = 1 << 15, SENDING_GRAIN = 1 << 16, SENDING_SILO = 1 << 17, //IS_NEW_PLACEMENT = 1 << 18, TARGET_ACTIVATION = 1 << 19, TARGET_GRAIN = 1 << 20, TARGET_SILO = 1 << 21, TARGET_OBSERVER = 1 << 22, IS_UNORDERED = 1 << 23, REQUEST_CONTEXT = 1 << 24, INTERFACE_VERSION = 1 << 26, CALL_CHAIN_ID = 1 << 29, INTERFACE_TYPE = 1 << 31 // Do not add over int.MaxValue of these. } internal Headers GetHeadersMask() { var headers = Headers.NONE; if (Category != default) { headers |= Headers.CATEGORY; } headers = _direction == null ? headers & ~Headers.DIRECTION : headers | Headers.DIRECTION; if (IsReadOnly) { headers |= Headers.READ_ONLY; } if (IsAlwaysInterleave) { headers |= Headers.ALWAYS_INTERLEAVE; } if (IsUnordered) { headers |= Headers.IS_UNORDERED; } headers = _id.ToInt64() == 0 ? headers & ~Headers.CORRELATION_ID : headers | Headers.CORRELATION_ID; if (_forwardCount != default(int)) { headers |= Headers.FORWARD_COUNT; } headers = _targetSilo == null ? headers & ~Headers.TARGET_SILO : headers | Headers.TARGET_SILO; headers = _targetGrain.IsDefault ? headers & ~Headers.TARGET_GRAIN : headers | Headers.TARGET_GRAIN; headers = _targetActivation.IsDefault ? headers & ~Headers.TARGET_ACTIVATION : headers | Headers.TARGET_ACTIVATION; headers = _sendingSilo is null ? headers & ~Headers.SENDING_SILO : headers | Headers.SENDING_SILO; headers = _sendingGrain.IsDefault ? headers & ~Headers.SENDING_GRAIN : headers | Headers.SENDING_GRAIN; headers = _sendingActivation.IsDefault ? headers & ~Headers.SENDING_ACTIVATION : headers | Headers.SENDING_ACTIVATION; headers = _interfaceVersion == 0 ? headers & ~Headers.INTERFACE_VERSION : headers | Headers.INTERFACE_VERSION; headers = _result == default(ResponseTypes) ? headers & ~Headers.RESULT : headers | Headers.RESULT; headers = _timeToLive == null ? headers & ~Headers.TIME_TO_LIVE : headers | Headers.TIME_TO_LIVE; headers = _cacheInvalidationHeader == null || _cacheInvalidationHeader.Count == 0 ? headers & ~Headers.CACHE_INVALIDATION_HEADER : headers | Headers.CACHE_INVALIDATION_HEADER; headers = _rejectionType == default(RejectionTypes) ? headers & ~Headers.REJECTION_TYPE : headers | Headers.REJECTION_TYPE; headers = string.IsNullOrEmpty(_rejectionInfo) ? headers & ~Headers.REJECTION_INFO : headers | Headers.REJECTION_INFO; headers = _requestContextData == null || _requestContextData.Count == 0 ? headers & ~Headers.REQUEST_CONTEXT : headers | Headers.REQUEST_CONTEXT; headers = _callChainId.ToInt64() == 0 ? headers & ~Headers.CALL_CHAIN_ID : headers | Headers.CALL_CHAIN_ID; headers = _interfaceType.IsDefault ? headers & ~Headers.INTERFACE_TYPE : headers | Headers.INTERFACE_TYPE; return headers; } } }
/* Copyright (c) 2010 by Genstein This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.ComponentModel; using System.Windows.Forms; using System.Diagnostics; using System.Collections.Generic; namespace Trizbort { partial class Canvas { public bool IsAutomapping { get { return m_automap != null; } } public void StartAutomapping(AutomapSettings settings) { if (m_automap != null) { StopAutomapping(); } m_automap = new Automap(m_threadSafeAutomapCanvas, settings); m_dontAskAboutAmbiguities = false; } public void StopAutomapping() { if (m_automap != null) { m_automap.Dispose(); m_automap = null; } } public string AutomappingStatus { get { if (m_automap != null) { return m_automap.Status; } return "Automapping is not running."; } } Room IAutomapCanvas.FindRoom(string roomName, string roomDescription, RoomMatcher matcher) { var list = new List<Room>(); foreach (var element in Project.Current.Elements) { if (element is Room) { var room = (Room)element; var matches = matcher(roomName, roomDescription, room); if (matches.HasValue && matches.Value) { // it's definitely this room return room; } else if (!matches.HasValue) { // it's ambiguous list.Add(room); } } } if (list.Count == 0) { return null; } if (m_dontAskAboutAmbiguities) { // the user has long given up on this process; // use the first ambiguous room in the list. return list[0]; } if ((string.IsNullOrEmpty(roomDescription) || !list[0].HasDescription) && list.Count == 1) { // technically it's ambiguous, but we don't two descriptions for the user to compare; // there's only one option, so use it. They probably didn't have VERBOSE on for the whole transcript. return list[0]; } using (var dialog = new DisambiguateRoomsDialog()) { dialog.SetTranscriptContext(roomName, roomDescription); dialog.AddAmbiguousRooms(list); dialog.ShowDialog(); if (dialog.UserDoesntCareAnyMore) { // The user has given up on this process! Can't say I blame them. // Use the first ambiguous room on the list, as above. m_dontAskAboutAmbiguities = true; return list[0]; } // Either the user picked a room, or they said "New Room" in which case we don't match, returning null. return dialog.Disambiguation; } } Room IAutomapCanvas.CreateRoom(Room existing, string name) { // start by placing the room at the origin var room = new Room(Project.Current); room.Name = name; if (existing != null) { // if we know which room we were just in, start at that instead room.Position = existing.Position; } room.Position = Settings.Snap(room.Position); // while we can't place the room, try to the left, then the right, // expanding our distance as we go, until we find a blank space. bool tryOtherSideNext = false; bool tryLeft = true; int distance = 0; var initialPosition = room.Position; while (AnyRoomsIntersect(room)) { if (tryOtherSideNext) { tryLeft = !tryLeft; tryOtherSideNext = false; } else { tryOtherSideNext = true; ++distance; } if (tryLeft) { room.Position = Settings.Snap(new Vector(initialPosition.X - distance * (Settings.PreferredDistanceBetweenRooms + room.Width), room.Position.Y)); } else { room.Position = Settings.Snap(new Vector(initialPosition.X + distance * (Settings.PreferredDistanceBetweenRooms + room.Width), room.Position.Y)); } Debug.WriteLine(string.Format("Try again, more to the {0}.", tryLeft ? "left" : "right")); } // after we set the position, set this flag, // since setting the position clears this flag if set. room.ArbitraryAutomappedPosition = true; Project.Current.Elements.Add(room); return room; } Room IAutomapCanvas.CreateRoom(Room existing, AutomapDirection directionFromExisting, string name) { if (!Project.Current.Elements.Contains(existing)) { // avoid issues if the user has just deleted the existing room return null; } var room = new Room(Project.Current); room.Name = name; Vector delta; PositionRelativeTo(room, existing, CompassPointHelper.GetCompassDirection(directionFromExisting), out delta); if (AnyRoomsIntersect(room)) { ShiftMap(room.InnerBounds, delta); Debug.WriteLine("Shift map."); } Project.Current.Elements.Add(room); return room; } private bool AnyRoomsIntersect(Room room) { var bounds = room.InnerBounds; foreach (var element in Project.Current.Elements) { if (element is Room && element != room && element.Intersects(bounds)) { Debug.WriteLine(string.Format("{0} is blocking {1}.", (element as Room).Name, room.Name)); return true; } } return false; } void PositionRelativeTo(Room room, Room existing, CompassPoint existingCompassPoint, out Vector delta) { delta = CompassPointHelper.GetAutomapDirectionVector(existingCompassPoint); delta.X *= Settings.PreferredDistanceBetweenRooms + room.Width; delta.Y *= Settings.PreferredDistanceBetweenRooms + room.Height; var newRoomCenter = existing.InnerBounds.Center + delta; room.Position = Settings.Snap(new Vector(newRoomCenter.X - room.Width / 2, newRoomCenter.Y - room.Height / 2)); } void ShiftMap(Rect deltaOrigin, Vector delta) { // move all elements to the left/right of the origin left/right by the given delta foreach (var element in Project.Current.Elements) { if (element is Room) { var room = (Room)element; var bounds = room.InnerBounds; if (delta.X < 0) { if (bounds.Center.X < deltaOrigin.Right) { room.Position = new Vector(room.Position.X + delta.X, room.Position.Y); } } else if (delta.X > 0) { if (bounds.Center.X > deltaOrigin.Left) { room.Position = new Vector(room.Position.X + delta.X, room.Position.Y); } } } } // move all elements above/below the origin up/down by the given delta foreach (var element in Project.Current.Elements) { if (element is Room) { var room = (Room)element; var bounds = room.InnerBounds; if (delta.Y < 0) { if (bounds.Center.Y < deltaOrigin.Bottom) { room.Position = new Vector(room.Position.X, room.Position.Y + delta.Y); } } else if (bounds.Center.Y > deltaOrigin.Top) { if (bounds.Bottom > deltaOrigin.Y) { room.Position = new Vector(room.Position.X, room.Position.Y + delta.Y); } } } } } /// <summary> /// Approximately match two directions, allowing for aesthetic rearrangement by the user. /// </summary> /// <remarks> /// Two compass points match if they are on the same side of a box representing the room. /// </remarks> bool ApproximateDirectionMatch(CompassPoint one, CompassPoint two) { return CompassPointHelper.GetAutomapDirectionVector(one) == CompassPointHelper.GetAutomapDirectionVector(two); } Connection FindConnection(Room source, Room target, CompassPoint? directionFromSource, out bool wrongWay) { foreach (var element in Project.Current.Elements) { if (element is Connection) { var connection = (Connection)element; CompassPoint fromDirection, toDirection; var fromRoom = connection.GetSourceRoom(out fromDirection); var toRoom = connection.GetTargetRoom(out toDirection); if (fromRoom == source && toRoom == target && (directionFromSource == null || ApproximateDirectionMatch(directionFromSource.Value, fromDirection))) { // the two rooms are connected already in the given direction, A to B or both ways. wrongWay = false; return connection; } if (fromRoom == target && toRoom == source && (directionFromSource == null || ApproximateDirectionMatch(directionFromSource.Value, toDirection))) { // the two rooms are connected already in the given direction, B to A or both ways. wrongWay = connection.Flow == ConnectionFlow.OneWay; return connection; } } } wrongWay = false; return null; } void IAutomapCanvas.AddExitStub(Room room, AutomapDirection direction) { if (!Project.Current.Elements.Contains(room)) { // avoid issues if the user has just deleted one of these rooms return; } var sourceCompassPoint = CompassPointHelper.GetCompassDirection(direction); var connection = AddConnection(room, sourceCompassPoint, room, sourceCompassPoint); switch (direction) { case AutomapDirection.Up: connection.StartText = Connection.Up; break; case AutomapDirection.Down: connection.StartText = Connection.Down; break; } } void IAutomapCanvas.RemoveExitStub(Room room, AutomapDirection direction) { if (!Project.Current.Elements.Contains(room)) { // avoid issues if the user has just deleted one of these rooms return; } var compassPoint = CompassPointHelper.GetCompassDirection(direction); foreach (var connection in room.GetConnections(compassPoint)) { CompassPoint sourceCompassPoint, targetCompassPoint; var source = connection.GetSourceRoom(out sourceCompassPoint); var target = connection.GetTargetRoom(out targetCompassPoint); if (source == room && target == room && sourceCompassPoint == compassPoint && targetCompassPoint == compassPoint) { Project.Current.Elements.Remove(connection); } } } void IAutomapCanvas.Connect(Room source, AutomapDirection directionFromSource, Room target) { if (!Project.Current.Elements.Contains(source) || !Project.Current.Elements.Contains(target)) { // avoid issues if the user has just deleted one of these rooms return; } // work out the correct compass point to use for the given direction // look for existing connections: // if the given direction is up/down/in/out, any existing connection will suffice; // otherwise, only match an existing connection if it's pretty close to the one we want. var sourceCompassPoint = CompassPointHelper.GetCompassDirection(directionFromSource); CompassPoint? acceptableSourceCompassPoint; switch (directionFromSource) { case AutomapDirection.Up: case AutomapDirection.Down: case AutomapDirection.In: case AutomapDirection.Out: acceptableSourceCompassPoint = null; // any existing connection will do break; default: acceptableSourceCompassPoint = sourceCompassPoint; break; } bool wrongWay; var connection = FindConnection(source, target, acceptableSourceCompassPoint, out wrongWay); if (connection == null) { // there is no suitable connection between these rooms: var targetCompassPoint = CompassPointHelper.GetAutomapOpposite(sourceCompassPoint); // check whether we can move one of the rooms to make the connection tidier; // we won't need this very often, but it can be useful especially if the user teleports into a room // and then steps out into an existing one (this can appear to happen if the user moves into a // dark room, turns on the light, then leaves). TryMoveRoomsForTidyConnection(source, sourceCompassPoint, target, targetCompassPoint); // add a new connection connection = AddConnection(source, sourceCompassPoint, target, targetCompassPoint); connection.Style = ConnectionStyle.Solid; connection.Flow = ConnectionFlow.OneWay; } else if (wrongWay) { // there is a suitable connection between these rooms, but it goes the wrong way; // make it bidirectional since we can now go both ways. connection.Flow = ConnectionFlow.TwoWay; } // if this is an up/down/in/out connection, mark it as such; // but don't override any existing text. switch (directionFromSource) { case AutomapDirection.Up: case AutomapDirection.Down: case AutomapDirection.In: case AutomapDirection.Out: if (string.IsNullOrEmpty(connection.StartText) && string.IsNullOrEmpty(connection.EndText)) { switch (directionFromSource) { case AutomapDirection.Up: connection.SetText(wrongWay ? ConnectionLabel.Down : ConnectionLabel.Up); break; case AutomapDirection.Down: connection.SetText(wrongWay ? ConnectionLabel.Up : ConnectionLabel.Down); break; case AutomapDirection.In: connection.SetText(wrongWay ? ConnectionLabel.Out : ConnectionLabel.In); break; case AutomapDirection.Out: connection.SetText(wrongWay ? ConnectionLabel.In : ConnectionLabel.Out); break; } } break; } } void TryMoveRoomsForTidyConnection(Room source, CompassPoint sourceCompassPoint, Room target, CompassPoint targetCompassPoint) { if (source.ArbitraryAutomappedPosition && !source.IsConnected) { if (TryMoveRoomForTidyConnection(source, targetCompassPoint, target)) { return; } } if (target.ArbitraryAutomappedPosition && !target.IsConnected) { TryMoveRoomForTidyConnection(target, sourceCompassPoint, source); } } bool TryMoveRoomForTidyConnection(Room source, CompassPoint targetCompassPoint, Room target) { var sourceArbitrary = source.ArbitraryAutomappedPosition; var sourcePosition = source.Position; Vector delta; PositionRelativeTo(source, target, targetCompassPoint, out delta); if (AnyRoomsIntersect(source)) { // didn't work; restore previous position source.Position = sourcePosition; source.ArbitraryAutomappedPosition = sourceArbitrary; return false; } // that's better return true; } void IAutomapCanvas.SelectRoom(Room room) { if (!Project.Current.Elements.Contains(room)) { // avoid issues if the user has just deleted this room return; } SelectedElement = room; if (room != null) { EnsureVisible(room); } } /// <summary> /// A proxy class which implements IAutomapCanvas, marshalling calls to the real canvas on the main thread. /// </summary> private class MultithreadedAutomapCanvas : IAutomapCanvas { public MultithreadedAutomapCanvas(Canvas canvas) { m_control = canvas; m_canvas = canvas; } public Room FindRoom(string roomName, string roomDescription, RoomMatcher matcher) { Room room = null; try { m_control.Invoke((MethodInvoker)delegate() { room = m_canvas.FindRoom(roomName, roomDescription, matcher); }); } catch (Exception) { } return room; } public Room CreateRoom(Room existing, string name) { Room room = null; try { m_control.Invoke((MethodInvoker)delegate() { room = m_canvas.CreateRoom(existing, name); }); } catch (Exception) { } return room; } public Room CreateRoom(Room existing, AutomapDirection directionFromExisting, string name) { Room room = null; try { m_control.Invoke((MethodInvoker)delegate() { room = m_canvas.CreateRoom(existing, directionFromExisting, name); }); } catch (Exception) { } return room; } public void Connect(Room source, AutomapDirection directionFromSource, Room target) { try { m_control.Invoke((MethodInvoker)delegate() { m_canvas.Connect(source, directionFromSource, target); }); } catch (Exception) { } } public void AddExitStub(Room room, AutomapDirection direction) { try { m_control.Invoke((MethodInvoker)delegate() { m_canvas.AddExitStub(room, direction); }); } catch (Exception) { } } public void RemoveExitStub(Room room, AutomapDirection direction) { try { m_control.Invoke((MethodInvoker)delegate() { m_canvas.RemoveExitStub(room, direction); }); } catch (Exception) { } } public void SelectRoom(Room room) { try { m_control.Invoke((MethodInvoker)delegate() { m_canvas.SelectRoom(room); }); } catch (Exception) { } } private Control m_control; private IAutomapCanvas m_canvas; } private MultithreadedAutomapCanvas m_threadSafeAutomapCanvas; private Automap m_automap; private bool m_dontAskAboutAmbiguities = false; } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Udf { using System; using System.Collections.Generic; using System.Text; internal class FileContentBuffer : IBuffer { private UdfContext _context; private Partition _partition; private FileEntry _fileEntry; private uint _blockSize; private List<CookedExtent> _extents; public FileContentBuffer(UdfContext context, Partition partition, FileEntry fileEntry, uint blockSize) { _context = context; _partition = partition; _fileEntry = fileEntry; _blockSize = blockSize; LoadExtents(); } public bool CanRead { get { return true; } } public bool CanWrite { get { return false; } } public long Capacity { get { return (long)_fileEntry.InformationLength; } } public IEnumerable<StreamExtent> Extents { get { throw new NotImplementedException(); } } public int Read(long pos, byte[] buffer, int offset, int count) { if (_fileEntry.InformationControlBlock.AllocationType == AllocationType.Embedded) { byte[] srcBuffer = _fileEntry.AllocationDescriptors; if (pos > srcBuffer.Length) { return 0; } int toCopy = (int)Math.Min(srcBuffer.Length - pos, count); Array.Copy(srcBuffer, (int)pos, buffer, offset, toCopy); return toCopy; } else { return ReadFromExtents(pos, buffer, offset, count); } } public void Write(long pos, byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public void Clear(long pos, int count) { throw new NotSupportedException(); } public void Flush() { } public void SetCapacity(long value) { throw new NotImplementedException(); } public IEnumerable<StreamExtent> GetExtentsInRange(long start, long count) { throw new NotImplementedException(); } private void LoadExtents() { _extents = new List<CookedExtent>(); byte[] activeBuffer = _fileEntry.AllocationDescriptors; AllocationType allocType = _fileEntry.InformationControlBlock.AllocationType; if (allocType == AllocationType.ShortDescriptors) { long filePos = 0; int i = 0; while (i < activeBuffer.Length) { ShortAllocationDescriptor sad = Utilities.ToStruct<ShortAllocationDescriptor>(activeBuffer, i); if (sad.ExtentLength == 0) { break; } if (sad.Flags != ShortAllocationFlags.RecordedAndAllocated) { throw new NotImplementedException("Extents that are not 'recorded and allocated' not implemented"); } CookedExtent newExtent = new CookedExtent { FileContentOffset = filePos, Partition = int.MaxValue, StartPos = sad.ExtentLocation * (long)_blockSize, Length = sad.ExtentLength }; _extents.Add(newExtent); filePos += sad.ExtentLength; i += sad.Size; } } else if (allocType == AllocationType.Embedded) { // do nothing } else if (allocType == AllocationType.LongDescriptors) { long filePos = 0; int i = 0; while (i < activeBuffer.Length) { LongAllocationDescriptor lad = Utilities.ToStruct<LongAllocationDescriptor>(activeBuffer, i); if (lad.ExtentLength == 0) { break; } CookedExtent newExtent = new CookedExtent { FileContentOffset = filePos, Partition = lad.ExtentLocation.Partition, StartPos = lad.ExtentLocation.LogicalBlock * (long)_blockSize, Length = lad.ExtentLength }; _extents.Add(newExtent); filePos += lad.ExtentLength; i += lad.Size; } } else { throw new NotImplementedException("Allocation Type: " + _fileEntry.InformationControlBlock.AllocationType); } } private int ReadFromExtents(long pos, byte[] buffer, int offset, int count) { int totalToRead = (int)Math.Min(Capacity - pos, count); int totalRead = 0; while (totalRead < totalToRead) { CookedExtent extent = FindExtent(pos + totalRead); long extentOffset = (pos + totalRead) - extent.FileContentOffset; int toRead = (int)Math.Min(totalToRead - totalRead, extent.Length - extentOffset); Partition part; if (extent.Partition != int.MaxValue) { part = _context.LogicalPartitions[extent.Partition]; } else { part = _partition; } int numRead = part.Content.Read(extent.StartPos + extentOffset, buffer, offset + totalRead, toRead); if (numRead == 0) { return totalRead; } totalRead += numRead; } return totalRead; } private CookedExtent FindExtent(long pos) { foreach (var extent in _extents) { if (extent.FileContentOffset + extent.Length > pos) { return extent; } } return null; } private class CookedExtent { public long FileContentOffset; public int Partition; public long StartPos; public long Length; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using NPOI.OpenXmlFormats.Wordprocessing; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; using NPOI.Util; using NPOI.OpenXmlFormats.Dml; using System.Xml.Serialization; using NPOI.OpenXmlFormats.Dml.WordProcessing; using NPOI.WP.UserModel; /** * @see <a href="http://msdn.microsoft.com/en-us/library/ff533743(v=office.12).aspx">[MS-OI29500] Run Fonts</a> */ public enum FontCharRange { None, Ascii /* char 0-127 */, CS /* complex symbol */, EastAsia /* east asia */, HAnsi /* high ansi */ }; /** * XWPFrun.object defines a region of text with a common Set of properties * * @author Yegor Kozlov * @author Gregg Morris (gregg dot morris at gmail dot com) - added getColor(), setColor() */ public class XWPFRun : ISDTContents, IRunElement, ICharacterRun { private CT_R run; private String pictureText; //private XWPFParagraph paragraph; private IRunBody parent; private List<XWPFPicture> pictures; /** * @param r the CT_R bean which holds the run.attributes * @param p the parent paragraph */ public XWPFRun(CT_R r, IRunBody p) { this.run = r; this.parent = p; /** * reserve already occupied Drawing ids, so reserving new ids later will * not corrupt the document */ IList<CT_Drawing> drawingList = r.GetDrawingList(); foreach (CT_Drawing ctDrawing in drawingList) { List<CT_Anchor> anchorList = ctDrawing.GetAnchorList(); foreach (CT_Anchor anchor in anchorList) { if (anchor.docPr != null) { this.Document.DrawingIdManager.Reserve(anchor.docPr.id); } } List<CT_Inline> inlineList = ctDrawing.GetInlineList(); foreach (CT_Inline inline in inlineList) { if (inline.docPr != null) { this.Document.DrawingIdManager.Reserve(inline.docPr.id); } } } //// Look for any text in any of our pictures or Drawings StringBuilder text = new StringBuilder(); List<object> pictTextObjs = new List<object>(); foreach (CT_Picture pic in r.GetPictList()) pictTextObjs.Add(pic); foreach (CT_Drawing draw in drawingList) pictTextObjs.Add(draw); //foreach (object o in pictTextObjs) //{ //todo:: imlement this //XmlObject[] t = o.SelectPath("declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' .//w:t"); //for (int m = 0; m < t.Length; m++) //{ // NodeList kids = t[m].DomNode.ChildNodes; // for (int n = 0; n < kids.Length; n++) // { // if (kids.Item(n) is Text) // { // if (text.Length > 0) // text.Append("\n"); // text.Append(kids.Item(n).NodeValue); // } // } //} //} pictureText = text.ToString(); // Do we have any embedded pictures? // (They're a different CT_Picture, under the Drawingml namespace) pictures = new List<XWPFPicture>(); foreach (object o in pictTextObjs) { foreach (OpenXmlFormats.Dml.Picture.CT_Picture pict in GetCTPictures(o)) { XWPFPicture picture = new XWPFPicture(pict, this); pictures.Add(picture); } } } /** * @deprecated Use {@link XWPFRun#XWPFRun(CTR, IRunBody)} */ [Obsolete("Use XWPFRun(CTR, IRunBody)")] public XWPFRun(CT_R r, XWPFParagraph p) : this(r, (IRunBody)p) { } private List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> GetCTPictures(object o) { List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures = new List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture>(); //XmlObject[] picts = o.SelectPath("declare namespace pic='"+CT_Picture.type.Name.NamespaceURI+"' .//pic:pic"); //XmlElement[] picts = o.Any; //foreach (XmlElement pict in picts) //{ //if(pict is XmlAnyTypeImpl) { // // Pesky XmlBeans bug - see Bugzilla #49934 // try { // pict = CT_Picture.Factory.Parse( pict.ToString() ); // } catch(XmlException e) { // throw new POIXMLException(e); // } //} //if (pict is NPOI.OpenXmlFormats.Dml.CT_Picture) //{ // pictures.Add((NPOI.OpenXmlFormats.Dml.CT_Picture)pict); //} //} if (o is CT_Drawing) { CT_Drawing drawing = o as CT_Drawing; if (drawing.inline != null) { foreach (CT_Inline inline in drawing.inline) { GetPictures(inline.graphic.graphicData, pictures); } } } else if (o is CT_GraphicalObjectData) { GetPictures(o as CT_GraphicalObjectData, pictures); } return pictures; } private void GetPictures(CT_GraphicalObjectData god, List<NPOI.OpenXmlFormats.Dml.Picture.CT_Picture> pictures) { XmlSerializer xmlse = new XmlSerializer(typeof(NPOI.OpenXmlFormats.Dml.Picture.CT_Picture)); foreach (string el in god.Any) { System.IO.StringReader stringReader = new System.IO.StringReader(el); NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pict = xmlse.Deserialize(System.Xml.XmlReader.Create(stringReader)) as NPOI.OpenXmlFormats.Dml.Picture.CT_Picture; pictures.Add(pict); } } /** * Get the currently used CT_R object * @return CT_R object */ public CT_R GetCTR() { return run; } /** * Get the currently referenced paragraph/SDT object * @return current parent */ public IRunBody Parent { get { return parent; } } /** * Get the currently referenced paragraph, or null if a SDT object * @deprecated use {@link XWPFRun#getParent()} instead */ public XWPFParagraph Paragraph { get { if (parent is XWPFParagraph) return (XWPFParagraph)parent; return null; } } /** * @return The {@link XWPFDocument} instance, this run.belongs to, or * <code>null</code> if parent structure (paragraph > document) is not properly Set. */ public XWPFDocument Document { get { if (parent != null) { return parent.Document; } return null; } } /** * For isBold, isItalic etc */ private bool IsCTOnOff(CT_OnOff onoff) { if (!onoff.IsSetVal()) return true; return onoff.val; } /** * Whether the bold property shall be applied to all non-complex script * characters in the contents of this run.when displayed in a document. * <p> * This formatting property is a toggle property, which specifies that its * behavior differs between its use within a style defInition and its use as * direct formatting. When used as part of a style defInition, Setting this * property shall toggle the current state of that property as specified up * to this point in the hierarchy (i.e. applied to not applied, and vice * versa). Setting it to <code>false</code> (or an equivalent) shall * result in the current Setting remaining unChanged. However, when used as * direct formatting, Setting this property to true or false shall Set the * absolute state of the resulting property. * </p> * <p> * If this element is not present, the default value is to leave the * formatting applied at previous level in the style hierarchy. If this * element is never applied in the style hierarchy, then bold shall not be * applied to non-complex script characters. * </p> * * @param value <code>true</code> if the bold property is applied to * this run */ public bool IsBold { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetB()) { return false; } return IsCTOnOff(pr.b); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff bold = pr.IsSetB() ? pr.b : pr.AddNewB(); bold.val = value; } } /** * Get text color. The returned value is a string in the hex form "RRGGBB". */ public String GetColor() { String color = null; if (run.IsSetRPr()) { CT_RPr pr = run.rPr; if (pr.IsSetColor()) { NPOI.OpenXmlFormats.Wordprocessing.CT_Color clr = pr.color; color = clr.val; //clr.xgetVal().getStringValue(); } } return color; } /** * Set text color. * @param rgbStr - the desired color, in the hex form "RRGGBB". */ public void SetColor(String rgbStr) { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); NPOI.OpenXmlFormats.Wordprocessing.CT_Color color = pr.IsSetColor() ? pr.color : pr.AddNewColor(); color.val = (rgbStr); } /** * Return the string content of this text run * * @return the text of this text run.or <code>null</code> if not Set */ public String GetText(int pos) { return run.SizeOfTArray() == 0 ? null : run.GetTArray(pos).Value; } /** * Returns text embedded in pictures */ public String PictureText { get { return pictureText; } } public void ReplaceText(string oldText, string newText) { string text = this.Text.Replace(oldText, newText); this.SetText(text); } /** * Sets the text of this text run * * @param value the literal text which shall be displayed in the document */ public void SetText(String value) { this.SetText(value, run.SizeOfTArray()); } public void AppendText(String value) { SetText(value, run.GetTList().Count); } /** * Sets the text of this text run.in the * * @param value the literal text which shall be displayed in the document * @param pos - position in the text array (NB: 0 based) */ public void SetText(String value, int pos) { int length = run.SizeOfTArray(); if (pos > length) throw new IndexOutOfRangeException("Value too large for the parameter position in XWPFrun.Text=(String value,int pos)"); CT_Text t = (pos < length && pos >= 0) ? run.GetTArray(pos) as CT_Text : run.AddNewT(); t.Value = (value); preserveSpaces(t); } /** * Whether the italic property should be applied to all non-complex script * characters in the contents of this run.when displayed in a document. * * @return <code>true</code> if the italic property is applied */ public bool IsItalic { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetI()) return false; return IsCTOnOff(pr.i); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff italic = pr.IsSetI() ? pr.i : pr.AddNewI(); italic.val = value; } } /** * Specifies that the contents of this run.should be displayed along with an * underline appearing directly below the character heigh * * @return the Underline pattern Applyed to this run * @see UnderlinePatterns */ public UnderlinePatterns Underline { get { CT_RPr pr = run.rPr; return (pr != null && pr.IsSetU() && pr.u.val != null) ? EnumConverter.ValueOf<UnderlinePatterns, ST_Underline>(pr.u.val) : UnderlinePatterns.None; } } internal void InsertText(CT_Text text, int textIndex) { run.GetTList().Insert(textIndex, text); } /// <summary> /// insert text at start index in the run /// </summary> /// <param name="text">insert text</param> /// <param name="startIndex">start index of the insertion in the run text</param> public void InsertText(string text, int startIndex) { List<CT_Text> texts = run.GetTList(); int endPos = 0; int startPos = 0; for (int i = 0; i < texts.Count; i++) { startPos = endPos; endPos += texts[i].Value.Length; if (endPos > startIndex) { texts[i].Value = texts[i].Value.Insert(startIndex - startPos, text); break; } } } public string Text { get { StringBuilder text = new StringBuilder(); for (int i = 0; i < run.Items.Count; i++) { object o = run.Items[i]; if (o is CT_Text) { if (!(run.ItemsElementName[i] == RunItemsChoiceType.instrText)) { text.Append(((CT_Text)o).Value); } } // Complex type evaluation (currently only for extraction of check boxes) if (o is CT_FldChar) { CT_FldChar ctfldChar = ((CT_FldChar)o); if (ctfldChar.fldCharType == ST_FldCharType.begin) { if (ctfldChar.ffData != null) { foreach (CT_FFCheckBox checkBox in ctfldChar.ffData.GetCheckBoxList()) { if ([email protected] == true) { text.Append("|X|"); } else { text.Append("|_|"); } } } } } if (o is CT_PTab) { text.Append("\t"); } if (o is CT_Br) { text.Append("\n"); } if (o is CT_Empty) { // Some inline text elements Get returned not as // themselves, but as CTEmpty, owing to some odd // defInitions around line 5642 of the XSDs // This bit works around it, and replicates the above // rules for that case if (run.ItemsElementName[i] == RunItemsChoiceType.tab) { text.Append("\t"); } if (run.ItemsElementName[i] == RunItemsChoiceType.br) { text.Append("\n"); } if (run.ItemsElementName[i] == RunItemsChoiceType.cr) { text.Append("\n"); } } if (o is CT_FtnEdnRef) { CT_FtnEdnRef ftn = (CT_FtnEdnRef)o; String footnoteRef = ftn.DomNode.LocalName.Equals("footnoteReference") ? "[footnoteRef:" + ftn.id + "]" : "[endnoteRef:" + ftn.id + "]"; text.Append(footnoteRef); } } // Any picture text? if (pictureText != null && pictureText.Length > 0) { text.Append("\n").Append(pictureText); } return text.ToString(); } } /** * Specifies that the contents of this run.should be displayed along with an * underline appearing directly below the character heigh * If this element is not present, the default value is to leave the * formatting applied at previous level in the style hierarchy. If this * element is never applied in the style hierarchy, then an underline shall * not be applied to the contents of this run. * * @param value - * underline type * @see UnderlinePatterns : all possible patterns that could be applied */ public void SetUnderline(UnderlinePatterns value) { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_Underline underline = (pr.u == null) ? pr.AddNewU() : pr.u; underline.val = EnumConverter.ValueOf<ST_Underline, UnderlinePatterns>(value); } /** * Specifies that the contents of this run.shall be displayed with a single * horizontal line through the center of the line. * * @return <code>true</code> if the strike property is applied */ public bool IsStrikeThrough { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetStrike()) return false; return IsCTOnOff(pr.strike); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff strike = pr.IsSetStrike() ? pr.strike : pr.AddNewStrike(); strike.val = value;//(value ? ST_OnOff.True : ST_OnOff.False); } } /** * Specifies that the contents of this run.shall be displayed with a single * horizontal line through the center of the line. * <p/> * This formatting property is a toggle property, which specifies that its * behavior differs between its use within a style defInition and its use as * direct formatting. When used as part of a style defInition, Setting this * property shall toggle the current state of that property as specified up * to this point in the hierarchy (i.e. applied to not applied, and vice * versa). Setting it to false (or an equivalent) shall result in the * current Setting remaining unChanged. However, when used as direct * formatting, Setting this property to true or false shall Set the absolute * state of the resulting property. * </p> * <p/> * If this element is not present, the default value is to leave the * formatting applied at previous level in the style hierarchy. If this * element is never applied in the style hierarchy, then strikethrough shall * not be applied to the contents of this run. * </p> * * @param value <code>true</code> if the strike property is applied to * this run */ [Obsolete] public bool IsStrike { get { return IsStrikeThrough; } set { IsStrikeThrough = value; } } /** * Specifies that the contents of this run shall be displayed with a double * horizontal line through the center of the line. * * @return <code>true</code> if the double strike property is applied */ public bool IsDoubleStrikeThrough { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetDstrike()) return false; return IsCTOnOff(pr.dstrike); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff dstrike = pr.IsSetDstrike() ? pr.dstrike : pr.AddNewDstrike(); dstrike.val = value;//(value ? STOnOff.TRUE : STOnOff.FALSE); } } public bool IsSmallCaps { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetSmallCaps()) return false; return IsCTOnOff(pr.smallCaps); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff caps = pr.IsSetSmallCaps() ? pr.smallCaps : pr.AddNewSmallCaps(); caps.val = value;//(value ? ST_OnOff.True : ST_OnOff.False); } } public bool IsCapitalized { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetCaps()) return false; return IsCTOnOff(pr.caps); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff caps = pr.IsSetCaps() ? pr.caps : pr.AddNewCaps(); caps.val = value;//(value ? ST_OnOff.True : ST_OnOff.False); } } public bool IsShadowed { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetShadow()) return false; return IsCTOnOff(pr.shadow); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff shadow = pr.IsSetShadow() ? pr.shadow : pr.AddNewShadow(); shadow.val = value;//(value ? ST_OnOff.True : ST_OnOff.False); } } public bool IsImprinted { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetImprint()) return false; return IsCTOnOff(pr.imprint); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff imprinted = pr.IsSetImprint() ? pr.imprint : pr.AddNewImprint(); imprinted.val = value;//(value ? ST_OnOff.True : ST_OnOff.False); } } public bool IsEmbossed { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetEmboss()) return false; return IsCTOnOff(pr.emboss); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff emboss = pr.IsSetEmboss() ? pr.emboss : pr.AddNewEmboss(); emboss.val = value;//(value ? ST_OnOff.True : ST_OnOff.False); } } [Obsolete] public void SetStrike(bool value) { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_OnOff strike = pr.IsSetStrike() ? pr.strike : pr.AddNewStrike(); strike.val = value; } /** * Specifies the alignment which shall be applied to the contents of this * run.in relation to the default appearance of the run.s text. * This allows the text to be repositioned as subscript or superscript without * altering the font size of the run.properties. * * @return VerticalAlign * @see VerticalAlign all possible value that could be Applyed to this run */ public VerticalAlign Subscript { get { CT_RPr pr = run.rPr; return (pr != null && pr.IsSetVertAlign()) ? EnumConverter.ValueOf<VerticalAlign, ST_VerticalAlignRun>(pr.vertAlign.val) : VerticalAlign.BASELINE; } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_VerticalAlignRun ctValign = pr.IsSetVertAlign() ? pr.vertAlign : pr.AddNewVertAlign(); ctValign.val = EnumConverter.ValueOf<ST_VerticalAlignRun, VerticalAlign>(value); } } public int Kerning { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetKern()) return 0; return (int)pr.kern.val; } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_HpsMeasure kernmes = pr.IsSetKern() ? pr.kern : pr.AddNewKern(); kernmes.val = (ulong)value; } } public int CharacterSpacing { get { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetSpacing()) return 0; return int.Parse(pr.spacing.val); } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_SignedTwipsMeasure spc = pr.IsSetSpacing() ? pr.spacing : pr.AddNewSpacing(); spc.val = value.ToString(); } } /** * Specifies the fonts which shall be used to display the text contents of * this run. Specifies a font which shall be used to format all characters * in the ASCII range (0 - 127) within the parent run * * @return a string representing the font family */ public String FontFamily { get { return GetFontFamily(FontCharRange.None); } set { SetFontFamily(value, FontCharRange.None); } } public string FontName { get { return FontFamily; } } /** * Gets the font family for the specified font char range. * If fcr is null, the font char range "ascii" is used * * @param fcr the font char range, defaults to "ansi" * @return a string representing the font famil */ public String GetFontFamily(FontCharRange fcr) { CT_RPr pr = run.rPr; if (pr == null || !pr.IsSetRFonts()) return null; CT_Fonts fonts = pr.rFonts; switch (fcr == FontCharRange.None ? FontCharRange.Ascii : fcr) { default: case FontCharRange.Ascii: return fonts.ascii; case FontCharRange.CS: return fonts.cs; case FontCharRange.EastAsia: return fonts.eastAsia; case FontCharRange.HAnsi: return fonts.hAnsi; } } /** * Specifies the fonts which shall be used to display the text contents of * this run. The default handling for fcr == null is to overwrite the * ascii font char range with the given font family and also set all not * specified font ranges * * @param fontFamily * @param fcr FontCharRange or null for default handling */ public void SetFontFamily(String fontFamily, FontCharRange fcr) { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_Fonts fonts = pr.IsSetRFonts() ? pr.rFonts : pr.AddNewRFonts(); if (fcr == FontCharRange.None) { fonts.ascii = (fontFamily); if (!fonts.IsSetHAnsi()) { fonts.hAnsi = (fontFamily); } if (!fonts.IsSetCs()) { fonts.cs = (fontFamily); } if (!fonts.IsSetEastAsia()) { fonts.eastAsia = (fontFamily); } } else { switch (fcr) { case FontCharRange.Ascii: fonts.ascii = (fontFamily); break; case FontCharRange.CS: fonts.cs = (fontFamily); break; case FontCharRange.EastAsia: fonts.eastAsia = (fontFamily); break; case FontCharRange.HAnsi: fonts.hAnsi = (fontFamily); break; } } } /** * Specifies the font size which shall be applied to all non complex script * characters in the contents of this run.when displayed. * * @return value representing the font size */ public int FontSize { get { CT_RPr pr = run.rPr; return (pr != null && pr.IsSetSz()) ? (int)pr.sz.val / 2 : -1; } set { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_HpsMeasure ctSize = pr.IsSetSz() ? pr.sz : pr.AddNewSz(); ctSize.val = (ulong)value * 2; } } /** * This element specifies the amount by which text shall be raised or * lowered for this run.in relation to the default baseline of the * surrounding non-positioned text. This allows the text to be repositioned * without altering the font size of the contents. * * @return a big integer representing the amount of text shall be "moved" */ public int GetTextPosition() { CT_RPr pr = run.rPr; return (pr != null && pr.IsSetPosition()) ? int.Parse(pr.position.val) : -1; } /** * This element specifies the amount by which text shall be raised or * lowered for this run.in relation to the default baseline of the * surrounding non-positioned text. This allows the text to be repositioned * without altering the font size of the contents. * * If the val attribute is positive, then the parent run.shall be raised * above the baseline of the surrounding text by the specified number of * half-points. If the val attribute is negative, then the parent run.shall * be lowered below the baseline of the surrounding text by the specified * number of half-points. * * * If this element is not present, the default value is to leave the * formatting applied at previous level in the style hierarchy. If this * element is never applied in the style hierarchy, then the text shall not * be raised or lowered relative to the default baseline location for the * contents of this run. */ public void SetTextPosition(int val) { CT_RPr pr = run.IsSetRPr() ? run.rPr : run.AddNewRPr(); CT_SignedHpsMeasure position = pr.IsSetPosition() ? pr.position : pr.AddNewPosition(); position.val = (val.ToString()); } /** * */ public void RemoveBreak() { // TODO } /** * Specifies that a break shall be placed at the current location in the run * content. * A break is a special character which is used to override the * normal line breaking that would be performed based on the normal layout * of the document's contents. * @see #AddCarriageReturn() */ public void AddBreak() { run.AddNewBr(); } /** * Specifies that a break shall be placed at the current location in the run * content. * A break is a special character which is used to override the * normal line breaking that would be performed based on the normal layout * of the document's contents. * <p> * The behavior of this break character (the * location where text shall be restarted After this break) shall be * determined by its type values. * </p> * @see BreakType */ public void AddBreak(BreakType type) { CT_Br br = run.AddNewBr(); br.type = EnumConverter.ValueOf<ST_BrType, BreakType>(type); } /** * Specifies that a break shall be placed at the current location in the run * content. A break is a special character which is used to override the * normal line breaking that would be performed based on the normal layout * of the document's contents. * <p> * The behavior of this break character (the * location where text shall be restarted After this break) shall be * determined by its type (in this case is BreakType.TEXT_WRAPPING as default) and clear attribute values. * </p> * @see BreakClear */ public void AddBreak(BreakClear Clear) { CT_Br br = run.AddNewBr(); br.type = EnumConverter.ValueOf<ST_BrType, BreakType>(BreakType.TEXTWRAPPING); br.clear = EnumConverter.ValueOf<ST_BrClear, BreakClear>(Clear); } /** * Specifies that a tab shall be placed at the current location in * the run content. */ public void AddTab() { run.AddNewTab(); } public void RemoveTab() { //TODO } /** * Specifies that a carriage return shall be placed at the * current location in the run.content. * A carriage return is used to end the current line of text in * WordProcess. * The behavior of a carriage return in run.content shall be * identical to a break character with null type and clear attributes, which * shall end the current line and find the next available line on which to * continue. * The carriage return character forced the following text to be * restarted on the next available line in the document. */ public void AddCarriageReturn() { run.AddNewCr(); } public void RemoveCarriageReturn(int i) { throw new NotImplementedException(); } /** * Adds a picture to the run. This method handles * attaching the picture data to the overall file. * * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_EMF * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_WMF * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PICT * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_JPEG * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_PNG * @see NPOI.XWPF.UserModel.Document#PICTURE_TYPE_DIB * * @param pictureData The raw picture data * @param pictureType The type of the picture, eg {@link Document#PICTURE_TYPE_JPEG} * @param width width in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} * @param height height in EMUs. To convert to / from points use {@link org.apache.poi.util.Units} * @throws NPOI.Openxml4j.exceptions.InvalidFormatException * @throws IOException */ public XWPFPicture AddPicture(Stream pictureData, int pictureType, String filename, int width, int height) { XWPFDocument doc = parent.Document; // Add the picture + relationship String relationId = doc.AddPictureData(pictureData, pictureType); XWPFPictureData picData = (XWPFPictureData)doc.GetRelationById(relationId); // Create the Drawing entry for it CT_Drawing Drawing = run.AddNewDrawing(); CT_Inline inline = Drawing.AddNewInline(); // Do the fiddly namespace bits on the inline // (We need full control of what goes where and as what) //CT_GraphicalObject tmp = new CT_GraphicalObject(); //String xml = // "<a:graphic xmlns:a=\"" + "http://schemas.openxmlformats.org/drawingml/2006/main" + "\">" + // "<a:graphicData uri=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\">" + // "<pic:pic xmlns:pic=\"" + "http://schemas.openxmlformats.org/drawingml/2006/picture" + "\" />" + // "</a:graphicData>" + // "</a:graphic>"; //inline.Set((xml)); XmlDocument xmlDoc = new XmlDocument(); //XmlElement el = xmlDoc.CreateElement("pic", "pic", "http://schemas.openxmlformats.org/drawingml/2006/picture"); inline.graphic = new CT_GraphicalObject(); inline.graphic.graphicData = new CT_GraphicalObjectData(); inline.graphic.graphicData.uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"; // Setup the inline inline.distT = (0); inline.distR = (0); inline.distB = (0); inline.distL = (0); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr(); long id = parent.Document.DrawingIdManager.ReserveNew(); docPr.id = (uint)(id); /* This name is not visible in Word 2010 anywhere. */ docPr.name = ("Drawing " + id); docPr.descr = (filename); NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent(); extent.cx = (width); extent.cy = (height); // Grab the picture object NPOI.OpenXmlFormats.Dml.Picture.CT_Picture pic = new OpenXmlFormats.Dml.Picture.CT_Picture(); // Set it up NPOI.OpenXmlFormats.Dml.Picture.CT_PictureNonVisual nvPicPr = pic.AddNewNvPicPr(); NPOI.OpenXmlFormats.Dml.CT_NonVisualDrawingProps cNvPr = nvPicPr.AddNewCNvPr(); /* use "0" for the id. See ECM-576, 20.2.2.3 */ cNvPr.id = (0); /* This name is not visible in Word 2010 anywhere */ cNvPr.name = ("Picture " + id); cNvPr.descr = (filename); CT_NonVisualPictureProperties cNvPicPr = nvPicPr.AddNewCNvPicPr(); cNvPicPr.AddNewPicLocks().noChangeAspect = true; CT_BlipFillProperties blipFill = pic.AddNewBlipFill(); CT_Blip blip = blipFill.AddNewBlip(); blip.embed = (picData.GetPackageRelationship().Id); blipFill.AddNewStretch().AddNewFillRect(); CT_ShapeProperties spPr = pic.AddNewSpPr(); CT_Transform2D xfrm = spPr.AddNewXfrm(); CT_Point2D off = xfrm.AddNewOff(); off.x = (0); off.y = (0); NPOI.OpenXmlFormats.Dml.CT_PositiveSize2D ext = xfrm.AddNewExt(); ext.cx = (width); ext.cy = (height); CT_PresetGeometry2D prstGeom = spPr.AddNewPrstGeom(); prstGeom.prst = (ST_ShapeType.rect); prstGeom.AddNewAvLst(); using (var ms = new MemoryStream()) { StreamWriter sw = new StreamWriter(ms); pic.Write(sw, "pic:pic"); sw.Flush(); ms.Position = 0; var sr = new StreamReader(ms); var picXml = sr.ReadToEnd(); inline.graphic.graphicData.AddPicElement(picXml); } // Finish up XWPFPicture xwpfPicture = new XWPFPicture(pic, this); pictures.Add(xwpfPicture); return xwpfPicture; } /** * Returns the embedded pictures of the run. These * are pictures which reference an external, * embedded picture image such as a .png or .jpg */ public List<XWPFPicture> GetEmbeddedPictures() { return pictures; } /** * Add the xml:spaces="preserve" attribute if the string has leading or trailing white spaces * * @param xs the string to check */ static void preserveSpaces(CT_Text xs) { String text = xs.Value; if (text != null && (text.StartsWith(" ") || text.EndsWith(" "))) { // XmlCursor c = xs.NewCursor(); // c.ToNextToken(); // c.InsertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve"); // c.Dispose(); xs.space = "preserve"; } } /** * Returns the string version of the text, with tabs and * carriage returns in place of their xml equivalents. */ public override String ToString() { return Text; } } }
// 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 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 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(); } } } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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. Note: This code has been heavily modified for the Duality framework. */ #endregion using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace Duality { /// <summary> /// Represents a 2D vector using two single-precision floating-point numbers. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Vector2 : IEquatable<Vector2> { /// <summary> /// Defines a unit-length Vector2 that points along the X-axis. /// </summary> public static readonly Vector2 UnitX = new Vector2(1, 0); /// <summary> /// Defines a unit-length Vector2 that points along the Y-axis. /// </summary> public static readonly Vector2 UnitY = new Vector2(0, 1); /// <summary> /// Defines a zero-length Vector2. /// </summary> public static readonly Vector2 Zero = new Vector2(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2 One = new Vector2(1, 1); /// <summary> /// The X component of the Vector2. /// </summary> public float X; /// <summary> /// The Y component of the Vector2. /// </summary> public float Y; /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2(float value) { this.X = value; this.Y = value; } /// <summary> /// Constructs a new Vector2. /// </summary> /// <param name="x">The x coordinate of the net Vector2.</param> /// <param name="y">The y coordinate of the net Vector2.</param> public Vector2(float x, float y) { this.X = x; this.Y = y; } /// <summary> /// Constructs a new vector from angle and length. /// </summary> /// <param name="angle"></param> /// <param name="length"></param> public static Vector2 FromAngleLength(float angle, float length) { return new Vector2((float)Math.Sin(angle) * length, (float)Math.Cos(angle) * -length); } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(this.X * this.X + this.Y * this.Y); } } /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public float LengthSquared { get { return this.X * this.X + this.Y * this.Y; } } /// <summary> /// Returns the vectors angle /// </summary> public float Angle { get { return (float)((Math.Atan2(this.Y, this.X) + Math.PI * 2.5) % (Math.PI * 2)); } } /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2 PerpendicularRight { get { return new Vector2(-this.Y, this.X); } } /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2 PerpendicularLeft { get { return new Vector2(this.Y, -this.X); } } /// <summary> /// Returns a normalized version of this vector. /// </summary> public Vector2 Normalized { get { float length = this.Length; if (length < 1e-15f) return Vector2.Zero; float scale = 1.0f / length; return new Vector2( this.X * scale, this.Y * scale); } } /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public float this[int index] { get { switch (index) { case 0: return this.X; case 1: return this.Y; default: throw new IndexOutOfRangeException("Vector2 access at index: " + index); } } set { switch (index) { case 0: this.X = value; return; case 1: this.Y = value; return; default: throw new IndexOutOfRangeException("Vector2 access at index: " + index); } } } /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { float length = this.Length; if (length < 1e-15f) { this = Vector2.Zero; } else { float scale = 1.0f / length; this.X *= scale; this.Y *= scale; } } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X + b.X, a.Y + b.Y); } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector2 a, ref Vector2 b, out Vector2 result) { result = new Vector2(a.X - b.X, a.Y - b.Y); } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2 vector, float scale, out Vector2 result) { result = new Vector2(vector.X * scale, vector.Y * scale); } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X * scale.X, vector.Y * scale.Y); } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2 vector, float scale, out Vector2 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2 vector, ref Vector2 scale, out Vector2 result) { result = new Vector2(vector.X / scale.X, vector.Y / scale.Y); } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector2 Min(Vector2 a, Vector2 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector2 Max(Vector2 a, Vector2 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector2 a, ref Vector2 b, out Vector2 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector2 left, Vector2 right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector2 left, ref Vector2 right, out float result) { result = left.X * right.X + left.Y * right.Y; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector2 Lerp(Vector2 a, Vector2 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector2 a, ref Vector2 b, float blend, out Vector2 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <returns>Angle (in radians) between the vectors.</returns> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static float AngleBetween(Vector2 first, Vector2 second) { return (float)System.Math.Acos((Vector2.Dot(first, second)) / (first.Length * second.Length)); } /// <summary> /// Calculates the angle (in radians) between two vectors. /// </summary> /// <param name="first">The first vector.</param> /// <param name="second">The second vector.</param> /// <param name="result">Angle (in radians) between the vectors.</param> /// <remarks>Note that the returned angle is never bigger than the constant Pi.</remarks> public static void AngleBetween(ref Vector2 first, ref Vector2 second, out float result) { float temp; Vector2.Dot(ref first, ref second, out temp); result = (float)System.Math.Acos(temp / (first.Length * second.Length)); } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector2 Transform(Vector2 vec, Quaternion quat) { Vector2 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector2 vec, ref Quaternion quat, out Vector2 result) { Quaternion v = new Quaternion(vec.X, vec.Y, 0, 0), i, t; Quaternion.Invert(ref quat, out i); Quaternion.Multiply(ref quat, ref v, out t); Quaternion.Multiply(ref t, ref i, out v); result = new Vector2(v.X, v.Y); } /// <summary> /// Transforms the vector /// </summary> /// <param name="vec"></param> /// <param name="mat"></param> public static Vector2 Transform(Vector2 vec, Matrix4 mat) { Vector2 result; Transform(ref vec, ref mat, out result); return result; } /// <summary> /// Transforms the vector /// </summary> /// <param name="vec"></param> /// <param name="mat"></param> /// <param name="result"></param> public static void Transform(ref Vector2 vec, ref Matrix4 mat, out Vector2 result) { Vector4 row0 = mat.Row0; Vector4 row1 = mat.Row1; Vector4 row3 = mat.Row3; result.X = vec.X * row0.X + vec.Y * row1.X + row3.X; result.Y = vec.X * row0.Y + vec.Y * row1.Y + row3.Y; } /// <summary> /// Adds the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of addition.</returns> public static Vector2 operator +(Vector2 left, Vector2 right) { return new Vector2( left.X + right.X, left.Y + right.Y); } /// <summary> /// Subtracts the specified instances. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>Result of subtraction.</returns> public static Vector2 operator -(Vector2 left, Vector2 right) { return new Vector2( left.X - right.X, left.Y - right.Y); } /// <summary> /// Negates the specified instance. /// </summary> /// <param name="vec">Operand.</param> /// <returns>Result of negation.</returns> public static Vector2 operator -(Vector2 vec) { return new Vector2( -vec.X, -vec.Y); } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, float scale) { return new Vector2( vec.X * scale, vec.Y * scale); } /// <summary> /// Multiplies the specified instance by a scalar. /// </summary> /// <param name="scale">Left operand.</param> /// <param name="vec">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(float scale, Vector2 vec) { return vec * scale; } /// <summary> /// Scales the specified instance by a vector. /// </summary> /// <param name="vec">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of multiplication.</returns> public static Vector2 operator *(Vector2 vec, Vector2 scale) { return new Vector2( vec.X * scale.X, vec.Y * scale.Y); } /// <summary> /// Divides the specified instance by a scalar. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, float scale) { return vec * (1.0f / scale); } /// <summary> /// Divides the specified instance by a vector. /// </summary> /// <param name="vec">Left operand</param> /// <param name="scale">Right operand</param> /// <returns>Result of the division.</returns> public static Vector2 operator /(Vector2 vec, Vector2 scale) { return new Vector2( vec.X / scale.X, vec.Y / scale.Y); } /// <summary> /// Compares the specified instances for equality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2 left, Vector2 right) { return left.Equals(right); } /// <summary> /// Compares the specified instances for inequality. /// </summary> /// <param name="left">Left operand.</param> /// <param name="right">Right operand.</param> /// <returns>True if both instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2 left, Vector2 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Vector2. /// </summary> public override string ToString() { return string.Format("({0:F}, {1:F})", this.X, this.Y); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return this.X.GetHashCode() ^ this.Y.GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector2)) return false; return this.Equals((Vector2)obj); } /// <summary> /// Indicates whether the current vector is equal to another vector. /// </summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector2 other) { return this.X == other.X && this.Y == other.Y; } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// ParcelBoundary /// </summary> [DataContract] public partial class ParcelBoundary : IEquatable<ParcelBoundary> { /// <summary> /// Initializes a new instance of the <see cref="ParcelBoundary" /> class. /// </summary> /// <param name="ObjectId">ObjectId.</param> /// <param name="Apn">Apn.</param> /// <param name="Pid">Pid.</param> /// <param name="Center">Center.</param> /// <param name="Countyfips">Countyfips.</param> /// <param name="Geometry">Geometry.</param> /// <param name="ParcelList">ParcelList.</param> /// <param name="AdjacentParcelBoundary">AdjacentParcelBoundary.</param> /// <param name="MatchedAddress">MatchedAddress.</param> public ParcelBoundary(string ObjectId = null, string Apn = null, string Pid = null, Center Center = null, string Countyfips = null, CommonGeometry Geometry = null, List<Parcel> ParcelList = null, List<ParcelBoundary> AdjacentParcelBoundary = null, MatchedAddress MatchedAddress = null) { this.ObjectId = ObjectId; this.Apn = Apn; this.Pid = Pid; this.Center = Center; this.Countyfips = Countyfips; this.Geometry = Geometry; this.ParcelList = ParcelList; this.AdjacentParcelBoundary = AdjacentParcelBoundary; this.MatchedAddress = MatchedAddress; } /// <summary> /// Gets or Sets ObjectId /// </summary> [DataMember(Name="objectId", EmitDefaultValue=false)] public string ObjectId { get; set; } /// <summary> /// Gets or Sets Apn /// </summary> [DataMember(Name="apn", EmitDefaultValue=false)] public string Apn { get; set; } /// <summary> /// Gets or Sets Pid /// </summary> [DataMember(Name="pid", EmitDefaultValue=false)] public string Pid { get; set; } /// <summary> /// Gets or Sets Center /// </summary> [DataMember(Name="center", EmitDefaultValue=false)] public Center Center { get; set; } /// <summary> /// Gets or Sets Countyfips /// </summary> [DataMember(Name="countyfips", EmitDefaultValue=false)] public string Countyfips { get; set; } /// <summary> /// Gets or Sets Geometry /// </summary> [DataMember(Name="geometry", EmitDefaultValue=false)] public CommonGeometry Geometry { get; set; } /// <summary> /// Gets or Sets ParcelList /// </summary> [DataMember(Name="parcelList", EmitDefaultValue=false)] public List<Parcel> ParcelList { get; set; } /// <summary> /// Gets or Sets AdjacentParcelBoundary /// </summary> [DataMember(Name="adjacentParcelBoundary", EmitDefaultValue=false)] public List<ParcelBoundary> AdjacentParcelBoundary { get; set; } /// <summary> /// Gets or Sets MatchedAddress /// </summary> [DataMember(Name="matchedAddress", EmitDefaultValue=false)] public MatchedAddress MatchedAddress { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ParcelBoundary {\n"); sb.Append(" ObjectId: ").Append(ObjectId).Append("\n"); sb.Append(" Apn: ").Append(Apn).Append("\n"); sb.Append(" Pid: ").Append(Pid).Append("\n"); sb.Append(" Center: ").Append(Center).Append("\n"); sb.Append(" Countyfips: ").Append(Countyfips).Append("\n"); sb.Append(" Geometry: ").Append(Geometry).Append("\n"); sb.Append(" ParcelList: ").Append(ParcelList).Append("\n"); sb.Append(" AdjacentParcelBoundary: ").Append(AdjacentParcelBoundary).Append("\n"); sb.Append(" MatchedAddress: ").Append(MatchedAddress).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ParcelBoundary); } /// <summary> /// Returns true if ParcelBoundary instances are equal /// </summary> /// <param name="other">Instance of ParcelBoundary to be compared</param> /// <returns>Boolean</returns> public bool Equals(ParcelBoundary other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ObjectId == other.ObjectId || this.ObjectId != null && this.ObjectId.Equals(other.ObjectId) ) && ( this.Apn == other.Apn || this.Apn != null && this.Apn.Equals(other.Apn) ) && ( this.Pid == other.Pid || this.Pid != null && this.Pid.Equals(other.Pid) ) && ( this.Center == other.Center || this.Center != null && this.Center.Equals(other.Center) ) && ( this.Countyfips == other.Countyfips || this.Countyfips != null && this.Countyfips.Equals(other.Countyfips) ) && ( this.Geometry == other.Geometry || this.Geometry != null && this.Geometry.Equals(other.Geometry) ) && ( this.ParcelList == other.ParcelList || this.ParcelList != null && this.ParcelList.SequenceEqual(other.ParcelList) ) && ( this.AdjacentParcelBoundary == other.AdjacentParcelBoundary || this.AdjacentParcelBoundary != null && this.AdjacentParcelBoundary.SequenceEqual(other.AdjacentParcelBoundary) ) && ( this.MatchedAddress == other.MatchedAddress || this.MatchedAddress != null && this.MatchedAddress.Equals(other.MatchedAddress) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ObjectId != null) hash = hash * 59 + this.ObjectId.GetHashCode(); if (this.Apn != null) hash = hash * 59 + this.Apn.GetHashCode(); if (this.Pid != null) hash = hash * 59 + this.Pid.GetHashCode(); if (this.Center != null) hash = hash * 59 + this.Center.GetHashCode(); if (this.Countyfips != null) hash = hash * 59 + this.Countyfips.GetHashCode(); if (this.Geometry != null) hash = hash * 59 + this.Geometry.GetHashCode(); if (this.ParcelList != null) hash = hash * 59 + this.ParcelList.GetHashCode(); if (this.AdjacentParcelBoundary != null) hash = hash * 59 + this.AdjacentParcelBoundary.GetHashCode(); if (this.MatchedAddress != null) hash = hash * 59 + this.MatchedAddress.GetHashCode(); return hash; } } } }
// ReSharper disable InconsistentNaming namespace ExcelDataReader.Core.BinaryFormat { internal enum BIFFTYPE : ushort { WorkbookGlobals = 0x0005, VBModule = 0x0006, Worksheet = 0x0010, Chart = 0x0020, #pragma warning disable SA1300 // Element must begin with upper-case letter v4MacroSheet = 0x0040, v4WorkbookGlobals = 0x0100 #pragma warning restore SA1300 // Element must begin with upper-case letter } internal enum BIFFRECORDTYPE : ushort { INTERFACEHDR = 0x00E1, MMS = 0x00C1, MERGECELLS = 0x00E5, // Record containing list of merged cell ranges INTERFACEEND = 0x00E2, WRITEACCESS = 0x005C, CODEPAGE = 0x0042, DSF = 0x0161, TABID = 0x013D, FNGROUPCOUNT = 0x009C, FILEPASS = 0x002F, WINDOWPROTECT = 0x0019, PROTECT = 0x0012, PASSWORD = 0x0013, PROT4REV = 0x01AF, PROT4REVPASSWORD = 0x01BC, WINDOW1 = 0x003D, BACKUP = 0x0040, HIDEOBJ = 0x008D, RECORD1904 = 0x0022, REFRESHALL = 0x01B7, BOOKBOOL = 0x00DA, FONT = 0x0031, // Font record, BIFF2, 5 and later FONT_V34 = 0x0231, // Font record, BIFF3, 4 FORMAT = 0x041E, // Format record, BIFF4 and later FORMAT_V23 = 0x001E, // Format record, BIFF2, 3 XF = 0x00E0, // Extended format record, BIFF5 and later XF_V4 = 0x0443, // Extended format record, BIFF4 XF_V3 = 0x0243, // Extended format record, BIFF3 XF_V2 = 0x0043, // Extended format record, BIFF2 IXFE = 0x0044, // Index to XF, BIFF2 STYLE = 0x0293, BOUNDSHEET = 0x0085, COUNTRY = 0x008C, SST = 0x00FC, // Global string storage (for BIFF8) CONTINUE = 0x003C, EXTSST = 0x00FF, BOF = 0x0809, // BOF Id for BIFF5 and later BOF_V2 = 0x0009, // BOF Id for BIFF2 BOF_V3 = 0x0209, // BOF Id for BIFF3 BOF_V4 = 0x0409, // BOF Id for BIFF4 EOF = 0x000A, // End of block started with BOF CALCCOUNT = 0x000C, CALCMODE = 0x000D, PRECISION = 0x000E, REFMODE = 0x000F, DELTA = 0x0010, ITERATION = 0x0011, SAVERECALC = 0x005F, PRINTHEADERS = 0x002A, PRINTGRIDLINES = 0x002B, GUTS = 0x0080, WSBOOL = 0x0081, GRIDSET = 0x0082, DEFAULTROWHEIGHT_V2 = 0x0025, DEFAULTROWHEIGHT = 0x0225, HEADER = 0x0014, FOOTER = 0x0015, HCENTER = 0x0083, VCENTER = 0x0084, PRINTSETUP = 0x00A1, DFAULTCOLWIDTH = 0x0055, DIMENSIONS = 0x0200, // Size of area used for data DIMENSIONS_V2 = 0x0000, // BIFF2 ROW_V2 = 0x0008, // Row record ROW = 0x0208, // Row record WINDOW2 = 0x023E, SELECTION = 0x001D, INDEX = 0x020B, // Index record, unsure about signature DBCELL = 0x00D7, // DBCell record, unsure about signature BLANK = 0x0201, // Empty cell BLANK_OLD = 0x0001, // Empty cell, old format MULBLANK = 0x00BE, // Equivalent of up to 256 blank cells INTEGER = 0x0202, // Integer cell (0..65535) INTEGER_OLD = 0x0002, // Integer cell (0..65535), old format NUMBER = 0x0203, // Numeric cell NUMBER_OLD = 0x0003, // Numeric cell, old format LABEL = 0x0204, // String cell (up to 255 symbols) LABEL_OLD = 0x0004, // String cell (up to 255 symbols), old format LABELSST = 0x00FD, // String cell with value from SST (for BIFF8) FORMULA = 0x0006, // Formula cell, BIFF2, BIFF5-8 FORMULA_V3 = 0x0206, // Formula cell, BIFF3 FORMULA_V4 = 0x0406, // Formula cell, BIFF4 BOOLERR = 0x0205, // Boolean or error cell BOOLERR_OLD = 0x0005, // Boolean or error cell, old format ARRAY = 0x0221, // Range of cells for multi-cell formula RK = 0x027E, // RK-format numeric cell MULRK = 0x00BD, // Equivalent of up to 256 RK cells RSTRING = 0x00D6, // Rich-formatted string cell SHAREDFMLA = 0x04BC, // One more formula optimization element SHAREDFMLA_OLD = 0x00BC, // One more formula optimization element, old format STRING = 0x0207, // And one more, for string formula results STRING_OLD = 0x0007, // Old string formula results CF = 0x01B1, CODENAME = 0x01BA, CONDFMT = 0x01B0, DCONBIN = 0x01B5, DV = 0x01BE, DVAL = 0x01B2, HLINK = 0x01B8, MSODRAWINGGROUP = 0x00EB, MSODRAWING = 0x00EC, MSODRAWINGSELECTION = 0x00ED, PARAMQRY = 0x00DC, QSI = 0x01AD, SUPBOOK = 0x01AE, SXDB = 0x00C6, SXDBEX = 0x0122, SXFDBTYPE = 0x01BB, SXRULE = 0x00F0, SXEX = 0x00F1, SXFILT = 0x00F2, SXNAME = 0x00F6, SXSELECT = 0x00F7, SXPAIR = 0x00F8, SXFMLA = 0x00F9, SXFORMAT = 0x00FB, SXFORMULA = 0x0103, SXVDEX = 0x0100, TXO = 0x01B6, USERBVIEW = 0x01A9, USERSVIEWBEGIN = 0x01AA, USERSVIEWEND = 0x01AB, USESELFS = 0x0160, XL5MODIFY = 0x0162, OBJ = 0x005D, NOTE = 0x001C, SXEXT = 0x00DC, VERTICALPAGEBREAKS = 0x001A, XCT = 0x0059, /// <summary> /// If present the Calculate Message was in the status bar when Excel saved the file. /// This occurs if the sheet changed, the Manual calculation option was on, and the Recalculate Before Save option was off. /// </summary> UNCALCED = 0x005E, QUICKTIP = 0x0800, COLINFO = 0x007D } internal enum FORMULAERROR : byte { NULL = 0x00, // #NULL! DIV0 = 0x07, // #DIV/0! VALUE = 0x0F, // #VALUE! REF = 0x17, // #REF! NAME = 0x1D, // #NAME? NUM = 0x24, // #NUM! NA = 0x2A, // #N/A } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** CLASS: Parser ** ** <OWNER>[....]</OWNER> ** ** ** PURPOSE: Parse "Elementary XML", that is, XML without ** attributes or DTDs, in other words, XML with ** elements only. ** ** ===========================================================*/ namespace System.Security.Util { using System.Text; using System.Runtime.InteropServices; using System; using BinaryReader = System.IO.BinaryReader ; using ArrayList = System.Collections.ArrayList; using Stream = System.IO.Stream; using StreamReader = System.IO.StreamReader; using Encoding = System.Text.Encoding; sealed internal class Parser { private SecurityDocument _doc; private Tokenizer _t; internal SecurityElement GetTopElement() { return _doc.GetRootElement(); } private const short c_flag = 0x4000; private const short c_elementtag = (short)(SecurityDocument.c_element << 8 | c_flag); private const short c_attributetag = (short)(SecurityDocument.c_attribute << 8 | c_flag); private const short c_texttag = (short)(SecurityDocument.c_text << 8 | c_flag); private const short c_additionaltexttag = (short)(SecurityDocument.c_text << 8 | c_flag | 0x2000); private const short c_childrentag = (short)(SecurityDocument.c_children << 8 | c_flag); private const short c_wastedstringtag = (short)(0x1000 | c_flag); private void GetRequiredSizes( TokenizerStream stream, ref int index ) { // // Iteratively collect stuff up until the next end-tag. // We've already seen the open-tag. // bool needToBreak = false; bool needToPop = false; bool createdNode = false; bool intag = false; int stackDepth = 1; SecurityElementType type = SecurityElementType.Regular; String strValue = null; bool sawEquals = false; bool sawText = false; int status = 0; short i; do { for (i = stream.GetNextToken() ; i != -1 ; i = stream.GetNextToken()) { switch (i & 0x00FF) { case Tokenizer.cstr: { if (intag) { if (type == SecurityElementType.Comment) { // Ignore data in comments but still get the data // to keep the stream in the right place. stream.ThrowAwayNextString(); stream.TagLastToken( c_wastedstringtag ); } else { // We're in a regular tag, so we've found an attribute/value pair. if (strValue == null) { // Found attribute name, save it for later. strValue = stream.GetNextString(); } else { // Found attribute text, add the pair to the current element. if (!sawEquals) throw new XmlSyntaxException( _t.LineNo ); stream.TagLastToken( c_attributetag ); index += SecurityDocument.EncodedStringSize( strValue ) + SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; strValue = null; sawEquals = false; } } } else { // We're not in a tag, so we've found text between tags. if (sawText) { stream.TagLastToken( c_additionaltexttag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + SecurityDocument.EncodedStringSize( " " ); } else { stream.TagLastToken( c_texttag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; sawText = true; } } } break; case Tokenizer.bra: intag = true; sawText = false; i = stream.GetNextToken(); if (i == Tokenizer.slash) { stream.TagLastToken( c_childrentag ); while (true) { // spin; don't care what's in here i = stream.GetNextToken(); if (i == Tokenizer.cstr) { stream.ThrowAwayNextString(); stream.TagLastToken( c_wastedstringtag ); } else if (i == -1) throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); else break; } if (i != Tokenizer.ket) { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedCloseBracket" )); } intag = false; // Found the end of this element index++; sawText = false; stackDepth--; needToBreak = true; } else if (i == Tokenizer.cstr) { // Found a child createdNode = true; stream.TagLastToken( c_elementtag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; if (type != SecurityElementType.Regular) throw new XmlSyntaxException( _t.LineNo ); needToBreak = true; stackDepth++; } else if (i == Tokenizer.bang) { // Found a child that is a comment node. Next up better be a cstr. status = 1; do { i = stream.GetNextToken(); switch (i) { case Tokenizer.bra: status++; break; case Tokenizer.ket: status--; break; case Tokenizer.cstr: stream.ThrowAwayNextString(); stream.TagLastToken( c_wastedstringtag ); break; default: break; } } while (status > 0); intag = false; sawText = false; needToBreak = true; } else if (i == Tokenizer.quest) { // Found a child that is a format node. Next up better be a cstr. i = stream.GetNextToken(); if (i != Tokenizer.cstr) throw new XmlSyntaxException( _t.LineNo ); createdNode = true; type = SecurityElementType.Format; stream.TagLastToken( c_elementtag ); index += SecurityDocument.EncodedStringSize( stream.GetNextString() ) + 1; status = 1; stackDepth++; needToBreak = true; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedSlashOrString" )); } break ; case Tokenizer.equals: sawEquals = true; break; case Tokenizer.ket: if (intag) { intag = false; continue; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedCloseBracket" )); } // not reachable case Tokenizer.slash: i = stream.GetNextToken(); if (i == Tokenizer.ket) { // Found the end of this element stream.TagLastToken( c_childrentag ); index++; stackDepth--; sawText = false; needToBreak = true; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedCloseBracket" )); } break; case Tokenizer.quest: if (intag && type == SecurityElementType.Format && status == 1) { i = stream.GetNextToken(); if (i == Tokenizer.ket) { stream.TagLastToken( c_childrentag ); index++; stackDepth--; sawText = false; needToBreak = true; } else { throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_ExpectedCloseBracket" )); } } else { throw new XmlSyntaxException (_t.LineNo); } break; case Tokenizer.dash: default: throw new XmlSyntaxException (_t.LineNo) ; } if (needToBreak) { needToBreak = false; needToPop = false; break; } else { needToPop = true; } } if (needToPop) { index++; stackDepth--; sawText = false; } else if (i == -1 && (stackDepth != 1 || !createdNode)) { // This means that we still have items on the stack, but the end of our // stream has been reached. throw new XmlSyntaxException( _t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); } } while (stackDepth > 1); } private int DetermineFormat( TokenizerStream stream ) { if (stream.GetNextToken() == Tokenizer.bra) { if (stream.GetNextToken() == Tokenizer.quest) { _t.GetTokens( stream, -1, true ); stream.GoToPosition( 2 ); bool sawEquals = false; bool sawEncoding = false; short i; for (i = stream.GetNextToken(); i != -1 && i != Tokenizer.ket; i = stream.GetNextToken()) { switch (i) { case Tokenizer.cstr: if (sawEquals && sawEncoding) { _t.ChangeFormat( System.Text.Encoding.GetEncoding( stream.GetNextString() ) ); return 0; } else if (!sawEquals) { if (String.Compare( stream.GetNextString(), "encoding", StringComparison.Ordinal) == 0) sawEncoding = true; } else { sawEquals = false; sawEncoding = false; stream.ThrowAwayNextString(); } break; case Tokenizer.equals: sawEquals = true; break; default: throw new XmlSyntaxException (_t.LineNo, Environment.GetResourceString( "XMLSyntax_UnexpectedEndOfFile" )); } } return 0; } } return 2; } private void ParseContents() { short i; TokenizerStream stream = new TokenizerStream(); _t.GetTokens( stream, 2, false ); stream.Reset(); int gotoPosition = DetermineFormat( stream ); stream.GoToPosition( gotoPosition ); _t.GetTokens( stream, -1, false ); stream.Reset(); int neededIndex = 0; GetRequiredSizes( stream, ref neededIndex ); _doc = new SecurityDocument( neededIndex ); int position = 0; stream.Reset(); for (i = stream.GetNextFullToken(); i != -1; i = stream.GetNextFullToken()) { if ((i & c_flag) != c_flag) continue; else { switch((short)(i & 0xFF00)) { case c_elementtag: _doc.AddToken( SecurityDocument.c_element, ref position ); _doc.AddString( stream.GetNextString(), ref position ); break; case c_attributetag: _doc.AddToken( SecurityDocument.c_attribute, ref position ); _doc.AddString( stream.GetNextString(), ref position ); _doc.AddString( stream.GetNextString(), ref position ); break; case c_texttag: _doc.AddToken( SecurityDocument.c_text, ref position ); _doc.AddString( stream.GetNextString(), ref position ); break; case c_additionaltexttag: _doc.AppendString( " ", ref position ); _doc.AppendString( stream.GetNextString(), ref position ); break; case c_childrentag: _doc.AddToken( SecurityDocument.c_children, ref position ); break; case c_wastedstringtag: stream.ThrowAwayNextString(); break; default: throw new XmlSyntaxException(); } } } } private Parser(Tokenizer t) { _t = t; _doc = null; try { ParseContents(); } finally { _t.Recycle(); } } internal Parser (String input) : this (new Tokenizer (input)) { } internal Parser (String input, String[] searchStrings, String[] replaceStrings) : this (new Tokenizer (input, searchStrings, replaceStrings)) { } internal Parser( byte[] array, Tokenizer.ByteTokenEncoding encoding ) : this (new Tokenizer( array, encoding, 0 ) ) { } internal Parser( byte[] array, Tokenizer.ByteTokenEncoding encoding, int startIndex ) : this (new Tokenizer( array, encoding, startIndex ) ) { } internal Parser( StreamReader input ) : this (new Tokenizer( input ) ) { } internal Parser( char[] array ) : this (new Tokenizer( array ) ) { } } }
using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { public sealed partial class ImmutableList<T> { /// <summary> /// Enumerates the contents of a binary tree. /// </summary> /// <remarks> /// This struct can and should be kept in exact sync with the other binary tree enumerators: /// <see cref="ImmutableList{T}.Enumerator"/>, <see cref="ImmutableSortedDictionary{TKey, TValue}.Enumerator"/>, and <see cref="ImmutableSortedSet{T}.Enumerator"/>. /// /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator : IEnumerator<T>, ISecurePooledObjectUser, IStrongEnumerator<T> { /// <summary> /// The resource pool of reusable mutable stacks for purposes of enumeration. /// </summary> /// <remarks> /// We utilize this resource pool to make "allocation free" enumeration achievable. /// </remarks> private static readonly SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator> s_EnumeratingStacks = new SecureObjectPool<Stack<RefAsValueType<Node>>, Enumerator>(); /// <summary> /// The builder being enumerated, if applicable. /// </summary> private readonly Builder _builder; /// <summary> /// A unique ID for this instance of this enumerator. /// Used to protect pooled objects from use after they are recycled. /// </summary> private readonly int _poolUserId; /// <summary> /// The starting index of the collection at which to begin enumeration. /// </summary> private readonly int _startIndex; /// <summary> /// The number of elements to include in the enumeration. /// </summary> private readonly int _count; /// <summary> /// The number of elements left in the enumeration. /// </summary> private int _remainingCount; /// <summary> /// A value indicating whether this enumerator walks in reverse order. /// </summary> private bool _reversed; /// <summary> /// The set being enumerated. /// </summary> private Node _root; /// <summary> /// The stack to use for enumerating the binary tree. /// </summary> private SecurePooledObject<Stack<RefAsValueType<Node>>> _stack; /// <summary> /// The node currently selected. /// </summary> private Node _current; /// <summary> /// The version of the builder (when applicable) that is being enumerated. /// </summary> private int _enumeratingBuilderVersion; /// <summary> /// Initializes an <see cref="Enumerator"/> structure. /// </summary> /// <param name="root">The root of the set to be enumerated.</param> /// <param name="builder">The builder, if applicable.</param> /// <param name="startIndex">The index of the first element to enumerate.</param> /// <param name="count">The number of elements in this collection.</param> /// <param name="reversed"><c>true</c> if the list should be enumerated in reverse order.</param> internal Enumerator(Node root, Builder builder = null, int startIndex = -1, int count = -1, bool reversed = false) { Requires.NotNull(root, nameof(root)); Requires.Range(startIndex >= -1, nameof(startIndex)); Requires.Range(count >= -1, nameof(count)); Requires.Argument(reversed || count == -1 || (startIndex == -1 ? 0 : startIndex) + count <= root.Count); Requires.Argument(!reversed || count == -1 || (startIndex == -1 ? root.Count - 1 : startIndex) - count + 1 >= 0); _root = root; _builder = builder; _current = null; _startIndex = startIndex >= 0 ? startIndex : (reversed ? root.Count - 1 : 0); _count = count == -1 ? root.Count : count; _remainingCount = _count; _reversed = reversed; _enumeratingBuilderVersion = builder != null ? builder.Version : -1; _poolUserId = SecureObjectPool.NewId(); _stack = null; if (_count > 0) { if (!s_EnumeratingStacks.TryTake(this, out _stack)) { _stack = s_EnumeratingStacks.PrepNew(this, new Stack<RefAsValueType<Node>>(root.Height)); } this.ResetStack(); } } /// <inheritdoc/> int ISecurePooledObjectUser.PoolUserId => _poolUserId; /// <summary> /// The current element. /// </summary> public T Current { get { this.ThrowIfDisposed(); if (_current != null) { return _current.Value; } throw new InvalidOperationException(); } } /// <summary> /// The current element. /// </summary> object System.Collections.IEnumerator.Current => this.Current; /// <summary> /// Disposes of this enumerator and returns the stack reference to the resource pool. /// </summary> public void Dispose() { _root = null; _current = null; Stack<RefAsValueType<Node>> stack; if (_stack != null && _stack.TryUse(ref this, out stack)) { stack.ClearFastWhenEmpty(); s_EnumeratingStacks.TryAdd(this, _stack); } _stack = null; } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); this.ThrowIfChanged(); if (_stack != null) { var stack = _stack.Use(ref this); if (_remainingCount > 0 && stack.Count > 0) { Node n = stack.Pop().Value; _current = n; this.PushNext(this.NextBranch(n)); _remainingCount--; return true; } } _current = null; return false; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _enumeratingBuilderVersion = _builder != null ? _builder.Version : -1; _remainingCount = _count; if (_stack != null) { this.ResetStack(); } } /// <summary>Resets the stack used for enumeration.</summary> private void ResetStack() { var stack = _stack.Use(ref this); stack.ClearFastWhenEmpty(); var node = _root; var skipNodes = _reversed ? _root.Count - _startIndex - 1 : _startIndex; while (!node.IsEmpty && skipNodes != this.PreviousBranch(node).Count) { if (skipNodes < this.PreviousBranch(node).Count) { stack.Push(new RefAsValueType<Node>(node)); node = this.PreviousBranch(node); } else { skipNodes -= this.PreviousBranch(node).Count + 1; node = this.NextBranch(node); } } if (!node.IsEmpty) { stack.Push(new RefAsValueType<Node>(node)); } } /// <summary> /// Obtains the right branch of the given node (or the left, if walking in reverse). /// </summary> private Node NextBranch(Node node) => _reversed ? node.Left : node.Right; /// <summary> /// Obtains the left branch of the given node (or the right, if walking in reverse). /// </summary> private Node PreviousBranch(Node node) => _reversed ? node.Right : node.Left; /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this enumerator has been disposed. /// </summary> private void ThrowIfDisposed() { Contract.Ensures(_root != null); Contract.EnsuresOnThrow<ObjectDisposedException>(_root == null); // Since this is a struct, copies might not have been marked as disposed. // But the stack we share across those copies would know. // This trick only works when we have a non-null stack. // For enumerators of empty collections, there isn't any natural // way to know when a copy of the struct has been disposed of. if (_root == null || (_stack != null && !_stack.IsOwned(ref this))) { Requires.FailObjectDisposed(this); } } /// <summary> /// Throws an exception if the underlying builder's contents have been changed since enumeration started. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the collection has changed.</exception> private void ThrowIfChanged() { if (_builder != null && _builder.Version != _enumeratingBuilderVersion) { throw new InvalidOperationException(SR.CollectionModifiedDuringEnumeration); } } /// <summary> /// Pushes this node and all its Left descendants onto the stack. /// </summary> /// <param name="node">The starting node to push onto the stack.</param> private void PushNext(Node node) { Requires.NotNull(node, nameof(node)); if (!node.IsEmpty) { var stack = _stack.Use(ref this); while (!node.IsEmpty) { stack.Push(new RefAsValueType<Node>(node)); node = this.PreviousBranch(node); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using log4net; using NetGore; using NetGore.Collections; using NetGore.IO; namespace NetGore.Network { /// <summary> /// Manages a group of message processing methods, each identified by the attribute /// <see cref="MessageHandlerAttribute"/>. /// </summary> public class MessageProcessorManager : IMessageProcessorManager { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly byte _messageIDBitLength; readonly IMessageProcessor[] _processors; /// <summary> /// Initializes a new instance of the <see cref="MessageProcessorManager"/> class. /// </summary> /// <param name="source">Root object instance containing all the classes (null if static).</param> /// <param name="messageIDBitLength">The length of the message ID in bits. Must be between a value /// greater than or equal to 1, and less than or equal to 32.</param> /// <returns>Returns a list of all the found message processors for a given class.</returns> /// <exception cref="ArgumentNullException"><paramref name="source" /> is <c>null</c>.</exception> /// <exception cref="ArgumentOutOfRangeException"><c>messageIDBitLength</c> is out of range.</exception> public MessageProcessorManager(object source, int messageIDBitLength) { if (source == null) throw new ArgumentNullException("source"); if (messageIDBitLength > (sizeof(int) * 8) || messageIDBitLength < 1) throw new ArgumentOutOfRangeException("messageIDBitLength"); _messageIDBitLength = (byte)messageIDBitLength; _processors = BuildMessageProcessors(source); } /// <summary> /// Asserts that the rest of a <see cref="BitStream"/> contains only unset bits. /// </summary> /// <param name="data">The <see cref="BitStream"/> to check.</param> [Conditional("DEBUG")] static void AssertRestOfStreamIsZero(BitStream data) { if (!RestOfStreamIsZero(data)) { const string errmsg = "Encountered msgID = 0, but there was set bits remaining in the stream."; if (log.IsWarnEnabled) log.WarnFormat(errmsg); Debug.Fail(errmsg); } } /// <summary> /// Builds the array of <see cref="IMessageProcessor"/>s. /// </summary> /// <param name="source">Root object instance containing all the classes (null if static).</param> /// <returns>The array of <see cref="IMessageProcessor"/>s.</returns> /// <exception cref="ArgumentException">Multiple <see cref="MessageHandlerAttribute"/>s found on a method.</exception> /// <exception cref="DuplicateKeyException">Multiple <see cref="MessageHandlerAttribute"/> found for the same ID.</exception> [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "MessageHandlerAttribute") ] IMessageProcessor[] BuildMessageProcessors(object source) { const BindingFlags bindFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Static; var mpdType = typeof(MessageProcessorHandler); var atbType = typeof(MessageHandlerAttribute); var voidType = typeof(void); var tmpProcessors = new DArray<IMessageProcessor>(); // Search through all types in the Assembly var assemb = Assembly.GetAssembly(source.GetType()); foreach (var type in assemb.GetTypes()) { // Search through every method in the class foreach (var method in type.GetMethods(bindFlags)) { // Only accept a method if it returns a void if (method.ReturnType != voidType) continue; // Get all of the MessageAttributes for the method (should only be one) var atbs = (MessageHandlerAttribute[])method.GetCustomAttributes(atbType, true); if (atbs.Length > 1) { const string errmsg = "Multiple MessageHandlerAttributes found for method `{0}`."; Debug.Fail(string.Format(errmsg, method.Name)); throw new ArgumentException(string.Format(errmsg, method.Name), "source"); } // Create the message processor for the method foreach (var atb in atbs) { var msgId = atb.MsgID.GetRawValue(); if (tmpProcessors.CanGet(msgId) && tmpProcessors[msgId] != null) { const string errmsg = "A MessageHandlerAttribute with ID `{0}` already exists. Methods in question: {1} and {2}"; Debug.Fail(string.Format(errmsg, atb.MsgID, tmpProcessors[msgId].Call.Method, method)); throw new DuplicateKeyException(string.Format(errmsg, atb.MsgID, tmpProcessors[msgId].Call.Method, method)); } var del = (MessageProcessorHandler)Delegate.CreateDelegate(mpdType, source, method); Debug.Assert(del != null); var msgProcessor = CreateMessageProcessor(atb, del); tmpProcessors.Insert(msgId, msgProcessor); } } } return tmpProcessors.ToArray(); } /// <summary> /// Creates a <see cref="IMessageProcessor"/>. Can be overridden in the derived classes to provide a different /// <see cref="IMessageProcessor"/> implementation. /// </summary> /// <param name="atb">The <see cref="MessageHandlerAttribute"/> that was attached to the method that the /// <see cref="IMessageProcessor"/> is being created for.</param> /// <param name="handler">The <see cref="MessageProcessorHandler"/> for invoking the method.</param> /// <returns>The <see cref="IMessageProcessor"/> instance.</returns> protected virtual IMessageProcessor CreateMessageProcessor(MessageHandlerAttribute atb, MessageProcessorHandler handler) { return new MessageProcessor(atb.MsgID, handler); } /// <summary> /// Creates the <see cref="BitStream"/> to read the data. /// </summary> /// <param name="data">The data to read.</param> /// <returns>The <see cref="BitStream"/> to read the <paramref name="data"/>.</returns> protected virtual BitStream CreateReader(byte[] data) { return new BitStream(data); } /// <summary> /// Gets the <see cref="IMessageProcessor"/> with the given ID. This will only ever return the <see cref="IMessageProcessor"/> /// for the method that was specified using a <see cref="MessageHandlerAttribute"/>. Is intended to only be used by /// <see cref="MessageProcessorManager.GetMessageProcessor"/> to allow for access of the <see cref="IMessageProcessor"/>s loaded /// through the attribute. /// </summary> /// <param name="msgID">The ID of the message.</param> /// <returns>The <see cref="IMessageProcessor"/> for the <paramref name="msgID"/>, or null if an invalid ID.</returns> protected IMessageProcessor GetInternalMessageProcessor(MessageProcessorID msgID) { return _processors[msgID.GetRawValue()]; } /// <summary> /// Gets the <see cref="IMessageProcessor"/> for the corresponding message ID. Can be overridden by the derived class to allow /// for using a <see cref="IMessageProcessor"/> other than what is acquired by /// <see cref="MessageProcessorManager.GetInternalMessageProcessor"/>. /// </summary> /// <param name="msgID">The ID of the message.</param> /// <returns>The <see cref="IMessageProcessor"/> for the <paramref name="msgID"/>, or null if an invalid ID.</returns> protected virtual IMessageProcessor GetMessageProcessor(MessageProcessorID msgID) { return GetInternalMessageProcessor(msgID); } /// <summary> /// Invokes the <see cref="IMessageProcessor"/> for handle processing a message block. /// </summary> /// <param name="socket">The <see cref="IIPSocket"/> that the data came from.</param> /// <param name="processor">The <see cref="IMessageProcessor"/> to invoke.</param> /// <param name="reader">The <see cref="BitStream"/> containing the data to process.</param> protected virtual void InvokeProcessor(IIPSocket socket, IMessageProcessor processor, BitStream reader) { processor.Call(socket, reader); } /// <summary> /// Reads the next message ID. /// </summary> /// <param name="reader">The <see cref="BitStream"/> to read the ID from.</param> /// <returns>The next message ID.</returns> protected virtual MessageProcessorID ReadMessageID(BitStream reader) { return (MessageProcessorID)reader.ReadUInt(_messageIDBitLength); } /// <summary> /// Checks that the rest of the <paramref name="bitStream"/> contains only unset bits. /// </summary> /// <param name="bitStream"><see cref="BitStream"/> to check.</param> /// <returns>True if all of the bits in the <paramref name="bitStream"/> are unset; otherwise false.</returns> static bool RestOfStreamIsZero(BitStream bitStream) { // Read 32 bits at a time while (bitStream.PositionBits + 32 <= bitStream.LengthBits) { if (bitStream.ReadUInt() != 0) return false; } // Read the remaining bits if (bitStream.ReadUInt(bitStream.LengthBits - bitStream.PositionBits) != 0) return false; return true; } #region IMessageProcessorManager Members /// <summary> /// Gets the <see cref="IMessageProcessor"/>s handled by this <see cref="IMessageProcessorManager"/>. /// </summary> public IEnumerable<IMessageProcessor> Processors { get { return _processors.Where(x => x != null); } } /// <summary> /// Handles received data and forwards it to the corresponding <see cref="IMessageProcessor"/>. /// </summary> /// <param name="socket"><see cref="IIPSocket"/> the data came from.</param> /// <param name="data">Data to process.</param> public void Process(IIPSocket socket, BitStream data) { ThreadAsserts.IsMainThread(); // Validate the arguments if (socket == null) { const string errmsg = "socket is null."; Debug.Fail(errmsg); if (log.IsErrorEnabled) log.Error(errmsg); return; } if (data == null) { const string errmsg = "data is null."; Debug.Fail(errmsg); if (log.IsErrorEnabled) log.Error(errmsg); return; } if (data.Length == 0) { const string errmsg = "data array is empty."; Debug.Fail(errmsg); if (log.IsErrorEnabled) log.Error(errmsg); return; } Debug.Assert(data.PositionBits == 0); // Loop through the data until it is emptied while (data.PositionBits < data.LengthBits) { // Get the ID of the message var msgID = ReadMessageID(data); if (log.IsDebugEnabled) log.DebugFormat("Parsing message ID `{0}`. Stream now at bit position `{1}`.", msgID, data.PositionBits); // If we get a message ID of 0, we have likely hit the end if (msgID.GetRawValue() == 0) { AssertRestOfStreamIsZero(data); return; } // Find the corresponding processor and call it var processor = GetMessageProcessor(msgID); // Ensure the processor exists if (processor == null) { const string errmsg = "Processor for message ID {0} is null."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, msgID); Debug.Fail(string.Format(errmsg, msgID)); return; } // Ensure the processor contains a valid handler if (processor.Call == null) { const string errmsg = "Processor for message ID {0} contains null Call delegate."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, msgID); Debug.Fail(string.Format(errmsg, msgID)); return; } // Call the processor InvokeProcessor(socket, processor, data); } } /// <summary> /// Handles a list of received data and forwards it to the corresponding <see cref="IMessageProcessor"/>. /// </summary> /// <param name="recvData">IEnumerable of <see cref="BitStream"/> to process and the corresponding /// <see cref="IIPSocket"/> that the data came from.</param> public void Process(IEnumerable<KeyValuePair<IIPSocket, BitStream>> recvData) { if (recvData == null) return; // Loop through the received data collections from each socket foreach (var rec in recvData) { Process(rec.Key, rec.Value); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Data.SqlClient.SNI { /// <summary> /// SNI MARS connection. Multiple MARS streams will be overlaid on this connection. /// </summary> internal class SNIMarsConnection { private readonly Guid _connectionId = Guid.NewGuid(); private readonly Dictionary<int, SNIMarsHandle> _sessions = new Dictionary<int, SNIMarsHandle>(); private readonly byte[] _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH]; private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader(); private SNIHandle _lowerHandle; private ushort _nextSessionId = 0; private int _currentHeaderByteCount = 0; private int _dataBytesLeft = 0; private SNIPacket _currentPacket; /// <summary> /// Connection ID /// </summary> public Guid ConnectionId { get { return _connectionId; } } /// <summary> /// Constructor /// </summary> /// <param name="lowerHandle">Lower handle</param> public SNIMarsConnection(SNIHandle lowerHandle) { _lowerHandle = lowerHandle; _lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete); } public SNIMarsHandle CreateMarsSession(object callbackObject, bool async) { lock (this) { ushort sessionId = _nextSessionId++; SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, async); _sessions.Add(sessionId, handle); return handle; } } /// <summary> /// Start receiving /// </summary> /// <returns></returns> public uint StartReceive() { SNIPacket packet = null; if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING) { return TdsEnums.SNI_SUCCESS_IO_PENDING; } return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty); } /// <summary> /// Send a packet synchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public uint Send(SNIPacket packet) { lock (this) { return _lowerHandle.Send(packet); } } /// <summary> /// Send a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <param name="callback">Completion callback</param> /// <returns>SNI error code</returns> public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback) { lock (this) { return _lowerHandle.SendAsync(packet, false, callback); } } /// <summary> /// Receive a packet asynchronously /// </summary> /// <param name="packet">SNI packet</param> /// <returns>SNI error code</returns> public uint ReceiveAsync(ref SNIPacket packet) { if (packet != null) { packet.Release(); packet = null; } lock (this) { return _lowerHandle.ReceiveAsync(ref packet); } } /// <summary> /// Check SNI handle connection /// </summary> /// <returns>SNI error status</returns> public uint CheckConnection() { lock (this) { return _lowerHandle.CheckConnection(); } } /// <summary> /// Process a receive error /// </summary> public void HandleReceiveError(SNIPacket packet) { Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked."); foreach (SNIMarsHandle handle in _sessions.Values) { handle.HandleReceiveError(packet); } packet?.Release(); } /// <summary> /// Process a send completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) { packet.InvokeCompletionCallback(sniErrorCode); } /// <summary> /// Process a receive completion /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) { SNISMUXHeader currentHeader = null; SNIPacket currentPacket = null; SNIMarsHandle currentSession = null; if (sniErrorCode != TdsEnums.SNI_SUCCESS) { lock (this) { HandleReceiveError(packet); return; } } while (true) { lock (this) { if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH) { currentHeader = null; currentPacket = null; currentSession = null; while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH) { int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount); _currentHeaderByteCount += bytesTaken; if (bytesTaken == 0) { sniErrorCode = ReceiveAsync(ref packet); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { return; } HandleReceiveError(packet); return; } } _currentHeader.Read(_headerBytes); _dataBytesLeft = (int)_currentHeader.length; _currentPacket = new SNIPacket(headerSize: 0, dataSize: (int)_currentHeader.length); } currentHeader = _currentHeader; currentPacket = _currentPacket; if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA) { if (_dataBytesLeft > 0) { int length = packet.TakeData(_currentPacket, _dataBytesLeft); _dataBytesLeft -= length; if (_dataBytesLeft > 0) { sniErrorCode = ReceiveAsync(ref packet); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { return; } HandleReceiveError(packet); return; } } } _currentHeaderByteCount = 0; if (!_sessions.ContainsKey(_currentHeader.sessionId)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.InvalidParameterError, string.Empty); HandleReceiveError(packet); _lowerHandle.Dispose(); _lowerHandle = null; return; } if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN) { _sessions.Remove(_currentHeader.sessionId); } else { currentSession = _sessions[_currentHeader.sessionId]; } } if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA) { currentSession.HandleReceiveComplete(currentPacket, currentHeader); } if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK) { try { currentSession.HandleAck(currentHeader.highwater); } catch (Exception e) { SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); } } lock (this) { if (packet.DataLeft == 0) { sniErrorCode = ReceiveAsync(ref packet); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { return; } HandleReceiveError(packet); return; } } } } /// <summary> /// Enable SSL /// </summary> public uint EnableSsl(uint options) { return _lowerHandle.EnableSsl(options); } /// <summary> /// Disable SSL /// </summary> public void DisableSsl() { _lowerHandle.DisableSsl(); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public void KillConnection() { _lowerHandle.KillConnection(); } #endif } }
namespace Mosa.Tool.TinySimulator { partial class SymbolView : SimulatorDockContent { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripLabel2 = new System.Windows.Forms.ToolStripLabel(); this.toolStripTextBox1 = new System.Windows.Forms.ToolStripTextBox(); this.toolStripLabel4 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox2 = new System.Windows.Forms.ToolStripComboBox(); this.toolStripLabel3 = new System.Windows.Forms.ToolStripLabel(); this.toolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.toolStrip1.SuspendLayout(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToOrderColumns = true; this.dataGridView1.AllowUserToResizeRows = false; this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control; this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.Font = new System.Drawing.Font("Consolas", 8F); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window; dataGridViewCellStyle2.Font = new System.Drawing.Font("Consolas", 8F); dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False; this.dataGridView1.DefaultCellStyle = dataGridViewCellStyle2; this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView1.Location = new System.Drawing.Point(0, 28); this.dataGridView1.Margin = new System.Windows.Forms.Padding(0); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle3.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle3.Font = new System.Drawing.Font("Consolas", 8F); dataGridViewCellStyle3.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle3; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.dataGridView1.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Consolas", 8F); this.dataGridView1.RowTemplate.Height = 18; this.dataGridView1.Size = new System.Drawing.Size(890, 232); this.dataGridView1.TabIndex = 2; this.dataGridView1.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_CellMouseClick); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.toolStripSeparator1, this.toolStripLabel2, this.toolStripTextBox1, this.toolStripLabel4, this.toolStripComboBox2, this.toolStripLabel3, this.toolStripComboBox1}); this.toolStrip1.Location = new System.Drawing.Point(0, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(890, 28); this.toolStrip1.TabIndex = 5; this.toolStrip1.Text = "toolStrip1"; // // toolStripLabel1 // this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(33, 25); this.toolStripLabel1.Text = "Filter"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 28); // // toolStripLabel2 // this.toolStripLabel2.Name = "toolStripLabel2"; this.toolStripLabel2.Size = new System.Drawing.Size(85, 25); this.toolStripLabel2.Text = "Symbols Name:"; // // toolStripTextBox1 // this.toolStripTextBox1.BackColor = System.Drawing.SystemColors.Window; this.toolStripTextBox1.Margin = new System.Windows.Forms.Padding(1, 3, 1, 2); this.toolStripTextBox1.Name = "toolStripTextBox1"; this.toolStripTextBox1.Size = new System.Drawing.Size(100, 23); this.toolStripTextBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged); // // toolStripLabel4 // this.toolStripLabel4.Name = "toolStripLabel4"; this.toolStripLabel4.Size = new System.Drawing.Size(47, 25); this.toolStripLabel4.Text = "Length:"; // // toolStripComboBox2 // this.toolStripComboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBox2.Items.AddRange(new object[] { "<Any>", "1-Byte", "2-Word", "4-Integer", "8-Long"}); this.toolStripComboBox2.Name = "toolStripComboBox2"; this.toolStripComboBox2.Size = new System.Drawing.Size(75, 28); this.toolStripComboBox2.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox2_SelectedIndexChanged); // // toolStripLabel3 // this.toolStripLabel3.Name = "toolStripLabel3"; this.toolStripLabel3.Size = new System.Drawing.Size(76, 25); this.toolStripLabel3.Text = "Section Kind:"; // // toolStripComboBox1 // this.toolStripComboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.toolStripComboBox1.Items.AddRange(new object[] { "<Any>", "Text", "BSS", "ROData"}); this.toolStripComboBox1.Name = "toolStripComboBox1"; this.toolStripComboBox1.Size = new System.Drawing.Size(75, 28); this.toolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.toolStripComboBox1_SelectedIndexChanged); // // SymbolView // this.ClientSize = new System.Drawing.Size(890, 260); this.CloseButton = false; this.CloseButtonVisible = false; this.Controls.Add(this.dataGridView1); this.Controls.Add(this.toolStrip1); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Name = "SymbolView"; this.TabText = "Symbols"; this.Text = "Symbols"; this.Load += new System.EventHandler(this.SymbolView_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripLabel toolStripLabel2; private System.Windows.Forms.ToolStripTextBox toolStripTextBox1; private System.Windows.Forms.ToolStripComboBox toolStripComboBox1; private System.Windows.Forms.ToolStripLabel toolStripLabel3; private System.Windows.Forms.ToolStripLabel toolStripLabel4; private System.Windows.Forms.ToolStripComboBox toolStripComboBox2; } }
// 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 System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resolution; using Microsoft.DotNet.Tools.Test.Utilities; using FluentAssertions; using Xunit; namespace Microsoft.DotNet.ProjectModel.Tests { public class LibraryExporterPackageTests { private const string PackagePath = "PackagePath"; private PackageDescription CreateDescription(LockFileTargetLibrary target = null, LockFilePackageLibrary package = null) { return new PackageDescription(PackagePath, package ?? new LockFilePackageLibrary(), target ?? new LockFileTargetLibrary(), new List<LibraryRange>(), compatible: true, resolved: true); } [Fact] public void ExportsPackageNativeLibraries() { var description = CreateDescription( new LockFileTargetLibrary() { NativeLibraries = new List<LockFileItem>() { { new LockFileItem() { Path = "lib/Native.so" } } } }); var result = ExportSingle(description); result.NativeLibraryGroups.Should().HaveCount(1); var libraryAsset = result.NativeLibraryGroups.GetDefaultAssets().First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("lib/Native.so"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Native.so")); } [Fact] public void ExportsPackageCompilationAssebmlies() { var description = CreateDescription( new LockFileTargetLibrary() { CompileTimeAssemblies = new List<LockFileItem>() { { new LockFileItem() { Path = "ref/Native.dll" } } } }); var result = ExportSingle(description); result.CompilationAssemblies.Should().HaveCount(1); var libraryAsset = result.CompilationAssemblies.First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("ref/Native.dll"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll")); } [Fact] public void ExportsPackageRuntimeAssebmlies() { var description = CreateDescription( new LockFileTargetLibrary() { RuntimeAssemblies = new List<LockFileItem>() { { new LockFileItem() { Path = "ref/Native.dll" } } } }); var result = ExportSingle(description); result.RuntimeAssemblyGroups.Should().HaveCount(1); var libraryAsset = result.RuntimeAssemblyGroups.GetDefaultAssets().First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("ref/Native.dll"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll")); } [Fact] public void ExportsPackageRuntimeTargets() { var description = CreateDescription( new LockFileTargetLibrary() { RuntimeTargets = new List<LockFileRuntimeTarget>() { new LockFileRuntimeTarget("native/native.dylib", "osx", "native"), new LockFileRuntimeTarget("lib/Something.OSX.dll", "osx", "runtime") } }); var result = ExportSingle(description); result.RuntimeAssemblyGroups.Should().HaveCount(2); result.RuntimeAssemblyGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0); result.RuntimeAssemblyGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1); result.NativeLibraryGroups.Should().HaveCount(2); result.NativeLibraryGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0); result.NativeLibraryGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1); var nativeAsset = result.NativeLibraryGroups.GetRuntimeAssets("osx").First(); nativeAsset.Name.Should().Be("native"); nativeAsset.Transform.Should().BeNull(); nativeAsset.RelativePath.Should().Be("native/native.dylib"); nativeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "native/native.dylib")); var runtimeAsset = result.RuntimeAssemblyGroups.GetRuntimeAssets("osx").First(); runtimeAsset.Name.Should().Be("Something.OSX"); runtimeAsset.Transform.Should().BeNull(); runtimeAsset.RelativePath.Should().Be("lib/Something.OSX.dll"); runtimeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Something.OSX.dll")); } [Fact] public void ExportsSources() { var description = CreateDescription( package: new LockFilePackageLibrary() { Files = new List<string>() { Path.Combine("shared", "file.cs") } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Name.Should().Be("file"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("shared", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "shared", "file.cs")); } [Fact] public void ExportsCopyToOutputContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { CopyToOutput = true, Path = Path.Combine("content", "file.txt"), OutputPath = Path.Combine("Out","Path.txt"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.RuntimeAssets.Should().HaveCount(1); var libraryAsset = result.RuntimeAssets.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("Out", "Path.txt")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt")); } [Fact] public void ExportsResourceContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.EmbeddedResource, Path = Path.Combine("content", "file.txt"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.EmbeddedResources.Should().HaveCount(1); var libraryAsset = result.EmbeddedResources.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.txt")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt")); } [Fact] public void ExportsCompileContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.cs"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs")); } [Fact] public void SelectsContentFilesOfProjectCodeLanguage() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.cs"), PPOutputPath = "something", CodeLanguage = "cs" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.vb"), PPOutputPath = "something", CodeLanguage = "vb" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.any"), PPOutputPath = "something", } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs")); } [Fact] public void SelectsContentFilesWithNoLanguageIfProjectLanguageNotMathed() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.vb"), PPOutputPath = "something", CodeLanguage = "vb" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.any"), PPOutputPath = "something", } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.any")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.any")); } private LibraryExport ExportSingle(LibraryDescription description = null) { var rootProject = new Project() { Name = "RootProject", CompilerName = "csc" }; var rootProjectDescription = new ProjectDescription( new LibraryRange(), rootProject, new LibraryRange[] { }, new TargetFrameworkInformation(), true); if (description == null) { description = rootProjectDescription; } else { description.Parents.Add(rootProjectDescription); } var libraryManager = new LibraryManager(new[] { description }, new DiagnosticMessage[] { }, ""); var allExports = new LibraryExporter(rootProjectDescription, libraryManager, "config", "runtime", null, "basepath", "solutionroot").GetAllExports(); var export = allExports.Single(); return export; } } }
using System; using Microsoft.SPOT.Hardware; using System.Runtime.CompilerServices; namespace Microsoft.SPOT.Hardware { /// <summary> /// type for PWM port /// </summary> public class PWM : IDisposable { public enum ScaleFactor : uint { Milliseconds = 1000, Microseconds = 1000000, Nanoseconds = 1000000000, } //--// /// <summary> /// The pin used for this PWM port, can be set only when the port is constructed /// </summary> private readonly Cpu.Pin m_pin; /// <summary> /// The channel used for this PWM port, can be set only when the port is constructed /// </summary> private readonly Cpu.PWMChannel m_channel; /// <summary> /// The period of the PWM in microseconds /// </summary> private uint m_period; /// <summary> /// The Duty Cycle of the PWM wave in microseconds /// </summary> private uint m_duration; /// <summary> /// Polarity of the wave, it determines the idle state of the port /// </summary> private bool m_invert; /// <summary> /// Scale of the period/duration (mS, uS, nS) /// </summary> private ScaleFactor m_scale; /// <summary> /// Whether this object has been disposed. /// </summary> private bool m_disposed = false; //--// /// <summary> /// Build an instance of the PWM type /// </summary> /// <param name="channel">The channel to use</param> /// <param name="frequency_Hz">The frequency of the pulse in Hz</param> /// <param name="dutyCycle">The duty cycle of the pulse as a fraction of unity. Value should be between 0.0 and 1.0</param> /// <param name="invert">Whether the output should be inverted or not</param> public PWM(Cpu.PWMChannel channel, double frequency_Hz, double dutyCycle, bool invert) { HardwareProvider hwProvider = HardwareProvider.HwProvider; if(hwProvider == null) throw new InvalidOperationException(); m_pin = hwProvider.GetPwmPinForChannel(channel); m_channel = channel; //--// m_period = PeriodFromFrequency(frequency_Hz, out m_scale); m_duration = DurationFromDutyCycleAndPeriod(dutyCycle, m_period); m_invert = invert; //--// try { Init(); Commit(); Port.ReservePin(m_pin, true); } catch { Dispose(false); } } /// <summary> /// Build an instance of the PWM type /// </summary> /// <param name="channel">The channel</param> /// <param name="period">The period of the pulse</param> /// <param name="duration">The duration of the pulse. The value should be a fraction of the period</param> /// <param name="scale">The scale factor for the period/duration (nS, uS, mS)</param> /// <param name="invert">Whether the output should be inverted or not</param> public PWM(Cpu.PWMChannel channel, uint period, uint duration, ScaleFactor scale, bool invert) { HardwareProvider hwProvider = HardwareProvider.HwProvider; if (hwProvider == null) throw new InvalidOperationException(); m_pin = hwProvider.GetPwmPinForChannel(channel); m_channel = channel; //--// m_period = period; m_duration = duration; m_scale = scale; m_invert = invert; //--// try { Init(); Commit(); Port.ReservePin(m_pin, true); } catch { Dispose(false); } } /// <summary> /// Finalizer for the PWM type, will stop the port if still running and un-reserve the underlying pin /// </summary> ~PWM() { Dispose(false); } /// <summary> /// Diposes the PWM type, will stop the port if still running and un-reserve the PIN /// </summary> public void Dispose() { if (!m_disposed) { Dispose(true); GC.SuppressFinalize(this); m_disposed = true; } } /// <summary> /// Starts the PWM port for an indefinite amount of time /// </summary> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public void Start(); /// <summary> /// Stop the PWM port /// </summary> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public void Stop(); //--// /// <summary> /// The GPIO pin chosen for the selected channel /// </summary> public Cpu.Pin Pin { get { return m_pin; } } /// <summary> /// Gets and sets the frequency (in Hz) of the pulse /// </summary> public double Frequency { get { return FrequencyFromPeriod(m_period, m_scale); } set { // save the duty cycle so that we can preserve it after changing the period double dutyCycle = DutyCycle; m_period = PeriodFromFrequency(value, out m_scale); // restore the proper duty cycle m_duration = DurationFromDutyCycleAndPeriod(dutyCycle, m_period); Commit(); //--// } } /// <summary> /// Gets and sets the duty cycle of the pulse as a fraction of unity. Value should be included between 0.0 and 1.0 /// </summary> public double DutyCycle { get { return DutyCycleFromDurationAndPeriod(m_period, m_duration); } set { m_duration = DurationFromDutyCycleAndPeriod(value, m_period); Commit(); //--// } } /// <summary> /// Gets and sets the period of the pulse /// </summary> public uint Period { get { return m_period; } set { m_period = value; Commit(); //--// } } /// <summary> /// Gets and sets the duration of the pulse. The Value should be a fraction of the period. /// </summary> public uint Duration { get { return m_duration; } set { m_duration = value; Commit(); //--// } } /// <summary> /// Gets or sets the scale factor for the Duration and Period. Setting the Scale does not cause /// an immediate update to the PWM. The update occurs when Duration or Period are set. /// </summary> public ScaleFactor Scale { get { return m_scale; } set { m_scale = value; Commit(); //--// } } //--// /// <summary> /// Starts a number of PWM ports at the same time /// </summary> /// <param name="ports"></param> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static void Start(PWM[] ports); /// <summary> /// Stops a number of PWM ports at the same time /// </summary> /// <param name="ports"></param> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static void Stop(PWM[] ports); //--// protected void Dispose(bool disposing) { try { Stop(); } catch { // hide all exceptions... } finally { Uninit(); Port.ReservePin(m_pin, false); } } /// <summary> /// Moves values to the HAL /// </summary> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern protected void Commit(); /// <summary> /// Initializes the controller /// </summary> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern protected void Init(); /// <summary> /// Uninitializes the controller /// </summary> [MethodImplAttribute(MethodImplOptions.InternalCall)] extern protected void Uninit(); //--// private static uint PeriodFromFrequency(double f, out ScaleFactor scale) { if(f >= 1000.0) { scale = ScaleFactor.Nanoseconds; return (uint)(((uint)ScaleFactor.Nanoseconds / f) + 0.5); } else if(f >= 1.0) { scale = ScaleFactor.Microseconds; return (uint)(((uint)ScaleFactor.Microseconds / f) + 0.5); } else { scale = ScaleFactor.Milliseconds; return (uint)(((uint)ScaleFactor.Milliseconds / f) + 0.5); } } private static uint DurationFromDutyCycleAndPeriod(double dutyCycle, double period) { if (period <= 0) throw new ArgumentException(); if (dutyCycle < 0) return 0; if (dutyCycle > 1) return 1; return (uint)(dutyCycle * period); } private static double FrequencyFromPeriod(double period, ScaleFactor scale) { return ((uint)scale / period); } private static double DutyCycleFromDurationAndPeriod(double period, double duration) { if (period <= 0) throw new ArgumentException(); if (duration < 0) return 0; if (duration > period) return 1; return (duration / period); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.SS.UserModel { using System.Globalization; using System; using System.Text.RegularExpressions; using System.Text; using NPOI.Util; /// <summary> /// Contains methods for dealing with Excel dates. /// @author Michael Harhen /// @author Glen Stampoultzis (glens at apache.org) /// @author Dan Sherman (dsherman at Isisph.com) /// @author Hack Kampbjorn (hak at 2mba.dk) /// @author Alex Jacoby (ajacoby at gmail.com) /// @author Pavel Krupets (pkrupets at palmtreebusiness dot com) /// @author Thies Wellpott /// </summary> public class DateUtil { public const int SECONDS_PER_MINUTE = 60; public const int MINUTES_PER_HOUR = 60; public const int HOURS_PER_DAY = 24; public const int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); private const int BAD_DATE = -1; // used to specify that date Is invalid public const long DAY_MILLISECONDS = 24 * 60 * 60 * 1000; private static readonly char[] TIME_SEPARATOR_PATTERN = new char[] { ':' }; /** * The following patterns are used in {@link #isADateFormat(int, String)} */ private static Regex date_ptrn1 = new Regex("^\\[\\$\\-.*?\\]", RegexOptions.Compiled); private static Regex date_ptrn2 = new Regex("^\\[[a-zA-Z]+\\]", RegexOptions.Compiled); private static Regex date_ptrn3a = new Regex("[yYmMdDhHsS]", RegexOptions.Compiled); private static Regex date_ptrn3b = new Regex("^[\\[\\]yYmMdDhHsS\\-T/,. :\"\\\\]+0*[ampAMP/]*$", RegexOptions.Compiled); // elapsed time patterns: [h],[m] and [s] //private static Regex date_ptrn4 = new Regex("^\\[([hH]+|[mM]+|[sS]+)\\]", RegexOptions.Compiled); private static Regex date_ptrn4 = new Regex("^\\[([hH]+|[mM]+|[sS]+)\\]$", RegexOptions.Compiled); /// <summary> /// Given a Calendar, return the number of days since 1899/12/31. /// </summary> /// <param name="cal">the date</param> /// <param name="use1904windowing">if set to <c>true</c> [use1904windowing].</param> /// <returns>number of days since 1899/12/31</returns> public static int absoluteDay(DateTime cal, bool use1904windowing) { int daynum = (cal - new DateTime(1899, 12, 31)).Days; if (cal > new DateTime(1900, 3, 1) && use1904windowing) { daynum++; } return daynum; } public static int AbsoluteDay(DateTime cal, bool use1904windowing) { return cal.DayOfYear + DaysInPriorYears(cal.Year, use1904windowing); } /// <summary> /// Return the number of days in prior years since 1900 /// </summary> /// <param name="yr">a year (1900 &lt; yr &gt; 4000).</param> /// <param name="use1904windowing"></param> /// <returns>number of days in years prior to yr</returns> private static int DaysInPriorYears(int yr, bool use1904windowing) { if ((!use1904windowing && yr < 1900) || (use1904windowing && yr < 1904)) { throw new ArgumentException("'year' must be 1900 or greater"); } int yr1 = yr - 1; int leapDays = yr1 / 4 // plus julian leap days in prior years - yr1 / 100 // minus prior century years + yr1 / 400 // plus years divisible by 400 - 460; // leap days in previous 1900 years return 365 * (yr - (use1904windowing ? 1904 : 1900)) + leapDays; } /// <summary> /// Given a Date, Converts it into a double representing its internal Excel representation, /// which Is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. /// </summary> /// <param name="date">Excel representation of Date (-1 if error - test for error by Checking for less than 0.1)</param> /// <returns>the Date</returns> public static double GetExcelDate(DateTime date) { return GetExcelDate(date, false); } /// <summary> /// Gets the excel date. /// </summary> /// <param name="year">The year.</param> /// <param name="month">The month.</param> /// <param name="day">The day.</param> /// <param name="hour">The hour.</param> /// <param name="minute">The minute.</param> /// <param name="second">The second.</param> /// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param> /// <returns></returns> public static double GetExcelDate(int year, int month, int day, int hour, int minute, int second, bool use1904windowing) { if ((!use1904windowing && year < 1900) //1900 date system must bigger than 1900 || (use1904windowing && year < 1904)) //1904 date system must bigger than 1904 { return BAD_DATE; } DateTime startdate; if (use1904windowing) { startdate = new DateTime(1904, 1, 1); } else { startdate = new DateTime(1900, 1, 1); } int nextyearmonth = 0; if (month > 12) { nextyearmonth = month - 12; month = 12; } int nextmonthday = 0; if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)) { //big month if (day > 31) { nextmonthday = day - 31; day = 31; } } else if ((month == 4 || month == 6 || month == 9 || month == 11)) { //small month if (day > 30) { nextmonthday = day - 30; day = 30; } } else if (DateTime.IsLeapYear(year)) { //Feb. with leap year if (day > 29) { nextmonthday = day - 29; day = 29; } } else { //Feb without leap year if (day > 28) { nextmonthday = day - 28; day = 28; } } if (day <= 0) { nextmonthday = day - 1; day = 1; } DateTime date = new DateTime(year, month, day, hour, minute, second); date = date.AddMonths(nextyearmonth); date = date.AddDays(nextmonthday); double value = (date - startdate).TotalDays + 1; if (!use1904windowing && value >= 60) { value++; } else if (use1904windowing) { value--; } return value; } /// <summary> /// Given a Date, Converts it into a double representing its internal Excel representation, /// which Is the number of days since 1/1/1900. Fractional days represent hours, minutes, and seconds. /// </summary> /// <param name="date">The date.</param> /// <param name="use1904windowing">Should 1900 or 1904 date windowing be used?</param> /// <returns>Excel representation of Date (-1 if error - test for error by Checking for less than 0.1)</returns> public static double GetExcelDate(DateTime date, bool use1904windowing) { if ((!use1904windowing && date.Year < 1900) //1900 date system must bigger than 1900 || (use1904windowing && date.Year < 1904)) //1904 date system must bigger than 1904 { return BAD_DATE; } DateTime startdate; if (use1904windowing) { startdate = new DateTime(1904, 1, 1); } else { startdate = new DateTime(1900, 1, 1); } double value = (date - startdate).TotalDays + 1; if (!use1904windowing && value >= 60) { value++; } else if (use1904windowing) { value--; } return value; } /// <summary> /// Given an Excel date with using 1900 date windowing, and converts it to a java.util.Date. /// Excel Dates and Times are stored without any timezone /// information. If you know (through other means) that your file /// uses a different TimeZone to the system default, you can use /// this version of the getJavaDate() method to handle it. /// </summary> /// <param name="date">The Excel date.</param> /// <returns>null if date is not a valid Excel date</returns> public static DateTime GetJavaDate(double date) { return GetJavaDate(date, false); } public static DateTime GetJavaDate(double date, TimeZoneInfo tz) { return GetJavaDate(date, false, tz, false); } [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaDate(double date, TimeZone tz) { return GetJavaDate(date, false, tz, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * Converts it to a Date. * * NOTE: If the default <c>TimeZone</c> in Java uses Daylight * Saving Time then the conversion back to an Excel date may not give * the same value, that Is the comparison * <CODE>excelDate == GetExcelDate(GetJavaDate(excelDate,false))</CODE> * Is not always true. For example if default timezone Is * <c>Europe/Copenhagen</c>, on 2004-03-28 the minute after * 01:59 CET Is 03:00 CEST, if the excel date represents a time between * 02:00 and 03:00 then it Is Converted to past 03:00 summer time * * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date Is not a valid Excel date * @see TimeZone */ public static DateTime GetJavaDate(double date, bool use1904windowing) { return GetJavaCalendar(date, use1904windowing, (TimeZoneInfo)null, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZoneInfo tz) { return GetJavaCalendar(date, use1904windowing, tz, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZone tz) { return GetJavaCalendar(date, use1904windowing, tz, false); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param roundSeconds round to closest second * @return Java representation of the date, or null if date is not a valid Excel date */ public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZoneInfo tz, bool roundSeconds) { return GetJavaCalendar(date, use1904windowing, tz, roundSeconds); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param tz The TimeZone to evaluate the date in * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param roundSeconds round to closest second * @return Java representation of the date, or null if date is not a valid Excel date */ [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaDate(double date, bool use1904windowing, TimeZone tz, bool roundSeconds) { return GetJavaCalendar(date, use1904windowing, tz, roundSeconds); } public static DateTime SetCalendar(int wholeDays, int millisecondsInDay, bool use1904windowing, bool roundSeconds) { int startYear = 1900; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't if (use1904windowing) { startYear = 1904; dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day } else if (wholeDays < 61) { // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation dayAdjust = 0; } DateTime dt = (new DateTime(startYear, 1, 1)).AddDays(wholeDays + dayAdjust - 1).AddMilliseconds(millisecondsInDay); if (roundSeconds) { dt = dt.AddMilliseconds(500); dt = dt.AddMilliseconds(-dt.Millisecond); } return dt; } public static DateTime GetJavaCalendar(double date) { return GetJavaCalendar(date, false, (TimeZoneInfo)null, false); } /** * Get EXCEL date as Java Calendar with given time zone. * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param timeZone The TimeZone to evaluate the date in * @return Java representation of the date, or null if date is not a valid Excel date */ public static DateTime GetJavaCalendar(double date, bool use1904windowing) { return GetJavaCalendar(date, use1904windowing, (TimeZoneInfo)null, false); } public static DateTime GetJavaCalendarUTC(double date, bool use1904windowing) { DateTime dt = GetJavaCalendar(date, use1904windowing, (TimeZoneInfo)null, false); return TimeZoneInfo.ConvertTimeToUtc(dt); } public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZoneInfo timeZone) { return GetJavaCalendar(date, use1904windowing, timeZone, false); } /// <summary> /// Get EXCEL date as Java Calendar (with default time zone). This is like GetJavaDate(double, boolean) but returns a Calendar object. /// </summary> /// <param name="date">The Excel date.</param> /// <param name="use1904windowing">true if date uses 1904 windowing, or false if using 1900 date windowing.</param> /// <param name="timeZone"></param> /// <param name="roundSeconds"></param> /// <returns>null if date is not a valid Excel date</returns> public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZoneInfo timeZone, bool roundSeconds) { if (!IsValidExcelDate(date)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid Excel date double value: {0}", date)); } int wholeDays = (int)Math.Floor(date); int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); DateTime calendar= DateTime.Now; //if (timeZone != null) //{ // calendar = LocaleUtil.GetLocaleCalendar(timeZone); //} //else //{ // calendar = LocaleUtil.GetLocaleCalendar(); // using default time-zone //} calendar = SetCalendar(wholeDays, millisecondsInDay, use1904windowing, roundSeconds); return calendar; } [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZone timeZone) { return GetJavaCalendar(date, use1904windowing, timeZone, false); } /// <summary> /// Get EXCEL date as Java Calendar (with default time zone). This is like GetJavaDate(double, boolean) but returns a Calendar object. /// </summary> /// <param name="date">The Excel date.</param> /// <param name="use1904windowing">true if date uses 1904 windowing, or false if using 1900 date windowing.</param> /// <param name="timeZone"></param> /// <param name="roundSeconds"></param> /// <returns>null if date is not a valid Excel date</returns> [Obsolete("The class TimeZone was marked obsolete, Use the Overload using TimeZoneInfo instead.")] public static DateTime GetJavaCalendar(double date, bool use1904windowing, TimeZone timeZone, bool roundSeconds) { if (!IsValidExcelDate(date)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid Excel date double value: {0}", date)); } int wholeDays = (int)Math.Floor(date); int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); DateTime calendar= DateTime.Now; //if (timeZone != null) //{ // calendar = LocaleUtil.GetLocaleCalendar(timeZone); //} //else //{ // calendar = LocaleUtil.GetLocaleCalendar(); // using default time-zone //} calendar = SetCalendar(wholeDays, millisecondsInDay, use1904windowing, roundSeconds); return calendar; } /// <summary> /// Converts a string of format "HH:MM" or "HH:MM:SS" to its (Excel) numeric equivalent /// </summary> /// <param name="timeStr">The time STR.</param> /// <returns> a double between 0 and 1 representing the fraction of the day</returns> public static double ConvertTime(String timeStr) { try { return ConvertTimeInternal(timeStr); } catch (FormatException e) { String msg = "Bad time format '" + timeStr + "' expected 'HH:MM' or 'HH:MM:SS' - " + e.Message; throw new ArgumentException(msg); } } /// <summary> /// Converts the time internal. /// </summary> /// <param name="timeStr">The time STR.</param> /// <returns></returns> private static double ConvertTimeInternal(String timeStr) { int len = timeStr.Length; if (len < 4 || len > 8) { throw new FormatException("Bad length"); } String[] parts = timeStr.Split(TIME_SEPARATOR_PATTERN); String secStr; switch (parts.Length) { case 2: secStr = "00"; break; case 3: secStr = parts[2]; break; default: throw new FormatException("Expected 2 or 3 fields but got (" + parts.Length + ")"); } String hourStr = parts[0]; String minStr = parts[1]; int hours = ParseInt(hourStr, "hour", HOURS_PER_DAY); int minutes = ParseInt(minStr, "minute", MINUTES_PER_HOUR); int seconds = ParseInt(secStr, "second", SECONDS_PER_MINUTE); double totalSeconds = seconds + (minutes + (hours) * 60) * 60; return totalSeconds / (SECONDS_PER_DAY); } // variables for performance optimization: // avoid re-checking DataUtil.isADateFormat(int, String) if a given format // string represents a date format if the same string is passed multiple times. // see https://issues.apache.org/bugzilla/show_bug.cgi?id=55611 private static int lastFormatIndex = -1; private static String lastFormatString = null; private static bool cached = false; private static string syncIsADateFormat = "IsADateFormat"; /// <summary> /// Given a format ID and its format String, will Check to see if the /// format represents a date format or not. /// Firstly, it will Check to see if the format ID corresponds to an /// internal excel date format (eg most US date formats) /// If not, it will Check to see if the format string only Contains /// date formatting Chars (ymd-/), which covers most /// non US date formats. /// </summary> /// <param name="formatIndex">The index of the format, eg from ExtendedFormatRecord.GetFormatIndex</param> /// <param name="formatString">The format string, eg from FormatRecord.GetFormatString</param> /// <returns> /// <c>true</c> if [is A date format] [the specified format index]; otherwise, <c>false</c>. /// </returns> public static bool IsADateFormat(int formatIndex, String formatString) { lock (syncIsADateFormat) { if (formatString != null && formatIndex == lastFormatIndex && formatString.Equals(lastFormatString)) { return cached; } // First up, Is this an internal date format? if (IsInternalDateFormat(formatIndex)) { lastFormatIndex = formatIndex; lastFormatString = formatString; cached = true; return true; } // If we didn't get a real string, it can't be if (formatString == null || formatString.Length == 0) { lastFormatIndex = formatIndex; lastFormatString = formatString; cached = false; return false; } String fs = formatString; // If it end in ;@, that's some crazy dd/mm vs mm/dd // switching stuff, which we can ignore fs = Regex.Replace(fs, ";@", ""); int length = fs.Length; StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = fs[i]; if (i < length - 1) { char nc = fs[i + 1]; if (c == '\\') { switch (nc) { case '-': case ',': case '.': case ' ': case '\\': // skip current '\' and continue to the next char continue; } } else if (c == ';' && nc == '@') { i++; // skip ";@" duplets continue; } } sb.Append(c); } fs = sb.ToString(); // short-circuit if it indicates elapsed time: [h], [m] or [s] //if (Regex.IsMatch(fs, "^\\[([hH]+|[mM]+|[sS]+)\\]")) if (date_ptrn4.IsMatch(fs)) { lastFormatIndex = formatIndex; lastFormatString = formatString; cached = true; return true; } // If it starts with [$-...], then could be a date, but // who knows what that starting bit Is all about //fs = Regex.Replace(fs, "^\\[\\$\\-.*?\\]", ""); fs = date_ptrn1.Replace(fs, ""); // If it starts with something like [Black] or [Yellow], // then it could be a date //fs = Regex.Replace(fs, "^\\[[a-zA-Z]+\\]", ""); fs = date_ptrn2.Replace(fs, ""); // You're allowed something like dd/mm/yy;[red]dd/mm/yy // which would place dates before 1900/1904 in red // For now, only consider the first one int separatorIndex = fs.IndexOf(';'); if (separatorIndex > 0 && separatorIndex < fs.Length - 1) { fs = fs.Substring(0, separatorIndex); } // Ensure it has some date letters in it // (Avoids false positives on the rest of pattern 3) if (!date_ptrn3a.Match(fs).Success) //if (!Regex.Match(fs, "[yYmMdDhHsS]").Success) { return false; } // If we get here, check it's only made up, in any case, of: // y m d h s - \ / , . : [ ] T // optionally followed by AM/PM // Delete any string literals. fs = Regex.Replace(fs, @"""[^""\\]*(?:\\.[^""\\]*)*""", ""); //if (Regex.IsMatch(fs, @"^[\[\]yYmMdDhHsS\-/,. :\""\\]+0*[ampAMP/]*$")) //{ // return true; //} //return false; bool result = date_ptrn3b.IsMatch(fs); lastFormatIndex = formatIndex; lastFormatString = formatString; cached = result; return result; } } /// <summary> /// Converts a string of format "YYYY/MM/DD" to its (Excel) numeric equivalent /// </summary> /// <param name="dateStr">The date STR.</param> /// <returns>a double representing the (integer) number of days since the start of the Excel epoch</returns> public static DateTime ParseYYYYMMDDDate(String dateStr) { try { return ParseYYYYMMDDDateInternal(dateStr); } catch (FormatException e) { String msg = "Bad time format " + dateStr + " expected 'YYYY/MM/DD' - " + e.Message; throw new ArgumentException(msg); } } /// <summary> /// Parses the YYYYMMDD date internal. /// </summary> /// <param name="timeStr">The time string.</param> /// <returns></returns> private static DateTime ParseYYYYMMDDDateInternal(String timeStr) { if (timeStr.Length != 10) { throw new FormatException("Bad length"); } String yearStr = timeStr.Substring(0, 4); String monthStr = timeStr.Substring(5, 2); String dayStr = timeStr.Substring(8, 2); int year = ParseInt(yearStr, "year", short.MinValue, short.MaxValue); int month = ParseInt(monthStr, "month", 1, 12); int day = ParseInt(dayStr, "day", 1, 31); DateTime cal = new DateTime(year, month, day, 0, 0, 0); return cal; } /// <summary> /// Parses the int. /// </summary> /// <param name="strVal">The string value.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="rangeMax">The range max.</param> /// <returns></returns> private static int ParseInt(String strVal, String fieldName, int rangeMax) { return ParseInt(strVal, fieldName, 0, rangeMax - 1); } /// <summary> /// Parses the int. /// </summary> /// <param name="strVal">The STR val.</param> /// <param name="fieldName">Name of the field.</param> /// <param name="lowerLimit">The lower limit.</param> /// <param name="upperLimit">The upper limit.</param> /// <returns></returns> private static int ParseInt(String strVal, String fieldName, int lowerLimit, int upperLimit) { int result; try { result = int.Parse(strVal, CultureInfo.InvariantCulture); } catch (FormatException) { throw new FormatException("Bad int format '" + strVal + "' for " + fieldName + " field"); } if (result < lowerLimit || result > upperLimit) { throw new FormatException(fieldName + " value (" + result + ") is outside the allowable range(0.." + upperLimit + ")"); } return result; } /// <summary> /// Given a format ID this will Check whether the format represents an internal excel date format or not. /// </summary> /// <param name="format">The format.</param> public static bool IsInternalDateFormat(int format) { bool retval = false; switch (format) { // Internal Date Formats as described on page 427 in // Microsoft Excel Dev's Kit... case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x2d: case 0x2e: case 0x2f: retval = true; break; default: retval = false; break; } return retval; } /// <summary> /// Check if a cell Contains a date /// Since dates are stored internally in Excel as double values /// we infer it Is a date if it Is formatted as such. /// </summary> /// <param name="cell">The cell.</param> public static bool IsCellDateFormatted(ICell cell) { if (cell == null) return false; bool bDate = false; double d = cell.NumericCellValue; if (DateUtil.IsValidExcelDate(d)) { ICellStyle style = cell.CellStyle; if (style == null) return false; int i = style.DataFormat; String f = style.GetDataFormatString(); bDate = IsADateFormat(i, f); } return bDate; } /// <summary> /// Check if a cell contains a date, Checking only for internal excel date formats. /// As Excel stores a great many of its dates in "non-internal" date formats, you will not normally want to use this method. /// </summary> /// <param name="cell">The cell.</param> public static bool IsCellInternalDateFormatted(ICell cell) { if (cell == null) return false; bool bDate = false; double d = cell.NumericCellValue; if (DateUtil.IsValidExcelDate(d)) { ICellStyle style = cell.CellStyle; int i = style.DataFormat; bDate = IsInternalDateFormat(i); } return bDate; } /// <summary> /// Given a double, Checks if it Is a valid Excel date. /// </summary> /// <param name="value">the double value.</param> /// <returns> /// <c>true</c> if [is valid excel date] [the specified value]; otherwise, <c>false</c>. /// </returns> public static bool IsValidExcelDate(double value) { //return true; return value > -Double.Epsilon; } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace Newtonsoft.Json.Serialization { public static class __JsonProperty { public static IObservable<System.String> ToString(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ToString()); } public static IObservable<System.String> get_PropertyName(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.PropertyName); } public static IObservable<System.Type> get_DeclaringType(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.DeclaringType); } public static IObservable<System.Nullable<System.Int32>> get_Order(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.Order); } public static IObservable<System.String> get_UnderlyingName(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.UnderlyingName); } public static IObservable<Newtonsoft.Json.Serialization.IValueProvider> get_ValueProvider(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ValueProvider); } public static IObservable<Newtonsoft.Json.Serialization.IAttributeProvider> get_AttributeProvider(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.AttributeProvider); } public static IObservable<System.Type> get_PropertyType(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.PropertyType); } public static IObservable<Newtonsoft.Json.JsonConverter> get_Converter(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.Converter); } public static IObservable<Newtonsoft.Json.JsonConverter> get_MemberConverter(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.MemberConverter); } public static IObservable<System.Boolean> get_Ignored(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.Ignored); } public static IObservable<System.Boolean> get_Readable(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.Readable); } public static IObservable<System.Boolean> get_Writable(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.Writable); } public static IObservable<System.Boolean> get_HasMemberAttribute(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.HasMemberAttribute); } public static IObservable<System.Object> get_DefaultValue(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.DefaultValue); } public static IObservable<Newtonsoft.Json.Required> get_Required(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.Required); } public static IObservable<System.Nullable<System.Boolean>> get_IsReference(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.IsReference); } public static IObservable<System.Nullable<Newtonsoft.Json.NullValueHandling>> get_NullValueHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.NullValueHandling); } public static IObservable<System.Nullable<Newtonsoft.Json.DefaultValueHandling>> get_DefaultValueHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.DefaultValueHandling); } public static IObservable<System.Nullable<Newtonsoft.Json.ReferenceLoopHandling>> get_ReferenceLoopHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ReferenceLoopHandling); } public static IObservable<System.Nullable<Newtonsoft.Json.ObjectCreationHandling>> get_ObjectCreationHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ObjectCreationHandling); } public static IObservable<System.Nullable<Newtonsoft.Json.TypeNameHandling>> get_TypeNameHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.TypeNameHandling); } public static IObservable<System.Predicate<System.Object>> get_ShouldSerialize(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ShouldSerialize); } public static IObservable<System.Predicate<System.Object>> get_ShouldDeserialize(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ShouldDeserialize); } public static IObservable<System.Predicate<System.Object>> get_GetIsSpecified(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.GetIsSpecified); } public static IObservable<System.Action<System.Object, System.Object>> get_SetIsSpecified(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.SetIsSpecified); } public static IObservable<Newtonsoft.Json.JsonConverter> get_ItemConverter(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ItemConverter); } public static IObservable<System.Nullable<System.Boolean>> get_ItemIsReference(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ItemIsReference); } public static IObservable<System.Nullable<Newtonsoft.Json.TypeNameHandling>> get_ItemTypeNameHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ItemTypeNameHandling); } public static IObservable<System.Nullable<Newtonsoft.Json.ReferenceLoopHandling>> get_ItemReferenceLoopHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue) { return Observable.Select(JsonPropertyValue, (JsonPropertyValueLambda) => JsonPropertyValueLambda.ItemReferenceLoopHandling); } public static IObservable<System.Reactive.Unit> set_PropertyName(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.PropertyName = valueLambda); } public static IObservable<System.Reactive.Unit> set_DeclaringType(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Type> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.DeclaringType = valueLambda); } public static IObservable<System.Reactive.Unit> set_Order(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<System.Int32>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.Order = valueLambda); } public static IObservable<System.Reactive.Unit> set_UnderlyingName(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.UnderlyingName = valueLambda); } public static IObservable<System.Reactive.Unit> set_ValueProvider(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<Newtonsoft.Json.Serialization.IValueProvider> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ValueProvider = valueLambda); } public static IObservable<System.Reactive.Unit> set_AttributeProvider(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<Newtonsoft.Json.Serialization.IAttributeProvider> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.AttributeProvider = valueLambda); } public static IObservable<System.Reactive.Unit> set_PropertyType(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Type> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.PropertyType = valueLambda); } public static IObservable<System.Reactive.Unit> set_Converter(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<Newtonsoft.Json.JsonConverter> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.Converter = valueLambda); } public static IObservable<System.Reactive.Unit> set_MemberConverter(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<Newtonsoft.Json.JsonConverter> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.MemberConverter = valueLambda); } public static IObservable<System.Reactive.Unit> set_Ignored(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.Ignored = valueLambda); } public static IObservable<System.Reactive.Unit> set_Readable(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.Readable = valueLambda); } public static IObservable<System.Reactive.Unit> set_Writable(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.Writable = valueLambda); } public static IObservable<System.Reactive.Unit> set_HasMemberAttribute(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Boolean> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.HasMemberAttribute = valueLambda); } public static IObservable<System.Reactive.Unit> set_DefaultValue(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Object> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.DefaultValue = valueLambda); } public static IObservable<System.Reactive.Unit> set_Required(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<Newtonsoft.Json.Required> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.Required = valueLambda); } public static IObservable<System.Reactive.Unit> set_IsReference(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<System.Boolean>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.IsReference = valueLambda); } public static IObservable<System.Reactive.Unit> set_NullValueHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.NullValueHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.NullValueHandling = valueLambda); } public static IObservable<System.Reactive.Unit> set_DefaultValueHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.DefaultValueHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.DefaultValueHandling = valueLambda); } public static IObservable<System.Reactive.Unit> set_ReferenceLoopHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.ReferenceLoopHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ReferenceLoopHandling = valueLambda); } public static IObservable<System.Reactive.Unit> set_ObjectCreationHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.ObjectCreationHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ObjectCreationHandling = valueLambda); } public static IObservable<System.Reactive.Unit> set_TypeNameHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.TypeNameHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.TypeNameHandling = valueLambda); } public static IObservable<System.Reactive.Unit> set_ShouldSerialize(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Predicate<System.Object>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ShouldSerialize = valueLambda); } public static IObservable<System.Reactive.Unit> set_ShouldDeserialize(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Predicate<System.Object>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ShouldDeserialize = valueLambda); } public static IObservable<System.Reactive.Unit> set_GetIsSpecified(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Predicate<System.Object>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.GetIsSpecified = valueLambda); } public static IObservable<System.Reactive.Unit> set_SetIsSpecified(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Action<System.Object, System.Object>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.SetIsSpecified = valueLambda); } public static IObservable<System.Reactive.Unit> set_ItemConverter(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<Newtonsoft.Json.JsonConverter> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ItemConverter = valueLambda); } public static IObservable<System.Reactive.Unit> set_ItemIsReference(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<System.Boolean>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ItemIsReference = valueLambda); } public static IObservable<System.Reactive.Unit> set_ItemTypeNameHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.TypeNameHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ItemTypeNameHandling = valueLambda); } public static IObservable<System.Reactive.Unit> set_ItemReferenceLoopHandling(this IObservable<Newtonsoft.Json.Serialization.JsonProperty> JsonPropertyValue, IObservable<System.Nullable<Newtonsoft.Json.ReferenceLoopHandling>> value) { return ObservableExt.ZipExecute(JsonPropertyValue, value, (JsonPropertyValueLambda, valueLambda) => JsonPropertyValueLambda.ItemReferenceLoopHandling = valueLambda); } } }
using System.Collections.Generic; using GuiLabs.Canvas.Controls; using GuiLabs.Utils; using GuiLabs.Canvas.Events; namespace GuiLabs.Editor.Blocks { public class UniversalBlock : ContainerBlock { #region ctors public UniversalBlock() : base() { HMembers = CreateHMembers(); VMembers = CreateVMembers(); InitControl(); } public UniversalBlock(VContainerBlock vMembers) : base() { HMembers = CreateHMembers(); if (vMembers == null) { VMembers = CreateVMembers(); } else { VMembers = vMembers; } InitControl(); } #endregion #region Control public override Control MyControl { get { return MyUniversalControl; } } protected virtual void InitControl() { MyUniversalControl = new UniversalControl( HMembers.MyListControl, VMembers.MyListControl); } private UniversalControl mMyUniversalControl; public UniversalControl MyUniversalControl { get { return mMyUniversalControl; } set { if (mMyUniversalControl != null) { UnSubscribeControl(); } mMyUniversalControl = value; if (mMyUniversalControl != null) { SubscribeControl(); } } } #endregion #region OnEvents protected override void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { Block nextFocusable = null; if (IsMoveUpDown(e)) { e.Handled = true; return; } switch (e.KeyCode) { case System.Windows.Forms.Keys.Right: nextFocusable = this.FindFirstFocusableChild(); if (nextFocusable == null) { nextFocusable = this.FindNextFocusableBlockInChain(); } nextFocusable.SetCursorToTheBeginning(); e.Handled = true; return; case System.Windows.Forms.Keys.Down: if (VMembers.Visible && this.MyUniversalControl.LinearLayoutStrategy.Orientation == OrientationType.Vertical) { nextFocusable = VMembers.FindFirstFocusableBlock(); if (nextFocusable != null) { nextFocusable.SetFocus(); e.Handled = true; return; } } break; case System.Windows.Forms.Keys.End: nextFocusable = HMembers.FindLastFocusableBlock(); if (nextFocusable != null) { nextFocusable.SetCursorToTheEnd(); e.Handled = true; return; } break; default: break; } if (nextFocusable != null && nextFocusable.CanGetFocus) { nextFocusable.SetFocus(); e.Handled = true; } if (!e.Handled) { base.OnKeyDown(sender, e); } } protected override void OnDoubleClick(MouseWithKeysEventArgs e) { if (this.HasPoint(e.X, e.Y)) { this.MyUniversalControl.ToggleCollapse(true); e.Handled = true; } } #endregion #region Memento public override IEnumerable<Block> GetChildrenToSerialize() { return this.VMembers.Children; } #endregion #region HMembers private HContainerBlock mHMembers; public virtual HContainerBlock HMembers { get { return mHMembers; } private set { if (mHMembers != null) { mHMembers.KeyDown -= HMembers_KeyDown; this.Children.Delete(mHMembers); } mHMembers = value; if (mHMembers != null) { this.Children.Prepend(mHMembers); mHMembers.CanBeSelected = false; mHMembers.KeyDown += HMembers_KeyDown; } } } protected virtual HContainerBlock CreateHMembers() { HContainerBlock result = new HContainerBlock(); return result; } void HMembers_KeyDown(Block Block, System.Windows.Forms.KeyEventArgs e) { Block nextFocusable = null; switch (e.KeyCode) { case System.Windows.Forms.Keys.Return: case System.Windows.Forms.Keys.Down: case System.Windows.Forms.Keys.Right: if (VMembers != null && this.VMembers.MyControl.Visible) { nextFocusable = this.VMembers.FindFirstFocusableBlock(); } break; case System.Windows.Forms.Keys.Left: case System.Windows.Forms.Keys.Home: nextFocusable = this; break; case System.Windows.Forms.Keys.End: nextFocusable = this.HMembers.FindLastFocusableChild(); break; default: break; } if (nextFocusable != null && nextFocusable.CanGetFocus) { nextFocusable.SetFocus(); e.Handled = true; } RaiseKeyDown(e); } #endregion #region VMembers private VContainerBlock mVMembers; public virtual VContainerBlock VMembers { get { return mVMembers; } set { if (mVMembers != null) { mVMembers.KeyDown -= VMembers_KeyDown; this.Children.Delete(mVMembers); } mVMembers = value; if (mVMembers != null) { mVMembers.CanBeSelected = false; mVMembers.KeyDown += VMembers_KeyDown; this.Children.Add(mVMembers); if (this.MyUniversalControl != null) { this.MyUniversalControl.VMembers = this.VMembers.MyListControl; } } } } protected virtual VContainerBlock CreateVMembers() { VContainerBlock result = new VContainerBlock(); return result; } void VMembers_KeyDown(Block Block, System.Windows.Forms.KeyEventArgs e) { Block nextFocusable = null; switch (e.KeyCode) { case System.Windows.Forms.Keys.Left: nextFocusable = VMembers.FindPrevFocusableBlockInChain(); if (nextFocusable != null && nextFocusable.IsInStrictSubtreeOf(this)) { nextFocusable.SetCursorToTheEnd(); e.Handled = true; return; } break; case System.Windows.Forms.Keys.Up: //Let's select ourselves each time we're going up //if (HMembers != null && HMembers.GetFirstFocusableChild() != null) //{ // nextFocusable = HMembers.GetFirstFocusableChild(); //} case System.Windows.Forms.Keys.Home: nextFocusable = this; if (!this.CanGetFocus) { nextFocusable = this.FindNearestFocusableParent(); } break; default: break; } if (nextFocusable != null && nextFocusable.CanGetFocus) { nextFocusable.SetFocus(); e.Handled = true; } RaiseKeyDown(e); } #endregion #region Help protected override void OnCollapseChanged(Control itemChanged) { this.DisplayContextHelp(); } private static string[] mHelpStrings = new string[] { HelpBase.Delete }; public override IEnumerable<string> HelpStrings { get { yield return HelpBase.SelectFirstChild(this); foreach (string pageDownUp in HelpBase.PressPageDownAndOrUp(this)) { yield return pageDownUp; } if (this.ParentParent != null) { yield return HelpBase.PressHomeToSelectParent; } foreach (string current in mHelpStrings) { yield return current; } yield return HelpBase.SpaceCollapse(this.MyControl.Collapsed); foreach (string baseString in GetOldHelpStrings()) { yield return baseString; } } } private IEnumerable<string> GetOldHelpStrings() { return base.HelpStrings; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualDouble() { var test = new SimpleBinaryOpTest__CompareEqualDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualDouble { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__CompareEqualDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareEqual( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareEqual( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareEqual( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualDouble(); var result = Sse2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] == right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] == right[i]) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Runtime.Serialization; using System.Threading.Tasks; using Orleans.CodeGeneration; using Orleans.Serialization; namespace Orleans.Runtime { /// <summary> /// This is the base class for all typed grain references. /// </summary> [Serializable] public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable { private readonly string genericArguments; private readonly GuidId observerId; /// <summary> /// Invoke method options specific to this grain reference instance /// </summary> [NonSerialized] private readonly InvokeMethodOptions invokeMethodOptions; internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } } internal bool IsObserverReference { get { return GrainId.IsClient; } } internal GuidId ObserverId { get { return observerId; } } internal bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } } internal IGrainReferenceRuntime Runtime { get { if (this.runtime == null) throw new GrainReferenceNotBoundException(this); return this.runtime; } } /// <summary> /// Gets a value indicating whether this instance is bound to a runtime and hence valid for making requests. /// </summary> internal bool IsBound => this.runtime != null; internal GrainId GrainId { get; private set; } /// <summary> /// Called from generated code. /// </summary> protected internal readonly SiloAddress SystemTargetSilo; [NonSerialized] private IGrainReferenceRuntime runtime; /// <summary> /// Whether the runtime environment for system targets has been initialized yet. /// Called from generated code. /// </summary> protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } } internal string GenericArguments => this.genericArguments; #region Constructors /// <summary>Constructs a reference to the grain with the specified Id.</summary> /// <param name="grainId">The Id of the grain to refer to.</param> /// <param name="genericArgument">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> /// <param name="observerId">Observer ID in case of an observer reference.</param> /// <param name="runtime">The runtime which this grain reference is bound to.</param> private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId, IGrainReferenceRuntime runtime) { GrainId = grainId; this.genericArguments = genericArgument; this.SystemTargetSilo = systemTargetSilo; this.observerId = observerId; this.runtime = runtime; if (String.IsNullOrEmpty(genericArgument)) { genericArguments = null; // always keep it null instead of empty. } // SystemTarget checks if (grainId.IsSystemTarget && systemTargetSilo==null) { throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId)); } if (grainId.IsSystemTarget && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsSystemTarget && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument"); } if (!grainId.IsSystemTarget && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo"); } // ObserverId checks if (grainId.IsClient && observerId == null) { throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId)); } if (grainId.IsClient && genericArguments != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument"); } if (grainId.IsClient && systemTargetSilo != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument"); } if (!grainId.IsClient && observerId != null) { throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId"); } } /// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId, other.runtime) { this.invokeMethodOptions = other.invokeMethodOptions; } protected internal GrainReference(GrainReference other, InvokeMethodOptions invokeMethodOptions) : this(other) { this.invokeMethodOptions = invokeMethodOptions; } #endregion #region Instance creator factory functions /// <summary>Constructs a reference to the grain with the specified ID.</summary> /// <param name="grainId">The ID of the grain to refer to.</param> /// <param name="runtime">The runtime client</param> /// <param name="genericArguments">Type arguments in case of a generic grain.</param> /// <param name="systemTargetSilo">Target silo in case of a system target reference.</param> internal static GrainReference FromGrainId(GrainId grainId, IGrainReferenceRuntime runtime, string genericArguments = null, SiloAddress systemTargetSilo = null) { return new GrainReference(grainId, genericArguments, systemTargetSilo, null, runtime); } internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId, IGrainReferenceRuntime runtime) { return new GrainReference(grainId, null, null, observerId, runtime); } #endregion /// <summary> /// Binds this instance to a runtime. /// </summary> /// <param name="runtime">The runtime.</param> internal void Bind(IGrainReferenceRuntime runtime) { this.runtime = runtime; } /// <summary> /// Tests this reference for equality to another object. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="obj">The object to test for equality against this reference.</param> /// <returns><c>true</c> if the object is equal to this reference.</returns> public override bool Equals(object obj) { return Equals(obj as GrainReference); } public bool Equals(GrainReference other) { if (other == null) return false; if (genericArguments != other.genericArguments) return false; if (!GrainId.Equals(other.GrainId)) { return false; } if (IsSystemTarget) { return Equals(SystemTargetSilo, other.SystemTargetSilo); } if (IsObserverReference) { return observerId.Equals(other.observerId); } return true; } /// <summary> Calculates a hash code for a grain reference. </summary> public override int GetHashCode() { int hash = GrainId.GetHashCode(); if (IsSystemTarget) { hash = hash ^ SystemTargetSilo.GetHashCode(); } if (IsObserverReference) { hash = hash ^ observerId.GetHashCode(); } return hash; } /// <summary>Get a uniform hash code for this grain reference.</summary> public uint GetUniformHashCode() { // GrainId already includes the hashed type code for generic arguments. return GrainId.GetUniformHashCode(); } /// <summary> /// Compares two references for equality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns> public static bool operator ==(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) == null; return reference1.Equals(reference2); } /// <summary> /// Compares two references for inequality. /// Two grain references are equal if they both refer to the same grain. /// </summary> /// <param name="reference1">First grain reference to compare.</param> /// <param name="reference2">Second grain reference to compare.</param> /// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns> public static bool operator !=(GrainReference reference1, GrainReference reference2) { if (((object)reference1) == null) return ((object)reference2) != null; return !reference1.Equals(reference2); } #region Protected members /// <summary> /// Implemented by generated subclasses to return a constant /// Implemented in generated code. /// </summary> public virtual int InterfaceId { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual ushort InterfaceVersion { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Implemented in generated code. /// </summary> public virtual bool IsCompatible(int interfaceId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Return the name of the interface for this GrainReference. /// Implemented in Orleans generated code. /// </summary> public virtual string InterfaceName { get { throw new InvalidOperationException("Should be overridden by subclass"); } } /// <summary> /// Return the method name associated with the specified interfaceId and methodId values. /// </summary> /// <param name="interfaceId">Interface Id</param> /// <param name="methodId">Method Id</param> /// <returns>Method name string.</returns> public virtual string GetMethodName(int interfaceId, int methodId) { throw new InvalidOperationException("Should be overridden by subclass"); } /// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | invokeMethodOptions, silo); } /// <summary> /// Called from generated code. /// </summary> protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { return this.Runtime.InvokeMethodAsync<T>(this, methodId, arguments, options | invokeMethodOptions, silo); } #endregion private const string GRAIN_REFERENCE_STR = "GrainReference"; private const string SYSTEM_TARGET_STR = "SystemTarget"; private const string OBSERVER_ID_STR = "ObserverId"; private const string GENERIC_ARGUMENTS_STR = "GenericArguments"; /// <summary>Returns a string representation of this reference.</summary> public override string ToString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId, !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } internal string ToDetailedString() { if (IsSystemTarget) { return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo); } if (IsObserverReference) { return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString()); } return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(), !HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments)); } /// <summary> Get the key value for this grain, as a string. </summary> public string ToKeyString() { if (IsObserverReference) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString()); } if (IsSystemTarget) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString()); } if (HasGenericArgument) { return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments); } return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString()); } internal static GrainReference FromKeyString(string key, IGrainReferenceRuntime runtime) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key"); string trimmed = key.Trim(); string grainIdStr; int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length; int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal); int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal); int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal); if (genericIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim(); string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length); if (String.IsNullOrEmpty(genericStr)) { genericStr = null; } return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, genericStr); } else if (observerIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim(); string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length); GuidId observerId = GuidId.FromParsableString(observerIdStr); return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId, runtime); } else if (systemTargetIndex >= 0) { grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim(); string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length); SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime, null, siloAddress); } else { grainIdStr = trimmed.Substring(grainIdIndex); return FromGrainId(GrainId.FromParsableString(grainIdStr), runtime); } //return FromGrainId(GrainId.FromParsableString(grainIdStr), generic); } #region ISerializable Members public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { // Use the AddValue method to specify serialized values. info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string)); if (IsSystemTarget) { info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string)); } if (IsObserverReference) { info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string)); } string genericArg = String.Empty; if (HasGenericArgument) genericArg = genericArguments; info.AddValue("GenericArguments", genericArg, typeof(string)); } // The special constructor is used to deserialize values. protected GrainReference(SerializationInfo info, StreamingContext context) { // Reset the property value using the GetValue method. var grainIdStr = info.GetString("GrainId"); GrainId = GrainId.FromParsableString(grainIdStr); if (IsSystemTarget) { var siloAddressStr = info.GetString("SystemTargetSilo"); SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr); } if (IsObserverReference) { var observerIdStr = info.GetString(OBSERVER_ID_STR); observerId = GuidId.FromParsableString(observerIdStr); } var genericArg = info.GetString("GenericArguments"); if (String.IsNullOrEmpty(genericArg)) genericArg = null; genericArguments = genericArg; #if !NETSTANDARD_TODO this.OnDeserialized(context); #endif } #if !NETSTANDARD_TODO /// <summary> /// Called by BinaryFormatter after deserialization has completed. /// </summary> /// <param name="context">The context.</param> [OnDeserialized] private void OnDeserialized(StreamingContext context) { var serializerContext = context.Context as ISerializerContext; var runtimeClient = serializerContext?.AdditionalContext as IRuntimeClient; this.runtime = runtimeClient?.GrainReferenceRuntime; } #endif #endregion } }
using System; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Avalonia.Platform.Interop; // ReSharper disable IdentifierTypo namespace Avalonia.X11.NativeDialogs { static unsafe class Glib { private const string GlibName = "libglib-2.0.so.0"; private const string GObjectName = "libgobject-2.0.so.0"; [DllImport(GlibName)] public static extern void g_slist_free(GSList* data); [DllImport(GObjectName)] private static extern void g_object_ref(IntPtr instance); [DllImport(GObjectName)] private static extern ulong g_signal_connect_object(IntPtr instance, Utf8Buffer signal, IntPtr handler, IntPtr userData, int flags); [DllImport(GObjectName)] private static extern void g_object_unref(IntPtr instance); [DllImport(GObjectName)] private static extern ulong g_signal_handler_disconnect(IntPtr instance, ulong connectionId); private delegate bool timeout_callback(IntPtr data); [DllImport(GlibName)] private static extern ulong g_timeout_add_full(int prio, uint interval, timeout_callback callback, IntPtr data, IntPtr destroy); class ConnectedSignal : IDisposable { private readonly IntPtr _instance; private GCHandle _handle; private readonly ulong _id; public ConnectedSignal(IntPtr instance, GCHandle handle, ulong id) { _instance = instance; g_object_ref(instance); _handle = handle; _id = id; } public void Dispose() { if (_handle.IsAllocated) { g_signal_handler_disconnect(_instance, _id); g_object_unref(_instance); _handle.Free(); } } } public static IDisposable ConnectSignal<T>(IntPtr obj, string name, T handler) { var handle = GCHandle.Alloc(handler); var ptr = Marshal.GetFunctionPointerForDelegate((Delegate)(object)handler); using (var utf = new Utf8Buffer(name)) { var id = g_signal_connect_object(obj, utf, ptr, IntPtr.Zero, 0); if (id == 0) throw new ArgumentException("Unable to connect to signal " + name); return new ConnectedSignal(obj, handle, id); } } static bool TimeoutHandler(IntPtr data) { var handle = GCHandle.FromIntPtr(data); var cb = (Func<bool>)handle.Target; if (!cb()) { handle.Free(); return false; } return true; } private static readonly timeout_callback s_pinnedHandler; static Glib() { s_pinnedHandler = TimeoutHandler; } static void AddTimeout(int priority, uint interval, Func<bool> callback) { var handle = GCHandle.Alloc(callback); g_timeout_add_full(priority, interval, s_pinnedHandler, GCHandle.ToIntPtr(handle), IntPtr.Zero); } public static Task<T> RunOnGlibThread<T>(Func<T> action) { var tcs = new TaskCompletionSource<T>(); AddTimeout(0, 0, () => { try { tcs.SetResult(action()); } catch (Exception e) { tcs.TrySetException(e); } return false; }); return tcs.Task; } } [StructLayout(LayoutKind.Sequential)] unsafe struct GSList { public readonly IntPtr Data; public readonly GSList* Next; } enum GtkFileChooserAction { Open, Save, SelectFolder, } // ReSharper disable UnusedMember.Global enum GtkResponseType { Help = -11, Apply = -10, No = -9, Yes = -8, Close = -7, Cancel = -6, Ok = -5, DeleteEvent = -4, Accept = -3, Reject = -2, None = -1, } // ReSharper restore UnusedMember.Global static unsafe class Gtk { private static IntPtr s_display; private const string GdkName = "libgdk-3.so.0"; private const string GtkName = "libgtk-3.so.0"; [DllImport(GtkName)] static extern void gtk_main_iteration(); [DllImport(GtkName)] public static extern void gtk_window_set_modal(IntPtr window, bool modal); [DllImport(GtkName)] public static extern void gtk_window_present(IntPtr gtkWindow); public delegate bool signal_generic(IntPtr gtkWidget, IntPtr userData); public delegate bool signal_dialog_response(IntPtr gtkWidget, GtkResponseType response, IntPtr userData); [DllImport(GtkName)] public static extern IntPtr gtk_file_chooser_dialog_new(Utf8Buffer title, IntPtr parent, GtkFileChooserAction action, IntPtr ignore); [DllImport(GtkName)] public static extern void gtk_file_chooser_set_select_multiple(IntPtr chooser, bool allow); [DllImport(GtkName)] public static extern void gtk_dialog_add_button(IntPtr raw, Utf8Buffer button_text, GtkResponseType response_id); [DllImport(GtkName)] public static extern GSList* gtk_file_chooser_get_filenames(IntPtr chooser); [DllImport(GtkName)] public static extern void gtk_file_chooser_set_filename(IntPtr chooser, Utf8Buffer file); [DllImport(GtkName)] public static extern void gtk_file_chooser_set_current_name(IntPtr chooser, Utf8Buffer file); [DllImport(GtkName)] public static extern IntPtr gtk_file_filter_new(); [DllImport(GtkName)] public static extern IntPtr gtk_file_filter_set_name(IntPtr filter, Utf8Buffer name); [DllImport(GtkName)] public static extern IntPtr gtk_file_filter_add_pattern(IntPtr filter, Utf8Buffer pattern); [DllImport(GtkName)] public static extern IntPtr gtk_file_chooser_add_filter(IntPtr chooser, IntPtr filter); [DllImport(GtkName)] public static extern IntPtr gtk_file_chooser_get_filter(IntPtr chooser); [DllImport(GtkName)] public static extern void gtk_widget_realize(IntPtr gtkWidget); [DllImport(GtkName)] public static extern void gtk_widget_destroy(IntPtr gtkWidget); [DllImport(GtkName)] public static extern IntPtr gtk_widget_get_window(IntPtr gtkWidget); [DllImport(GtkName)] public static extern void gtk_widget_hide(IntPtr gtkWidget); [DllImport(GtkName)] static extern bool gtk_init_check(int argc, IntPtr argv); [DllImport(GdkName)] static extern IntPtr gdk_x11_window_foreign_new_for_display(IntPtr display, IntPtr xid); [DllImport(GdkName)] public static extern IntPtr gdk_x11_window_get_xid(IntPtr window); [DllImport(GtkName)] public static extern IntPtr gtk_container_add(IntPtr container, IntPtr widget); [DllImport(GdkName)] static extern IntPtr gdk_set_allowed_backends(Utf8Buffer backends); [DllImport(GdkName)] static extern IntPtr gdk_display_get_default(); [DllImport(GtkName)] static extern IntPtr gtk_application_new(Utf8Buffer appId, int flags); [DllImport(GdkName)] public static extern void gdk_window_set_transient_for(IntPtr window, IntPtr parent); public static IntPtr GetForeignWindow(IntPtr xid) => gdk_x11_window_foreign_new_for_display(s_display, xid); public static Task<bool> StartGtk() { var tcs = new TaskCompletionSource<bool>(); new Thread(() => { try { using (var backends = new Utf8Buffer("x11")) gdk_set_allowed_backends(backends); } catch { //Ignore } Environment.SetEnvironmentVariable("WAYLAND_DISPLAY", "/proc/fake-display-to-prevent-wayland-initialization-by-gtk3"); if (!gtk_init_check(0, IntPtr.Zero)) { tcs.SetResult(false); return; } IntPtr app; using (var utf = new Utf8Buffer($"avalonia.app.a{Guid.NewGuid():N}")) app = gtk_application_new(utf, 0); if (app == IntPtr.Zero) { tcs.SetResult(false); return; } s_display = gdk_display_get_default(); tcs.SetResult(true); while (true) gtk_main_iteration(); }) {Name = "GTK3THREAD", IsBackground = true}.Start(); return tcs.Task; } } }
namespace Ioke.Lang { using NRegex; using System; using System.Collections; using System.Collections.Generic; using System.Text; using Ioke.Lang.Util; internal class UnicodeBlock { private static readonly string blockData = "0000..007F:BASIC_LATIN;0080..00FF:LATIN_1_SUPPLEMENT;0100..017F:LATIN_EXTENDED_A;" +"0180..024F:LATIN_EXTENDED_B;0250..02AF:IPA_EXTENSIONS;02B0..02FF:SPACING_MODIFIER_LETTERS;" +"0300..036F:COMBINING_DIACRITICAL_MARKS;0370..03FF:GREEK;0400..04FF:CYRILLIC;0530..058F:ARMENIAN;" +"0590..05FF:HEBREW;0600..06FF:ARABIC;0700..074F:SYRIAC;0780..07BF:THAANA;0900..097F:DEVANAGARI;" +"0980..09FF:BENGALI;0A00..0A7F:GURMUKHI;0A80..0AFF:GUJARATI;0B00..0B7F:ORIYA;0B80..0BFF:TAMIL;" +"0C00..0C7F:TELUGU;0C80..0CFF:KANNADA;0D00..0D7F:MALAYALAM;0D80..0DFF:SINHALA;0E00..0E7F:THAI;" +"0E80..0EFF:LAO;0F00..0FFF:TIBETAN;1000..109F:MYANMAR;10A0..10FF:GEORGIAN;1100..11FF:HANGULJAMO;" +"1200..137F:ETHIOPIC;13A0..13FF:CHEROKEE;1400..167F:UNIFIED_CANADIAN_ABORIGINAL_SYLLABICS;" +"1680..169F:OGHAM;16A0..16FF:RUNIC;1780..17FF:KHMER;1800..18AF:MONGOLIAN;" +"1E00..1EFF:LATIN_EXTENDED_ADDITIONAL;1F00..1FFF:GREEK_EXTENDED;2000..206F:GENERAL_PUNCTUATION;" +"2070..209F:SUPERSCRIPTS_AND_SUBSCRIPTS;20A0..20CF:CURRENCY_SYMBOLS;" +"20D0..20FF:COMBINING_MARKS_FOR_SYMBOLS;2100..214F:LETTERLIKE_SYMBOLS;2150..218F:NUMBER_FORMS;" +"2190..21FF:ARROWS;2200..22FF:MATHEMATICAL_OPERATORS;2300..23FF:MISCELLANEOUS_TECHNICAL;" +"2400..243F:CONTROL_PICTURES;2440..245F:OPTICAL_CHARACTER_RECOGNITION;" +"2460..24FF:ENCLOSED_ALPHANUMERICS;2500..257F:BOX_DRAWING;2580..259F:BLOCK_ELEMENTS;" +"25A0..25FF:GEOMETRIC_SHAPES;2600..26FF:MISCELLANEOUS_SYMBOLS;2700..27BF:DINGBATS;" +"2800..28FF:BRAILLE_PATTERNS;2E80..2EFF:CJK_RADICALS_SUPPLEMENT;2F00..2FDF:KANGXI_RADICALS;" +"2FF0..2FFF:IDEOGRAPHIC_DESCRIPTION_CHARACTERS;3000..303F:CJK_SYMBOLS_AND_PUNCTUATION;" +"3040..309F:HIRAGANA;30A0..30FF:KATAKANA;3100..312F:BOPOMOFO;3130..318F:HANGUL_COMPATIBILITY_JAMO;" +"3190..319F:KANBUN;31A0..31BF:BOPOMOFO_EXTENDED;3200..32FF:ENCLOSED_CJK_LETTERS_AND_MONTHS;" +"3300..33FF:CJK_COMPATIBILITY;3400..4DB5:CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A;" +"4E00..9FFF:CJK_UNIFIED_IDEOGRAPHS;A000..A48F:YI_SYLLABLES;A490..A4CF:YI_RADICALS;" +"AC00..D7A3:HANGUL_SYLLABLES;D800..DB7F:HIGH_SURROGATES;DB80..DBFF:HIGH_PRIVATE_USE_SURROGATES;" +"DC00..DFFF:LOW_SURROGATES;E000..F8FF:PRIVATE_USE_AREA;F900..FAFF:CJK_COMPATIBILITY_IDEOGRAPHS;" +"FB00..FB4F:ALPHABETIC_PRESENTATION_FORMS;FB50..FDFF:ARABIC_PRESENTATION_FORMS_A;" +"FE20..FE2F:COMBINING_HALF_MARKS;FE30..FE4F:CJK_COMPATIBILITY_FORMS;FE50..FE6F:SMALL_FORM_VARIANTS;" +"FE70..FEFE:ARABIC_PRESENTATION_FORMS_B;FEFF..FEFF:SPECIALS;FF00..FFEF:HALFWIDTH_AND_FULLWIDTH_FORMS;" +"FFF0..FFFD:SPECIALS"; private static string[] blocks = new string[65536]; static UnicodeBlock() { string[] separate = blockData.Split(';'); foreach(string part in separate) { string[] parts = part.Split(':'); string name = parts[1]; int firstIndex = Convert.ToInt32(parts[0].Substring(0,4), 16); int lastIndex = Convert.ToInt32(parts[0].Substring(6,4), 16); for(; firstIndex <= lastIndex; firstIndex++) { blocks[firstIndex] = name; } } } public static string Of(char c) { return blocks[(int)c]; } } public class Text : IokeData { private readonly string text; public Text(string text) { this.text = text; } public static string GetText(object on) { return ((Text)(IokeObject.dataOf(on))).GetText(); } public string GetText() { return text; } public static bool IsText(object on) { return IokeObject.dataOf(on) is Text; } public override string ToString(IokeObject self) { return text; } public override void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "Text"; obj.Mimics(IokeObject.As(IokeObject.FindCell(runtime.Mixins, "Comparing"), null), runtime.nul, runtime.nul); obj.RegisterMethod(runtime.NewNativeMethod("returns a hash for the text", new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); return context.runtime.NewNumber(((Text)IokeObject.dataOf(on)).text.GetHashCode()); }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side text is equal to the right hand side text.", new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(runtime.Text) .WithRequiredPositional("other") .Arguments, (method, on, args, keywords, context, message) => { Text d = (Text)IokeObject.dataOf(on); object other = args[0]; return ((other is IokeObject) && (IokeObject.dataOf(other) is Text) && ((on == context.runtime.Text || other == context.runtime.Text) ? on == other : d.text.Equals(((Text)IokeObject.dataOf(other)).text))) ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a text representation of the object", new NativeMethod.WithNoArguments("asText", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("Takes any number of arguments, and expects the text receiver to contain format specifications. The currently supported specifications are only %s and %{, %}. These have several parameters that can be used. See the spec for more info about these. The format method will return a new text based on the content of the receiver, and the arguments given.", new TypeCheckingNativeMethod("format", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRest("replacements") .Arguments, (self, on, args, keywords, context, message) => { StringBuilder result = new StringBuilder(); Format(on, message, context, args, result); return context.runtime.NewText(result.ToString()); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Converts the content of this text into a rational value", new TypeCheckingNativeMethod.WithNoArguments("toRational", obj, (self, on, args, keywords, context, message) => { return Text.ToRational(on, context, message); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Converts the content of this text into a decimal value", new TypeCheckingNativeMethod.WithNoArguments("toDecimal", obj, (self, on, args, keywords, context, message) => { return Text.ToDecimal(on, context, message); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("inspect", obj, (self, on, args, keywords, context, message) => { return self.runtime.NewText(Text.GetInspect(on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object", new TypeCheckingNativeMethod.WithNoArguments("notice", obj, (self, on, args, keywords, context, message) => { return self.runtime.NewText(Text.GetInspect(on)); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text where all non-safe characters have been replaced with safe ones", new TypeCheckingNativeMethod.WithNoArguments("makeXMLSafe", obj, (self, on, args, keywords, context, message) => { return self.runtime.NewText(new StringUtils().XmlSafe(Text.GetText(on))); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a lower case version of this text", new TypeCheckingNativeMethod.WithNoArguments("lower", obj, (self, on, args, keywords, context, message) => { return self.runtime.NewText(Text.GetText(on).ToLower()); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns an upper case version of this text", new TypeCheckingNativeMethod.WithNoArguments("upper", obj, (self, on, args, keywords, context, message) => { return self.runtime.NewText(Text.GetText(on).ToUpper()); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a version of this text with leading and trailing whitespace removed", new TypeCheckingNativeMethod.WithNoArguments("trim", obj, (self, on, args, keywords, context, message) => { return self.runtime.NewText(Text.GetText(on).Trim()); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns an array of texts split around the argument", new TypeCheckingNativeMethod("split", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithOptionalPositional("splitAround", "") .Arguments, (self, on, args, keywords, context, message) => { string real = Text.GetText(on); var r = new SaneArrayList(); Pattern p = null; if(args.Count == 0) { p = new Pattern("\\s"); } else { object arg = args[0]; if(IokeObject.dataOf(arg) is Regexp) { p = Regexp.GetRegexp(arg); } else { string around = Text.GetText(arg); p = new Pattern(Pattern.Quote(around)); } } RETokenizer tok = new RETokenizer(p, real); tok.EmptyEnabled = false; while(tok.HasMore) { r.Add(context.runtime.NewText(tok.NextToken)); } return context.runtime.NewList(r); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Takes two text arguments where the first is the substring to replace, and the second is the replacement to insert. Will only replace the first match, if any is found, and return a new Text with the result.", new TypeCheckingNativeMethod("replace", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("pattern") .WithRequiredPositional("replacement") .Arguments, (self, on, args, keywords, context, message) => { string initial = Text.GetText(on); string repl = Text.GetText(args[1]); object arg = args[0]; Pattern pat = null; if(IokeObject.dataOf(arg) is Regexp) { pat = Regexp.GetRegexp(arg); } else { string around = Text.GetText(arg); pat = new Pattern(Pattern.Quote(around)); } Replacer r = pat.Replacer(repl); string result = r.ReplaceFirst(initial); return context.runtime.NewText(result); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Takes two text arguments where the first is the substring to replace, and the second is the replacement to insert. Will replace all matches, if any is found, and return a new Text with the result.", new TypeCheckingNativeMethod("replaceAll", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("pattern") .WithRequiredPositional("replacement") .Arguments, (self, on, args, keywords, context, message) => { string initial = Text.GetText(on); string repl = Text.GetText(args[1]); object arg = args[0]; Pattern pat = null; if(IokeObject.dataOf(arg) is Regexp) { pat = Regexp.GetRegexp(arg); } else { string around = Text.GetText(arg); pat = new Pattern(Pattern.Quote(around)); } Replacer r = pat.Replacer(repl); String result = r.Replace(initial); return context.runtime.NewText(result); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns the length of this text", new TypeCheckingNativeMethod.WithNoArguments("length", obj, (self, on, args, keywords, context, message) => { return context.runtime.NewNumber(GetText(on).Length); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("compares this text against the argument, returning -1, 0 or 1 based on which one is lexically larger", new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("other") .Arguments, (self, on, args, keywords, context, message) => { object arg = args[0]; if(!(IokeObject.dataOf(arg) is Text)) { arg = IokeObject.ConvertToText(arg, message, context, false); if(!(IokeObject.dataOf(arg) is Text)) { // Can't compare, so bail out return context.runtime.nil; } } if(on == context.runtime.Text || arg == context.runtime.Text) { if(on == arg) { return context.runtime.NewNumber(0); } return context.runtime.nil; } int result = string.CompareOrdinal(Text.GetText(on), Text.GetText(arg)); if(result < 0) { result = -1; } else if(result > 0) { result = 1; } return context.runtime.NewNumber(result); }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("takes one argument, that can be either an index or a range of two indicis. this slicing works the same as for Lists, so you can index from the end, both with the single index and with the range.", new TypeCheckingNativeMethod("[]", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(obj) .WithRequiredPositional("index") .Arguments, (self, on, args, keywords, context, message) => { object arg = args[0]; IokeData data = IokeObject.dataOf(arg); if(data is Range) { int first = Number.ExtractInt(Range.GetFrom(arg), message, context); if(first < 0) { return context.runtime.NewText(""); } int last = Number.ExtractInt(Range.GetTo(arg), message, context); bool inclusive = Range.IsInclusive(arg); string str = GetText(on); int size = str.Length; if(last < 0) { last = size + last; } if(last < 0) { return context.runtime.NewText(""); } if(last >= size) { last = inclusive ? size-1 : size; } if(first > last || (!inclusive && first == last)) { return context.runtime.NewText(""); } if(!inclusive) { last--; } return context.runtime.NewText(str.Substring(first, (last+1)-first)); } else if(data is Number) { string str = GetText(on); int len = str.Length; int ix = ((Number)data).AsNativeInteger(); if(ix < 0) { ix = len + ix; } if(ix >= 0 && ix < len) { return context.runtime.NewNumber(str[ix]); } else { return context.runtime.nil; } } return on; }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a symbol representing the Unicode category of the character", new TypeCheckingNativeMethod.WithNoArguments("category", obj, (self, on, args, keywords, context, message) => { string character = GetText(on); if(character.Length == 1) { return context.runtime.GetSymbol(UnicodeBlock.Of(character[0])); } IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Default"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("text", context.runtime.NewText("Text does not contain exactly one character")); runtime.ErrorCondition(condition); return null; }))); obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a new text where all the escapes in the current text have been evaluated - exactly as if another parsing step had been applied. This does not evaluate embedded code, though.", new TypeCheckingNativeMethod.WithNoArguments("evaluateEscapes", obj, (self, on, args, keywords, context, message) => { return context.runtime.NewText(new StringUtils().ReplaceEscapes(GetText(on))); }))); } public static string GetInspect(object on) { return ((Text)(IokeObject.dataOf(on))).Inspect(on); } public override IokeObject ConvertToText(IokeObject self, IokeObject m, IokeObject context, bool signalCondition) { return self; } public override IokeObject TryConvertToText(IokeObject self, IokeObject m, IokeObject context) { return self; } public static void Format(object on, IokeObject message, IokeObject context, IList positionalArgs, StringBuilder result) { FormatString(Text.GetText(on), 0, message, context, positionalArgs, result); } private static int FormatString(string format, int index, IokeObject message, IokeObject context, IList positionalArgs, StringBuilder result) { int argIndex = 0; int formatIndex = index; int justify = 0; bool splat = false; bool splatPairs = false; bool negativeJustify = false; bool doAgain = false; int formatLength = format.Length; object arg = null; StringBuilder missingText = new StringBuilder(); object seq = null; IList args = null; while(formatIndex < formatLength) { char c = format[formatIndex++]; switch(c) { case '%': justify = 0; missingText.Append(c); do { doAgain = false; if(formatIndex < formatLength) { c = format[formatIndex++]; missingText.Append(c); switch(c) { case '*': splat = true; doAgain = true; break; case ':': splatPairs = true; doAgain = true; break; case ']': return formatIndex; case '[': arg = positionalArgs[argIndex++]; int endLoop = -1; seq = Interpreter.Send(context.runtime.seqMessage, context, arg); while(IokeObject.IsObjectTrue(Interpreter.Send(context.runtime.nextPMessage, context, seq))) { object receiver = Interpreter.Send(context.runtime.nextMessage, context, seq); if(splat) { args = IokeList.GetList(receiver); } else if(splatPairs) { args = new SaneArrayList() {Pair.GetFirst(receiver), Pair.GetSecond(receiver)}; } else { args = new SaneArrayList() {receiver}; } int newVal = FormatString(format, formatIndex, message, context, args, result); endLoop = newVal; } splat = false; splatPairs = false; if(endLoop == -1) { int opened = 1; while(opened > 0 && formatIndex < formatLength) { char c2 = format[formatIndex++]; if(c2 == '%' && formatIndex < formatLength) { c2 = format[formatIndex++]; if(c2 == '[') { opened++; } else if(c2 == ']') { opened--; } } } } else { formatIndex = endLoop; } break; case 's': arg = positionalArgs[argIndex++]; object txt = IokeObject.TryConvertToText(arg, message, context); if(txt == null) { txt = Interpreter.Send(context.runtime.asText, context, arg); } string outTxt = Text.GetText(txt); if(outTxt.Length < justify) { int missing = justify - outTxt.Length; char[] spaces = new char[missing]; for(int ixx=0; ixx<spaces.Length; ixx++) spaces[ixx] = ' '; if(negativeJustify) { result.Append(outTxt); result.Append(spaces); } else { result.Append(spaces); result.Append(outTxt); } } else { result.Append(outTxt); } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': justify *= 10; justify += (c - '0'); doAgain = true; break; case '-': negativeJustify = !negativeJustify; doAgain = true; break; default: result.Append(missingText); missingText = new StringBuilder(); break; } } else { result.Append(missingText); missingText = new StringBuilder(); } } while(doAgain); break; default: result.Append(c); break; } } return formatLength; } private class TakeLongestRational : Restart.ArgumentGivingRestart { string namex; object[] place; public TakeLongestRational(string name, object[] place) : base("takeLongest") { this.namex = name; this.place = place; } public override string Report() { return "Parse the longest number possible from " + namex; } public override IList<string> ArgumentNames { get { return new SaneList<string>(); } } public override IokeObject Invoke(IokeObject context, IList arguments) { int ix = 0; int len = namex.Length; while(ix < len) { char c = namex[ix]; switch(c) { case '-': case '+': if(ix != 0) { goto breakOuter; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; default: goto breakOuter; } ix++; } breakOuter: place[0] = context.runtime.NewNumber(namex.Substring(0, ix)); return context.runtime.nil; } } private class TakeLongestDecimal : Restart.ArgumentGivingRestart { string namex; object[] place; public TakeLongestDecimal(string name, object[] place) : base("takeLongest") { this.namex = name; this.place = place; } public override string Report() { return "Parse the longest number possible from " + namex; } public override IList<string> ArgumentNames { get { return new SaneList<string>(); } } public override IokeObject Invoke(IokeObject context, IList arguments) { int ix = 0; int len = namex.Length; bool hadDot = false; bool hadE = false; while(ix < len) { char c = namex[ix]; switch(c) { case '-': case '+': if(ix != 0 && namex[ix-1] != 'e' && namex[ix-1] != 'E') { goto breakOuter; } break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': break; case '.': if(hadDot || hadE) { goto breakOuter; } hadDot = true; break; case 'e': case 'E': if(hadE) { goto breakOuter; } hadE = true; break; default: goto breakOuter; } ix++; } breakOuter: place[0] = context.runtime.NewDecimal(namex.Substring(0, ix)); return context.runtime.nil; } } public static object ToRational(object on, IokeObject context, IokeObject message) { string tvalue = GetText(on); try { return context.runtime.NewNumber(tvalue); } catch(Exception) { Runtime runtime = context.runtime; IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Arithmetic", "NotParseable"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("text", on); object[] newCell = new object[]{null}; runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context, new IokeObject.UseValue("rational", newCell), new TakeLongestRational(tvalue, newCell)); return newCell[0]; } } public static object ToDecimal(object on, IokeObject context, IokeObject message) { string tvalue = GetText(on); try { return context.runtime.NewDecimal(tvalue); } catch(Exception) { Runtime runtime = context.runtime; IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Arithmetic", "NotParseable"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("text", on); object[] newCell = new object[]{null}; runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context, new IokeObject.UseValue("decimal", newCell), new TakeLongestDecimal(tvalue, newCell)); return newCell[0]; } } public string Inspect(object obj) { return "\"" + new StringUtils().Escape(text) + "\""; } } }
// 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.Linq; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace System.Runtime.CompilerServices.Tests { public partial class ConditionalWeakTableTests { [Fact] public static void InvalidArgs_Throws() { var cwt = new ConditionalWeakTable<object, object>(); object ignored; AssertExtensions.Throws<ArgumentNullException>("key", () => cwt.Add(null, new object())); // null key AssertExtensions.Throws<ArgumentNullException>("key", () => cwt.TryGetValue(null, out ignored)); // null key AssertExtensions.Throws<ArgumentNullException>("key", () => cwt.Remove(null)); // null key AssertExtensions.Throws<ArgumentNullException>("createValueCallback", () => cwt.GetValue(new object(), null)); // null delegate object key = new object(); cwt.Add(key, key); AssertExtensions.Throws<ArgumentException>(null, () => cwt.Add(key, key)); // duplicate key } [Theory] [InlineData(1)] [InlineData(100)] public static void Add(int numObjects) { // Isolated to ensure we drop all references even in debug builds where lifetime is extended by the JIT to the end of the method Func<int, Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]>> body = count => { object[] keys = Enumerable.Range(0, count).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, count).Select(_ => new object()).ToArray(); var cwt = new ConditionalWeakTable<object, object>(); for (int i = 0; i < count; i++) { cwt.Add(keys[i], values[i]); } for (int i = 0; i < count; i++) { object value; Assert.True(cwt.TryGetValue(keys[i], out value)); Assert.Same(values[i], value); Assert.Same(value, cwt.GetOrCreateValue(keys[i])); Assert.Same(value, cwt.GetValue(keys[i], _ => new object())); } return Tuple.Create(cwt, keys.Select(k => new WeakReference(k)).ToArray(), values.Select(v => new WeakReference(v)).ToArray()); }; Tuple<ConditionalWeakTable<object, object>, WeakReference[], WeakReference[]> result = body(numObjects); GC.Collect(); Assert.NotNull(result.Item1); for (int i = 0; i < numObjects; i++) { Assert.False(result.Item2[i].IsAlive, $"Expected not to find key #{i}"); Assert.False(result.Item3[i].IsAlive, $"Expected not to find value #{i}"); } } [Theory] [InlineData(1)] [InlineData(100)] public static void AddMany_ThenRemoveAll(int numObjects) { object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); var cwt = new ConditionalWeakTable<object, object>(); for (int i = 0; i < numObjects; i++) { cwt.Add(keys[i], values[i]); } for (int i = 0; i < numObjects; i++) { Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object())); } for (int i = 0; i < numObjects; i++) { Assert.True(cwt.Remove(keys[i])); Assert.False(cwt.Remove(keys[i])); } for (int i = 0; i < numObjects; i++) { object ignored; Assert.False(cwt.TryGetValue(keys[i], out ignored)); } } [Theory] [InlineData(100)] public static void AddRemoveIteratively(int numObjects) { object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); var cwt = new ConditionalWeakTable<object, object>(); for (int i = 0; i < numObjects; i++) { cwt.Add(keys[i], values[i]); Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object())); Assert.True(cwt.Remove(keys[i])); Assert.False(cwt.Remove(keys[i])); } } [Fact] public static void Concurrent_AddMany_DropReferences() // no asserts, just making nothing throws { var cwt = new ConditionalWeakTable<object, object>(); for (int i = 0; i < 10000; i++) { cwt.Add(i.ToString(), i.ToString()); if (i % 1000 == 0) GC.Collect(); } } [Fact] public static void Concurrent_Add_Read_Remove_DifferentObjects() { var cwt = new ConditionalWeakTable<object, object>(); DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25); Parallel.For(0, Environment.ProcessorCount, i => { while (DateTime.UtcNow < end) { object key = new object(); object value = new object(); cwt.Add(key, value); Assert.Same(value, cwt.GetValue(key, _ => new object())); Assert.True(cwt.Remove(key)); Assert.False(cwt.Remove(key)); } }); } [Fact] public static void Concurrent_GetValue_Read_Remove_DifferentObjects() { var cwt = new ConditionalWeakTable<object, object>(); DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25); Parallel.For(0, Environment.ProcessorCount, i => { while (DateTime.UtcNow < end) { object key = new object(); object value = new object(); Assert.Same(value, cwt.GetValue(key, _ => value)); Assert.True(cwt.Remove(key)); Assert.False(cwt.Remove(key)); } }); } [Fact] public static void Concurrent_GetValue_Read_Remove_SameObject() { object key = new object(); object value = new object(); var cwt = new ConditionalWeakTable<object, object>(); DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(0.25); Parallel.For(0, Environment.ProcessorCount, i => { while (DateTime.UtcNow < end) { Assert.Same(value, cwt.GetValue(key, _ => value)); cwt.Remove(key); } }); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static WeakReference GetWeakCondTabRef(out ConditionalWeakTable<object, object> cwt_out, out object key_out) { var key = new object(); var value = new object(); var cwt = new ConditionalWeakTable<object, object>(); cwt.Add(key, value); cwt.Remove(key); // Return 3 values to the caller, drop everything else on the floor. cwt_out = cwt; key_out = key; return new WeakReference(value); } [Fact] public static void AddRemove_DropValue() { // Verify that the removed entry is not keeping the value alive ConditionalWeakTable<object, object> cwt; object key; var wrValue = GetWeakCondTabRef(out cwt, out key); GC.Collect(); Assert.False(wrValue.IsAlive); GC.KeepAlive(cwt); GC.KeepAlive(key); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void GetWeakRefPair(out WeakReference<object> key_out, out WeakReference<object> val_out) { var cwt = new ConditionalWeakTable<object, object>(); var key = new object(); object value = cwt.GetOrCreateValue(key); Assert.True(cwt.TryGetValue(key, out value)); Assert.Equal(value, cwt.GetValue(key, k => new object())); val_out = new WeakReference<object>(value, false); key_out = new WeakReference<object>(key, false); } [Fact] public static void GetOrCreateValue() { WeakReference<object> wrValue; WeakReference<object> wrKey; GetWeakRefPair(out wrKey, out wrValue); GC.Collect(); // key and value must be collected object obj; Assert.False(wrValue.TryGetTarget(out obj)); Assert.False(wrKey.TryGetTarget(out obj)); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static void GetWeakRefValPair(out WeakReference<object> key_out, out WeakReference<object> val_out) { var cwt = new ConditionalWeakTable<object, object>(); var key = new object(); object value = cwt.GetValue(key, k => new object()); Assert.True(cwt.TryGetValue(key, out value)); Assert.Equal(value, cwt.GetOrCreateValue(key)); val_out = new WeakReference<object>(value, false); key_out = new WeakReference<object>(key, false); } [Fact] public static void GetValue() { WeakReference<object> wrValue; WeakReference<object> wrKey; GetWeakRefValPair(out wrKey, out wrValue); GC.Collect(); // key and value must be collected object obj; Assert.False(wrValue.TryGetTarget(out obj)); Assert.False(wrKey.TryGetTarget(out obj)); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(100)] public static void Clear_AllValuesRemoved(int numObjects) { var cwt = new ConditionalWeakTable<object, object>(); MethodInfo clear = cwt.GetType().GetMethod("Clear", BindingFlags.NonPublic | BindingFlags.Instance); if (clear == null) { // Couldn't access the Clear method; skip the test. return; } object[] keys = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); object[] values = Enumerable.Range(0, numObjects).Select(_ => new object()).ToArray(); for (int iter = 0; iter < 2; iter++) { // Add the objects for (int i = 0; i < numObjects; i++) { cwt.Add(keys[i], values[i]); Assert.Same(values[i], cwt.GetValue(keys[i], _ => new object())); } // Clear the table clear.Invoke(cwt, null); // Verify the objects are removed for (int i = 0; i < numObjects; i++) { object ignored; Assert.False(cwt.TryGetValue(keys[i], out ignored)); } // Do it a couple of times, to make sure the table is still usable after a clear. } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using 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.Retail.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCatalogServiceClientTest { [xunit::FactAttribute] public void UpdateCatalogRequestObject() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); UpdateCatalogRequest request = new UpdateCatalogRequest { Catalog = new Catalog(), UpdateMask = new wkt::FieldMask(), }; Catalog expectedResponse = new Catalog { CatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), DisplayName = "display_name137f65c2", ProductLevelConfig = new ProductLevelConfig(), }; mockGrpcClient.Setup(x => x.UpdateCatalog(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); Catalog response = client.UpdateCatalog(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateCatalogRequestObjectAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); UpdateCatalogRequest request = new UpdateCatalogRequest { Catalog = new Catalog(), UpdateMask = new wkt::FieldMask(), }; Catalog expectedResponse = new Catalog { CatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), DisplayName = "display_name137f65c2", ProductLevelConfig = new ProductLevelConfig(), }; mockGrpcClient.Setup(x => x.UpdateCatalogAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Catalog>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); Catalog responseCallSettings = await client.UpdateCatalogAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Catalog responseCancellationToken = await client.UpdateCatalogAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateCatalog() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); UpdateCatalogRequest request = new UpdateCatalogRequest { Catalog = new Catalog(), UpdateMask = new wkt::FieldMask(), }; Catalog expectedResponse = new Catalog { CatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), DisplayName = "display_name137f65c2", ProductLevelConfig = new ProductLevelConfig(), }; mockGrpcClient.Setup(x => x.UpdateCatalog(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); Catalog response = client.UpdateCatalog(request.Catalog, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateCatalogAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); UpdateCatalogRequest request = new UpdateCatalogRequest { Catalog = new Catalog(), UpdateMask = new wkt::FieldMask(), }; Catalog expectedResponse = new Catalog { CatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), DisplayName = "display_name137f65c2", ProductLevelConfig = new ProductLevelConfig(), }; mockGrpcClient.Setup(x => x.UpdateCatalogAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Catalog>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); Catalog responseCallSettings = await client.UpdateCatalogAsync(request.Catalog, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Catalog responseCancellationToken = await client.UpdateCatalogAsync(request.Catalog, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetDefaultBranchRequestObject() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), BranchIdAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Note = "noteca53d6aa", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.SetDefaultBranch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); client.SetDefaultBranch(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetDefaultBranchRequestObjectAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), BranchIdAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), Note = "noteca53d6aa", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.SetDefaultBranchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); await client.SetDefaultBranchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.SetDefaultBranchAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetDefaultBranch() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.SetDefaultBranch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); client.SetDefaultBranch(request.Catalog); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetDefaultBranchAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.SetDefaultBranchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); await client.SetDefaultBranchAsync(request.Catalog, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.SetDefaultBranchAsync(request.Catalog, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetDefaultBranchResourceNames() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.SetDefaultBranch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); client.SetDefaultBranch(request.CatalogAsCatalogName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetDefaultBranchResourceNamesAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); SetDefaultBranchRequest request = new SetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.SetDefaultBranchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); await client.SetDefaultBranchAsync(request.CatalogAsCatalogName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.SetDefaultBranchAsync(request.CatalogAsCatalogName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDefaultBranchRequestObject() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; GetDefaultBranchResponse expectedResponse = new GetDefaultBranchResponse { BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), SetTime = new wkt::Timestamp(), Note = "noteca53d6aa", }; mockGrpcClient.Setup(x => x.GetDefaultBranch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); GetDefaultBranchResponse response = client.GetDefaultBranch(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDefaultBranchRequestObjectAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; GetDefaultBranchResponse expectedResponse = new GetDefaultBranchResponse { BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), SetTime = new wkt::Timestamp(), Note = "noteca53d6aa", }; mockGrpcClient.Setup(x => x.GetDefaultBranchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetDefaultBranchResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); GetDefaultBranchResponse responseCallSettings = await client.GetDefaultBranchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GetDefaultBranchResponse responseCancellationToken = await client.GetDefaultBranchAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDefaultBranch() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; GetDefaultBranchResponse expectedResponse = new GetDefaultBranchResponse { BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), SetTime = new wkt::Timestamp(), Note = "noteca53d6aa", }; mockGrpcClient.Setup(x => x.GetDefaultBranch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); GetDefaultBranchResponse response = client.GetDefaultBranch(request.Catalog); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDefaultBranchAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; GetDefaultBranchResponse expectedResponse = new GetDefaultBranchResponse { BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), SetTime = new wkt::Timestamp(), Note = "noteca53d6aa", }; mockGrpcClient.Setup(x => x.GetDefaultBranchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetDefaultBranchResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); GetDefaultBranchResponse responseCallSettings = await client.GetDefaultBranchAsync(request.Catalog, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GetDefaultBranchResponse responseCancellationToken = await client.GetDefaultBranchAsync(request.Catalog, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetDefaultBranchResourceNames() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; GetDefaultBranchResponse expectedResponse = new GetDefaultBranchResponse { BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), SetTime = new wkt::Timestamp(), Note = "noteca53d6aa", }; mockGrpcClient.Setup(x => x.GetDefaultBranch(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); GetDefaultBranchResponse response = client.GetDefaultBranch(request.CatalogAsCatalogName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetDefaultBranchResourceNamesAsync() { moq::Mock<CatalogService.CatalogServiceClient> mockGrpcClient = new moq::Mock<CatalogService.CatalogServiceClient>(moq::MockBehavior.Strict); GetDefaultBranchRequest request = new GetDefaultBranchRequest { CatalogAsCatalogName = CatalogName.FromProjectLocationCatalog("[PROJECT]", "[LOCATION]", "[CATALOG]"), }; GetDefaultBranchResponse expectedResponse = new GetDefaultBranchResponse { BranchAsBranchName = BranchName.FromProjectLocationCatalogBranch("[PROJECT]", "[LOCATION]", "[CATALOG]", "[BRANCH]"), SetTime = new wkt::Timestamp(), Note = "noteca53d6aa", }; mockGrpcClient.Setup(x => x.GetDefaultBranchAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GetDefaultBranchResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CatalogServiceClient client = new CatalogServiceClientImpl(mockGrpcClient.Object, null); GetDefaultBranchResponse responseCallSettings = await client.GetDefaultBranchAsync(request.CatalogAsCatalogName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GetDefaultBranchResponse responseCancellationToken = await client.GetDefaultBranchAsync(request.CatalogAsCatalogName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.ApplicationFramework { /// <summary> /// Summary description for ColorPopup. /// </summary> public class ColorPopup : System.Windows.Forms.UserControl { private Color m_color = Color.Empty; private Bitmap m_dropDownArrow = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.BlackDropArrow.png"); private Bitmap m_buttonOutlineHover = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.ToolbarButtonHover.png"); private Bitmap m_buttonOutlinePressed = ResourceHelper.LoadAssemblyResourceBitmap("Images.HIG.ToolbarButtonPressed.png"); private bool m_hover = false; private bool m_pressed = false; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ColorPopup() { // enable double buffered painting. SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } public Color Color { get { return m_color; } set { m_color = value; if (ColorSelected != null) ColorSelected(this, new ColorSelectedEventArgs(value)); Invalidate(); } } public Color EffectiveColor { get { if (m_color == Color.Empty) return Color.FromArgb(86, 150, 172); else return m_color; } } public event ColorSelectedEventHandler ColorSelected; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // ColorPopup // this.Name = "ColorPopup"; this.Size = new System.Drawing.Size(150, 40); this.Text = "&Color Scheme"; } #endregion public void AutoSizeForm() { using (Graphics g = Graphics.FromHwnd(User32.GetDesktopWindow())) { StringFormat sf = new StringFormat(StringFormat.GenericDefault); sf.HotkeyPrefix = ShowKeyboardCues ? HotkeyPrefix.Show : HotkeyPrefix.Hide; SizeF size = g.MeasureString(Text, Font, new PointF(0, 0), sf); Width = PADDING*2 + GUTTER_SIZE*2 + COLOR_SIZE + (int)Math.Ceiling(size.Width) + m_dropDownArrow.Width; Height = PADDING*2 + COLOR_SIZE; } } protected override void OnResize(EventArgs e) { base.OnResize (e); Invalidate(); } protected override void OnMouseEnter(EventArgs e) { base.OnMouseEnter (e); m_hover = true; Invalidate(); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave (e); m_hover = false; Invalidate(); } const int PADDING = 6; const int GUTTER_SIZE = 3; const int COLOR_SIZE = 14; protected override void OnPaint(PaintEventArgs e) { BidiGraphics g = new BidiGraphics(e.Graphics, ClientRectangle); if (m_pressed) { SystemButtonHelper.DrawSystemButtonFacePushed(g, false, ClientRectangle, false); } else if (m_hover) { SystemButtonHelper.DrawSystemButtonFace(g, false, false, ClientRectangle, false); } Rectangle colorRect = new Rectangle(PADDING, PADDING, COLOR_SIZE, COLOR_SIZE); Rectangle dropDownArrowRect = new Rectangle(Width - PADDING - m_dropDownArrow.Width, PADDING, m_dropDownArrow.Width, colorRect.Height); Rectangle textRect = new Rectangle(PADDING + GUTTER_SIZE + colorRect.Width, PADDING, Width - (PADDING + GUTTER_SIZE + colorRect.Width) - (PADDING + GUTTER_SIZE + dropDownArrowRect.Width), colorRect.Height); using (Brush b = new SolidBrush(EffectiveColor)) g.FillRectangle(b, colorRect); using (Pen p = new Pen(SystemColors.Highlight, 1)) g.DrawRectangle(p, colorRect); g.DrawText(Text, Font, textRect, SystemColors.ControlText, ShowKeyboardCues ? TextFormatFlags.Default : TextFormatFlags.NoPrefix); g.DrawImage(false, m_dropDownArrow, RectangleHelper.Center(m_dropDownArrow.Size, dropDownArrowRect, false), 0, 0, m_dropDownArrow.Width, m_dropDownArrow.Height, GraphicsUnit.Pixel); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown (e); ColorPickerForm form = new ColorPickerForm(); form.Color = Color; form.ColorSelected += new ColorSelectedEventHandler(form_ColorSelected); form.Closed += new EventHandler(form_Closed); form.TopMost = true; form.StartPosition = FormStartPosition.Manual; Point p = PointToScreen(new Point(0, Height)); form.Location = p; form.Show(); m_pressed = true; Invalidate(); } private void form_ColorSelected(object sender, ColorSelectedEventArgs args) { Color = args.SelectedColor; } private void form_Closed(object sender, EventArgs e) { m_pressed = false; Invalidate(); } } }
// This file has been generated by the GUI designer. Do not modify. namespace Moscrif.IDE.Option { internal partial class GlobalOptionsWidget { private global::Gtk.VBox vbox3; private global::Gtk.Table table1; private global::Gtk.ColorButton cbBackground; private global::Gtk.CheckButton chbAutoselectProject; private global::Gtk.CheckButton chbOpenLastOpenedW; private global::Gtk.CheckButton chbShowDebugDevic; private global::Gtk.CheckButton chbShowUnsupportDevic; private global::Gtk.FontButton fontbutton1; private global::Gtk.Label label1; private global::Gtk.Label label2; private global::Gtk.Label label3; private global::Gtk.Label label4; private global::Gtk.Label label6; private global::Gtk.Notebook notebook1; private global::Gtk.Frame frame1; private global::Gtk.Alignment GtkAlignment2; private global::Gtk.HBox hbox1; private global::Gtk.Label label5; private global::Gtk.ScrolledWindow GtkScrolledWindow1; private global::Gtk.TreeView tvIgnoreFolder; private global::Gtk.VButtonBox vbuttonbox1; private global::Gtk.Button btnAddIF; private global::Gtk.Button btnEditIF; private global::Gtk.Button btnDeleteIF; private global::Gtk.Button button8; private global::Gtk.Label GtkLabel11; private global::Gtk.Label label7; private global::Gtk.Frame frame2; private global::Gtk.Alignment GtkAlignment3; private global::Gtk.HBox hbox2; private global::Gtk.Label labelFi; private global::Gtk.ScrolledWindow GtkScrolledWindow2; private global::Gtk.TreeView tvIgnoreFiles; private global::Gtk.VButtonBox vbuttonbox2; private global::Gtk.Button btnAddIFi; private global::Gtk.Button btnEditIFi; private global::Gtk.Button btnDeleteIFi; private global::Gtk.Button btnResetIFi; private global::Gtk.Label GtkLabel16; private global::Gtk.Label label8; protected virtual void Build () { global::Stetic.Gui.Initialize (this); // Widget Moscrif.IDE.Option.GlobalOptionsWidget global::Stetic.BinContainer.Attach (this); this.Name = "Moscrif.IDE.Option.GlobalOptionsWidget"; // Container child Moscrif.IDE.Option.GlobalOptionsWidget.Gtk.Container+ContainerChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.table1 = new global::Gtk.Table (((uint)(10)), ((uint)(3)), false); this.table1.Name = "table1"; this.table1.RowSpacing = ((uint)(6)); this.table1.ColumnSpacing = ((uint)(6)); // Container child table1.Gtk.Table+TableChild this.cbBackground = new global::Gtk.ColorButton (); this.cbBackground.CanFocus = true; this.cbBackground.Events = ((global::Gdk.EventMask)(784)); this.cbBackground.Name = "cbBackground"; this.table1.Add (this.cbBackground); global::Gtk.Table.TableChild w1 = ((global::Gtk.Table.TableChild)(this.table1 [this.cbBackground])); w1.TopAttach = ((uint)(3)); w1.BottomAttach = ((uint)(4)); w1.LeftAttach = ((uint)(1)); w1.RightAttach = ((uint)(2)); w1.XOptions = ((global::Gtk.AttachOptions)(4)); w1.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.chbAutoselectProject = new global::Gtk.CheckButton (); this.chbAutoselectProject.CanFocus = true; this.chbAutoselectProject.Name = "chbAutoselectProject"; this.chbAutoselectProject.Label = global::Mono.Unix.Catalog.GetString ("Auto select project"); this.chbAutoselectProject.DrawIndicator = true; this.chbAutoselectProject.UseUnderline = true; this.table1.Add (this.chbAutoselectProject); global::Gtk.Table.TableChild w2 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbAutoselectProject])); w2.TopAttach = ((uint)(4)); w2.BottomAttach = ((uint)(5)); w2.LeftAttach = ((uint)(1)); w2.RightAttach = ((uint)(2)); w2.XOptions = ((global::Gtk.AttachOptions)(4)); w2.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.chbOpenLastOpenedW = new global::Gtk.CheckButton (); this.chbOpenLastOpenedW.CanFocus = true; this.chbOpenLastOpenedW.Name = "chbOpenLastOpenedW"; this.chbOpenLastOpenedW.Label = global::Mono.Unix.Catalog.GetString ("Open last opened workspace."); this.chbOpenLastOpenedW.DrawIndicator = true; this.chbOpenLastOpenedW.UseUnderline = true; this.table1.Add (this.chbOpenLastOpenedW); global::Gtk.Table.TableChild w3 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbOpenLastOpenedW])); w3.TopAttach = ((uint)(5)); w3.BottomAttach = ((uint)(6)); w3.LeftAttach = ((uint)(1)); w3.RightAttach = ((uint)(2)); w3.XOptions = ((global::Gtk.AttachOptions)(4)); w3.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.chbShowDebugDevic = new global::Gtk.CheckButton (); this.chbShowDebugDevic.CanFocus = true; this.chbShowDebugDevic.Name = "chbShowDebugDevic"; this.chbShowDebugDevic.Label = global::Mono.Unix.Catalog.GetString ("Show beta platforms."); this.chbShowDebugDevic.DrawIndicator = true; this.chbShowDebugDevic.UseUnderline = true; this.table1.Add (this.chbShowDebugDevic); global::Gtk.Table.TableChild w4 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowDebugDevic])); w4.TopAttach = ((uint)(7)); w4.BottomAttach = ((uint)(8)); w4.LeftAttach = ((uint)(1)); w4.RightAttach = ((uint)(2)); w4.XOptions = ((global::Gtk.AttachOptions)(4)); w4.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.chbShowUnsupportDevic = new global::Gtk.CheckButton (); this.chbShowUnsupportDevic.CanFocus = true; this.chbShowUnsupportDevic.Name = "chbShowUnsupportDevic"; this.chbShowUnsupportDevic.Label = global::Mono.Unix.Catalog.GetString ("Show obsolete platforms."); this.chbShowUnsupportDevic.DrawIndicator = true; this.chbShowUnsupportDevic.UseUnderline = true; this.table1.Add (this.chbShowUnsupportDevic); global::Gtk.Table.TableChild w5 = ((global::Gtk.Table.TableChild)(this.table1 [this.chbShowUnsupportDevic])); w5.TopAttach = ((uint)(6)); w5.BottomAttach = ((uint)(7)); w5.LeftAttach = ((uint)(1)); w5.RightAttach = ((uint)(2)); w5.XOptions = ((global::Gtk.AttachOptions)(4)); w5.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.fontbutton1 = new global::Gtk.FontButton (); this.fontbutton1.CanFocus = true; this.fontbutton1.Name = "fontbutton1"; this.fontbutton1.FontName = "Monospace 10"; this.fontbutton1.ShowStyle = false; this.fontbutton1.UseFont = true; this.fontbutton1.UseSize = true; this.table1.Add (this.fontbutton1); global::Gtk.Table.TableChild w6 = ((global::Gtk.Table.TableChild)(this.table1 [this.fontbutton1])); w6.TopAttach = ((uint)(8)); w6.BottomAttach = ((uint)(9)); w6.LeftAttach = ((uint)(1)); w6.RightAttach = ((uint)(2)); w6.XOptions = ((global::Gtk.AttachOptions)(4)); w6.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.Xalign = 1F; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Color :"); this.table1.Add (this.label1); global::Gtk.Table.TableChild w7 = ((global::Gtk.Table.TableChild)(this.table1 [this.label1])); w7.TopAttach = ((uint)(3)); w7.BottomAttach = ((uint)(4)); w7.XOptions = ((global::Gtk.AttachOptions)(4)); w7.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label2 = new global::Gtk.Label (); this.label2.TooltipMarkup = "Path to Publish Tools"; this.label2.Name = "label2"; this.label2.Xalign = 1F; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("Publish Tools :"); this.table1.Add (this.label2); global::Gtk.Table.TableChild w8 = ((global::Gtk.Table.TableChild)(this.table1 [this.label2])); w8.XOptions = ((global::Gtk.AttachOptions)(4)); w8.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label3 = new global::Gtk.Label (); this.label3.TooltipMarkup = "Path to Framework"; this.label3.Name = "label3"; this.label3.Xalign = 1F; this.label3.LabelProp = global::Mono.Unix.Catalog.GetString ("Libs Directory :"); this.table1.Add (this.label3); global::Gtk.Table.TableChild w9 = ((global::Gtk.Table.TableChild)(this.table1 [this.label3])); w9.TopAttach = ((uint)(1)); w9.BottomAttach = ((uint)(2)); w9.XOptions = ((global::Gtk.AttachOptions)(4)); w9.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label4 = new global::Gtk.Label (); this.label4.TooltipMarkup = "Path to Emulator and Compiler"; this.label4.Name = "label4"; this.label4.Xalign = 1F; this.label4.LabelProp = global::Mono.Unix.Catalog.GetString ("Emulator :"); this.table1.Add (this.label4); global::Gtk.Table.TableChild w10 = ((global::Gtk.Table.TableChild)(this.table1 [this.label4])); w10.TopAttach = ((uint)(2)); w10.BottomAttach = ((uint)(3)); w10.XOptions = ((global::Gtk.AttachOptions)(4)); w10.YOptions = ((global::Gtk.AttachOptions)(4)); // Container child table1.Gtk.Table+TableChild this.label6 = new global::Gtk.Label (); this.label6.Name = "label6"; this.label6.Xalign = 1F; this.label6.LabelProp = global::Mono.Unix.Catalog.GetString ("Console and task font :"); this.table1.Add (this.label6); global::Gtk.Table.TableChild w11 = ((global::Gtk.Table.TableChild)(this.table1 [this.label6])); w11.TopAttach = ((uint)(8)); w11.BottomAttach = ((uint)(9)); w11.XOptions = ((global::Gtk.AttachOptions)(4)); w11.YOptions = ((global::Gtk.AttachOptions)(4)); this.vbox3.Add (this.table1); global::Gtk.Box.BoxChild w12 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.table1])); w12.Position = 0; // Container child vbox3.Gtk.Box+BoxChild this.notebook1 = new global::Gtk.Notebook (); this.notebook1.CanFocus = true; this.notebook1.Name = "notebook1"; this.notebook1.CurrentPage = 0; // Container child notebook1.Gtk.Notebook+NotebookChild this.frame1 = new global::Gtk.Frame (); this.frame1.Name = "frame1"; this.frame1.BorderWidth = ((uint)(1)); // Container child frame1.Gtk.Container+ContainerChild this.GtkAlignment2 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment2.Name = "GtkAlignment2"; this.GtkAlignment2.LeftPadding = ((uint)(12)); // Container child GtkAlignment2.Gtk.Container+ContainerChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.HeightRequest = 102; this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.label5 = new global::Gtk.Label (); this.label5.Name = "label5"; this.label5.Xalign = 1F; this.label5.LabelProp = global::Mono.Unix.Catalog.GetString ("Ignored :"); this.hbox1.Add (this.label5); global::Gtk.Box.BoxChild w13 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.label5])); w13.Position = 0; w13.Expand = false; w13.Fill = false; // Container child hbox1.Gtk.Box+BoxChild this.GtkScrolledWindow1 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow1.Name = "GtkScrolledWindow1"; this.GtkScrolledWindow1.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow1.Gtk.Container+ContainerChild this.tvIgnoreFolder = new global::Gtk.TreeView (); this.tvIgnoreFolder.CanFocus = true; this.tvIgnoreFolder.Name = "tvIgnoreFolder"; this.GtkScrolledWindow1.Add (this.tvIgnoreFolder); this.hbox1.Add (this.GtkScrolledWindow1); global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.GtkScrolledWindow1])); w15.Position = 1; // Container child hbox1.Gtk.Box+BoxChild this.vbuttonbox1 = new global::Gtk.VButtonBox (); this.vbuttonbox1.Name = "vbuttonbox1"; this.vbuttonbox1.Spacing = -1; this.vbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(3)); // Container child vbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnAddIF = new global::Gtk.Button (); this.btnAddIF.CanFocus = true; this.btnAddIF.Name = "btnAddIF"; this.btnAddIF.UseUnderline = true; this.btnAddIF.Label = global::Mono.Unix.Catalog.GetString ("Add"); this.vbuttonbox1.Add (this.btnAddIF); global::Gtk.ButtonBox.ButtonBoxChild w16 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox1 [this.btnAddIF])); w16.Expand = false; w16.Fill = false; // Container child vbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnEditIF = new global::Gtk.Button (); this.btnEditIF.CanFocus = true; this.btnEditIF.Name = "btnEditIF"; this.btnEditIF.UseUnderline = true; this.btnEditIF.Label = global::Mono.Unix.Catalog.GetString ("Edit"); this.vbuttonbox1.Add (this.btnEditIF); global::Gtk.ButtonBox.ButtonBoxChild w17 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox1 [this.btnEditIF])); w17.Position = 1; w17.Expand = false; w17.Fill = false; // Container child vbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btnDeleteIF = new global::Gtk.Button (); this.btnDeleteIF.CanFocus = true; this.btnDeleteIF.Name = "btnDeleteIF"; this.btnDeleteIF.UseUnderline = true; this.btnDeleteIF.Label = global::Mono.Unix.Catalog.GetString ("Delete"); this.vbuttonbox1.Add (this.btnDeleteIF); global::Gtk.ButtonBox.ButtonBoxChild w18 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox1 [this.btnDeleteIF])); w18.Position = 2; w18.Expand = false; w18.Fill = false; // Container child vbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.button8 = new global::Gtk.Button (); this.button8.CanFocus = true; this.button8.Name = "button8"; this.button8.UseUnderline = true; this.button8.Label = global::Mono.Unix.Catalog.GetString ("Reset"); this.vbuttonbox1.Add (this.button8); global::Gtk.ButtonBox.ButtonBoxChild w19 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox1 [this.button8])); w19.Position = 3; w19.Expand = false; w19.Fill = false; this.hbox1.Add (this.vbuttonbox1); global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vbuttonbox1])); w20.Position = 2; w20.Expand = false; w20.Fill = false; this.GtkAlignment2.Add (this.hbox1); this.frame1.Add (this.GtkAlignment2); this.GtkLabel11 = new global::Gtk.Label (); this.GtkLabel11.Name = "GtkLabel11"; this.GtkLabel11.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Ignore Folder</b>"); this.GtkLabel11.UseMarkup = true; this.frame1.LabelWidget = this.GtkLabel11; this.notebook1.Add (this.frame1); // Notebook tab this.label7 = new global::Gtk.Label (); this.label7.Name = "label7"; this.label7.LabelProp = global::Mono.Unix.Catalog.GetString ("Ignore Folder"); this.notebook1.SetTabLabel (this.frame1, this.label7); this.label7.ShowAll (); // Container child notebook1.Gtk.Notebook+NotebookChild this.frame2 = new global::Gtk.Frame (); this.frame2.Name = "frame2"; this.frame2.BorderWidth = ((uint)(1)); // Container child frame2.Gtk.Container+ContainerChild this.GtkAlignment3 = new global::Gtk.Alignment (0F, 0F, 1F, 1F); this.GtkAlignment3.Name = "GtkAlignment3"; this.GtkAlignment3.LeftPadding = ((uint)(12)); // Container child GtkAlignment3.Gtk.Container+ContainerChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.HeightRequest = 102; this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; // Container child hbox2.Gtk.Box+BoxChild this.labelFi = new global::Gtk.Label (); this.labelFi.Name = "labelFi"; this.labelFi.Xalign = 1F; this.labelFi.LabelProp = global::Mono.Unix.Catalog.GetString ("Ignored :"); this.hbox2.Add (this.labelFi); global::Gtk.Box.BoxChild w24 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.labelFi])); w24.Position = 0; w24.Expand = false; w24.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.GtkScrolledWindow2 = new global::Gtk.ScrolledWindow (); this.GtkScrolledWindow2.Name = "GtkScrolledWindow2"; this.GtkScrolledWindow2.ShadowType = ((global::Gtk.ShadowType)(1)); // Container child GtkScrolledWindow2.Gtk.Container+ContainerChild this.tvIgnoreFiles = new global::Gtk.TreeView (); this.tvIgnoreFiles.CanFocus = true; this.tvIgnoreFiles.Name = "tvIgnoreFiles"; this.GtkScrolledWindow2.Add (this.tvIgnoreFiles); this.hbox2.Add (this.GtkScrolledWindow2); global::Gtk.Box.BoxChild w26 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.GtkScrolledWindow2])); w26.Position = 1; // Container child hbox2.Gtk.Box+BoxChild this.vbuttonbox2 = new global::Gtk.VButtonBox (); this.vbuttonbox2.Name = "vbuttonbox2"; this.vbuttonbox2.Spacing = -1; this.vbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(3)); // Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btnAddIFi = new global::Gtk.Button (); this.btnAddIFi.CanFocus = true; this.btnAddIFi.Name = "btnAddIFi"; this.btnAddIFi.UseUnderline = true; this.btnAddIFi.Label = global::Mono.Unix.Catalog.GetString ("Add"); this.vbuttonbox2.Add (this.btnAddIFi); global::Gtk.ButtonBox.ButtonBoxChild w27 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2 [this.btnAddIFi])); w27.Expand = false; w27.Fill = false; // Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btnEditIFi = new global::Gtk.Button (); this.btnEditIFi.CanFocus = true; this.btnEditIFi.Name = "btnEditIFi"; this.btnEditIFi.UseUnderline = true; this.btnEditIFi.Label = global::Mono.Unix.Catalog.GetString ("Edit"); this.vbuttonbox2.Add (this.btnEditIFi); global::Gtk.ButtonBox.ButtonBoxChild w28 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2 [this.btnEditIFi])); w28.Position = 1; w28.Expand = false; w28.Fill = false; // Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btnDeleteIFi = new global::Gtk.Button (); this.btnDeleteIFi.CanFocus = true; this.btnDeleteIFi.Name = "btnDeleteIFi"; this.btnDeleteIFi.UseUnderline = true; this.btnDeleteIFi.Label = global::Mono.Unix.Catalog.GetString ("Delete"); this.vbuttonbox2.Add (this.btnDeleteIFi); global::Gtk.ButtonBox.ButtonBoxChild w29 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2 [this.btnDeleteIFi])); w29.Position = 2; w29.Expand = false; w29.Fill = false; // Container child vbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btnResetIFi = new global::Gtk.Button (); this.btnResetIFi.CanFocus = true; this.btnResetIFi.Name = "btnResetIFi"; this.btnResetIFi.UseUnderline = true; this.btnResetIFi.Label = global::Mono.Unix.Catalog.GetString ("Reset"); this.vbuttonbox2.Add (this.btnResetIFi); global::Gtk.ButtonBox.ButtonBoxChild w30 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.vbuttonbox2 [this.btnResetIFi])); w30.Position = 3; w30.Expand = false; w30.Fill = false; this.hbox2.Add (this.vbuttonbox2); global::Gtk.Box.BoxChild w31 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.vbuttonbox2])); w31.Position = 2; w31.Expand = false; w31.Fill = false; this.GtkAlignment3.Add (this.hbox2); this.frame2.Add (this.GtkAlignment3); this.GtkLabel16 = new global::Gtk.Label (); this.GtkLabel16.Name = "GtkLabel16"; this.GtkLabel16.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Ignore Files</b>"); this.GtkLabel16.UseMarkup = true; this.frame2.LabelWidget = this.GtkLabel16; this.notebook1.Add (this.frame2); global::Gtk.Notebook.NotebookChild w34 = ((global::Gtk.Notebook.NotebookChild)(this.notebook1 [this.frame2])); w34.Position = 1; // Notebook tab this.label8 = new global::Gtk.Label (); this.label8.Name = "label8"; this.label8.LabelProp = global::Mono.Unix.Catalog.GetString ("Ignore Files"); this.notebook1.SetTabLabel (this.frame2, this.label8); this.label8.ShowAll (); this.vbox3.Add (this.notebook1); global::Gtk.Box.BoxChild w35 = ((global::Gtk.Box.BoxChild)(this.vbox3 [this.notebook1])); w35.Position = 1; w35.Expand = false; w35.Fill = false; this.Add (this.vbox3); if ((this.Child != null)) { this.Child.ShowAll (); } this.Hide (); this.btnAddIF.Clicked += new global::System.EventHandler (this.OnBtnAddIFClicked); this.btnEditIF.Clicked += new global::System.EventHandler (this.OnBtnEditIFClicked); this.btnDeleteIF.Clicked += new global::System.EventHandler (this.OnBtnDeleteIFClicked); this.button8.Clicked += new global::System.EventHandler (this.OnButton8Clicked); this.btnAddIFi.Clicked += new global::System.EventHandler (this.OnBtnAddIFiClicked); this.btnEditIFi.Clicked += new global::System.EventHandler (this.OnBtnEditIFiClicked); this.btnDeleteIFi.Clicked += new global::System.EventHandler (this.OnBtnDeleteIFiClicked); this.btnResetIFi.Clicked += new global::System.EventHandler (this.OnBtnResetIFiClicked); } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Xml; namespace tk2dEditor.Font { // Internal structures to fill and process public class Char { public int id = 0, x = 0, y = 0, width = 0, height = 0, xoffset = 0, yoffset = 0, xadvance = 0; public int texOffsetX, texOffsetY; public int texX, texY, texW, texH; public bool texFlipped; public bool texOverride; public int channel = 0; }; public class Kerning { public int first = 0, second = 0, amount = 0; }; public class Info { public string[] texturePaths = new string[0]; public int scaleW = 0, scaleH = 0; public int lineHeight = 0; public int numPages = 0; public bool isPacked = false; public float textureScale = 1; public List<Char> chars = new List<Char>(); public List<Kerning> kernings = new List<Kerning>(); }; class BMFontXmlImporter { static int ReadIntAttribute(XmlNode node, string attribute) { return int.Parse(node.Attributes[attribute].Value, System.Globalization.NumberFormatInfo.InvariantInfo); } static float ReadFloatAttribute(XmlNode node, string attribute) { return float.Parse(node.Attributes[attribute].Value, System.Globalization.NumberFormatInfo.InvariantInfo); } static string ReadStringAttribute(XmlNode node, string attribute) { return node.Attributes[attribute].Value; } static Vector2 ReadVector2Attributes(XmlNode node, string attributeX, string attributeY) { return new Vector2(ReadFloatAttribute(node, attributeX), ReadFloatAttribute(node, attributeY)); } static bool HasAttribute(XmlNode node, string attribute) { return node.Attributes[attribute] != null; } public static Info Parse(string path) { XmlDocument doc = new XmlDocument(); doc.Load(path); Info fontInfo = new Info(); XmlNode nodeCommon = doc.SelectSingleNode("/font/common"); fontInfo.scaleW = ReadIntAttribute(nodeCommon, "scaleW"); fontInfo.scaleH = ReadIntAttribute(nodeCommon, "scaleH"); fontInfo.lineHeight = ReadIntAttribute(nodeCommon, "lineHeight"); int pages = ReadIntAttribute(nodeCommon, "pages"); if (pages != 1) { EditorUtility.DisplayDialog("Fatal error", "Only one page supported in font. Please change the setting and re-export.", "Ok"); return null; } fontInfo.numPages = pages; fontInfo.texturePaths = new string[pages]; for (int i = 0; i < pages; ++i) fontInfo.texturePaths[i] = string.Empty; foreach (XmlNode node in doc.SelectNodes("/font/pages/page")) { int id = ReadIntAttribute(node, "id"); fontInfo.texturePaths[id] = ReadStringAttribute(node, "file"); } foreach (XmlNode node in doc.SelectNodes(("/font/chars/char"))) { Char thisChar = new Char(); thisChar.id = ReadIntAttribute(node, "id"); thisChar.x = ReadIntAttribute(node, "x"); thisChar.y = ReadIntAttribute(node, "y"); thisChar.width = ReadIntAttribute(node, "width"); thisChar.height = ReadIntAttribute(node, "height"); thisChar.xoffset = ReadIntAttribute(node, "xoffset"); thisChar.yoffset = ReadIntAttribute(node, "yoffset"); thisChar.xadvance = ReadIntAttribute(node, "xadvance"); thisChar.texOverride = false; if (thisChar.id == -1) thisChar.id = 0; fontInfo.chars.Add(thisChar); } foreach (XmlNode node in doc.SelectNodes("/font/kernings/kerning")) { Kerning thisKerning = new Kerning(); thisKerning.first = ReadIntAttribute(node, "first"); thisKerning.second = ReadIntAttribute(node, "second"); thisKerning.amount = ReadIntAttribute(node, "amount"); fontInfo.kernings.Add(thisKerning); } return fontInfo; } } class BMFontTextImporter { static string FindKeyValue(string[] tokens, string key) { string keyMatch = key + "="; for (int i = 0; i < tokens.Length; ++i) { if (tokens[i].Length > keyMatch.Length && tokens[i].Substring(0, keyMatch.Length) == keyMatch) return tokens[i].Substring(keyMatch.Length); } return ""; } public static Info Parse(string path) { Info fontInfo = new Info(); System.IO.FileInfo finfo = new System.IO.FileInfo(path); System.IO.StreamReader reader = finfo.OpenText(); string line; while ((line = reader.ReadLine()) != null) { string[] tokens = line.Split( ' ' ); if (tokens[0] == "common") { fontInfo.lineHeight = int.Parse( FindKeyValue(tokens, "lineHeight") ); fontInfo.scaleW = int.Parse( FindKeyValue(tokens, "scaleW") ); fontInfo.scaleH = int.Parse( FindKeyValue(tokens, "scaleH") ); int pages = int.Parse( FindKeyValue(tokens, "pages") ); if (pages != 1) { EditorUtility.DisplayDialog("Fatal error", "Only one page supported in font. Please change the setting and re-export.", "Ok"); return null; } fontInfo.numPages = pages; if (FindKeyValue(tokens, "packed") != "") fontInfo.isPacked = int.Parse(FindKeyValue(tokens, "packed")) != 0; fontInfo.texturePaths = new string[pages]; for (int i = 0 ; i < pages; ++i) fontInfo.texturePaths[i] = string.Empty; } else if (tokens[0] == "page") { int id = int.Parse(FindKeyValue(tokens, "id")); string file = FindKeyValue(tokens, "file"); if (file[0] == '"' && file[file.Length - 1] == '"') { file = file.Substring(1, file.Length - 2); } else if (file[0] == '"' && file[file.Length - 1] != '"') { System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(line, "file[\\s]*=[\\s]*\"([^\"]*)\""); try { file = match.Groups[1].Value; } catch { file = ""; } } fontInfo.texturePaths[id] = file; } else if (tokens[0] == "char") { Char thisChar = new Char(); thisChar.id = int.Parse(FindKeyValue(tokens, "id")); thisChar.x = int.Parse(FindKeyValue(tokens, "x")); thisChar.y = int.Parse(FindKeyValue(tokens, "y")); thisChar.width = int.Parse(FindKeyValue(tokens, "width")); thisChar.height = int.Parse(FindKeyValue(tokens, "height")); thisChar.xoffset = int.Parse(FindKeyValue(tokens, "xoffset")); thisChar.yoffset = int.Parse(FindKeyValue(tokens, "yoffset")); thisChar.xadvance = int.Parse(FindKeyValue(tokens, "xadvance")); if (fontInfo.isPacked) { int chnl = int.Parse(FindKeyValue(tokens, "chnl")); thisChar.channel = (int)Mathf.Round(Mathf.Log(chnl) / Mathf.Log(2)); } if (thisChar.id == -1) thisChar.id = 0; fontInfo.chars.Add(thisChar); } else if (tokens[0] == "kerning") { Kerning thisKerning = new Kerning(); thisKerning.first = int.Parse(FindKeyValue(tokens, "first")); thisKerning.second = int.Parse(FindKeyValue(tokens, "second")); thisKerning.amount = int.Parse(FindKeyValue(tokens, "amount")); fontInfo.kernings.Add(thisKerning); } } reader.Close(); return fontInfo; } } public static class Builder { public static Info ParseBMFont(string path) { Info fontInfo = null; try { fontInfo = BMFontXmlImporter.Parse(path); } catch { fontInfo = BMFontTextImporter.Parse(path); } if (fontInfo == null || fontInfo.chars.Count == 0) { Debug.LogError("Font parsing returned 0 characters, check source bmfont file for errors"); return null; } return fontInfo; } public static bool BuildFont(Info fontInfo, tk2dFontData target, float scale, int charPadX, bool dupeCaps, bool flipTextureY, Texture2D gradientTexture, int gradientCount) { float texWidth = fontInfo.scaleW; float texHeight = fontInfo.scaleH; float lineHeight = fontInfo.lineHeight; float texScale = fontInfo.textureScale; target.version = tk2dFontData.CURRENT_VERSION; target.lineHeight = lineHeight * scale; target.texelSize = new Vector2(scale, scale); target.isPacked = fontInfo.isPacked; // Get number of characters (lastindex + 1) int maxCharId = 0; int maxUnicodeChar = 100000; foreach (var theChar in fontInfo.chars) { if (theChar.id > maxUnicodeChar) { // in most cases the font contains unwanted characters! Debug.LogError("Unicode character id exceeds allowed limit: " + theChar.id.ToString() + ". Skipping."); continue; } if (theChar.id > maxCharId) maxCharId = theChar.id; } // decide to use dictionary if necessary // 2048 is a conservative lower floor bool useDictionary = maxCharId > 2048; Dictionary<int, tk2dFontChar> charDict = (useDictionary)?new Dictionary<int, tk2dFontChar>():null; tk2dFontChar[] chars = (useDictionary)?null:new tk2dFontChar[maxCharId + 1]; int minChar = 0x7fffffff; int maxCharWithinBounds = 0; int numLocalChars = 0; float largestWidth = 0.0f; foreach (var theChar in fontInfo.chars) { tk2dFontChar thisChar = new tk2dFontChar(); int id = theChar.id; int x = theChar.x; int y = theChar.y; int width = theChar.width; int height = theChar.height; int xoffset = theChar.xoffset; int yoffset = theChar.yoffset; int xadvance = theChar.xadvance + charPadX; // special case, if the width and height are zero, the origin doesn't need to be offset // handles problematic case highlighted here: // http://2dtoolkit.com/forum/index.php/topic,89.msg220.html if (width == 0 && height == 0) { xoffset = 0; yoffset = 0; } // precompute required data if (theChar.texOverride) { float w = theChar.texW / texScale; float h = theChar.texH / texScale; if (theChar.texFlipped) { h = theChar.texW / texScale; w = theChar.texH / texScale; } float px = (xoffset + theChar.texOffsetX * texScale) * scale; float py = (lineHeight - yoffset - theChar.texOffsetY * texScale) * scale; thisChar.p0 = new Vector3(px, py , 0); thisChar.p1 = new Vector3(px + w * scale, py - h * scale, 0); thisChar.uv0 = new Vector2((theChar.texX) / texWidth, (theChar.texY + theChar.texH) / texHeight); thisChar.uv1 = new Vector2((theChar.texX + theChar.texW) / texWidth, (theChar.texY) / texHeight); if (flipTextureY) { float tmp = 0; if (theChar.texFlipped) { tmp = thisChar.uv1.x; thisChar.uv1.x = thisChar.uv0.x; thisChar.uv0.x = tmp; } else { tmp = thisChar.uv1.y; thisChar.uv1.y = thisChar.uv0.y; thisChar.uv0.y = tmp; } } thisChar.flipped = theChar.texFlipped; } else { float px = xoffset * scale; float py = (lineHeight - yoffset) * scale; thisChar.p0 = new Vector3(px, py, 0); thisChar.p1 = new Vector3(px + width * scale, py - height * scale, 0); if (flipTextureY) { thisChar.uv0 = new Vector2(x / texWidth, y / texHeight); thisChar.uv1 = new Vector2(thisChar.uv0.x + width / texWidth, thisChar.uv0.y + height / texHeight); } else { thisChar.uv0 = new Vector2(x / texWidth, 1.0f - y / texHeight); thisChar.uv1 = new Vector2(thisChar.uv0.x + width / texWidth, thisChar.uv0.y - height / texHeight); } thisChar.flipped = false; } thisChar.advance = xadvance * scale; thisChar.channel = theChar.channel; largestWidth = Mathf.Max(thisChar.advance, largestWidth); // Needs gradient data if (gradientTexture != null) { // build it up assuming the first gradient float x0 = (float)(0.0f / gradientCount); float x1 = (float)(1.0f / gradientCount); float y0 = 1.0f; float y1 = 0.0f; // align to glyph if necessary thisChar.gradientUv = new Vector2[4]; thisChar.gradientUv[0] = new Vector2(x0, y0); thisChar.gradientUv[1] = new Vector2(x1, y0); thisChar.gradientUv[2] = new Vector2(x0, y1); thisChar.gradientUv[3] = new Vector2(x1, y1); } if (id <= maxCharId) { maxCharWithinBounds = (id > maxCharWithinBounds) ? id : maxCharWithinBounds; minChar = (id < minChar) ? id : minChar; if (useDictionary) charDict[id] = thisChar; else chars[id] = thisChar; ++numLocalChars; } } // duplicate capitals to lower case, or vice versa depending on which ones exist if (dupeCaps) { for (int uc = 'A'; uc <= 'Z'; ++uc) { int lc = uc + ('a' - 'A'); if (useDictionary) { if (charDict.ContainsKey(uc)) charDict[lc] = charDict[uc]; else if (charDict.ContainsKey(lc)) charDict[uc] = charDict[lc]; } else { if (chars[lc] == null) chars[lc] = chars[uc]; else if (chars[uc] == null) chars[uc] = chars[lc]; } } } // share null char, same pointer var nullChar = new tk2dFontChar(); nullChar.gradientUv = new Vector2[4]; // this would be null otherwise nullChar.channel = 0; target.largestWidth = largestWidth; if (useDictionary) { // guarantee at least the first 256 characters for (int i = 0; i < 256; ++i) { if (!charDict.ContainsKey(i)) charDict[i] = nullChar; } target.chars = null; target.charDict = null; target.SetDictionary(charDict); target.useDictionary = true; } else { target.chars = new tk2dFontChar[maxCharId + 1]; for (int i = 0; i <= maxCharId; ++i) { target.chars[i] = chars[i]; if (target.chars[i] == null) { target.chars[i] = nullChar; // zero everything, null char } } target.charDict = null; target.useDictionary = false; } // kerning target.kerning = new tk2dFontKerning[fontInfo.kernings.Count]; for (int i = 0; i < target.kerning.Length; ++i) { tk2dFontKerning kerning = new tk2dFontKerning(); kerning.c0 = fontInfo.kernings[i].first; kerning.c1 = fontInfo.kernings[i].second; kerning.amount = fontInfo.kernings[i].amount * scale; target.kerning[i] = kerning; } return true; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using Azure; using Management; using Network; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Linq; /// <summary> /// Peering in an ExpressRouteCircuit resource. /// </summary> [JsonTransformation] public partial class ExpressRouteCircuitPeering : SubResource { /// <summary> /// Initializes a new instance of the ExpressRouteCircuitPeering class. /// </summary> public ExpressRouteCircuitPeering() { } /// <summary> /// Initializes a new instance of the ExpressRouteCircuitPeering class. /// </summary> /// <param name="id">Resource ID.</param> /// <param name="peeringType">The PeeringType. Possible values are: /// 'AzurePublicPeering', 'AzurePrivatePeering', and /// 'MicrosoftPeering'. Possible values include: 'AzurePublicPeering', /// 'AzurePrivatePeering', 'MicrosoftPeering'</param> /// <param name="state">The state of peering. Possible values are: /// 'Disabled' and 'Enabled'. Possible values include: 'Disabled', /// 'Enabled'</param> /// <param name="azureASN">The Azure ASN.</param> /// <param name="peerASN">The peer ASN.</param> /// <param name="primaryPeerAddressPrefix">The primary address /// prefix.</param> /// <param name="secondaryPeerAddressPrefix">The secondary address /// prefix.</param> /// <param name="primaryAzurePort">The primary port.</param> /// <param name="secondaryAzurePort">The secondary port.</param> /// <param name="sharedKey">The shared key.</param> /// <param name="vlanId">The VLAN ID.</param> /// <param name="microsoftPeeringConfig">The Microsoft peering /// configuration.</param> /// <param name="stats">Gets peering stats.</param> /// <param name="provisioningState">Gets the provisioning state of the /// public IP resource. Possible values are: 'Updating', 'Deleting', /// and 'Failed'.</param> /// <param name="gatewayManagerEtag">The GatewayManager Etag.</param> /// <param name="lastModifiedBy">Gets whether the provider or the /// customer last modified the peering.</param> /// <param name="name">Gets name of the resource that is unique within /// a resource group. This name can be used to access the /// resource.</param> /// <param name="etag">A unique read-only string that changes whenever /// the resource is updated.</param> /// <param name="routeFilter">The reference of the RouteFilter /// resource.</param> public ExpressRouteCircuitPeering(string id = default(string), string peeringType = default(string), string state = default(string), int? azureASN = default(int?), int? peerASN = default(int?), string primaryPeerAddressPrefix = default(string), string secondaryPeerAddressPrefix = default(string), string primaryAzurePort = default(string), string secondaryAzurePort = default(string), string sharedKey = default(string), int? vlanId = default(int?), ExpressRouteCircuitPeeringConfig microsoftPeeringConfig = default(ExpressRouteCircuitPeeringConfig), ExpressRouteCircuitStats stats = default(ExpressRouteCircuitStats), string provisioningState = default(string), string gatewayManagerEtag = default(string), string lastModifiedBy = default(string), string name = default(string), string etag = default(string), RouteFilter routeFilter = default(RouteFilter)) : base(id) { PeeringType = peeringType; State = state; AzureASN = azureASN; PeerASN = peerASN; PrimaryPeerAddressPrefix = primaryPeerAddressPrefix; SecondaryPeerAddressPrefix = secondaryPeerAddressPrefix; PrimaryAzurePort = primaryAzurePort; SecondaryAzurePort = secondaryAzurePort; SharedKey = sharedKey; VlanId = vlanId; MicrosoftPeeringConfig = microsoftPeeringConfig; Stats = stats; ProvisioningState = provisioningState; GatewayManagerEtag = gatewayManagerEtag; LastModifiedBy = lastModifiedBy; Name = name; Etag = etag; RouteFilter = routeFilter; } /// <summary> /// Gets or sets the PeeringType. Possible values are: /// 'AzurePublicPeering', 'AzurePrivatePeering', and /// 'MicrosoftPeering'. Possible values include: 'AzurePublicPeering', /// 'AzurePrivatePeering', 'MicrosoftPeering' /// </summary> [JsonProperty(PropertyName = "properties.peeringType")] public string PeeringType { get; set; } /// <summary> /// Gets or sets the state of peering. Possible values are: 'Disabled' /// and 'Enabled'. Possible values include: 'Disabled', 'Enabled' /// </summary> [JsonProperty(PropertyName = "properties.state")] public string State { get; set; } /// <summary> /// Gets or sets the Azure ASN. /// </summary> [JsonProperty(PropertyName = "properties.azureASN")] public int? AzureASN { get; set; } /// <summary> /// Gets or sets the peer ASN. /// </summary> [JsonProperty(PropertyName = "properties.peerASN")] public int? PeerASN { get; set; } /// <summary> /// Gets or sets the primary address prefix. /// </summary> [JsonProperty(PropertyName = "properties.primaryPeerAddressPrefix")] public string PrimaryPeerAddressPrefix { get; set; } /// <summary> /// Gets or sets the secondary address prefix. /// </summary> [JsonProperty(PropertyName = "properties.secondaryPeerAddressPrefix")] public string SecondaryPeerAddressPrefix { get; set; } /// <summary> /// Gets or sets the primary port. /// </summary> [JsonProperty(PropertyName = "properties.primaryAzurePort")] public string PrimaryAzurePort { get; set; } /// <summary> /// Gets or sets the secondary port. /// </summary> [JsonProperty(PropertyName = "properties.secondaryAzurePort")] public string SecondaryAzurePort { get; set; } /// <summary> /// Gets or sets the shared key. /// </summary> [JsonProperty(PropertyName = "properties.sharedKey")] public string SharedKey { get; set; } /// <summary> /// Gets or sets the VLAN ID. /// </summary> [JsonProperty(PropertyName = "properties.vlanId")] public int? VlanId { get; set; } /// <summary> /// Gets or sets the Microsoft peering configuration. /// </summary> [JsonProperty(PropertyName = "properties.microsoftPeeringConfig")] public ExpressRouteCircuitPeeringConfig MicrosoftPeeringConfig { get; set; } /// <summary> /// Gets peering stats. /// </summary> [JsonProperty(PropertyName = "properties.stats")] public ExpressRouteCircuitStats Stats { get; set; } /// <summary> /// Gets the provisioning state of the public IP resource. Possible /// values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; set; } /// <summary> /// Gets or sets the GatewayManager Etag. /// </summary> [JsonProperty(PropertyName = "properties.gatewayManagerEtag")] public string GatewayManagerEtag { get; set; } /// <summary> /// Gets whether the provider or the customer last modified the /// peering. /// </summary> [JsonProperty(PropertyName = "properties.lastModifiedBy")] public string LastModifiedBy { get; set; } /// <summary> /// Gets name of the resource that is unique within a resource group. /// This name can be used to access the resource. /// </summary> [JsonProperty(PropertyName = "name")] public string Name { get; set; } /// <summary> /// Gets a unique read-only string that changes whenever the resource /// is updated. /// </summary> [JsonProperty(PropertyName = "etag")] public string Etag { get; protected set; } /// <summary> /// Gets or sets the reference of the RouteFilter resource. /// </summary> [JsonProperty(PropertyName = "properties.routeFilter")] public RouteFilter RouteFilter { get; set; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.IdentityModel.Selectors { using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Tokens; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; using System.Security; using System.Security.AccessControl; using System.Security.Permissions; using System.Security.Principal; using System.Text; public class X509SecurityTokenAuthenticator : SecurityTokenAuthenticator { X509CertificateValidator validator; bool mapToWindows; bool includeWindowsGroups; bool cloneHandle; public X509SecurityTokenAuthenticator() : this(X509CertificateValidator.ChainTrust) { } public X509SecurityTokenAuthenticator(X509CertificateValidator validator) : this(validator, false) { } public X509SecurityTokenAuthenticator(X509CertificateValidator validator, bool mapToWindows) : this(validator, mapToWindows, WindowsClaimSet.DefaultIncludeWindowsGroups) { } public X509SecurityTokenAuthenticator(X509CertificateValidator validator, bool mapToWindows, bool includeWindowsGroups) : this(validator, mapToWindows, includeWindowsGroups, true) { } internal X509SecurityTokenAuthenticator(X509CertificateValidator validator, bool mapToWindows, bool includeWindowsGroups, bool cloneHandle) { if (validator == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("validator"); } this.validator = validator; this.mapToWindows = mapToWindows; this.includeWindowsGroups = includeWindowsGroups; this.cloneHandle = cloneHandle; } public bool MapCertificateToWindowsAccount { get { return this.mapToWindows; } } protected override bool CanValidateTokenCore(SecurityToken token) { return token is X509SecurityToken; } protected override ReadOnlyCollection<IAuthorizationPolicy> ValidateTokenCore(SecurityToken token) { X509SecurityToken x509Token = (X509SecurityToken)token; this.validator.Validate(x509Token.Certificate); X509CertificateClaimSet x509ClaimSet = new X509CertificateClaimSet(x509Token.Certificate, this.cloneHandle); if (!this.mapToWindows) return SecurityUtils.CreateAuthorizationPolicies(x509ClaimSet, x509Token.ValidTo); WindowsClaimSet windowsClaimSet; if (token is X509WindowsSecurityToken) { windowsClaimSet = new WindowsClaimSet( ( (X509WindowsSecurityToken)token ).WindowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, this.cloneHandle ); } else { // Ensure NT_AUTH chain policy for certificate account mapping X509CertificateValidator.NTAuthChainTrust.Validate(x509Token.Certificate); WindowsIdentity windowsIdentity = null; // for Vista, LsaLogon supporting mapping cert to NTToken if (Environment.OSVersion.Version.Major >= SecurityUtils.WindowsVistaMajorNumber) { windowsIdentity = KerberosCertificateLogon(x509Token.Certificate); } else { // Downlevel, S4U over PrincipalName SubjectAltNames string name = x509Token.Certificate.GetNameInfo(X509NameType.UpnName, false); if (string.IsNullOrEmpty(name)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.GetString(SR.InvalidNtMapping, SecurityUtils.GetCertificateId(x509Token.Certificate)))); } using (WindowsIdentity initialWindowsIdentity = new WindowsIdentity(name, SecurityUtils.AuthTypeCertMap)) { // This is to make sure that the auth Type is shoved down to the class as the above constructor does not do it. windowsIdentity = new WindowsIdentity(initialWindowsIdentity.Token, SecurityUtils.AuthTypeCertMap); } } windowsClaimSet = new WindowsClaimSet(windowsIdentity, SecurityUtils.AuthTypeCertMap, this.includeWindowsGroups, false); } List<ClaimSet> claimSets = new List<ClaimSet>(2); claimSets.Add(windowsClaimSet); claimSets.Add(x509ClaimSet); List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1); policies.Add(new UnconditionalPolicy(claimSets.AsReadOnly(), x509Token.ValidTo)); return policies.AsReadOnly(); } // For Vista, LsaLogon supporting mapping cert to NTToken. W/O SeTcbPrivilege // the identify token is returned; otherwise, impersonation. This is consistent // with S4U. Note: duplicate code partly from CLR's WindowsIdentity Class (S4U). [Fx.Tag.SecurityNote(Critical = "Uses critical type SafeHGlobalHandle.", Safe = "Performs a Demand for full trust.")] [SecuritySafeCritical] [SecurityPermission(SecurityAction.Demand, Unrestricted = true)] internal static WindowsIdentity KerberosCertificateLogon(X509Certificate2 certificate) { int status; SafeHGlobalHandle pSourceName = null; SafeHGlobalHandle pPackageName = null; SafeHGlobalHandle pLogonInfo = null; SafeLsaLogonProcessHandle logonHandle = null; SafeLsaReturnBufferHandle profileHandle = null; SafeCloseHandle tokenHandle = null; try { pSourceName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaSourceName.Length + 1); Marshal.Copy(NativeMethods.LsaSourceName, 0, pSourceName.DangerousGetHandle(), NativeMethods.LsaSourceName.Length); UNICODE_INTPTR_STRING sourceName = new UNICODE_INTPTR_STRING(NativeMethods.LsaSourceName.Length, NativeMethods.LsaSourceName.Length + 1, pSourceName.DangerousGetHandle()); Privilege privilege = null; RuntimeHelpers.PrepareConstrainedRegions(); // Try to get an impersonation token. try { // Try to enable the TCB privilege if possible try { privilege = new Privilege(Privilege.SeTcbPrivilege); privilege.Enable(); } catch (PrivilegeNotHeldException ex) { DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information); } IntPtr dummy = IntPtr.Zero; status = NativeMethods.LsaRegisterLogonProcess(ref sourceName, out logonHandle, out dummy); if (NativeMethods.ERROR_ACCESS_DENIED == NativeMethods.LsaNtStatusToWinError(status)) { // We don't have the Tcb privilege. The best we can hope for is to get an Identification token. status = NativeMethods.LsaConnectUntrusted(out logonHandle); } if (status < 0) // non-negative numbers indicate success { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status))); } } finally { // if reverting privilege fails, fail fast! int revertResult = -1; string message = null; try { revertResult = privilege.Revert(); if (revertResult != 0) { message = SR.GetString(SR.RevertingPrivilegeFailed, new Win32Exception(revertResult)); } } finally { if (revertResult != 0) { DiagnosticUtility.FailFast(message); } } } // package name ("Kerberos") pPackageName = SafeHGlobalHandle.AllocHGlobal(NativeMethods.LsaKerberosName.Length + 1); Marshal.Copy(NativeMethods.LsaKerberosName, 0, pPackageName.DangerousGetHandle(), NativeMethods.LsaKerberosName.Length); UNICODE_INTPTR_STRING packageName = new UNICODE_INTPTR_STRING(NativeMethods.LsaKerberosName.Length, NativeMethods.LsaKerberosName.Length + 1, pPackageName.DangerousGetHandle()); uint packageId = 0; status = NativeMethods.LsaLookupAuthenticationPackage(logonHandle, ref packageName, out packageId); if (status < 0) // non-negative numbers indicate success { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status))); } // source context TOKEN_SOURCE sourceContext = new TOKEN_SOURCE(); if (!NativeMethods.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier)) { int dwErrorCode = Marshal.GetLastWin32Error(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode)); } // SourceContext sourceContext.Name = new char[8]; sourceContext.Name[0] = 'W'; sourceContext.Name[1] = 'C'; sourceContext.Name[2] = 'F'; // LogonInfo byte[] certRawData = certificate.RawData; int logonInfoSize = KERB_CERTIFICATE_S4U_LOGON.Size + certRawData.Length; pLogonInfo = SafeHGlobalHandle.AllocHGlobal(logonInfoSize); unsafe { KERB_CERTIFICATE_S4U_LOGON* pInfo = (KERB_CERTIFICATE_S4U_LOGON*)pLogonInfo.DangerousGetHandle().ToPointer(); pInfo->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbCertificateS4ULogon; pInfo->Flags = NativeMethods.KERB_CERTIFICATE_S4U_LOGON_FLAG_CHECK_LOGONHOURS; pInfo->UserPrincipalName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero); pInfo->DomainName = new UNICODE_INTPTR_STRING(0, 0, IntPtr.Zero); pInfo->CertificateLength = (uint)certRawData.Length; pInfo->Certificate = new IntPtr(pLogonInfo.DangerousGetHandle().ToInt64() + KERB_CERTIFICATE_S4U_LOGON.Size); Marshal.Copy(certRawData, 0, pInfo->Certificate, certRawData.Length); } QUOTA_LIMITS quotas = new QUOTA_LIMITS(); LUID logonId = new LUID(); uint profileBufferLength; int subStatus = 0; // Call LsaLogonUser status = NativeMethods.LsaLogonUser( logonHandle, ref sourceName, SecurityLogonType.Network, packageId, pLogonInfo.DangerousGetHandle(), (uint)logonInfoSize, IntPtr.Zero, ref sourceContext, out profileHandle, out profileBufferLength, out logonId, out tokenHandle, out quotas, out subStatus ); // LsaLogon has restriction (eg. password expired). SubStatus indicates the reason. if ((uint)status == NativeMethods.STATUS_ACCOUNT_RESTRICTION && subStatus < 0) { status = subStatus; } if (status < 0) // non-negative numbers indicate success { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(status))); } if (subStatus < 0) // non-negative numbers indicate success { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(NativeMethods.LsaNtStatusToWinError(subStatus))); } return new WindowsIdentity(tokenHandle.DangerousGetHandle(), SecurityUtils.AuthTypeCertMap); } finally { if (tokenHandle != null) { tokenHandle.Close(); } if (pLogonInfo != null) { pLogonInfo.Close(); } if (profileHandle != null) { profileHandle.Close(); } if (pSourceName != null) { pSourceName.Close(); } if (pPackageName != null) { pPackageName.Close(); } if (logonHandle != null) { logonHandle.Close(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Reflection; using System.Runtime.CompilerServices; using System.Diagnostics; using Internal.Reflection.Core.NonPortable; using Internal.Runtime.Augments; namespace System { [System.Runtime.CompilerServices.DependencyReductionRoot] public static class InvokeUtils { // // Various reflection scenarios (Array.SetValue(), reflection Invoke, delegate DynamicInvoke and FieldInfo.Set()) perform // automatic conveniences such as automatically widening primitive types to fit the destination type. // // This method attempts to collect as much of that logic as possible in place. (This may not be completely possible // as the desktop CLR is not particularly consistent across all these scenarios either.) // // The transforms supported are: // // Value-preserving widenings of primitive integrals and floats. // Enums can be converted to the same or wider underlying primitive. // Primitives can be converted to an enum with the same or wider underlying primitive. // // null converted to default(T) (this is important when T is a valuetype.) // // There is also another transform of T -> Nullable<T>. This method acknowleges that rule but does not actually transform the T. // Rather, the transformation happens naturally when the caller unboxes the value to its final destination. // // This method is targeted by the Delegate ILTransformer. // // public static Object CheckArgument(Object srcObject, RuntimeTypeHandle dstType, BinderBundle binderBundle) { EETypePtr dstEEType = dstType.ToEETypePtr(); return CheckArgument(srcObject, dstEEType, CheckArgumentSemantics.DynamicInvoke, binderBundle, getExactTypeForCustomBinder: null); } // This option tweaks the coercion rules to match classic inconsistencies. internal enum CheckArgumentSemantics { ArraySet, // Throws InvalidCastException DynamicInvoke, // Throws ArgumentException SetFieldDirect, // Throws ArgumentException - other than that, like DynamicInvoke except that enums and integers cannot be intermingled, and null cannot substitute for default(valuetype). } internal static Object CheckArgument(Object srcObject, EETypePtr dstEEType, CheckArgumentSemantics semantics, BinderBundle binderBundle, Func<Type> getExactTypeForCustomBinder = null) { if (srcObject == null) { // null -> default(T) if (dstEEType.IsValueType && !dstEEType.IsNullable) { if (semantics == CheckArgumentSemantics.SetFieldDirect) throw CreateChangeTypeException(CommonRuntimeTypes.Object.TypeHandle.ToEETypePtr(), dstEEType, semantics); return Runtime.RuntimeImports.RhNewObject(dstEEType); } else { return null; } } else { EETypePtr srcEEType = srcObject.EETypePtr; if (RuntimeImports.AreTypesAssignable(srcEEType, dstEEType)) return srcObject; if (dstEEType.IsInterface) { ICastable castable = srcObject as ICastable; Exception castError; if (castable != null && castable.IsInstanceOfInterface(new RuntimeTypeHandle(dstEEType), out castError)) return srcObject; } object dstObject; Exception exception = ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(srcObject, srcEEType, dstEEType, semantics, out dstObject); if (exception == null) return dstObject; if (binderBundle == null) throw exception; // Our normal coercion rules could not convert the passed in argument but we were supplied a custom binder. See if it can do it. Type exactDstType; if (getExactTypeForCustomBinder == null) { // We were called by someone other than DynamicInvokeParamHelperCore(). Those callers pass the correct dstEEType. exactDstType = Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType)); } else { // We were called by DynamicInvokeParamHelperCore(). He passes a dstEEType that enums folded to int and possibly other adjustments. A custom binder // is app code however and needs the exact type. exactDstType = getExactTypeForCustomBinder(); } srcObject = binderBundle.ChangeType(srcObject, exactDstType); // For compat with desktop, the result of the binder call gets processed through the default rules again. dstObject = CheckArgument(srcObject, dstEEType, semantics, binderBundle: null, getExactTypeForCustomBinder: null); return dstObject; } } // Special coersion rules for primitives, enums and pointer. private static Exception ConvertOrWidenPrimitivesEnumsAndPointersIfPossible(object srcObject, EETypePtr srcEEType, EETypePtr dstEEType, CheckArgumentSemantics semantics, out object dstObject) { if (semantics == CheckArgumentSemantics.SetFieldDirect && (srcEEType.IsEnum || dstEEType.IsEnum)) { dstObject = null; return CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (!((srcEEType.IsEnum || srcEEType.IsPrimitive) && (dstEEType.IsEnum || dstEEType.IsPrimitive || dstEEType.IsPointer))) { dstObject = null; return CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (dstEEType.IsPointer) { dstObject = null; return NotImplemented.ActiveIssue("TFS 457960 - Passing Pointers through Reflection Invoke"); } RuntimeImports.RhCorElementType dstCorElementType = dstEEType.CorElementType; if (!srcEEType.CorElementTypeInfo.CanWidenTo(dstCorElementType)) { dstObject = null; return CreateChangeTypeArgumentException(srcEEType, dstEEType); } switch (dstCorElementType) { case RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN: dstObject = Convert.ToBoolean(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR: dstObject = Convert.ToChar(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I1: dstObject = Convert.ToSByte(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I2: dstObject = Convert.ToInt16(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I4: dstObject = Convert.ToInt32(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_I8: dstObject = Convert.ToInt64(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U1: dstObject = Convert.ToByte(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U2: dstObject = Convert.ToUInt16(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U4: dstObject = Convert.ToUInt32(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_U8: dstObject = Convert.ToUInt64(srcObject); break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4: if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR) { dstObject = (float)(char)srcObject; } else { dstObject = Convert.ToSingle(srcObject); } break; case RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8: if (srcEEType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_CHAR) { dstObject = (double)(char)srcObject; } else { dstObject = Convert.ToDouble(srcObject); } break; default: Debug.Assert(false, "Unexpected CorElementType: " + dstCorElementType + ": Not a valid widening target."); dstObject = null; return CreateChangeTypeException(srcEEType, dstEEType, semantics); } if (dstEEType.IsEnum) { Type dstType = ReflectionCoreNonPortable.GetRuntimeTypeForEEType(dstEEType); dstObject = Enum.ToObject(dstType, dstObject); } Debug.Assert(dstObject.EETypePtr == dstEEType); return null; } private static Exception CreateChangeTypeException(EETypePtr srcEEType, EETypePtr dstEEType, CheckArgumentSemantics semantics) { switch (semantics) { case CheckArgumentSemantics.DynamicInvoke: case CheckArgumentSemantics.SetFieldDirect: return CreateChangeTypeArgumentException(srcEEType, dstEEType); case CheckArgumentSemantics.ArraySet: return CreateChangeTypeInvalidCastException(srcEEType, dstEEType); default: Debug.Assert(false, "Unexpected CheckArgumentSemantics value: " + semantics); throw new InvalidOperationException(); } } private static ArgumentException CreateChangeTypeArgumentException(EETypePtr srcEEType, EETypePtr dstEEType) { return new ArgumentException(SR.Format(SR.Arg_ObjObjEx, Type.GetTypeFromHandle(new RuntimeTypeHandle(srcEEType)), Type.GetTypeFromHandle(new RuntimeTypeHandle(dstEEType)))); } private static InvalidCastException CreateChangeTypeInvalidCastException(EETypePtr srcEEType, EETypePtr dstEEType) { return new InvalidCastException(SR.InvalidCast_StoreArrayElement); } // ----------------------------------------------- // Infrastructure and logic for Dynamic Invocation // ----------------------------------------------- public enum DynamicInvokeParamType { In = 0, Ref = 1 } public enum DynamicInvokeParamLookupType { ValuetypeObjectReturned = 0, IndexIntoObjectArrayReturned = 1, } public struct ArgSetupState { public bool fComplete; public object[] nullableCopyBackObjects; } // These thread static fields are used instead of passing parameters normally through to the helper functions // that actually implement dynamic invocation. This allows the large number of dynamically generated // functions to be just that little bit smaller, which, when spread across the many invocation helper thunks // generated adds up quite a bit. [ThreadStatic] private static object[] s_parameters; [ThreadStatic] private static object[] s_nullableCopyBackObjects; [ThreadStatic] private static int s_curIndex; [ThreadStatic] private static object s_targetMethodOrDelegate; [ThreadStatic] private static BinderBundle s_binderBundle; [ThreadStatic] private static object[] s_customBinderProvidedParameters; private static object GetDefaultValue(RuntimeTypeHandle thType, int argIndex) { object targetMethodOrDelegate = s_targetMethodOrDelegate; if (targetMethodOrDelegate == null) { throw new ArgumentException(SR.Arg_DefaultValueMissingException); } object defaultValue; bool hasDefaultValue; Delegate delegateInstance = targetMethodOrDelegate as Delegate; if (delegateInstance != null) { hasDefaultValue = delegateInstance.TryGetDefaultParameterValue(thType, argIndex, out defaultValue); } else { hasDefaultValue = RuntimeAugments.Callbacks.TryGetDefaultParameterValue(targetMethodOrDelegate, thType, argIndex, out defaultValue); } if (!hasDefaultValue) { throw new ArgumentException(SR.Arg_DefaultValueMissingException); } // Note that we might return null even for value types which cannot have null value here. // This case is handled in the CheckArgument method which is called after this one on the returned parameter value. return defaultValue; } // This is only called if we have to invoke a custom binder to coerce a parameter type. It leverages s_targetMethodOrDelegate to retrieve // the unaltered parameter type to pass to the binder. private static Type GetExactTypeForCustomBinder() { Debug.Assert(s_binderBundle != null && s_targetMethodOrDelegate is MethodBase); MethodBase method = (MethodBase)s_targetMethodOrDelegate; // DynamicInvokeParamHelperCore() increments s_curIndex before calling us - that's why we have to subtract 1. return method.GetParametersNoCopy()[s_curIndex - 1].ParameterType; } private static readonly Func<Type> s_getExactTypeForCustomBinder = GetExactTypeForCustomBinder; [DebuggerGuidedStepThroughAttribute] internal static object CallDynamicInvokeMethod( object thisPtr, IntPtr methodToCall, object thisPtrDynamicInvokeMethod, IntPtr dynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperGenericDictionary, object targetMethodOrDelegate, object[] parameters, BinderBundle binderBundle, bool invokeMethodHelperIsThisCall = true, bool methodToCallIsThisCall = true) { // This assert is needed because we've double-purposed "targetMethodOrDelegate" (which is actually a MethodBase anytime a custom binder is used) // as a way of obtaining the true parameter type which we need to pass to Binder.ChangeType(). (The type normally passed to DynamicInvokeParamHelperCore // isn't always the exact type (byref stripped off, enums converted to int, etc.) Debug.Assert(!(binderBundle != null && !(targetMethodOrDelegate is MethodBase)), "The only callers that can pass a custom binder are those servicing MethodBase.Invoke() apis."); bool fDontWrapInTargetInvocationException = false; bool parametersNeedCopyBack = false; ArgSetupState argSetupState = default(ArgSetupState); // Capture state of thread static invoke helper statics object[] parametersOld = s_parameters; object[] nullableCopyBackObjectsOld = s_nullableCopyBackObjects; int curIndexOld = s_curIndex; object targetMethodOrDelegateOld = s_targetMethodOrDelegate; BinderBundle binderBundleOld = s_binderBundle; s_binderBundle = binderBundle; object[] customBinderProvidedParametersOld = s_customBinderProvidedParameters; s_customBinderProvidedParameters = null; try { // If the passed in array is not an actual object[] instance, we need to copy it over to an actual object[] // instance so that the rest of the code can safely create managed object references to individual elements. if (parameters != null && EETypePtr.EETypePtrOf<object[]>() != parameters.EETypePtr) { s_parameters = new object[parameters.Length]; Array.Copy(parameters, s_parameters, parameters.Length); parametersNeedCopyBack = true; } else { s_parameters = parameters; } s_nullableCopyBackObjects = null; s_curIndex = 0; s_targetMethodOrDelegate = targetMethodOrDelegate; try { object result = null; if (invokeMethodHelperIsThisCall) { Debug.Assert(methodToCallIsThisCall == true); result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, thisPtrDynamicInvokeMethod, thisPtr, methodToCall, ref argSetupState); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } else { if (dynamicInvokeHelperGenericDictionary != IntPtr.Zero) { result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, dynamicInvokeHelperGenericDictionary, thisPtr, methodToCall, ref argSetupState, methodToCallIsThisCall); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } else { result = CalliIntrinsics.Call(dynamicInvokeHelperMethod, thisPtr, methodToCall, ref argSetupState, methodToCallIsThisCall); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } } return result; } finally { if (parametersNeedCopyBack) { Array.Copy(s_parameters, parameters, parameters.Length); } if (!argSetupState.fComplete) { fDontWrapInTargetInvocationException = true; } else { // Nullable objects can't take advantage of the ability to update the boxed value on the heap directly, so perform // an update of the parameters array now. if (argSetupState.nullableCopyBackObjects != null) { for (int i = 0; i < argSetupState.nullableCopyBackObjects.Length; i++) { if (argSetupState.nullableCopyBackObjects[i] != null) { parameters[i] = DynamicInvokeBoxIntoNonNullable(argSetupState.nullableCopyBackObjects[i]); } } } } } } catch (Exception e) { if (fDontWrapInTargetInvocationException) { throw; } else { throw new System.Reflection.TargetInvocationException(e); } } finally { // Restore state of thread static helper statics s_parameters = parametersOld; s_nullableCopyBackObjects = nullableCopyBackObjectsOld; s_curIndex = curIndexOld; s_targetMethodOrDelegate = targetMethodOrDelegateOld; s_binderBundle = binderBundleOld; s_customBinderProvidedParameters = customBinderProvidedParametersOld; } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static void DynamicInvokeArgSetupComplete(ref ArgSetupState argSetupState) { int parametersLength = s_parameters != null ? s_parameters.Length : 0; if (s_curIndex != parametersLength) { throw new System.Reflection.TargetParameterCountException(); } argSetupState.fComplete = true; argSetupState.nullableCopyBackObjects = s_nullableCopyBackObjects; s_nullableCopyBackObjects = null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static unsafe void DynamicInvokeArgSetupPtrComplete(IntPtr argSetupStatePtr) { // argSetupStatePtr is a pointer to a *pinned* ArgSetupState object DynamicInvokeArgSetupComplete(ref Unsafe.As<byte, ArgSetupState>(ref *(byte*)argSetupStatePtr)); } [System.Runtime.InteropServices.McgIntrinsicsAttribute] private static class CalliIntrinsics { [DebuggerStepThrough] internal static object Call( IntPtr dynamicInvokeHelperMethod, object thisPtrForDynamicInvokeHelperMethod, object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState) { // This method is implemented elsewhere in the toolchain throw new NotSupportedException(); } [DebuggerStepThrough] internal static object Call( IntPtr dynamicInvokeHelperMethod, object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool isTargetThisCall) { // This method is implemented elsewhere in the toolchain throw new NotSupportedException(); } [DebuggerStepThrough] internal static object Call( IntPtr dynamicInvokeHelperMethod, IntPtr dynamicInvokeHelperGenericDictionary, object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool isTargetThisCall) { // This method is implemented elsewhere in the toolchain throw new NotSupportedException(); } } // Template function that is used to call dynamically internal static object DynamicInvokeThisCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState) { // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret return null; } internal static object DynamicInvokeCallTemplate(object thisPtr, IntPtr methodToCall, ref ArgSetupState argSetupState, bool targetIsThisCall) { // This function will look like // // !For each parameter to the method // !if (parameter is In Parameter) // localX is TypeOfParameterX& // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperIn(RuntimeTypeHandle) // stloc localX // !else // localX is TypeOfParameter // ldtoken TypeOfParameterX // call DynamicInvokeParamHelperRef(RuntimeTypeHandle) // stloc localX // ldarg.2 // call DynamicInvokeArgSetupComplete(ref ArgSetupState) // !if (targetIsThisCall) // ldarg.0 // Load this pointer // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType thiscall(TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret // !else // !For each parameter // !if (parameter is In Parameter) // ldloc localX // ldobj TypeOfParameterX // !else // ldloc localX // ldarg.1 // calli ReturnType (TypeOfParameter1, ...) // !if ((ReturnType != void) && !(ReturnType is a byref) // ldnull // !else // box ReturnType // ret return null; } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void DynamicInvokeUnboxIntoActualNullable(object actualBoxedNullable, object boxedFillObject, EETypePtr nullableType) { // get a byref to the data within the actual boxed nullable, and then call RhUnBox with the boxedFillObject as the boxed object, and nullableType as the unbox type, and unbox into the actualBoxedNullable RuntimeImports.RhUnbox(boxedFillObject, ref actualBoxedNullable.GetRawData(), nullableType); } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static object DynamicInvokeBoxIntoNonNullable(object actualBoxedNullable) { // grab the pointer to data, box using the EEType of the actualBoxedNullable, and then return the boxed object return RuntimeImports.RhBox(actualBoxedNullable.EETypePtr, ref actualBoxedNullable.GetRawData()); } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static ref IntPtr DynamicInvokeParamHelperIn(RuntimeTypeHandle rth) { // // Call DynamicInvokeParamHelperCore as an in parameter, and return a managed byref to the interesting bit. // // This function exactly matches DynamicInvokeParamHelperRef except for the value of the enum passed to DynamicInvokeParamHelperCore // int index; DynamicInvokeParamLookupType paramLookupType; object obj = DynamicInvokeParamHelperCore(rth, out paramLookupType, out index, DynamicInvokeParamType.In); if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned) { return ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()); } else { return ref Unsafe.As<object, IntPtr>(ref Unsafe.As<object[]>(obj)[index]); } } [DebuggerStepThrough] [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] internal static ref IntPtr DynamicInvokeParamHelperRef(RuntimeTypeHandle rth) { // // Call DynamicInvokeParamHelperCore as a ref parameter, and return a managed byref to the interesting bit. As this can't actually be defined in C# there is an IL transform that fills this in. // // This function exactly matches DynamicInvokeParamHelperIn except for the value of the enum passed to DynamicInvokeParamHelperCore // int index; DynamicInvokeParamLookupType paramLookupType; object obj = DynamicInvokeParamHelperCore(rth, out paramLookupType, out index, DynamicInvokeParamType.Ref); if (paramLookupType == DynamicInvokeParamLookupType.ValuetypeObjectReturned) { return ref Unsafe.As<byte, IntPtr>(ref obj.GetRawData()); } else { return ref Unsafe.As<object, IntPtr>(ref Unsafe.As<object[]>(obj)[index]); } } internal static object DynamicInvokeBoxedValuetypeReturn(out DynamicInvokeParamLookupType paramLookupType, object boxedValuetype, int index, RuntimeTypeHandle type, DynamicInvokeParamType paramType) { object finalObjectToReturn = boxedValuetype; EETypePtr eeType = type.ToEETypePtr(); bool nullable = eeType.IsNullable; if (finalObjectToReturn == null || nullable || paramType == DynamicInvokeParamType.Ref) { finalObjectToReturn = RuntimeImports.RhNewObject(eeType); if (boxedValuetype != null) { DynamicInvokeUnboxIntoActualNullable(finalObjectToReturn, boxedValuetype, eeType); } } if (nullable) { if (paramType == DynamicInvokeParamType.Ref) { if (s_nullableCopyBackObjects == null) { s_nullableCopyBackObjects = new object[s_parameters.Length]; } s_nullableCopyBackObjects[index] = finalObjectToReturn; s_parameters[index] = null; } } else { System.Diagnostics.Debug.Assert(finalObjectToReturn != null); if (paramType == DynamicInvokeParamType.Ref) s_parameters[index] = finalObjectToReturn; } paramLookupType = DynamicInvokeParamLookupType.ValuetypeObjectReturned; return finalObjectToReturn; } public static object DynamicInvokeParamHelperCore(RuntimeTypeHandle type, out DynamicInvokeParamLookupType paramLookupType, out int index, DynamicInvokeParamType paramType) { index = s_curIndex++; int parametersLength = s_parameters != null ? s_parameters.Length : 0; if (index >= parametersLength) throw new System.Reflection.TargetParameterCountException(); object incomingParam = s_parameters[index]; // Handle default parameters if ((incomingParam == System.Reflection.Missing.Value) && paramType == DynamicInvokeParamType.In) { incomingParam = GetDefaultValue(type, index); // The default value is captured into the parameters array s_parameters[index] = incomingParam; } RuntimeTypeHandle widenAndCompareType = type; bool nullable = type.ToEETypePtr().IsNullable; if (nullable) { widenAndCompareType = new RuntimeTypeHandle(type.ToEETypePtr().NullableType); } if (widenAndCompareType.ToEETypePtr().IsPrimitive || type.ToEETypePtr().IsEnum) { // Nullable requires exact matching if (incomingParam != null) { if (nullable || paramType == DynamicInvokeParamType.Ref) { if (widenAndCompareType.ToEETypePtr() != incomingParam.EETypePtr) { if (s_binderBundle == null) throw CreateChangeTypeArgumentException(incomingParam.EETypePtr, type.ToEETypePtr()); Type exactDstType = GetExactTypeForCustomBinder(); incomingParam = s_binderBundle.ChangeType(incomingParam, exactDstType); if (incomingParam != null && widenAndCompareType.ToEETypePtr() != incomingParam.EETypePtr) throw CreateChangeTypeArgumentException(incomingParam.EETypePtr, type.ToEETypePtr()); } } else { if (widenAndCompareType.ToEETypePtr().CorElementType != incomingParam.EETypePtr.CorElementType) { System.Diagnostics.Debug.Assert(paramType == DynamicInvokeParamType.In); incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); } } } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } else if (type.ToEETypePtr().IsValueType) { incomingParam = InvokeUtils.CheckArgument(incomingParam, type.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); if (s_binderBundle == null) { System.Diagnostics.Debug.Assert(s_parameters[index] == null || Object.ReferenceEquals(incomingParam, s_parameters[index])); } return DynamicInvokeBoxedValuetypeReturn(out paramLookupType, incomingParam, index, type, paramType); } else { incomingParam = InvokeUtils.CheckArgument(incomingParam, widenAndCompareType.ToEETypePtr(), InvokeUtils.CheckArgumentSemantics.DynamicInvoke, s_binderBundle, s_getExactTypeForCustomBinder); paramLookupType = DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned; if (s_binderBundle == null) { System.Diagnostics.Debug.Assert(Object.ReferenceEquals(incomingParam, s_parameters[index])); return s_parameters; } else { if (object.ReferenceEquals(incomingParam, s_parameters[index])) { return s_parameters; } else { // If we got here, the original argument object was superceded by invoking the custom binder. if (paramType == DynamicInvokeParamType.Ref) { s_parameters[index] = incomingParam; return s_parameters; } else { // Since this not a by-ref parameter, we don't want to bash the original user-owned argument array but the rules of DynamicInvokeParamHelperCore() require // that we return non-value types as the "index"th element in an array. Thus, create an on-demand throwaway array just for this purpose. if (s_customBinderProvidedParameters == null) { s_customBinderProvidedParameters = new object[s_parameters.Length]; } s_customBinderProvidedParameters[index] = incomingParam; return s_customBinderProvidedParameters; } } } } } } }
//----------------------------------------------------------------------- // <copyright file="LightEstimateApi.cs" company="Google LLC"> // // Copyright 2017 Google LLC. 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. // // </copyright> //----------------------------------------------------------------------- namespace GoogleARCoreInternal { using System; using GoogleARCore; using UnityEngine; using UnityEngine.Rendering; #if UNITY_IOS && !UNITY_EDITOR using AndroidImport = GoogleARCoreInternal.DllImportNoop; using IOSImport = System.Runtime.InteropServices.DllImportAttribute; #else using AndroidImport = System.Runtime.InteropServices.DllImportAttribute; using IOSImport = GoogleARCoreInternal.DllImportNoop; #endif internal class LightEstimateApi { internal static readonly float[] k_SHConstants = { 0.886227f, 1.023328f, 1.023328f, 1.023328f, 0.858086f, 0.858086f, 0.247708f, 0.858086f, 0.429043f }; private NativeSession m_NativeSession; #if !UNITY_2017_2_OR_NEWER private Color[] m_TempCubemapFacePixels = new Color[0]; #endif private float[] m_TempVector = new float[3]; private float[] m_TempColor = new float[3]; private float[] m_TempSHCoefficients = new float[27]; private Cubemap m_HDRCubemap = null; private long m_CubemapTimestamp = -1; private int m_CubemapTextureId = 0; private bool m_PluginInitialized = false; public LightEstimateApi(NativeSession nativeSession) { m_NativeSession = nativeSession; } public IntPtr Create() { IntPtr lightEstimateHandle = IntPtr.Zero; ExternApi.ArLightEstimate_create( m_NativeSession.SessionHandle, ref lightEstimateHandle); return lightEstimateHandle; } public void Destroy(IntPtr lightEstimateHandle) { ExternApi.ArLightEstimate_destroy(lightEstimateHandle); } public LightEstimateState GetState(IntPtr lightEstimateHandle) { ApiLightEstimateState state = ApiLightEstimateState.NotValid; ExternApi.ArLightEstimate_getState( m_NativeSession.SessionHandle, lightEstimateHandle, ref state); return state.ToLightEstimateState(); } public float GetPixelIntensity(IntPtr lightEstimateHandle) { float pixelIntensity = 0; ExternApi.ArLightEstimate_getPixelIntensity( m_NativeSession.SessionHandle, lightEstimateHandle, ref pixelIntensity); return pixelIntensity; } public Color GetColorCorrection(IntPtr lightEstimateHandle) { Color colorCorrection = Color.black; ExternApi.ArLightEstimate_getColorCorrection( m_NativeSession.SessionHandle, lightEstimateHandle, ref colorCorrection); return colorCorrection; } public void GetMainDirectionalLight(IntPtr sessionHandle, IntPtr lightEstimateHandle, out Quaternion lightRotation, out Color lightColor) { lightColor = Color.black; ExternApi.ArLightEstimate_getEnvironmentalHdrMainLightIntensity(sessionHandle, lightEstimateHandle, m_TempColor); lightColor.r = m_TempColor[0]; lightColor.g = m_TempColor[1]; lightColor.b = m_TempColor[2]; // Apply the energy conservation term to the light color directly since Unity doesn't // have that term in their PBR shader. lightColor = lightColor / Mathf.PI; ExternApi.ArLightEstimate_getEnvironmentalHdrMainLightDirection(sessionHandle, lightEstimateHandle, m_TempVector); Vector3 lightDirection = Vector3.one; ConversionHelper.ApiVectorToUnityVector(m_TempVector, out lightDirection); // The ARCore output the light direction defined for shader usage: lightPos-pixelPos // We need to invert the direction to set it Unity world space. lightRotation = Quaternion.LookRotation(-lightDirection); } public void GetAmbientSH(IntPtr sessionHandle, IntPtr lightEstimateHandle, float[,] outSHCoefficients) { ExternApi.ArLightEstimate_getEnvironmentalHdrAmbientSphericalHarmonics(sessionHandle, lightEstimateHandle, m_TempSHCoefficients); // We need to invert the coefficients that contains the z axis to map it to // Unity world coordinate. // See: https://en.wikipedia.org/wiki/Table_of_spherical_harmonics // We also premultiply the constant that Unity applies to the SH to avoid // calculation in the shader. // Unity uses the following equation to calculate SH color in their shaders where the // constants that are used to calculate the SH color are baked in the SH coefficients // before passing to the shader. // Say normal direction is (x, y, z) // The color from SH given the normal direction is: // color = SH[0] - SH[6] + SH[3]x + SH[1]y + SH[2]z (L0 + L1) // + SH[4]xy + SH[5]yz + 3*SH[6]zz + SH[7]xz + SH[8](xx - yy) (L2 + L3) for (int i = 0; i < 3; i++) { for (int j = 0; j < 9; j++) { outSHCoefficients[j, i] = m_TempSHCoefficients[(j * 3) + i]; if (j == 2 || j == 5 || j == 7) { outSHCoefficients[j, i] = outSHCoefficients[j, i] * -1.0f; } outSHCoefficients[j, i] = outSHCoefficients[j, i] * k_SHConstants[j]; // Apply the energy conservation to SH coefficients as well. outSHCoefficients[j, i] = outSHCoefficients[j, i] / Mathf.PI; } } } public Cubemap GetReflectionCubemap(IntPtr sessionHandle, IntPtr lightEstimateHandle) { int size = 0; bool usingGammaWorkflow = QualitySettings.activeColorSpace == ColorSpace.Gamma; #if UNITY_2017_2_OR_NEWER // Cubemap.CreateExternalTexture only exists in Unity 2017 above. int textureId = 0; ApiTextureDataType dataType = SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3 ? ApiTextureDataType.Half : ApiTextureDataType.Byte; TextureFormat format = dataType == ApiTextureDataType.Half ? TextureFormat.RGBAHalf : TextureFormat.RGBA32; if (!m_PluginInitialized) { ExternApi.ARCoreRenderingUtils_SetTextureDataType(dataType, true); ExternApi.ARCoreRenderingUtils_SetActiveColorSpace(usingGammaWorkflow); m_PluginInitialized = true; } ExternApi.ARCoreRenderingUtils_GetCubemapTexture(ref textureId, ref size); if (textureId != 0 && (m_HDRCubemap == null || textureId != m_CubemapTextureId)) { m_HDRCubemap = Cubemap.CreateExternalTexture(size, format, true, new IntPtr(textureId)); m_CubemapTextureId = textureId; } long timestamp = GetTimestamp(sessionHandle, lightEstimateHandle); if (m_CubemapTimestamp != timestamp) { ExternApi.ARCoreRenderingUtils_SetARCoreLightEstimation(sessionHandle, lightEstimateHandle); m_CubemapTimestamp = timestamp; } // Issue plugin event to update cubemap texture. GL.IssuePluginEvent(ExternApi.ARCoreRenderingUtils_GetRenderEventFunc(), (int)ApiRenderEvent.UpdateCubemapTexture); #else // Gets raw color data from native plugin then update cubemap textures by // Cubemap.SetPixel(). // Note, no GL texture will be created in this scenario. if (!m_PluginInitialized) { ExternApi.ARCoreRenderingUtils_SetTextureDataType( ApiTextureDataType.Float, false); ExternApi.ARCoreRenderingUtils_SetActiveColorSpace(usingGammaWorkflow); m_PluginInitialized = true; } ExternApi.ARCoreRenderingUtils_GetCubemapTexture(ref m_CubemapTextureId, ref size); if (size > 0) { if (m_HDRCubemap == null) { m_HDRCubemap = new Cubemap(size, TextureFormat.RGBAHalf, true); } if (m_TempCubemapFacePixels.Length != size) { Array.Resize(ref m_TempCubemapFacePixels, size * size); } } long timestamp = GetTimestamp(sessionHandle, lightEstimateHandle); if (m_CubemapTimestamp != timestamp) { ExternApi.ARCoreRenderingUtils_SetARCoreLightEstimation(sessionHandle, lightEstimateHandle); m_CubemapTimestamp = timestamp; if (m_HDRCubemap != null) { for (int i = 0; i < 6; i++) { ExternApi.ARCoreRenderingUtils_GetCubemapRawColors(i, m_TempCubemapFacePixels); m_HDRCubemap.SetPixels(m_TempCubemapFacePixels, CubemapFace.PositiveX + i); } // This operation is very expensive, only update cubemap texture when // the light estimate is updated in this frame. m_HDRCubemap.Apply(); } } #endif return m_HDRCubemap; } public long GetTimestamp(IntPtr sessionHandle, IntPtr lightEstimateHandle) { long timestamp = -1; ExternApi.ArLightEstimate_getTimestamp( sessionHandle, lightEstimateHandle, ref timestamp); return timestamp; } private struct ExternApi { #pragma warning disable 626 [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_create( IntPtr sessionHandle, ref IntPtr lightEstimateHandle); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_destroy(IntPtr lightEstimateHandle); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getState( IntPtr sessionHandle, IntPtr lightEstimateHandle, ref ApiLightEstimateState state); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getPixelIntensity( IntPtr sessionHandle, IntPtr lightEstimateHandle, ref float pixelIntensity); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getColorCorrection( IntPtr sessionHandle, IntPtr lightEstimateHandle, ref Color colorCorrection); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getEnvironmentalHdrMainLightDirection( IntPtr sessionHandle, IntPtr lightEstimateHandle, float[] direction); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getEnvironmentalHdrMainLightIntensity( IntPtr sessionHandle, IntPtr lightEstimateHandle, float[] color); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getEnvironmentalHdrAmbientSphericalHarmonics( IntPtr session, IntPtr light_estimate, float[] out_coefficients_27); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_acquireEnvironmentalHdrCubemap(IntPtr session, IntPtr light_estimate, ref IntPtr out_textures_6); [AndroidImport(ApiConstants.ARCoreNativeApi)] public static extern void ArLightEstimate_getTimestamp(IntPtr session, IntPtr light_estimate, ref long timestamp); [AndroidImport(ApiConstants.ARRenderingUtilsApi)] public static extern void ARCoreRenderingUtils_SetTextureDataType( ApiTextureDataType texture_data_type, bool create_gl_texture); [AndroidImport(ApiConstants.ARRenderingUtilsApi)] public static extern void ARCoreRenderingUtils_SetActiveColorSpace(bool is_gamma_space); [AndroidImport(ApiConstants.ARRenderingUtilsApi)] public static extern void ARCoreRenderingUtils_SetARCoreLightEstimation( IntPtr session, IntPtr cubemap_image); [AndroidImport(ApiConstants.ARRenderingUtilsApi)] public static extern void ARCoreRenderingUtils_GetCubemapTexture(ref int out_texture_id, ref int out_width_height); [AndroidImport(ApiConstants.ARRenderingUtilsApi)] public static extern void ARCoreRenderingUtils_GetCubemapRawColors( int face_index, Color[] out_pixel_colors); [AndroidImport(ApiConstants.ARRenderingUtilsApi)] public static extern IntPtr ARCoreRenderingUtils_GetRenderEventFunc(); #pragma warning restore 626 } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; namespace MonoMac.OpenGL { /// <summary>Represents a 2D vector using two double-precision floating-point numbers.</summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector2d : IEquatable<Vector2d> { #region Fields /// <summary>The X coordinate of this instance.</summary> public double X; /// <summary>The Y coordinate of this instance.</summary> public double Y; /// <summary> /// Defines a unit-length Vector2d that points towards the X-axis. /// </summary> public static Vector2d UnitX = new Vector2d(1, 0); /// <summary> /// Defines a unit-length Vector2d that points towards the Y-axis. /// </summary> public static Vector2d UnitY = new Vector2d(0, 1); /// <summary> /// Defines a zero-length Vector2d. /// </summary> public static Vector2d Zero = new Vector2d(0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector2d One = new Vector2d(1, 1); /// <summary> /// Defines the size of the Vector2d struct in bytes. /// </summary> public static readonly int SizeInBytes = Marshal.SizeOf(new Vector2d()); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2d(double value) { X = value; Y = value; } /// <summary>Constructs left vector with the given coordinates.</summary> /// <param name="x">The X coordinate.</param> /// <param name="y">The Y coordinate.</param> public Vector2d(double x, double y) { this.X = x; this.Y = y; } #endregion #region Public Members #region Instance #region public void Add() /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Add() method instead.")] public void Add(Vector2d right) { this.X += right.X; this.Y += right.Y; } /// <summary>Add the Vector passed as parameter to this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Add() method instead.")] public void Add(ref Vector2d right) { this.X += right.X; this.Y += right.Y; } #endregion public void Add() #region public void Sub() /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [Obsolete("Use static Subtract() method instead.")] public void Sub(Vector2d right) { this.X -= right.X; this.Y -= right.Y; } /// <summary>Subtract the Vector passed as parameter from this instance.</summary> /// <param name="right">Right operand. This parameter is only read from.</param> [CLSCompliant(false)] [Obsolete("Use static Subtract() method instead.")] public void Sub(ref Vector2d right) { this.X -= right.X; this.Y -= right.Y; } #endregion public void Sub() #region public void Mult() /// <summary>Multiply this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Multiply() method instead.")] public void Mult(double f) { this.X *= f; this.Y *= f; } #endregion public void Mult() #region public void Div() /// <summary>Divide this instance by a scalar.</summary> /// <param name="f">Scalar operand.</param> [Obsolete("Use static Divide() method instead.")] public void Div(double f) { double mult = 1.0 / f; this.X *= mult; this.Y *= mult; } #endregion public void Div() #region public double Length /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public double Length { get { return System.Math.Sqrt(X * X + Y * Y); } } #endregion #region public double LengthSquared /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public double LengthSquared { get { return X * X + Y * Y; } } #endregion #region public Vector2d PerpendicularRight /// <summary> /// Gets the perpendicular vector on the right side of this vector. /// </summary> public Vector2d PerpendicularRight { get { return new Vector2d(Y, -X); } } #endregion #region public Vector2d PerpendicularLeft /// <summary> /// Gets the perpendicular vector on the left side of this vector. /// </summary> public Vector2d PerpendicularLeft { get { return new Vector2d(-Y, X); } } #endregion #region public void Normalize() /// <summary> /// Scales the Vector2 to unit length. /// </summary> public void Normalize() { double scale = 1.0 / Length; X *= scale; Y *= scale; } #endregion #region public void Scale() /// <summary> /// Scales the current Vector2 by the given amounts. /// </summary> /// <param name="sx">The scale of the X component.</param> /// <param name="sy">The scale of the Y component.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(double sx, double sy) { X *= sx; Y *= sy; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [Obsolete("Use static Multiply() method instead.")] public void Scale(Vector2d scale) { this.X *= scale.X; this.Y *= scale.Y; } /// <summary>Scales this instance by the given parameter.</summary> /// <param name="scale">The scaling of the individual components.</param> [CLSCompliant(false)] [Obsolete("Use static Multiply() method instead.")] public void Scale(ref Vector2d scale) { this.X *= scale.X; this.Y *= scale.Y; } #endregion public void Scale() #endregion #region Static #region Obsolete #region Sub /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> [Obsolete("Use static Subtract() method instead.")] public static Vector2d Sub(Vector2d a, Vector2d b) { a.X -= b.X; a.Y -= b.Y; return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> [Obsolete("Use static Subtract() method instead.")] public static void Sub(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X - b.X; result.Y = a.Y - b.Y; } #endregion #region Mult /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <returns>Result of the multiplication</returns> [Obsolete("Use static Multiply() method instead.")] public static Vector2d Mult(Vector2d a, double d) { a.X *= d; a.Y *= d; return a; } /// <summary> /// Multiply a vector and a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <param name="result">Result of the multiplication</param> [Obsolete("Use static Multiply() method instead.")] public static void Mult(ref Vector2d a, double d, out Vector2d result) { result.X = a.X * d; result.Y = a.Y * d; } #endregion #region Div /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <returns>Result of the division</returns> [Obsolete("Use static Divide() method instead.")] public static Vector2d Div(Vector2d a, double d) { double mult = 1.0 / d; a.X *= mult; a.Y *= mult; return a; } /// <summary> /// Divide a vector by a scalar /// </summary> /// <param name="a">Vector operand</param> /// <param name="d">Scalar operand</param> /// <param name="result">Result of the division</param> [Obsolete("Use static Divide() method instead.")] public static void Div(ref Vector2d a, double d, out Vector2d result) { double mult = 1.0 / d; result.X = a.X * mult; result.Y = a.Y * mult; } #endregion #endregion #region Add /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <returns>Result of operation.</returns> public static Vector2d Add(Vector2d a, Vector2d b) { Add(ref a, ref b, out a); return a; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector2d a, ref Vector2d b, out Vector2d result) { result = new Vector2d(a.X + b.X, a.Y + b.Y); } #endregion #region Subtract /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>Result of subtraction</returns> public static Vector2d Subtract(Vector2d a, Vector2d b) { Subtract(ref a, ref b, out a); return a; } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector2d a, ref Vector2d b, out Vector2d result) { result = new Vector2d(a.X - b.X, a.Y - b.Y); } #endregion #region Multiply /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Multiply(Vector2d vector, double scale) { Multiply(ref vector, scale, out vector); return vector; } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2d vector, double scale, out Vector2d result) { result = new Vector2d(vector.X * scale, vector.Y * scale); } /// <summary> /// Multiplies a vector by the components a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Multiply(Vector2d vector, Vector2d scale) { Multiply(ref vector, ref scale, out vector); return vector; } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector2d vector, ref Vector2d scale, out Vector2d result) { result = new Vector2d(vector.X * scale.X, vector.Y * scale.Y); } #endregion #region Divide /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Divide(Vector2d vector, double scale) { Divide(ref vector, scale, out vector); return vector; } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2d vector, double scale, out Vector2d result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divides a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <returns>Result of the operation.</returns> public static Vector2d Divide(Vector2d vector, Vector2d scale) { Divide(ref vector, ref scale, out vector); return vector; } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector2d vector, ref Vector2d scale, out Vector2d result) { result = new Vector2d(vector.X / scale.X, vector.Y / scale.Y); } #endregion #region Min /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector2d Min(Vector2d a, Vector2d b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; } #endregion #region Max /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector2d Max(Vector2d a, Vector2d b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector2d a, ref Vector2d b, out Vector2d result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; } #endregion #region Clamp /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <returns>The clamped vector</returns> public static Vector2d Clamp(Vector2d vec, Vector2d min, Vector2d max) { vec.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; vec.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; return vec; } /// <summary> /// Clamp a vector to the given minimum and maximum vectors /// </summary> /// <param name="vec">Input vector</param> /// <param name="min">Minimum vector</param> /// <param name="max">Maximum vector</param> /// <param name="result">The clamped vector</param> public static void Clamp(ref Vector2d vec, ref Vector2d min, ref Vector2d max, out Vector2d result) { result.X = vec.X < min.X ? min.X : vec.X > max.X ? max.X : vec.X; result.Y = vec.Y < min.Y ? min.Y : vec.Y > max.Y ? max.Y : vec.Y; } #endregion #region Normalize /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2d Normalize(Vector2d vec) { double scale = 1.0 / vec.Length; vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void Normalize(ref Vector2d vec, out Vector2d result) { double scale = 1.0 / vec.Length; result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region NormalizeFast /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <returns>The normalized vector</returns> public static Vector2d NormalizeFast(Vector2d vec) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); vec.X *= scale; vec.Y *= scale; return vec; } /// <summary> /// Scale a vector to approximately unit length /// </summary> /// <param name="vec">The input vector</param> /// <param name="result">The normalized vector</param> public static void NormalizeFast(ref Vector2d vec, out Vector2d result) { double scale = MathHelper.InverseSqrtFast(vec.X * vec.X + vec.Y * vec.Y); result.X = vec.X * scale; result.Y = vec.Y * scale; } #endregion #region Dot /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static double Dot(Vector2d left, Vector2d right) { return left.X * right.X + left.Y * right.Y; } /// <summary> /// Calculate the dot (scalar) product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector2d left, ref Vector2d right, out double result) { result = left.X * right.X + left.Y * right.Y; } #endregion #region Lerp /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector2d Lerp(Vector2d a, Vector2d b, double blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector2d a, ref Vector2d b, double blend, out Vector2d result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; } #endregion #region Barycentric /// <summary> /// Interpolate 3 Vectors using Barycentric coordinates /// </summary> /// <param name="a">First input Vector</param> /// <param name="b">Second input Vector</param> /// <param name="c">Third input Vector</param> /// <param name="u">First Barycentric Coordinate</param> /// <param name="v">Second Barycentric Coordinate</param> /// <returns>a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</returns> public static Vector2d BaryCentric(Vector2d a, Vector2d b, Vector2d c, double u, double v) { return a + u * (b - a) + v * (c - a); } /// <summary>Interpolate 3 Vectors using Barycentric coordinates</summary> /// <param name="a">First input Vector.</param> /// <param name="b">Second input Vector.</param> /// <param name="c">Third input Vector.</param> /// <param name="u">First Barycentric Coordinate.</param> /// <param name="v">Second Barycentric Coordinate.</param> /// <param name="result">Output Vector. a when u=v=0, b when u=1,v=0, c when u=0,v=1, and a linear combination of a,b,c otherwise</param> public static void BaryCentric(ref Vector2d a, ref Vector2d b, ref Vector2d c, double u, double v, out Vector2d result) { result = a; // copy Vector2d temp = b; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, u, out temp); Add(ref result, ref temp, out result); temp = c; // copy Subtract(ref temp, ref a, out temp); Multiply(ref temp, v, out temp); Add(ref result, ref temp, out result); } #endregion #region Transform /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector2d Transform(Vector2d vec, Quaterniond quat) { Vector2d result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector2d vec, ref Quaterniond quat, out Vector2d result) { Quaterniond v = new Quaterniond(vec.X, vec.Y, 0, 0), i, t; Quaterniond.Invert(ref quat, out i); Quaterniond.Multiply(ref quat, ref v, out t); Quaterniond.Multiply(ref t, ref i, out v); result = new Vector2d(v.X, v.Y); } #endregion #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator +(Vector2d left, Vector2d right) { left.X += right.X; left.Y += right.Y; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator -(Vector2d left, Vector2d right) { left.X -= right.X; left.Y -= right.Y; return left; } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator -(Vector2d vec) { vec.X = -vec.X; vec.Y = -vec.Y; return vec; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="f">The scalar.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator *(Vector2d vec, double f) { vec.X *= f; vec.Y *= f; return vec; } /// <summary> /// Multiply an instance by a scalar. /// </summary> /// <param name="f">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator *(double f, Vector2d vec) { vec.X *= f; vec.Y *= f; return vec; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="f">The scalar.</param> /// <returns>The result of the operation.</returns> public static Vector2d operator /(Vector2d vec, double f) { double mult = 1.0 / f; vec.X *= mult; vec.Y *= mult; return vec; } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>True, if both instances are equal; false otherwise.</returns> public static bool operator ==(Vector2d left, Vector2d right) { return left.Equals(right); } /// <summary> /// Compares two instances for ienquality. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>True, if the instances are not equal; false otherwise.</returns> public static bool operator !=(Vector2d left, Vector2d right) { return !left.Equals(right); } /// <summary>Converts OpenTK.Vector2 to OpenTK.Vector2d.</summary> /// <param name="v2">The Vector2 to convert.</param> /// <returns>The resulting Vector2d.</returns> public static explicit operator Vector2d(Vector2 v2) { return new Vector2d(v2.X, v2.Y); } /// <summary>Converts OpenTK.Vector2d to OpenTK.Vector2.</summary> /// <param name="v2d">The Vector2d to convert.</param> /// <returns>The resulting Vector2.</returns> public static explicit operator Vector2(Vector2d v2d) { return new Vector2((float)v2d.X, (float)v2d.Y); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current instance. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("({0}, {1})", X, Y); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector2d)) return false; return this.Equals((Vector2d)obj); } #endregion #endregion #endregion #region IEquatable<Vector2d> Members /// <summary>Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector2d other) { return X == other.X && Y == other.Y; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Tools.ServiceModel.SvcUtil.XmlSerializer { using System; using System.Configuration; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; internal partial class Options { private ToolMode? _defaultMode; private ToolMode _validModes = ToolMode.Any; private string _modeSettingOption; private string _modeSettingValue; private string _targetValue; private string _outputFileArg; private string _directoryArg; private string _configFileArg; private bool _noLogo; private bool _quiet; private List<string> _inputParameters; private List<Type> _referencedTypes; private List<Assembly> _referencedAssemblies; private Dictionary<string, Type> _excludedTypes; private bool _nostdlib; private Dictionary<string, string> _namespaceMappings; internal string OutputFileArg { get { return _outputFileArg; } } internal string DirectoryArg { get { return _directoryArg; } } internal bool NoLogo { get { return _noLogo; } } internal bool Quiet { get { return _quiet; } } internal List<string> InputParameters { get { return _inputParameters; } } internal List<Type> ReferencedTypes { get { return _referencedTypes; } } internal List<Assembly> ReferencedAssemblies { get { return _referencedAssemblies; } } internal bool Nostdlib { get { return _nostdlib; } } internal Dictionary<string, string> NamespaceMappings { get { return _namespaceMappings; } } private TypeResolver _typeResolver; internal string ModeSettingOption { get { return _modeSettingOption; } } internal string ModeSettingValue { get { return _modeSettingValue; } } private Options(ArgumentDictionary arguments) { OptionProcessingHelper optionProcessor = new OptionProcessingHelper(this, arguments); optionProcessor.ProcessArguments(); } internal static Options ParseArguments(string[] args) { ArgumentDictionary arguments; try { arguments = CommandParser.ParseCommand(args, Options.Switches.All); } catch (ArgumentException ae) { throw new ToolOptionException(ae.Message); } return new Options(arguments); } internal void SetAllowedModes(ToolMode newDefaultMode, ToolMode validModes, string option, string value) { Tool.Assert(validModes != ToolMode.None, "validModes should never be set to None!"); Tool.Assert(newDefaultMode != ToolMode.None, "newDefaultMode should never be set to None!"); Tool.Assert((validModes & newDefaultMode) != ToolMode.None, "newDefaultMode must be a validMode!"); Tool.Assert(IsSingleBit(newDefaultMode), "newDefaultMode must Always represent a single mode!"); //update/filter list of valid modes _validModes &= validModes; if (_validModes == ToolMode.None) throw new InvalidToolModeException(); bool currentDefaultIsValid = (_defaultMode.HasValue && (_defaultMode & _validModes) != ToolMode.None); bool newDefaultIsValid = (newDefaultMode & _validModes) != ToolMode.None; if (!currentDefaultIsValid) { if (newDefaultIsValid) _defaultMode = newDefaultMode; else _defaultMode = null; } //If this is true, then this is an explicit mode setting if (IsSingleBit(validModes)) { _modeSettingOption = option; _modeSettingValue = value; } } internal ToolMode? GetToolMode() { if (IsSingleBit(_validModes)) return _validModes; return _defaultMode; } internal string GetCommandLineString(string option, string value) { return (value == null) ? option : option + ":" + value; } private static bool IsSingleBit(ToolMode mode) { //figures out if the mode has a single bit set ( is a power of 2) int x = (int)mode; return (x != 0) && ((x & (x + ~0)) == 0); } internal bool IsTypeExcluded(Type type) { return OptionProcessingHelper.IsTypeSpecified(type, _excludedTypes, Options.Cmd.ExcludeType); } private class OptionProcessingHelper { private Options _parent; private ArgumentDictionary _arguments; private static Type s_typeOfDateTimeOffset = typeof(DateTimeOffset); internal OptionProcessingHelper(Options options, ArgumentDictionary arguments) { _parent = options; _arguments = arguments; } internal void ProcessArguments() { CheckForBasicOptions(); if (CheckForHelpOption() || !CheckForQuietOption()) return; LoadSMReferenceAssembly(); ProcessDirectoryOption(); ProcessOutputOption(); ReadInputArguments(); ParseNamespaceMappings(); ParseReferenceAssemblies(); } private bool CheckForHelpOption() { if (_arguments.ContainsArgument(Options.Cmd.Help) || _arguments.Count == 0) { _parent.SetAllowedModes(ToolMode.DisplayHelp, ToolMode.DisplayHelp, Options.Cmd.Help, null); return true; } return false; } private bool CheckForQuietOption() { _parent._quiet = _arguments.ContainsArgument(Options.Cmd.Quiet); return _parent._quiet; } private void CheckForBasicOptions() { _parent._noLogo = _arguments.ContainsArgument(Options.Cmd.NoLogo); #if DEBUG ToolConsole.SetOptions(_arguments.ContainsArgument(Options.Cmd.Debug)); #endif } private void ProcessDirectoryOption() { // Directory //--------------------------------------------------------------------------------------------------------- if (_arguments.ContainsArgument(Options.Cmd.Directory)) { string directoryArgValue = _arguments.GetArgument(Options.Cmd.Directory); try { ValidateIsDirectoryPathOnly(Options.Cmd.Directory, directoryArgValue); if (!directoryArgValue.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) directoryArgValue += Path.DirectorySeparatorChar; _parent._directoryArg = Path.GetFullPath(directoryArgValue); } catch (ToolOptionException) { throw; } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolArgumentException(SR.Format(SR.ErrInvalidPath, directoryArgValue, Options.Cmd.Directory), e); } } else { _parent._directoryArg = null; } } private static void ValidateIsDirectoryPathOnly(string arg, string value) { ValidatePath(arg, value); FileInfo fileInfo = new FileInfo(value); if (fileInfo.Exists) throw new ToolOptionException(SR.Format(SR.ErrDirectoryPointsToAFile, arg, value)); } private static void ValidatePath(string arg, string value) { int invalidCharacterIndex = value.IndexOfAny(Path.GetInvalidPathChars()); if (invalidCharacterIndex != -1) { string invalidCharacter = value[invalidCharacterIndex].ToString(); throw new ToolOptionException(SR.Format(SR.ErrDirectoryContainsInvalidCharacters, arg, value, invalidCharacter)); } } private void ProcessOutputOption() { if (_arguments.ContainsArgument(Options.Cmd.Out)) { _parent._outputFileArg = _arguments.GetArgument(Options.Cmd.Out); if (_parent._outputFileArg != string.Empty) { SetAllowedModesFromOption(ToolMode.XmlSerializerGeneration, ToolMode.XmlSerializerGeneration, Options.Cmd.Out, ""); ValidatePath(Options.Cmd.Out, _parent._outputFileArg); } } else { _parent._outputFileArg = null; } } private void ReadInputArguments() { _parent._inputParameters = new List<string>(_arguments.GetArguments(String.Empty)); } private void ParseNamespaceMappings() { IList<string> namespaceMappingsArgs = _arguments.GetArguments(Options.Cmd.Namespace); _parent._namespaceMappings = new Dictionary<string, string>(namespaceMappingsArgs.Count); foreach (string namespaceMapping in namespaceMappingsArgs) { string[] parts = namespaceMapping.Split(','); if (parts == null || parts.Length != 2) throw new ToolOptionException(SR.Format(SR.ErrInvalidNamespaceArgument, Options.Cmd.Namespace, namespaceMapping)); string targetNamespace = parts[0].Trim(); string clrNamespace = parts[1].Trim(); if (_parent._namespaceMappings.ContainsKey(targetNamespace)) { string prevClrNamespace = _parent._namespaceMappings[targetNamespace]; if (prevClrNamespace != clrNamespace) throw new ToolOptionException(SR.Format(SR.ErrCannotSpecifyMultipleMappingsForNamespace, Options.Cmd.Namespace, targetNamespace, prevClrNamespace, clrNamespace)); } else { _parent._namespaceMappings.Add(targetNamespace, clrNamespace); } } } private void ParseReferenceAssemblies() { IList<string> referencedAssembliesArgs = _arguments.GetArguments(Options.Cmd.Reference); IList<string> excludeTypesArgs = _arguments.GetArguments(Options.Cmd.ExcludeType); IList<string> referencedCollectionTypesArgs = _arguments.GetArguments(Options.Cmd.CollectionType); bool nostdlib = _arguments.ContainsArgument(Options.Cmd.Nostdlib); if (excludeTypesArgs != null && excludeTypesArgs.Count > 0) SetAllowedModesFromOption(ToolMode.XmlSerializerGeneration, ToolMode.XmlSerializerGeneration, Options.Cmd.ExcludeType, null); AddReferencedTypes(referencedAssembliesArgs, excludeTypesArgs, referencedCollectionTypesArgs, nostdlib); _parent._typeResolver = CreateTypeResolver(_parent); } private void SetAllowedModesFromOption(ToolMode newDefaultMode, ToolMode allowedModes, string option, string value) { try { _parent.SetAllowedModes(newDefaultMode, allowedModes, option, value); } catch (InvalidToolModeException) { string optionStr = _parent.GetCommandLineString(option, value); if (_parent._modeSettingOption != null) { if (_parent._modeSettingOption == Options.Cmd.Target) { throw new ToolOptionException(SR.Format(SR.ErrOptionConflictsWithTarget, Options.Cmd.Target, _parent.ModeSettingValue, optionStr)); } else { string modeSettingStr = _parent.GetCommandLineString(_parent._modeSettingOption, _parent._modeSettingValue); throw new ToolOptionException(SR.Format(SR.ErrOptionModeConflict, optionStr, modeSettingStr)); } } else { throw new ToolOptionException(SR.Format(SR.ErrAmbiguousOptionModeConflict, optionStr)); } } } private void AddReferencedTypes(IList<string> referenceArgs, IList<string> excludedTypeArgs, IList<string> collectionTypesArgs, bool nostdlib) { _parent._referencedTypes = new List<Type>(); _parent._referencedAssemblies = new List<Assembly>(referenceArgs.Count); _parent._nostdlib = nostdlib; _parent._excludedTypes = AddSpecifiedTypesToDictionary(excludedTypeArgs, Options.Cmd.ExcludeType); Dictionary<string, Type> foundCollectionTypes = AddSpecifiedTypesToDictionary(collectionTypesArgs, Options.Cmd.CollectionType); LoadReferencedAssemblies(referenceArgs); foreach (Assembly assembly in _parent._referencedAssemblies) { AddReferencedTypesFromAssembly(assembly, foundCollectionTypes); } if (!nostdlib) { AddMscorlib(foundCollectionTypes); } } private void LoadReferencedAssemblies(IList<string> referenceArgs) { foreach (string path in referenceArgs) { Assembly assembly; try { assembly = InputModule.LoadAssembly(path); if (!_parent._referencedAssemblies.Contains(assembly)) { _parent._referencedAssemblies.Add(assembly); } else { throw new ToolOptionException(SR.Format(SR.ErrDuplicateReferenceValues, Options.Cmd.Reference, assembly.Location)); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; ToolConsole.WriteWarning(SR.Format(SR.ErrCouldNotLoadReferenceAssemblyAt, path)); } } } private Dictionary<string, Type> AddSpecifiedTypesToDictionary(IList<string> typeArgs, string cmd) { Dictionary<string, Type> specifiedTypes = new Dictionary<string, Type>(typeArgs.Count); foreach (string typeArg in typeArgs) { if (specifiedTypes.ContainsKey(typeArg)) throw new ToolOptionException(SR.Format(SR.ErrDuplicateValuePassedToTypeArg, cmd, typeArg)); specifiedTypes.Add(typeArg, null); } return specifiedTypes; } private void AddReferencedTypesFromAssembly(Assembly assembly, Dictionary<string, Type> foundCollectionTypes) { foreach (Type type in InputModule.LoadTypes(assembly)) { if (type.IsPublic || type.IsNestedPublic) { if (!_parent.IsTypeExcluded(type)) _parent._referencedTypes.Add(type); } } } private void AddMscorlib(Dictionary<string, Type> foundCollectionTypes) { Assembly mscorlib = typeof(int).Assembly; if (!_parent._referencedAssemblies.Contains(mscorlib)) { AddReferencedTypesFromAssembly(mscorlib, foundCollectionTypes); } } private void LoadSMReferenceAssembly() { string smReferenceArg = _arguments.GetArgument(Options.Cmd.SMReference); IList<string> referencedAssembliesArgs = smReferenceArg.Split(';').ToList(); if (referencedAssembliesArgs != null && referencedAssembliesArgs.Count > 0) { string smassembly = ""; string smpassembly = ""; foreach (string path in referencedAssembliesArgs) { var file = new FileInfo(path); if (file.Name.Equals("System.ServiceModel.Primitives.dll", StringComparison.OrdinalIgnoreCase)) { smassembly = path; } if (file.Name.Equals("System.Private.ServiceModel.dll", StringComparison.OrdinalIgnoreCase)) { smpassembly = path; } } if ((string.IsNullOrEmpty(smassembly)) || (string.IsNullOrEmpty(smpassembly))) { ToolConsole.WriteError("Missing one or both of the paths for System.ServiceModel.Primitives and System.Private.ServiceModel"); throw new ArgumentException("Invalid smreference value"); } try { ToolConsole.WriteLine("Load Assembly From " + smpassembly); InputModule.LoadAssembly(smpassembly); ToolConsole.WriteLine($"Successfully Load {smpassembly}"); } catch (Exception e) { ToolConsole.WriteError(string.Format("Fail to load the assembly {0} with the error {1}", smpassembly, e.Message)); throw; } try { ToolConsole.WriteLine("Load Assembly From " + smassembly); Tool.SMAssembly = InputModule.LoadAssembly(smassembly); ToolConsole.WriteLine($"Successfully Load {smassembly}"); } catch (Exception e) { ToolConsole.WriteError(string.Format("Fail to load the assembly {0} with the error {1}", smassembly, e.Message)); throw; } } else { ToolConsole.WriteError("Need to pass the System.ServiceModel.Primitives.dll and the System.Private.ServiceModel.dll paths through the 'smreference' parameter."); throw new ArgumentException("Need to pass the System.ServiceModel.Primitives.dll and the System.Private.ServiceModel.dll paths through the 'smreference' parameter."); } } internal static bool IsTypeSpecified(Type type, Dictionary<string, Type> specifiedTypes, string cmd) { Type foundType = null; string foundTypeName = null; // Search the Dictionary for the type // -------------------------------------------------------------------------------------------------------- if (specifiedTypes.TryGetValue(type.FullName, out foundType)) foundTypeName = type.FullName; if (specifiedTypes.TryGetValue(type.AssemblyQualifiedName, out foundType)) foundTypeName = type.AssemblyQualifiedName; // Throw appropriate error message if we found something and the entry value wasn't null // -------------------------------------------------------------------------------------------------------- if (foundTypeName != null) { if (foundType != null && foundType != type) { throw new ToolOptionException(SR.Format(SR.ErrCannotDisambiguateSpecifiedTypes, cmd, type.AssemblyQualifiedName, foundType.AssemblyQualifiedName)); } else { specifiedTypes[foundTypeName] = type; } return true; } return false; } static TypeResolver CreateTypeResolver(Options options) { TypeResolver typeResolver = new TypeResolver(options); AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(typeResolver.ResolveType); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(typeResolver.ResolveAssembly); return typeResolver; } } } }
// Copyright 2007 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Text; namespace Google.MailClientInterfaces { /// <summary> /// Interface for creating the email client objects /// </summary> public interface IClientFactory { /// <summary> /// Returns the list of process names that are associated with the client /// </summary> IEnumerable ClientProcessNames { get; } /// <summary> /// Creates the client object. /// </summary> IClient CreateClient(); } /// <summary> /// Interface representing the eMail client. For example: Outlook, Outlook /// Express, Thunderbird etc. /// </summary> public interface IClient : IDisposable { /// <summary> /// Name of the client. /// </summary> string Name { get; } /// <summary> /// Client stores currently opened by the client. /// </summary> IEnumerable Stores { get; } /// <summary> /// Identifies if the client supports contacts. /// </summary> bool SupportsContacts { get; } /// <summary> /// For opening a new store using the client. For example: opening mbox /// file in Thunderbird or pst in Outlook. If successful the opened store /// is added to the enumeration returned by Stores. /// </summary> /// <param name="filename">Name of the file containing the store.</param> /// <returns>Store if successful, null otherwise.</returns> IStore OpenStore(string filename); /// <summary> /// Retuns the list of file names of the stores loaded. /// </summary> IEnumerable LoadedStoreFileNames { get; } /// <summary> /// Identifies whether the client supports a loaded store. /// </summary> bool SupportsLoadingStore { get; } } /// <summary> /// The store containing the client email. /// </summary> public interface IStore { /// <summary> /// The client that opened this store. /// </summary> IClient Client { get; } /// <summary> /// Persisted name of the store. /// </summary> string PersistName { get; } /// <summary> /// Display name of the store. /// </summary> string DisplayName { get; } /// <summary> /// Folders in the store. /// </summary> IEnumerable Folders { get; } /// <summary> /// Count of number of contacts in the store. /// </summary> uint ContactCount { get; } /// <summary> /// Returns the list of contacts available with the client /// </summary> IEnumerable Contacts { get; } } /// <summary> /// Enumberation indicating if the folder is special. /// </summary> public enum FolderKind { /// <summary> /// The folder is inbox for the client. /// </summary> Inbox, /// <summary> /// The folder is sent items for the client. /// </summary> Sent, /// <summary> /// The folder stores draft (yet to be sent) mails. /// </summary> Draft, /// <summary> /// The folder stores deleted items. /// </summary> Trash, /// <summary> /// The folder is user created. /// </summary> Other, } /// <summary> /// Represents the folder in the client. /// </summary> public interface IFolder { /// <summary> /// Kind of the folder. /// </summary> FolderKind Kind { get; } /// <summary> /// The parent folder of this folder. Can be null if this is root folder /// in the store. /// </summary> IFolder ParentFolder { get; } /// <summary> /// The store that contains this folder. /// </summary> IStore Store { get; } /// <summary> /// Name of the folder. /// </summary> string Name { get; } /// <summary> /// Enumeration of all the direct subfolders of this folder. /// </summary> IEnumerable SubFolders { get; } /// <summary> /// Count of number of mails in the folder. /// </summary> uint MailCount { get; } /// <summary> /// Enumeration of the email in this folder. /// </summary> /// <remarks> /// To implementers: It is recomended that the mails are not stored in /// array lists as this would make them unclaimable by the garbage /// collector leading to blowup of memory usage. This property is best /// delay evaluated and not cached. Mails are to be read as the /// enumeration is done. /// </remarks> IEnumerable Mails { get; } } /// <summary> /// Represents the email. /// </summary> public interface IMail : IDisposable { /// <summary> /// Folder that contains the mail. /// </summary> IFolder Folder { get; } /// <summary> /// Identifier representing the mail. This should be same across /// Multiple instantiations of the client and should be persistable. /// </summary> string MailId { get; } /// <summary> /// Flag indicating that mail is marked in read state. /// </summary> bool IsRead { get; } /// <summary> /// Flag indicating that mail is marked/flagged in the client /// </summary> bool IsStarred { get; } /// <summary> /// Size of the message. Could be approximation. The exact size is given /// by the size of array returned by Rfc822Buffer. This is meant to /// filter out really huge mails. /// </summary> uint MessageSize { get; } /// <summary> /// Represents the rfc822 encoding of the contents of email. This includes /// the body as well as the attachments. In case of failure to read the /// message this returns an empty array. /// </summary> byte[] Rfc822Buffer { get; } } /// <summary> /// Represents the contact. /// </summary> public interface IContact : IDisposable { string ContactId { get; } string Title { get; } string OrganizationName { get; } string OrganizationTitle { get; } string HomePageUrl { get; } string Notes { get; } IEnumerable EmailAddresses { get; } IEnumerable IMIdentities { get; } IEnumerable PhoneNumbers { get; } IEnumerable PostalAddresses { get; } } public enum ContactRelation { Home, Mobile, Pager, Work, HomeFax, WorkFax, Other, Label, } public class ContactElement { string label; ContactRelation relation; public ContactElement(string label, ContactRelation relation) { this.label = label; this.relation = relation; } public string Label { get { return this.label; } } public ContactRelation Relation { get { return this.relation; } } } public class EmailContact : ContactElement { string emailAddress; bool isPrimary; public EmailContact(string emailAddress, string label, ContactRelation relation, bool isPrimary) : base(label, relation) { this.emailAddress = emailAddress; this.isPrimary = isPrimary; } public string EmailAddress { get { return this.emailAddress; } } public bool IsPrimary { get { return this.isPrimary; } } } public class IMContact : ContactElement { string imAddress; string protocol; public IMContact(string imAddress, string protocol, string label, ContactRelation relation) : base(label, relation) { this.imAddress = imAddress; this.protocol = protocol; } public string IMAddress { get { return this.imAddress; } } public string Protocol { get { return this.protocol; } } } public class PhoneContact : ContactElement { string phoneNumber; public PhoneContact(string phoneNumber, string label, ContactRelation relation) : base(label, relation) { this.phoneNumber = phoneNumber; } public string PhoneNumber { get { return this.phoneNumber; } } } public class PostalContact : ContactElement { string postalAddress; public PostalContact(string postalAddress, string label, ContactRelation relation) : base(label, relation) { this.postalAddress = postalAddress; } public string PostalAddress { get { return this.postalAddress; } } } /// <summary> /// Assembly level attribute used to identify the type implementing /// IClientFactory in the assembly which implements mail reading from /// client. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public class ClientFactoryAttribute : Attribute { Type clientFactoryType; /// <summary> /// Constructor for the MailClientAttrbute. /// </summary> /// <param name="clientFactoryType"> /// The type implementing IClientFactory /// </param> public ClientFactoryAttribute(Type clientFactoryType) { this.clientFactoryType = clientFactoryType; } /// <summary> /// Returns the mail client type that implements IClientFactory. /// </summary> public Type ClientFactoryType { get { return this.clientFactoryType; } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah.Assertions { #region Imports using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using Microsoft.JScript; using Microsoft.JScript.Vsa; using Convert=Microsoft.JScript.Convert; #endregion /// <summary> /// An assertion implementation that uses a JScript expression to /// determine the outcome. /// </summary> /// <remarks> /// Each instance of this type maintains a separate copy of the JScript /// engine so use it sparingly. For example, instead of creating several /// objects, each with different a expression, try and group all /// expressions that apply to particular context into a single compound /// JScript expression using the conditional-OR (||) operator. /// </remarks> public sealed class JScriptAssertion : IAssertion { private static readonly Regex _directiveExpression = new Regex( @"^ \s* // \s* @([a-zA-Z]+)", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); private readonly EvaluationStrategy _evaluationStrategy; public JScriptAssertion(string expression) : this(expression, null, null) {} public JScriptAssertion(string expression, string[] assemblyNames, string[] imports) { if (expression == null || expression.Length == 0 || expression.TrimStart().Length == 0) { return; } ProcessDirectives(expression, ref assemblyNames, ref imports); VsaEngine engine = VsaEngine.CreateEngineAndGetGlobalScope(/* fast */ false, assemblyNames != null ? assemblyNames : new string[0]).engine; if (imports != null && imports.Length > 0) { foreach (string import in imports) Import.JScriptImport(import, engine); } // // We pick on of two expression evaluation strategies depending // on the level of trust available. The full trust version is // faster as it compiles the expression once into a JScript // function and then simply invokes at the time it needs to // evaluate the context. The partial trust strategy is slower // as it compiles the expression each time an evaluation occurs // using the JScript eval. // _evaluationStrategy = FullTrustEvaluationStrategy.IsApplicable() ? (EvaluationStrategy) new FullTrustEvaluationStrategy(expression, engine) : new PartialTrustEvaluationStrategy(expression, engine); } public JScriptAssertion(NameValueCollection settings) : this(settings["expression"], settings.GetValues("assembly"), settings.GetValues("import")) {} public bool Test(object context) { if (context == null) throw new ArgumentNullException("context"); return _evaluationStrategy != null && _evaluationStrategy.Eval(context); } private static void ProcessDirectives(string expression, ref string[] assemblyNames, ref string[] imports) { Debug.Assert(expression != null); ArrayList assemblyNameList = null, importList = null; using (StringReader reader = new StringReader(expression)) { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { lineNumber++; if (line.Trim().Length == 0) continue; Match match = _directiveExpression.Match(line); if (!match.Success) // Exit processing on first non-match break; string directive = match.Groups[1].Value; string tail = line.Substring(match.Index + match.Length).Trim(); try { switch (directive) { case "assembly": assemblyNameList = AddDirectiveParameter(directive, tail, assemblyNameList, assemblyNames); break; case "import": importList = AddDirectiveParameter(directive, tail, importList, imports); break; default: throw new FormatException(string.Format("'{0}' is not a recognized directive.", directive)); } } catch (FormatException e) { throw new ArgumentException( string.Format( "Error processing directives section (lead comment) of the JScript expression (see line {0}). {1}", lineNumber.ToString("N0"), e.Message), "expression"); } } } assemblyNames = ListOrElseArray(assemblyNameList, assemblyNames); imports = ListOrElseArray(importList, imports); } private static ArrayList AddDirectiveParameter(string directive, string parameter, ArrayList list, string[] inits) { Debug.AssertStringNotEmpty(directive); Debug.Assert(parameter != null); if (parameter.Length == 0) throw new FormatException(string.Format("Missing parameter for {0} directive.", directive)); if (list == null) { list = new ArrayList(/* capacity */ (inits != null ? inits.Length : 0) + 4); if (inits != null) list.AddRange(inits); } list.Add(parameter); return list; } private static string[] ListOrElseArray(ArrayList list, string[] array) { return list != null ? (string[]) list.ToArray(typeof(string)) : array; } private abstract class EvaluationStrategy { private readonly VsaEngine _engine; protected EvaluationStrategy(VsaEngine engine) { Debug.Assert(engine != null); _engine = engine; } public VsaEngine Engine { get { return _engine; } } public abstract bool Eval(object context); } /// <summary> /// Uses the JScript eval function to compile and evaluate the /// expression against the context on each evaluation. /// </summary> private sealed class PartialTrustEvaluationStrategy : EvaluationStrategy { private readonly string _expression; private readonly GlobalScope _scope; private readonly FieldInfo _oldContextField; private readonly FieldInfo _newContextField; public PartialTrustEvaluationStrategy(string expression, VsaEngine engine) : base(engine) { // // Following is equivalent to declaring a "var" in JScript // at the level of the Global object. // _scope = (GlobalScope)engine.GetGlobalScope().GetObject(); _oldContextField = _scope.AddField("$context"); _newContextField = _scope.AddField("$"); _expression = expression; } public override bool Eval(object context) { VsaEngine engine = Engine; // // Following is equivalent to calling eval in JScript, // with the value of the context variable established at the // global scope in order for it to be available to the // expression source. // _oldContextField.SetValue(_scope, context); _newContextField.SetValue(_scope, context); try { With.JScriptWith(context, engine); return Convert.ToBoolean(Microsoft.JScript.Eval.JScriptEvaluate(_expression, engine)); } finally { engine.PopScriptObject(/* with */); } } } /// <summary> /// Compiles the given expression into a JScript function at time of /// construction and then simply invokes it during evaluation, using /// the context as a parameter. /// </summary> private sealed class FullTrustEvaluationStrategy : EvaluationStrategy { private readonly object _function; public FullTrustEvaluationStrategy(string expression, VsaEngine engine) : base(engine) { // // Equivalent to following in JScript: // new Function('$context', 'with ($context) return (' + expression + ')'); // // IMPORTANT! Leave the closing parentheses surrounding the // return expression on a separate line. This is to guard // against someone using a double-slash (//) to comment out // the remainder of an expression. // const string context = "$context"; _function = LateBinding.CallValue( DefaultThisObject(engine), engine.LenientGlobalObject.Function, new object[] { /* parameters */ context + ",$", /* body... */ @" with (" + context + @") { return ( " + expression + @" ); }" }, /* construct */ true, /* brackets */ false, engine); } public override bool Eval(object context) { // // Following is equivalent to calling apply in JScript. // See http://msdn.microsoft.com/en-us/library/84ht5z59.aspx. // object result = LateBinding.CallValue( DefaultThisObject(Engine), _function, /* args */ new object[] { context, context }, /* construct */ false, /* brackets */ false, Engine); return Convert.ToBoolean(result); } private static object DefaultThisObject(VsaEngine engine) { Debug.Assert(engine != null); return ((IActivationObject) engine.ScriptObjectStackTop()).GetDefaultThisObject(); } public static bool IsApplicable() { try { // // FullTrustEvaluationStrategy uses Microsoft.JScript.GlobalObject.Function.CreateInstance, // which requires unmanaged code permission... // new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); return true; } catch (SecurityException) { return false; } } } } }
// 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 System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Extensions.JsonParser.Sources; using Microsoft.Extensions.ProjectModel.Utilities; using NuGet.Frameworks; using NuGet.Packaging.Core; using NuGet.Versioning; namespace Microsoft.Extensions.ProjectModel.Graph { internal static class LockFileReader { public static LockFile Read(string filePath) { using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { try { return Read(stream); } catch (FileFormatException ex) { throw ex.WithFilePath(filePath); } catch (Exception ex) { throw FileFormatException.Create(ex, filePath); } } } internal static LockFile Read(Stream stream) { try { var reader = new StreamReader(stream); var jobject = JsonDeserializer.Deserialize(reader) as JsonObject; if (jobject != null) { return ReadLockFile(jobject); } else { throw new InvalidDataException(); } } catch { // Ran into parsing errors, mark it as unlocked and out-of-date return new LockFile { Version = int.MinValue }; } } private static LockFile ReadLockFile(JsonObject cursor) { var lockFile = new LockFile(); lockFile.Version = ReadInt(cursor, "version", defaultValue: int.MinValue); lockFile.Targets = ReadObject(cursor.ValueAsJsonObject("targets"), ReadTarget); lockFile.ProjectFileDependencyGroups = ReadObject(cursor.ValueAsJsonObject("projectFileDependencyGroups"), ReadProjectFileDependencyGroup); ReadLibrary(cursor.ValueAsJsonObject("libraries"), lockFile); return lockFile; } private static void ReadLibrary(JsonObject json, LockFile lockFile) { if (json == null) { return; } foreach (var key in json.Keys) { var value = json.ValueAsJsonObject(key); if (value == null) { throw FileFormatException.Create("The value type is not object.", json.Value(key)); } var parts = key.Split(new[] { '/' }, 2); var name = parts[0]; var version = parts.Length == 2 ? NuGetVersion.Parse(parts[1]) : null; var type = value.ValueAsString("type")?.Value; if (type == null || string.Equals(type, "package", StringComparison.OrdinalIgnoreCase)) { lockFile.PackageLibraries.Add(new LockFilePackageLibrary { Name = name, Version = version, IsServiceable = ReadBool(value, "serviceable", defaultValue: false), Sha512 = ReadString(value.Value("sha512")), Files = ReadPathArray(value.Value("files"), ReadString) }); } else if (type == "project") { lockFile.ProjectLibraries.Add(new LockFileProjectLibrary { Name = name, Version = version, Path = ReadString(value.Value("path")) }); } } } private static LockFileTarget ReadTarget(string property, JsonValue json) { var jobject = json as JsonObject; if (jobject == null) { throw FileFormatException.Create("The value type is not an object.", json); } var target = new LockFileTarget(); var parts = property.Split(new[] { '/' }, 2); target.TargetFramework = NuGetFramework.Parse(parts[0]); if (parts.Length == 2) { target.RuntimeIdentifier = parts[1]; } target.Libraries = ReadObject(jobject, ReadTargetLibrary); return target; } private static LockFileTargetLibrary ReadTargetLibrary(string property, JsonValue json) { var jobject = json as JsonObject; if (jobject == null) { throw FileFormatException.Create("The value type is not an object.", json); } var library = new LockFileTargetLibrary(); var parts = property.Split(new[] { '/' }, 2); library.Name = parts[0]; if (parts.Length == 2) { library.Version = NuGetVersion.Parse(parts[1]); } library.Type = jobject.ValueAsString("type"); var framework = jobject.ValueAsString("framework"); if (framework != null) { library.TargetFramework = NuGetFramework.Parse(framework); } library.Dependencies = ReadObject(jobject.ValueAsJsonObject("dependencies"), ReadPackageDependency); library.FrameworkAssemblies = new HashSet<string>(ReadArray(jobject.Value("frameworkAssemblies"), ReadFrameworkAssemblyReference), StringComparer.OrdinalIgnoreCase); library.RuntimeAssemblies = ReadObject(jobject.ValueAsJsonObject("runtime"), ReadFileItem); library.CompileTimeAssemblies = ReadObject(jobject.ValueAsJsonObject("compile"), ReadFileItem); library.ResourceAssemblies = ReadObject(jobject.ValueAsJsonObject("resource"), ReadFileItem); library.NativeLibraries = ReadObject(jobject.ValueAsJsonObject("native"), ReadFileItem); return library; } private static ProjectFileDependencyGroup ReadProjectFileDependencyGroup(string property, JsonValue json) { return new ProjectFileDependencyGroup( string.IsNullOrEmpty(property) ? null : NuGetFramework.Parse(property), ReadArray(json, ReadString)); } private static PackageDependency ReadPackageDependency(string property, JsonValue json) { var versionStr = ReadString(json); return new PackageDependency( property, versionStr == null ? null : VersionRange.Parse(versionStr)); } private static LockFileItem ReadFileItem(string property, JsonValue json) { var item = new LockFileItem { Path = PathUtility.GetPathWithDirectorySeparator(property) }; var jobject = json as JsonObject; if (jobject != null) { foreach (var subProperty in jobject.Keys) { item.Properties[subProperty] = jobject.ValueAsString(subProperty); } } return item; } private static string ReadFrameworkAssemblyReference(JsonValue json) { return ReadString(json); } private static IList<TItem> ReadArray<TItem>(JsonValue json, Func<JsonValue, TItem> readItem) { if (json == null) { return new List<TItem>(); } var jarray = json as JsonArray; if (jarray == null) { throw FileFormatException.Create("The value type is not array.", json); } var items = new List<TItem>(); for (int i = 0; i < jarray.Length; ++i) { items.Add(readItem(jarray[i])); } return items; } private static IList<string> ReadPathArray(JsonValue json, Func<JsonValue, string> readItem) { return ReadArray(json, readItem).Select(f => PathUtility.GetPathWithDirectorySeparator(f)).ToList(); } private static IList<TItem> ReadObject<TItem>(JsonObject json, Func<string, JsonValue, TItem> readItem) { if (json == null) { return new List<TItem>(); } var items = new List<TItem>(); foreach (var childKey in json.Keys) { items.Add(readItem(childKey, json.Value(childKey))); } return items; } private static bool ReadBool(JsonObject cursor, string property, bool defaultValue) { var valueToken = cursor.Value(property) as JsonBoolean; if (valueToken == null) { return defaultValue; } return valueToken.Value; } private static int ReadInt(JsonObject cursor, string property, int defaultValue) { var number = cursor.Value(property) as JsonNumber; if (number == null) { return defaultValue; } try { var resultInInt = Convert.ToInt32(number.Raw); return resultInInt; } catch (Exception ex) { // FormatException or OverflowException throw FileFormatException.Create(ex, cursor); } } private static string ReadString(JsonValue json) { if (json is JsonString) { return (json as JsonString).Value; } else if (json is JsonNull) { return null; } else { throw FileFormatException.Create("The value type is not string.", json); } } } }
/////////////////////////////////////////////////////////////////////////////// //File: Wrapper.cs // //Description: Contains the interface definitions for the MetaViewWrappers classes. // //References required: // System.Drawing // //This file is Copyright (c) 2010 VirindiPlugins // //Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; #if METAVIEW_PUBLIC_NS namespace MetaViewWrappers #else namespace MyClasses.MetaViewWrappers #endif { #if VVS_WRAPPERS_PUBLIC public #else internal #endif delegate void dClickedList(object sender, int row, int col); #region EventArgs Classes public class MVControlEventArgs : EventArgs { private int id; internal MVControlEventArgs(int ID) { this.id = ID; } public int Id { get { return this.id; } } } public class MVIndexChangeEventArgs : MVControlEventArgs { private int index; internal MVIndexChangeEventArgs(int ID, int Index) : base(ID) { this.index = Index; } public int Index { get { return this.index; } } } public class MVListSelectEventArgs : MVControlEventArgs { private int row; private int col; internal MVListSelectEventArgs(int ID, int Row, int Column) : base(ID) { this.row = Row; this.col = Column; } public int Row { get { return this.row; } } public int Column { get { return this.col; } } } public class MVCheckBoxChangeEventArgs : MVControlEventArgs { private bool check; internal MVCheckBoxChangeEventArgs(int ID, bool Check) : base(ID) { this.check = Check; } public bool Checked { get { return this.check; } } } public class MVTextBoxChangeEventArgs : MVControlEventArgs { private string text; internal MVTextBoxChangeEventArgs(int ID, string text) : base(ID) { this.text = text; } public string Text { get { return this.text; } } } public class MVTextBoxEndEventArgs : MVControlEventArgs { private bool success; internal MVTextBoxEndEventArgs(int ID, bool success) : base(ID) { this.success = success; } public bool Success { get { return this.success; } } } #endregion EventArgs Classes #region View #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IView: IDisposable { void Initialize(Decal.Adapter.Wrappers.PluginHost p, string pXML); void InitializeRawXML(Decal.Adapter.Wrappers.PluginHost p, string pXML); void SetIcon(int icon, int iconlibrary); void SetIcon(int portalicon); string Title { get; set; } bool Visible { get; set; } #if !VVS_WRAPPERS_PUBLIC ViewSystemSelector.eViewSystem ViewType { get; } #endif System.Drawing.Point Location { get; set; } System.Drawing.Rectangle Position { get; set; } System.Drawing.Size Size { get; } IControl this[string id] { get; } void Activate(); void Deactivate(); bool Activated { get; set; } } #endregion View #region Controls #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IControl : IDisposable { string Name { get; } bool Visible { get; } string TooltipText { get; set;} } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IButton : IControl { string Text { get; set; } event EventHandler Hit; event EventHandler<MVControlEventArgs> Click; System.Drawing.Color TextColor { get; set; } } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface ICheckBox : IControl { string Text { get; set; } bool Checked { get; set; } event EventHandler<MVCheckBoxChangeEventArgs> Change; event EventHandler Change_Old; } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface ITextBox : IControl { string Text { get; set; } event EventHandler<MVTextBoxChangeEventArgs> Change; event EventHandler Change_Old; event EventHandler<MVTextBoxEndEventArgs> End; int Caret { get; set; } } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface ICombo : IControl { IComboIndexer Text { get; } IComboDataIndexer Data { get; } int Count { get; } int Selected { get; set; } event EventHandler<MVIndexChangeEventArgs> Change; event EventHandler Change_Old; void Add(string text); void Add(string text, object obj); void Insert(int index, string text); void RemoveAt(int index); void Remove(int index); void Clear(); } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IComboIndexer { string this[int index] { get; set; } } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IComboDataIndexer { object this[int index] { get; set; } } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface ISlider : IControl { int Position { get; set; } event EventHandler<MVIndexChangeEventArgs> Change; event EventHandler Change_Old; } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IList : IControl { event EventHandler<MVListSelectEventArgs> Selected; event dClickedList Click; void Clear(); IListRow this[int row] { get; } IListRow AddRow(); IListRow Add(); IListRow InsertRow(int pos); IListRow Insert(int pos); int RowCount { get; } void RemoveRow(int index); void Delete(int index); int ColCount { get; } int ScrollPosition { get; set;} } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IListRow { IListCell this[int col] { get; } } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IListCell { System.Drawing.Color Color { get; set; } int Width { get; set; } object this[int subval] { get; set; } void ResetColor(); } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IStaticText : IControl { string Text { get; set; } event EventHandler<MVControlEventArgs> Click; } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface INotebook : IControl { event EventHandler<MVIndexChangeEventArgs> Change; int ActiveTab { get; set; } } #if VVS_WRAPPERS_PUBLIC public #else internal #endif interface IProgressBar : IControl { int Position { get; set; } int Value { get; set; } string PreText { get; set; } } #endregion Controls }
//----------------------------------------------------------------------- // <copyright file="GvrKeyboard.cs" company="Google Inc."> // Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- using UnityEngine; using UnityEngine.EventSystems; using Gvr.Internal; using System; using System.Collections; using System.Collections.Generic; /// <summary>Events to update the keyboard.</summary> /// <remarks>These values depend on C API keyboard values.</remarks> public enum GvrKeyboardEvent { /// Unknown error. GVR_KEYBOARD_ERROR_UNKNOWN = 0, /// The keyboard service could not be connected. This is usually due to the /// keyboard service not being installed. GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED = 1, /// No locale was found in the keyboard service. GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND = 2, /// The keyboard SDK tried to load dynamically but failed. This is usually due /// to the keyboard service not being installed or being out of date. GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED = 3, /// Keyboard becomes visible. GVR_KEYBOARD_SHOWN = 4, /// Keyboard becomes hidden. GVR_KEYBOARD_HIDDEN = 5, /// Text has been updated. GVR_KEYBOARD_TEXT_UPDATED = 6, /// Text has been committed. GVR_KEYBOARD_TEXT_COMMITTED = 7 } /// <summary>Keyboard error codes.</summary> /// <remarks>These values depend on C API keyboard values.</remarks> public enum GvrKeyboardError { UNKNOWN = 0, SERVICE_NOT_CONNECTED = 1, NO_LOCALES_FOUND = 2, SDK_LOAD_FAILED = 3 } /// <summary>The keyboard input modes.</summary> /// <remarks>These values depend on C API keyboard values.</remarks> public enum GvrKeyboardInputMode { DEFAULT = 0, NUMERIC = 1 } /// <summary>Handles keyboard state management such as hiding and displaying /// the keyboard, directly modifying text and stereoscopic rendering.</summary> [HelpURL("https://developers.google.com/vr/unity/reference/class/GvrKeyboard")] public class GvrKeyboard : MonoBehaviour { private static GvrKeyboard instance; private static IKeyboardProvider keyboardProvider; private KeyboardState keyboardState = new KeyboardState(); private IEnumerator keyboardUpdate; /// <summary>Standard keyboard delegate type.</summary> public delegate void StandardCallback(); /// <summary>Edit text keyboard delegate type.</summary> public delegate void EditTextCallback(string edit_text); /// <summary>Keyboard error delegate type.</summary> public delegate void ErrorCallback(GvrKeyboardError err); /// <summary>Keyboard delegate type.</summary> public delegate void KeyboardCallback(IntPtr closure, GvrKeyboardEvent evt); // Private data and callbacks. private ErrorCallback errorCallback = null; private StandardCallback showCallback = null; private StandardCallback hideCallback = null; private EditTextCallback updateCallback = null; private EditTextCallback enterCallback = null; #if UNITY_ANDROID // Which eye is currently being rendered. private bool isRight = false; #endif // UNITY_ANDROID private bool isKeyboardHidden = false; private const float kExecuterWait = 0.01f; private static List<GvrKeyboardEvent> threadSafeCallbacks = new List<GvrKeyboardEvent>(); private static System.Object callbacksLock = new System.Object(); /// <summary>Delegate to handle keyboard events and input.</summary> public GvrKeyboardDelegateBase keyboardDelegate = null; /// <summary>The input mode of the keyboard.</summary> public GvrKeyboardInputMode inputMode = GvrKeyboardInputMode.DEFAULT; /// <summary>Flag to use the recommended world matrix for the keyboard.</summary> public bool useRecommended = true; /// <summary>The distance to the keyboard.</summary> public float distance = 0; /// <summary>The text being affected by this keyboard.</summary> public string EditorText { get { return instance != null ? instance.keyboardState.editorText : string.Empty; } set { keyboardProvider.EditorText = value; } } /// <summary>Returns the current input mode of the keyboard.</summary> public GvrKeyboardInputMode Mode { get { return instance != null ? instance.keyboardState.mode : GvrKeyboardInputMode.DEFAULT; } } /// <summary>Returns true if this keyboard instance is valid.</summary> public bool IsValid { get { return instance != null ? instance.keyboardState.isValid : false; } } /// <summary>Returns true if the keyboard is ready.</summary> public bool IsReady { get { return instance != null ? instance.keyboardState.isReady : false; } } /// <summary> The world matrix of the keyboard.</summary> public Matrix4x4 WorldMatrix { get { return instance != null ? instance.keyboardState.worldMatrix : Matrix4x4.zero; } } void Awake() { if (instance != null) { Debug.LogError("More than one GvrKeyboard instance was found in your scene. " + "Ensure that there is only one GvrKeyboard."); enabled = false; return; } instance = this; if (keyboardProvider == null) { keyboardProvider = KeyboardProviderFactory.CreateKeyboardProvider(this); } } void OnDestroy() { instance = null; threadSafeCallbacks.Clear(); } // Use this for initialization. void Start() { if (keyboardDelegate != null) { errorCallback = keyboardDelegate.OnKeyboardError; showCallback = keyboardDelegate.OnKeyboardShow; hideCallback = keyboardDelegate.OnKeyboardHide; updateCallback = keyboardDelegate.OnKeyboardUpdate; enterCallback = keyboardDelegate.OnKeyboardEnterPressed; keyboardDelegate.KeyboardHidden += KeyboardDelegate_KeyboardHidden; keyboardDelegate.KeyboardShown += KeyboardDelegate_KeyboardShown; } keyboardProvider.ReadState(keyboardState); if (IsValid) { if (keyboardProvider.Create(OnKeyboardCallback)) { keyboardProvider.SetInputMode(inputMode); } } else { Debug.LogError("Could not validate keyboard"); } } // Update per-frame data. void Update() { if (keyboardProvider == null) { return; } keyboardProvider.ReadState(keyboardState); if (IsReady) { // Reset position of keyboard. if (transform.hasChanged) { Show(); transform.hasChanged = false; } keyboardProvider.UpdateData(); } } // Use this function for procedural rendering // Gets called twice per frame, once for each eye. // On each frame, left eye renders before right eye so // we keep track of a boolean that toggles back and forth // between each eye. void OnRenderObject() { if (keyboardProvider == null || !IsReady) { return; } #if UNITY_ANDROID Camera camera = Camera.current; if (camera && camera == Camera.main) { // Get current eye. Camera.StereoscopicEye camEye = isRight ? Camera.StereoscopicEye.Right : Camera.StereoscopicEye.Left; // Camera matrices. Matrix4x4 proj = camera.GetStereoProjectionMatrix(camEye); Matrix4x4 modelView = camera.GetStereoViewMatrix(camEye); // Camera viewport. Rect viewport = camera.pixelRect; // Render keyboard. keyboardProvider.Render((int)camEye, modelView, proj, viewport); // Swap. isRight = !isRight; } #endif // !UNITY_ANDROID } /// <summary>Resets keyboard text.</summary> public void ClearText() { if (keyboardProvider != null) { keyboardProvider.EditorText = string.Empty; } } /// <summary>Shows the keyboard.</summary> public void Show() { if (keyboardProvider == null) { return; } // Get user matrix. Quaternion fixRot = new Quaternion(transform.rotation.x * -1, transform.rotation.y * -1, transform.rotation.z, transform.rotation.w); // Need to convert from left handed to right handed for the Keyboard coordinates. Vector3 fixPos = new Vector3(transform.position.x, transform.position.y, transform.position.z * -1); Matrix4x4 modelMatrix = Matrix4x4.TRS(fixPos, fixRot, Vector3.one); Matrix4x4 mat = Matrix4x4.identity; Vector3 position = gameObject.transform.position; if (position.x == 0 && position.y == 0 && position.z == 0 && !useRecommended) { // Force use recommended to be true, otherwise keyboard won't show up. keyboardProvider.Show(mat, true, distance, modelMatrix); return; } // Matrix needs to be set only if we're not using the recommended one. // Uses the values of the keyboard gameobject transform as reported by Unity. If this is // the zero vector, parent it under another gameobject instead. if (!useRecommended) { mat = GetKeyboardObjectMatrix(position); } keyboardProvider.Show(mat, useRecommended, distance, modelMatrix); } /// <summary>Hides the keyboard.</summary> public void Hide() { if (keyboardProvider != null) { keyboardProvider.Hide(); } } /// <summary>Handle a pointer click on the keyboard.</summary> public void OnPointerClick(BaseEventData data) { if (isKeyboardHidden) { Show(); } } void OnEnable() { keyboardUpdate = Executer(); StartCoroutine(keyboardUpdate); } void OnDisable() { StopCoroutine(keyboardUpdate); } void OnApplicationPause(bool paused) { if (null == keyboardProvider) { return; } if (paused) { keyboardProvider.OnPause(); } else { keyboardProvider.OnResume(); } } IEnumerator Executer() { while (true) { yield return new WaitForSeconds(kExecuterWait); while (threadSafeCallbacks.Count > 0) { GvrKeyboardEvent keyboardEvent = threadSafeCallbacks[0]; PoolKeyboardCallbacks(keyboardEvent); lock (callbacksLock) { threadSafeCallbacks.RemoveAt(0); } } } } private void PoolKeyboardCallbacks(GvrKeyboardEvent keyboardEvent) { switch (keyboardEvent) { case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_UNKNOWN: errorCallback(GvrKeyboardError.UNKNOWN); break; case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SERVICE_NOT_CONNECTED: errorCallback(GvrKeyboardError.SERVICE_NOT_CONNECTED); break; case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_NO_LOCALES_FOUND: errorCallback(GvrKeyboardError.NO_LOCALES_FOUND); break; case GvrKeyboardEvent.GVR_KEYBOARD_ERROR_SDK_LOAD_FAILED: errorCallback(GvrKeyboardError.SDK_LOAD_FAILED); break; case GvrKeyboardEvent.GVR_KEYBOARD_SHOWN: showCallback(); break; case GvrKeyboardEvent.GVR_KEYBOARD_HIDDEN: hideCallback(); break; case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_UPDATED: updateCallback(keyboardProvider.EditorText); break; case GvrKeyboardEvent.GVR_KEYBOARD_TEXT_COMMITTED: enterCallback(keyboardProvider.EditorText); break; } } [AOT.MonoPInvokeCallback(typeof(GvrKeyboardEvent))] private static void OnKeyboardCallback(IntPtr closure, GvrKeyboardEvent keyboardEvent) { lock (callbacksLock) { threadSafeCallbacks.Add(keyboardEvent); } } private void KeyboardDelegate_KeyboardShown(object sender, System.EventArgs e) { isKeyboardHidden = false; } private void KeyboardDelegate_KeyboardHidden(object sender, System.EventArgs e) { isKeyboardHidden = true; } // Returns a matrix populated by the keyboard's gameobject position. If the position is not // zero, but comes back as zero, parent this under another gameobject instead. private Matrix4x4 GetKeyboardObjectMatrix(Vector3 position) { // Set keyboard position based on this gameObject's position. float angleX = Mathf.Atan2(position.y, position.x); float kTanAngleX = Mathf.Tan(angleX); float newPosX = kTanAngleX * position.x; float angleY = Mathf.Atan2(position.x, position.y); float kTanAngleY = Mathf.Tan(angleY); float newPosY = kTanAngleY * position.y; float angleZ = Mathf.Atan2(position.y, position.z); float kTanAngleZ = Mathf.Tan(angleZ); float newPosZ = kTanAngleZ * position.z; Vector3 keyboardPosition = new Vector3(newPosX, newPosY, newPosZ); Vector3 lookPosition = Camera.main.transform.position; Quaternion rotation = Quaternion.LookRotation(lookPosition); Matrix4x4 mat = new Matrix4x4(); mat.SetTRS(keyboardPosition, rotation, position); // Set diagonal to identity if any of them are zero. if (mat[0, 0] == 0) { Vector4 row0 = mat.GetRow(0); mat.SetRow(0, new Vector4(1, row0.y, row0.z, row0.w)); } if (mat[1, 1] == 0) { Vector4 row1 = mat.GetRow(1); mat.SetRow(1, new Vector4(row1.x, 1, row1.z, row1.w)); } if (mat[2, 2] == 0) { Vector4 row2 = mat.GetRow(2); mat.SetRow(2, new Vector4(row2.x, row2.y, 1, row2.w)); } return mat; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using Voyage.Terraingine.DXViewport; using Voyage.Terraingine.DataCore; namespace Voyage.Terraingine { /// <summary> /// Summary description for TerrainCreation. /// </summary> public class TerrainCreation : TerrainViewport { #region Data Members private bool _accepted; private DataInterfacing.DataManipulation _terrainData; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown numRows; private System.Windows.Forms.NumericUpDown numColumns; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.CheckBox chkGridDimensions; private System.Windows.Forms.GroupBox grpGridDimensions; private System.Windows.Forms.CheckBox chkGridSize; private System.Windows.Forms.NumericUpDown numColumnDistance; private System.Windows.Forms.NumericUpDown numRowDistance; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.GroupBox grpGridSize; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; #endregion #region Properties /// <summary> /// Gets if the OK button has been pressed. /// </summary> public bool Accepted { get { return _accepted; } } #endregion #region Basic Form Functions /// <summary> /// Creates the TerrainCreation form. /// </summary> public TerrainCreation() { // // Required for Windows Form Designer support // InitializeComponent(); this.CenterToParent(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Initialization /// <summary> /// Creates the TerrainCreation form. /// </summary> private void TerrainCreation_Load(object sender, System.EventArgs e) { // DXViewport initialization _viewport.InitializeViewport(); _viewport.InitializeDXDefaults(); _viewport.DXViewport.ClearColor = Color.Gray; _viewport.DXViewport.Camera.FirstPerson = false; _viewport.FillMode = FillMode.WireFrame; _viewport.CullMode = Cull.CounterClockwise; _viewport.DXViewport.Camera.FollowDistance = 2.0f; _viewport.InitializeCamera(); // Terrain initialization _viewport.TerrainData.EnableLighting = false; // Additional uninherited initialization _accepted = false; _terrainData = new DataInterfacing.DataManipulation( _viewport.DXViewport ); UpdateTerrain(); } #endregion #region Terrain Functions /// <summary> /// Creates the TerrainPatch of the form. /// </summary> /// <param name="rows">The number of rows in the TerrainPatch.</param> /// <param name="columns">The number of columns in the TerrainPatch.</param> /// <param name="height">The total height of the TerrainPatch.</param> /// <param name="width">The total width of the TerrainPatch.</param> public void CreateTerrain( int rows, int columns, float height, float width ) { if ( _viewport.TerrainData.TerrainPage != null ) _viewport.TerrainData.TerrainPage.Dispose(); _viewport.TerrainData.TerrainPage = _terrainData.CreateTerrain( rows, columns, height, width ); _viewport.TerrainData.RefreshAllBuffers(); if ( height > width ) _viewport.DXViewport.Camera.FollowDistance = height * 2.0f; else _viewport.DXViewport.Camera.FollowDistance = width * 2.0f; _viewport.InitializeCamera(); } /// <summary> /// Updates the TerrainPatch in the form. /// </summary> private void UpdateTerrain() { CreateTerrain( Convert.ToInt32( numRows.Value ), Convert.ToInt32( numColumns.Value ), ( float ) numRowDistance.Value, ( float ) numColumnDistance.Value ); } /// <summary> /// Cancels the TerrainPatch creation. /// </summary> public void btnCancel_Click() { this.Close(); } /// <summary> /// Updates and accepts the TerrainPatch creation. /// </summary> public void btnOK_Click() { UpdateTerrain(); _accepted = true; this.Close(); } #endregion #region Button Clicks /// <summary> /// Cancels the TerrainPatch creation. /// </summary> private void btnCancel_Click(object sender, System.EventArgs e) { btnCancel_Click(); } /// <summary> /// Updates and accepts the TerrainPatch creation. /// </summary> private void btnOK_Click(object sender, System.EventArgs e) { btnOK_Click(); } #endregion #region Other Form Callbacks /// <summary> /// Updates the TerrainPage when the control has a changed value. /// </summary> private void numRows_ValueChanged(object sender, System.EventArgs e) { if ( chkGridDimensions.Checked ) numColumns.Value = numRows.Value; UpdateTerrain(); } /// <summary> /// Updates the TerrainPage when the control has a changed value. /// </summary> private void numColumns_ValueChanged(object sender, System.EventArgs e) { if ( chkGridDimensions.Checked ) numRows.Value = numColumns.Value; UpdateTerrain(); } /// <summary> /// Updates the TerrainPage when the control loses focus. /// </summary> private void numRows_Leave(object sender, System.EventArgs e) { if ( chkGridDimensions.Checked ) numColumns.Value = numRows.Value; UpdateTerrain(); } /// <summary> /// Updates the TerrainPage when the control loses focus. /// </summary> private void numColumns_Leave(object sender, System.EventArgs e) { if ( chkGridDimensions.Checked ) numRows.Value = numColumns.Value; UpdateTerrain(); } /// <summary> /// Keeps the rows and columns equal in the TerrainPatch. /// </summary> private void chkGridDimensions_CheckedChanged(object sender, System.EventArgs e) { if ( chkGridDimensions.Checked ) { numColumns.Value = numRows.Value; UpdateTerrain(); } } /// <summary> /// Updates the distance between rows in the TerrainPatch. /// </summary> private void numRowDistance_ValueChanged(object sender, System.EventArgs e) { if ( chkGridSize.Checked ) numColumnDistance.Value = numRowDistance.Value; UpdateTerrain(); } /// <summary> /// Updates the distance between rows in the TerrainPatch. /// </summary> private void numRowDistance_Leave(object sender, System.EventArgs e) { if ( chkGridSize.Checked ) numColumnDistance.Value = numRowDistance.Value; UpdateTerrain(); } /// <summary> /// Updates the distance between columns in the TerrainPatch. /// </summary> private void numColumnDistance_ValueChanged(object sender, System.EventArgs e) { if ( chkGridSize.Checked ) numRowDistance.Value = numColumnDistance.Value; UpdateTerrain(); } /// <summary> /// Updates the distance between columns in the TerrainPatch. /// </summary> private void numColumnDistance_Leave(object sender, System.EventArgs e) { if ( chkGridSize.Checked ) numRowDistance.Value = numColumnDistance.Value; UpdateTerrain(); } /// <summary> /// Keeps the distances between rows and columns equal in the TerrainPatch. /// </summary> private void chkGridSize_CheckedChanged(object sender, System.EventArgs e) { if ( chkGridSize.Checked ) { numColumnDistance.Value = numRowDistance.Value; UpdateTerrain(); } } /// <summary> /// Safely disposes of the DirectX viewport. /// </summary> private void TerrainCreation_Closing(object sender, System.ComponentModel.CancelEventArgs e) { _viewport.DXViewport.Dispose(); } #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.numRows = new System.Windows.Forms.NumericUpDown(); this.numColumns = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.btnOK = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.chkGridDimensions = new System.Windows.Forms.CheckBox(); this.grpGridDimensions = new System.Windows.Forms.GroupBox(); this.chkGridSize = new System.Windows.Forms.CheckBox(); this.numColumnDistance = new System.Windows.Forms.NumericUpDown(); this.numRowDistance = new System.Windows.Forms.NumericUpDown(); this.label5 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.grpGridSize = new System.Windows.Forms.GroupBox(); ((System.ComponentModel.ISupportInitialize)(this.numRows)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numColumns)).BeginInit(); this.grpGridDimensions.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numColumnDistance)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numRowDistance)).BeginInit(); this.grpGridSize.SuspendLayout(); this.SuspendLayout(); // // _viewport // this._viewport.Location = new System.Drawing.Point(0, 24); this._viewport.Name = "_viewport"; this._viewport.Size = new System.Drawing.Size(200, 192); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.TabIndex = 1; this.label1.Text = "Preview:"; // // numRows // this.numRows.Location = new System.Drawing.Point(48, 16); this.numRows.Maximum = new System.Decimal(new int[] { 1000, 0, 0, 0}); this.numRows.Minimum = new System.Decimal(new int[] { 2, 0, 0, 0}); this.numRows.Name = "numRows"; this.numRows.Size = new System.Drawing.Size(56, 20); this.numRows.TabIndex = 2; this.numRows.Value = new System.Decimal(new int[] { 25, 0, 0, 0}); this.numRows.ValueChanged += new System.EventHandler(this.numRows_ValueChanged); this.numRows.Leave += new System.EventHandler(this.numRows_Leave); // // numColumns // this.numColumns.Location = new System.Drawing.Point(168, 16); this.numColumns.Maximum = new System.Decimal(new int[] { 1000, 0, 0, 0}); this.numColumns.Minimum = new System.Decimal(new int[] { 2, 0, 0, 0}); this.numColumns.Name = "numColumns"; this.numColumns.Size = new System.Drawing.Size(56, 20); this.numColumns.TabIndex = 3; this.numColumns.Value = new System.Decimal(new int[] { 25, 0, 0, 0}); this.numColumns.ValueChanged += new System.EventHandler(this.numColumns_ValueChanged); this.numColumns.Leave += new System.EventHandler(this.numColumns_Leave); // // label2 // this.label2.Location = new System.Drawing.Point(8, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 23); this.label2.TabIndex = 4; this.label2.Text = "Rows:"; // // label3 // this.label3.Location = new System.Drawing.Point(112, 16); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 23); this.label3.TabIndex = 5; this.label3.Text = "Columns:"; // // btnOK // this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(232, 176); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(72, 23); this.btnOK.TabIndex = 0; this.btnOK.Text = "OK"; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(344, 176); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(72, 23); this.btnCancel.TabIndex = 1; this.btnCancel.Text = "Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // chkGridDimensions // this.chkGridDimensions.Checked = true; this.chkGridDimensions.CheckState = System.Windows.Forms.CheckState.Checked; this.chkGridDimensions.Location = new System.Drawing.Point(40, 40); this.chkGridDimensions.Name = "chkGridDimensions"; this.chkGridDimensions.Size = new System.Drawing.Size(184, 24); this.chkGridDimensions.TabIndex = 9; this.chkGridDimensions.Text = "Lock Grid Dimensions"; this.chkGridDimensions.CheckedChanged += new System.EventHandler(this.chkGridDimensions_CheckedChanged); // // grpGridDimensions // this.grpGridDimensions.Controls.Add(this.numColumns); this.grpGridDimensions.Controls.Add(this.label2); this.grpGridDimensions.Controls.Add(this.label3); this.grpGridDimensions.Controls.Add(this.chkGridDimensions); this.grpGridDimensions.Controls.Add(this.numRows); this.grpGridDimensions.Location = new System.Drawing.Point(200, 8); this.grpGridDimensions.Name = "grpGridDimensions"; this.grpGridDimensions.Size = new System.Drawing.Size(232, 72); this.grpGridDimensions.TabIndex = 11; this.grpGridDimensions.TabStop = false; this.grpGridDimensions.Text = "Grid Dimensions"; // // chkGridSize // this.chkGridSize.Checked = true; this.chkGridSize.CheckState = System.Windows.Forms.CheckState.Checked; this.chkGridSize.Location = new System.Drawing.Point(32, 40); this.chkGridSize.Name = "chkGridSize"; this.chkGridSize.Size = new System.Drawing.Size(192, 24); this.chkGridSize.TabIndex = 14; this.chkGridSize.Text = "Lock Terrain Size"; this.chkGridSize.CheckedChanged += new System.EventHandler(this.chkGridSize_CheckedChanged); // // numColumnDistance // this.numColumnDistance.DecimalPlaces = 2; this.numColumnDistance.Increment = new System.Decimal(new int[] { 1, 0, 0, 131072}); this.numColumnDistance.Location = new System.Drawing.Point(168, 16); this.numColumnDistance.Maximum = new System.Decimal(new int[] { 1000, 0, 0, 0}); this.numColumnDistance.Minimum = new System.Decimal(new int[] { 1, 0, 0, 131072}); this.numColumnDistance.Name = "numColumnDistance"; this.numColumnDistance.Size = new System.Drawing.Size(56, 20); this.numColumnDistance.TabIndex = 13; this.numColumnDistance.Value = new System.Decimal(new int[] { 100, 0, 0, 131072}); this.numColumnDistance.ValueChanged += new System.EventHandler(this.numColumnDistance_ValueChanged); this.numColumnDistance.Leave += new System.EventHandler(this.numColumnDistance_Leave); // // numRowDistance // this.numRowDistance.DecimalPlaces = 2; this.numRowDistance.Increment = new System.Decimal(new int[] { 1, 0, 0, 131072}); this.numRowDistance.Location = new System.Drawing.Point(48, 16); this.numRowDistance.Maximum = new System.Decimal(new int[] { 1000, 0, 0, 0}); this.numRowDistance.Minimum = new System.Decimal(new int[] { 1, 0, 0, 131072}); this.numRowDistance.Name = "numRowDistance"; this.numRowDistance.Size = new System.Drawing.Size(56, 20); this.numRowDistance.TabIndex = 12; this.numRowDistance.Value = new System.Decimal(new int[] { 10, 0, 0, 65536}); this.numRowDistance.ValueChanged += new System.EventHandler(this.numRowDistance_ValueChanged); this.numRowDistance.Leave += new System.EventHandler(this.numRowDistance_Leave); // // label5 // this.label5.Location = new System.Drawing.Point(120, 16); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(48, 23); this.label5.TabIndex = 11; this.label5.Text = "Height:"; // // label4 // this.label4.Location = new System.Drawing.Point(8, 16); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(40, 23); this.label4.TabIndex = 10; this.label4.Text = "Width:"; // // grpGridSize // this.grpGridSize.Controls.Add(this.numColumnDistance); this.grpGridSize.Controls.Add(this.numRowDistance); this.grpGridSize.Controls.Add(this.label5); this.grpGridSize.Controls.Add(this.label4); this.grpGridSize.Controls.Add(this.chkGridSize); this.grpGridSize.Location = new System.Drawing.Point(200, 88); this.grpGridSize.Name = "grpGridSize"; this.grpGridSize.Size = new System.Drawing.Size(232, 72); this.grpGridSize.TabIndex = 12; this.grpGridSize.TabStop = false; this.grpGridSize.Text = "Total Terrain Size"; // // TerrainCreation // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(442, 216); this.Controls.Add(this.grpGridSize); this.Controls.Add(this.grpGridDimensions); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Location = new System.Drawing.Point(0, 0); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TerrainCreation"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "Create a Terrain Patch"; this.Closing += new System.ComponentModel.CancelEventHandler(this.TerrainCreation_Closing); this.Load += new System.EventHandler(this.TerrainCreation_Load); this.Controls.SetChildIndex(this._viewport, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.btnOK, 0); this.Controls.SetChildIndex(this.btnCancel, 0); this.Controls.SetChildIndex(this.grpGridDimensions, 0); this.Controls.SetChildIndex(this.grpGridSize, 0); ((System.ComponentModel.ISupportInitialize)(this.numRows)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numColumns)).EndInit(); this.grpGridDimensions.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.numColumnDistance)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numRowDistance)).EndInit(); this.grpGridSize.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Affinity; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Log; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Resource; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /// <summary> /// Default configuration section name. /// </summary> public const string ConfigurationSectionName = "igniteConfiguration"; /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _gcWarn; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/> /// name and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { // ReSharper disable once IntroduceOptionalParameters.Global return StartFromApplicationConfiguration(ConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); if (section.IgniteConfiguration == null) throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath"); var fileMap = GetConfigMap(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var section = config.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException( string.Format("Could not find {0} with name '{1}' in file '{2}'", typeof(IgniteConfigurationSection).Name, sectionName, configPath)); if (section.IgniteConfiguration == null) throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName, configPath)); return Start(section.IgniteConfiguration); } /// <summary> /// Gets the configuration file map. /// </summary> private static ExeConfigurationFileMap GetConfigMap(string fileName) { var fullFileName = Path.GetFullPath(fileName); if (!File.Exists(fullFileName)) throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName); return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName }; } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public static unsafe IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused. lock (SyncRoot) { // 0. Init logger var log = cfg.Logger ?? new JavaLogger(); log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version); // 1. Check GC settings. CheckServerGc(cfg, log); // 2. Create context. IgniteUtils.LoadDlls(cfg.JvmDllPath, log); var cbs = new UnmanagedCallbacks(log); IgniteManager.CreateJvmContext(cfg, cbs, log); log.Debug("JVM started."); var gridName = cfg.IgniteInstanceName; if (cfg.AutoGenerateIgniteInstanceName) { gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid(); } // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); PlatformJniTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(cbs.Context, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = (PlatformJniTarget)node.InteropProcessor; var javaLogger = log as JavaLogger; if (javaLogger != null) { javaLogger.SetIgnite(node); } // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(interopProc.Target.Context, gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) { // Wrap in a new exception to preserve original stack trace. throw new IgniteException("Failed to start Ignite.NET, check inner exception for details", _startup.Error); } throw; } finally { var ignite = _startup.Ignite; _startup = null; if (ignite != null) { ignite.ProcessorReleaseStart(); } } } } /// <summary> /// Check whether GC is set to server mode. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Log.</param> private static void CheckServerGc(IgniteConfiguration cfg, ILogger log) { if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0) log.Warn("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx)."); } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Input stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> /// <param name="log">Log.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry, ILogger log) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream, log); PrepareLifecycleHandlers(reader, outStream, handleRegistry); PrepareAffinityFunctions(reader, outStream); outStream.SynchronizeOutput(); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Prepare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> /// <param name="log">Log.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log); // 3. Send configuration details to Java cfg.Validate(log); cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream)); // Use system marshaller. } /// <summary> /// Prepare lifecycle handlers. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder> { new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events }; // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader))); // 2. Append beans defined in local configuration. ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers; if (nativeBeans != null) { foreach (ILifecycleHandler nativeBean in nativeBeans) beans.Add(new LifecycleHandlerHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleHandlerHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); // 4. Set beans to STARTUP object. _startup.LifecycleHandlers = beans; } /// <summary> /// Prepares the affinity functions. /// </summary> private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream) { var cnt = reader.ReadInt(); var writer = reader.Marshaller.StartMarshal(outStream); for (var i = 0; i < cnt; i++) { var objHolder = new ObjectInfoHolder(reader); AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder); } } /// <summary> /// Creates an object and sets the properties. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Resulting object.</returns> private static T CreateObject<T>(IBinaryRawReader reader) { return IgniteUtils.CreateInstance<T>(reader.ReadString(), reader.ReadDictionaryAsGeneric<string, object>()); } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "PlatformJniTarget is passed further")] internal static void OnStart(IUnmanagedTarget interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller, _startup.LifecycleHandlers, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (string s in assemblies) { // 1. Try loading as directory. if (Directory.Exists(s)) { string[] files = Directory.GetFiles(s, "*.dll"); #pragma warning disable 0168 foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } #pragma warning restore 0168 continue; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + s); } } } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p /> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned.</param> /// <returns> /// An instance of named grid. /// </returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite(string name) { var ignite = TryGetIgnite(name); if (ignite == null) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return ignite; } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// <para /> /// Note that caller of this method should not assume that it will return the same instance every time. /// </summary> /// <returns>Default Ignite instance.</returns> /// <exception cref="IgniteException">When there is no matching Ignite instance.</exception> public static IIgnite GetIgnite() { lock (SyncRoot) { if (Nodes.Count == 0) { throw new IgniteException("Failed to get default Ignite instance: " + "there are no instances started."); } if (Nodes.Count == 1) { return Nodes.Single().Value; } Ignite result; if (Nodes.TryGetValue(new NodeKey(null), out result)) { return result; } throw new IgniteException(string.Format("Failed to get default Ignite instance: " + "there are {0} instances started, and none of them has null name.", Nodes.Count)); } } /// <summary> /// Gets all started Ignite instances. /// </summary> /// <returns>All Ignite instances.</returns> public static ICollection<IIgnite> GetAll() { lock (SyncRoot) { return Nodes.Values.ToArray(); } } /// <summary> /// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid, or null.</returns> public static IIgnite TryGetIgnite(string name) { lock (SyncRoot) { Ignite result; return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result; } } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// Returns null when there are no Ignite instances started, or when there are more than one, /// and none of them has null name. /// </summary> /// <returns>An instance of default no-name grid, or null.</returns> public static IIgnite TryGetIgnite() { lock (SyncRoot) { if (Nodes.Count == 1) { return Nodes.Single().Value; } return TryGetIgnite(null); } } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="clientConfiguration">The client configuration.</param> /// <returns>Ignite instance.</returns> public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration) { IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration"); IgniteArgumentCheck.NotNull(clientConfiguration.Host, "clientConfiguration.Host"); return new IgniteClient(clientConfiguration); } /// <summary> /// Handles the DomainUnload event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private static void CurrentDomain_DomainUnload(object sender, EventArgs e) { // If we don't stop Ignite.NET on domain unload, // we end up with broken instances in Java (invalid callbacks, etc). // IIS, in particular, is known to unload and reload domains within the same process. StopAll(true); } /// <summary> /// Grid key. Workaround for non-null key requirement in Dictionary. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .Net methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle handlers. /// </summary> internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } /// <summary> /// Internal handler for event notification. /// </summary> private class InternalLifecycleHandler : ILifecycleHandler { /** */ #pragma warning disable 649 // unused field [InstanceResource] private readonly IIgnite _ignite; /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null) ((Ignite) _ignite).BeforeNodeStop(); } } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using MeetupManager.Portable.Helpers; using MeetupManager.Portable.Interfaces; using MeetupManager.Portable.Models; using MeetupManager.Portable.Services; using MeetupManager.Portable.Services.Responses; using Newtonsoft.Json; using Xamarin.Forms; [assembly:Dependency(typeof(MeetupService))] namespace MeetupManager.Portable.Services { public class MeetupService : IMeetupService { readonly IMessageDialog messageDialog; public MeetupService() { messageDialog = DependencyService.Get<IMessageDialog>(); } HttpClient CreateClient() { return new HttpClient(new ModernHttpClient.NativeMessageHandler()); } #region IMeetupService implementation public static string ClientId = "h0hrbvn9df1d817alnluab6d1s"; public static string ClientSecret = "o9dv5n3uanhrp08fdmas8jdaqb"; public static string AuthorizeUrl = "https://secure.meetup.com/oauth2/authorize"; public static string RedirectUrl = "http://www.refractored.com/login_success.html"; public static string AccessTokenUrl = "https://secure.meetup.com/oauth2/access"; const string GetGroupsUrl = @"https://api.meetup.com/2/groups?offset={0}&member_id={1}&page=100&order=name&access_token={2}&only=name,id,group_photo,members"; const string GetGroupsOrganizerUrl = @"https://api.meetup.com/2/groups?offset={0}&organizer_id={1}&page=100&order=name&access_token={2}&only=name,id,group_photo,members"; const string GetEventsUrl = @"https://api.meetup.com/2/events?offset={0}&group_id={1}&page=100&status=upcoming,past&desc=true&access_token={2}&only=name,id,time,yes_rsvp_count"; const string GetRSVPsUrl = @"https://api.meetup.com/2/rsvps?offset={0}&event_id={1}&page=100&order=name&rsvp=yes&access_token={2}&only=member,member_photo,guests"; const string GetUserUrl = @"https://api.meetup.com/2/member/self?access_token={0}&only=name,id,photo"; public async Task<EventsRootObject> GetEvents(string groupId, int skip) { var offset = skip / 100; if (!await RenewAccessToken()) { messageDialog.SendToast("Unable to get events, please re-login."); return new EventsRootObject() { Events = new List<Event>() }; } var client = CreateClient(); if (client.DefaultRequestHeaders.CacheControl == null) client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue(); client.DefaultRequestHeaders.CacheControl.NoCache = true; client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; client.DefaultRequestHeaders.CacheControl.NoStore = true; client.Timeout = new TimeSpan(0, 0, 30); var request = string.Format(GetEventsUrl, offset, groupId, Settings.AccessToken); if (!Settings.ShowAllEvents) request += "&time=-100m,2m"; var response = await client.GetStringAsync(request); return await DeserializeObjectAsync<EventsRootObject>(response); } public async Task<RSVPsRootObject> GetRSVPs(string eventId, int skip) { var offset = skip / 100; if (!await RenewAccessToken()) { messageDialog.SendToast("Unable to get RSVPs, please re-login."); return new RSVPsRootObject() { RSVPs = new List<RSVP>() }; } var client = CreateClient(); if (client.DefaultRequestHeaders.CacheControl == null) client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue(); client.DefaultRequestHeaders.CacheControl.NoCache = true; client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; client.DefaultRequestHeaders.CacheControl.NoStore = true; client.Timeout = new TimeSpan(0, 0, 30); var request = string.Format(GetRSVPsUrl, offset, eventId, Settings.AccessToken); var response = await client.GetStringAsync(request); return await DeserializeObjectAsync<RSVPsRootObject>(response); } public async Task<RequestTokenObject> GetToken(string code) { if (string.IsNullOrWhiteSpace(code)) return null; using (var client = CreateClient()) { try { if (client.DefaultRequestHeaders.CacheControl == null) client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue(); client.DefaultRequestHeaders.CacheControl.NoCache = true; client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; client.DefaultRequestHeaders.CacheControl.NoStore = true; client.Timeout = new TimeSpan(0, 0, 30); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("client_id", ClientId), new KeyValuePair<string, string>("client_secret", ClientSecret), new KeyValuePair<string, string>("grant_type", "authorization_code"), new KeyValuePair<string, string>("redirect_uri", RedirectUrl), new KeyValuePair<string, string>("code", code), }); var result = await client.PostAsync("https://secure.meetup.com/oauth2/access", content); var response = await result.Content.ReadAsStringAsync(); var refreshResponse = await DeserializeObjectAsync<RequestTokenObject>(response); return refreshResponse; } catch (Exception ex) { if (Settings.Insights) Xamarin.Insights.Report(ex); } } return null; } public class RequestTokenObject { public string access_token { get; set; } public string token_type { get; set; } public int expires_in { get; set; } public string refresh_token { get; set; } } public async Task<bool> RenewAccessToken() { if (string.IsNullOrWhiteSpace(Settings.AccessToken)) return false; if (DateTime.UtcNow < new DateTime(Settings.KeyValidUntil)) return true; using (var client = CreateClient()) { try { if (client.DefaultRequestHeaders.CacheControl == null) client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue(); client.DefaultRequestHeaders.CacheControl.NoCache = true; client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; client.DefaultRequestHeaders.CacheControl.NoStore = true; client.Timeout = new TimeSpan(0, 0, 30); var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("client_id", ClientId), new KeyValuePair<string, string>("client_secret", ClientSecret), new KeyValuePair<string, string>("grant_type", "refresh_token"), new KeyValuePair<string, string>("refresh_token", Settings.RefreshToken), }); var result = await client.PostAsync("https://secure.meetup.com/oauth2/access", content); var response = await result.Content.ReadAsStringAsync(); var refreshResponse = await DeserializeObjectAsync<RefreshRootObject>(response); Settings.AccessToken = refreshResponse.AccessToken; var nextTime = DateTime.UtcNow.AddSeconds(refreshResponse.ExpiresIn).Ticks; Settings.KeyValidUntil = nextTime; Settings.RefreshToken = refreshResponse.RefreshToken; } catch (Exception ex) { if (Settings.Insights) Xamarin.Insights.Report(ex); return false; } } return true; } public async Task<LoggedInUser> GetCurrentMember() { await RenewAccessToken(); var client = CreateClient(); if (client.DefaultRequestHeaders.CacheControl == null) client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue(); client.DefaultRequestHeaders.CacheControl.NoCache = true; client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; client.DefaultRequestHeaders.CacheControl.NoStore = true; client.Timeout = new TimeSpan(0, 0, 30); var request = string.Format(GetUserUrl, Settings.AccessToken); var response = await client.GetStringAsync(request); //should use async, but has issue for some reason and throws exception return DeserializeObject<LoggedInUser>(response); } #endregion public async Task<GroupsRootObject> GetGroups(string memberId, int skip) { var offset = skip / 100; if (!await RenewAccessToken()) { messageDialog.SendToast("Unable to get groups, please re-login."); return new GroupsRootObject{ Groups = new List<Group>() }; } var client = CreateClient(); if (client.DefaultRequestHeaders.CacheControl == null) client.DefaultRequestHeaders.CacheControl = new CacheControlHeaderValue(); client.DefaultRequestHeaders.CacheControl.NoCache = true; client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow; client.DefaultRequestHeaders.CacheControl.NoStore = true; client.Timeout = new TimeSpan(0, 0, 30); var request = string.Format(Settings.OrganizerMode ? GetGroupsOrganizerUrl : GetGroupsUrl, offset, memberId, Settings.AccessToken); var response = await client.GetStringAsync(request); return await DeserializeObjectAsync<GroupsRootObject>(response); } public Task<T> DeserializeObjectAsync<T>(string value) { return Task.Factory.StartNew(() => JsonConvert.DeserializeObject<T>(value)); } public T DeserializeObject<T>(string value) { return JsonConvert.DeserializeObject<T>(value); } } }
using System.Globalization; using System.Text; namespace Meziantou.Framework.Templating; public sealed class IndentedTextWriter : TextWriter { /// <summary> /// Specifies the default tab string. This field is constant. /// </summary> public const string DefaultTabString = " "; private int _indentLevel; private bool _tabsPending; private readonly string _tabString; /// <summary> /// Gets the encoding for the text writer to use. /// </summary> /// <returns> /// An <see cref="System.Text.Encoding" /> that indicates the encoding for the text writer to use. /// </returns> public override Encoding Encoding => InnerWriter.Encoding; /// <summary> /// Gets or sets the new line character to use. /// </summary> /// <returns> The new line character to use. </returns> [AllowNull] public override string NewLine { get => InnerWriter.NewLine; set => InnerWriter.NewLine = value; } /// <summary> /// Gets or sets the number of spaces to indent. /// </summary> /// <returns> The number of spaces to indent. </returns> public int Indent { get => _indentLevel; set { if (value < 0) { value = 0; } _indentLevel = value; } } /// <summary> /// Gets the <see cref="TextWriter" /> to use. /// </summary> /// <returns> /// The <see cref="TextWriter" /> to use. /// </returns> public TextWriter InnerWriter { get; } /// <summary> /// Initializes a new instance of the IndentedTextWriter class using the specified text writer and default tab string. /// </summary> /// <param name="writer"> /// The <see cref="TextWriter" /> to use for output. /// </param> public IndentedTextWriter(TextWriter writer) : this(writer, DefaultTabString) { } /// <summary> /// Initializes a new instance of the IndentedTextWriter class using the specified text writer and tab string. /// </summary> /// <param name="writer"> /// The <see cref="TextWriter" /> to use for output. /// </param> /// <param name="tabString"> The tab string to use for indentation. </param> public IndentedTextWriter(TextWriter writer, string tabString) : base(CultureInfo.InvariantCulture) { InnerWriter = writer; _tabString = tabString; _indentLevel = 0; _tabsPending = false; } protected override void Dispose(bool disposing) { InnerWriter.Dispose(); base.Dispose(disposing); } /// <summary> /// Flushes the stream. /// </summary> public override void Flush() { InnerWriter.Flush(); } /// <summary> /// Outputs the tab string once for each level of indentation according to the /// <see /// cref="System.CodeDom.Compiler.IndentedTextWriter.Indent" /> /// property. /// </summary> private void OutputTabs() { if (!_tabsPending) return; for (var index = 0; index < _indentLevel; ++index) { InnerWriter.Write(_tabString); } _tabsPending = false; } /// <summary> /// Writes the specified string to the text stream. /// </summary> /// <param name="value"> The string to write. </param> public override void Write(string? value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes the text representation of a Boolean value to the text stream. /// </summary> /// <param name="value"> The Boolean value to write. </param> public override void Write(bool value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes a character to the text stream. /// </summary> /// <param name="value"> The character to write. </param> public override void Write(char value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes a character array to the text stream. /// </summary> /// <param name="buffer"> The character array to write. </param> public override void Write(char[]? buffer) { OutputTabs(); InnerWriter.Write(buffer); } /// <summary> /// Writes a subarray of characters to the text stream. /// </summary> /// <param name="buffer"> The character array to write data from. </param> /// <param name="index"> Starting index in the buffer. </param> /// <param name="count"> The number of characters to write. </param> public override void Write(char[] buffer, int index, int count) { OutputTabs(); InnerWriter.Write(buffer, index, count); } /// <summary> /// Writes the text representation of a Double to the text stream. /// </summary> /// <param name="value"> The double to write. </param> public override void Write(double value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes the text representation of a Single to the text stream. /// </summary> /// <param name="value"> The single to write. </param> public override void Write(float value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes the text representation of an integer to the text stream. /// </summary> /// <param name="value"> The integer to write. </param> public override void Write(int value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes the text representation of an 8-byte integer to the text stream. /// </summary> /// <param name="value"> The 8-byte integer to write. </param> public override void Write(long value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes the text representation of an object to the text stream. /// </summary> /// <param name="value"> The object to write. </param> public override void Write(object? value) { OutputTabs(); InnerWriter.Write(value); } /// <summary> /// Writes out a formatted string, using the same semantics as specified. /// </summary> /// <param name="format"> The formatting string. </param> /// <param name="arg0"> The object to write into the formatted string. </param> public override void Write(string format, object? arg0) { OutputTabs(); InnerWriter.Write(format, arg0); } /// <summary> /// Writes out a formatted string, using the same semantics as specified. /// </summary> /// <param name="format"> The formatting string to use. </param> /// <param name="arg0"> The first object to write into the formatted string. </param> /// <param name="arg1"> The second object to write into the formatted string. </param> public override void Write(string format, object? arg0, object? arg1) { OutputTabs(); InnerWriter.Write(format, arg0, arg1); } /// <summary> /// Writes out a formatted string, using the same semantics as specified. /// </summary> /// <param name="format"> The formatting string to use. </param> /// <param name="arg"> The argument array to output. </param> public override void Write(string format, params object?[] arg) { OutputTabs(); InnerWriter.Write(format, arg); } /// <summary> /// Writes the specified string to a line without tabs. /// </summary> /// <param name="value"> The string to write. </param> public void WriteLineNoTabs(string value) { InnerWriter.WriteLine(value); } /// <summary> /// Writes the specified string, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The string to write. </param> public override void WriteLine(string? value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes a line terminator. /// </summary> public override void WriteLine() { OutputTabs(); InnerWriter.WriteLine(); _tabsPending = true; } /// <summary> /// Writes the text representation of a Boolean, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The Boolean to write. </param> public override void WriteLine(bool value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes a character, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The character to write. </param> public override void WriteLine(char value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes a character array, followed by a line terminator, to the text stream. /// </summary> /// <param name="buffer"> The character array to write. </param> public override void WriteLine(char[]? buffer) { OutputTabs(); InnerWriter.WriteLine(buffer); _tabsPending = true; } /// <summary> /// Writes a subarray of characters, followed by a line terminator, to the text stream. /// </summary> /// <param name="buffer"> The character array to write data from. </param> /// <param name="index"> Starting index in the buffer. </param> /// <param name="count"> The number of characters to write. </param> public override void WriteLine(char[] buffer, int index, int count) { OutputTabs(); InnerWriter.WriteLine(buffer, index, count); _tabsPending = true; } /// <summary> /// Writes the text representation of a Double, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The double to write. </param> public override void WriteLine(double value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes the text representation of a Single, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The single to write. </param> public override void WriteLine(float value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes the text representation of an integer, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The integer to write. </param> public override void WriteLine(int value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes the text representation of an 8-byte integer, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The 8-byte integer to write. </param> public override void WriteLine(long value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes the text representation of an object, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> The object to write. </param> public override void WriteLine(object? value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } /// <summary> /// Writes out a formatted string, followed by a line terminator, using the same semantics as specified. /// </summary> /// <param name="format"> The formatting string. </param> /// <param name="arg0"> The object to write into the formatted string. </param> public override void WriteLine(string format, object? arg0) { OutputTabs(); InnerWriter.WriteLine(format, arg0); _tabsPending = true; } /// <summary> /// Writes out a formatted string, followed by a line terminator, using the same semantics as specified. /// </summary> /// <param name="format"> The formatting string to use. </param> /// <param name="arg0"> The first object to write into the formatted string. </param> /// <param name="arg1"> The second object to write into the formatted string. </param> public override void WriteLine(string format, object? arg0, object? arg1) { OutputTabs(); InnerWriter.WriteLine(format, arg0, arg1); _tabsPending = true; } /// <summary> /// Writes out a formatted string, followed by a line terminator, using the same semantics as specified. /// </summary> /// <param name="format"> The formatting string to use. </param> /// <param name="arg"> The argument array to output. </param> public override void WriteLine(string format, params object?[] arg) { OutputTabs(); InnerWriter.WriteLine(format, arg); _tabsPending = true; } /// <summary> /// Writes the text representation of a UInt32, followed by a line terminator, to the text stream. /// </summary> /// <param name="value"> A UInt32 to output. </param> public override void WriteLine(uint value) { OutputTabs(); InnerWriter.WriteLine(value); _tabsPending = true; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.DeviceModels.Chipset.PXA27x { using System.Runtime.CompilerServices; using Microsoft.Zelig.Runtime; [MemoryMappedPeripheral(Base=0x40E00000U,Length=0x0000014CU)] public class GPIO { [MemoryMappedPeripheral(Base=0x0U,Length=0x0000004CU)] class Cluster { #pragma warning disable 649 [Register(Offset=0x00U)] internal uint GPLR; // GPIO<X+31:X> Pin-Level register [Register(Offset=0x0CU)] internal uint GPDR; // GPIO<X+31:X> Pin Direction register [Register(Offset=0x18U)] internal uint GPSR; // GPIO<X+31:X> Pin Output Set register [Register(Offset=0x24U)] internal uint GPCR; // GPIO<X+31:X> Pin Output Clear register [Register(Offset=0x30U)] internal uint GRER; // GPIO<X+31:X> Rising-Edge Detect Enable register [Register(Offset=0x3CU)] internal uint GFER; // GPIO<X+31:X> Falling-Edge Detect Enable register [Register(Offset=0x48U)] internal uint GEDR; // GPIO<X+31:X> Edge Detect Status register #pragma warning restore 649 // // Helper Methods // [Inline] internal void ConfigureAsInput( int pin ) { uint mask = 1u << (pin & 31); this.GPDR &= ~mask; } [Inline] internal void ConfigureAsOutput( int pin ) { uint mask = 1u << (pin & 31); this.GPDR |= mask; } [Inline] internal void ConfigureInterrupt( int pin , bool raisingEdge , bool fallingEdge ) { uint mask = 1u << (pin & 31); if(raisingEdge) { this.GRER |= mask; } else { this.GRER &= ~mask; } if(fallingEdge) { this.GFER |= mask; } else { this.GFER &= ~mask; } this.GEDR = mask; // Clear any pending interrupt for pin } [Inline] internal bool InterruptPending( int pin , bool clear ) { uint mask = 1u << (pin & 31); var res = this.GEDR & mask; if(res == 0) { return false; } if(clear) { this.GEDR = res; //write with 1-bits clears associated interrupts } return true; } [Inline] internal bool GetState( int pin ) { uint mask = 1u << (pin & 31); return (this.GPLR & mask) != 0; } [Inline] internal void SetState( int pin , bool fSet ) { uint mask = 1u << (pin & 31); if(fSet) { this.GPSR |= mask; } else { this.GPCR |= mask; } } } [MemoryMappedPeripheral(Base=0x0U,Length=0x0000004CU)] class AltFunctionCluster { [Register(Offset=0x00U)] internal uint GAFR_L; // GPIO<X+15:X > Alternate Function register [Register(Offset=0x04U)] internal uint GAFR_H; // GPIO<X+31:X+16> Alternate Function register // // Helper Methods // internal void Set( int pin , uint mode ) { pin %= 32; int shift = (pin % 16) * 2; uint mask = 3u << shift; uint val = mode << shift; if(pin < 16) { this.GAFR_L = (this.GAFR_L & ~mask) | (val & mask); } else { this.GAFR_H = (this.GAFR_H & ~mask) | (val & mask); } } } #pragma warning disable 649 [Register(Offset=0x000U)] private Cluster m_pin000_031; [Register(Offset=0x004U)] private Cluster m_pin032_063; [Register(Offset=0x008U)] private Cluster m_pin064_095; [Register(Offset=0x100U)] private Cluster m_pin096_120; [Register(Offset=0x054U)] private AltFunctionCluster m_altFunc000_031; [Register(Offset=0x05CU)] private AltFunctionCluster m_altFunc032_063; [Register(Offset=0x064U)] private AltFunctionCluster m_altFunc064_095; [Register(Offset=0x06CU)] private AltFunctionCluster m_altFunc096_120; #pragma warning restore 649 //--// // // Helper Methods // public void EnableAsInputAlternateFunction( int pin , int mode ) { var altFunc = GetAltFunctionCluster( pin ); altFunc.Set( pin, (uint)mode ); //--// var cls = GetCluster( pin ); cls.ConfigureAsInput( pin ); } public void EnableAsOutputAlternateFunction( int pin , int mode , bool fSet ) { var altFunc = GetAltFunctionCluster( pin ); altFunc.Set( pin, (uint)mode ); //--// var cls = GetCluster( pin ); cls.SetState ( pin, fSet ); cls.ConfigureAsOutput( pin ); } public void EnableAsInputPin( int pin ) { EnableAsInputAlternateFunction( pin, 0 ); } public void EnableAsOutputPin( int pin , bool fSet ) { EnableAsOutputAlternateFunction( pin, 0, fSet ); } public void ConfigureInterrupt( int pin , bool raisingEdge , bool fallingEdge ) { var cls = GetCluster(pin); cls.ConfigureInterrupt( pin, raisingEdge, fallingEdge ); } public bool InterruptPending( int pin , bool clear ) { var cls = GetCluster(pin); return cls.InterruptPending( pin, clear ); } //--// Cluster GetCluster( int pin ) { switch(pin / 32) { case 0: return this.m_pin000_031; case 1: return this.m_pin032_063; case 2: return this.m_pin064_095; case 3: return this.m_pin096_120; } BugCheck.Raise( BugCheck.StopCode.IncorrectArgument ); return null; } AltFunctionCluster GetAltFunctionCluster( int pin ) { switch(pin / 32) { case 0: return this.m_altFunc000_031; case 1: return this.m_altFunc032_063; case 2: return this.m_altFunc064_095; case 3: return this.m_altFunc096_120; } BugCheck.Raise( BugCheck.StopCode.IncorrectArgument ); return null; } // // Access Methods // public static extern GPIO Instance { [SingletonFactory()] [MethodImpl( MethodImplOptions.InternalCall )] get; } public bool this[int pin] { get { var cls = GetCluster( pin ); BugCheck.Assert(null != cls, BugCheck.StopCode.IncorrectArgument); return cls.GetState( pin ); } set { var cls = GetCluster( pin ); BugCheck.Assert(null != cls, BugCheck.StopCode.IncorrectArgument); cls.SetState( pin, value ); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Classes: NativeObjectSecurity class ** ** ===========================================================*/ using Microsoft.Win32; using System; using System.Collections; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Principal; using FileNotFoundException = System.IO.FileNotFoundException; namespace System.Security.AccessControl { public abstract class NativeObjectSecurity : CommonObjectSecurity { #region Private Members private readonly ResourceType _resourceType; private ExceptionFromErrorCode _exceptionFromErrorCode = null; private object _exceptionContext = null; private readonly uint ProtectedDiscretionaryAcl = 0x80000000; private readonly uint ProtectedSystemAcl = 0x40000000; private readonly uint UnprotectedDiscretionaryAcl = 0x20000000; private readonly uint UnprotectedSystemAcl = 0x10000000; #endregion #region Delegates protected internal delegate System.Exception ExceptionFromErrorCode(int errorCode, string name, SafeHandle handle, object context); #endregion #region Constructors protected NativeObjectSecurity(bool isContainer, ResourceType resourceType) : base(isContainer) { _resourceType = resourceType; } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : this(isContainer, resourceType) { _exceptionContext = exceptionContext; _exceptionFromErrorCode = exceptionFromErrorCode; } internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor) : this(resourceType, securityDescriptor, null) { } internal NativeObjectSecurity(ResourceType resourceType, CommonSecurityDescriptor securityDescriptor, ExceptionFromErrorCode exceptionFromErrorCode) : base(securityDescriptor) { _resourceType = resourceType; _exceptionFromErrorCode = exceptionFromErrorCode; } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : this(resourceType, CreateInternal(resourceType, isContainer, name, null, includeSections, true, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode) { } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections) : this(isContainer, resourceType, name, includeSections, null, null) { } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : this(resourceType, CreateInternal(resourceType, isContainer, null, handle, includeSections, false, exceptionFromErrorCode, exceptionContext), exceptionFromErrorCode) { } protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections) : this(isContainer, resourceType, handle, includeSections, null, null) { } #endregion #region Private Methods private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) { int error; RawSecurityDescriptor rawSD; if (createByName && name == null) { throw new ArgumentNullException(nameof(name)); } else if (!createByName && handle == null) { throw new ArgumentNullException(nameof(handle)); } error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (exceptionFromErrorCode != null) { exception = exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_PARAMETER) { exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException( SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = (name == null ? new FileNotFoundException() : new FileNotFoundException(name)); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Win32GetSecurityInfo() failed with unexpected error code {0}", error)); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } return new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true); } // // Attempts to persist the security descriptor onto the object // private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { WriteLock(); try { int error; SecurityInfos securityInfo = 0; SecurityIdentifier owner = null, group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && _securityDescriptor.SystemAcl != null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; } else { sacl = null; } if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl); } } if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent) { securityInfo |= SecurityInfos.DiscretionaryAcl; // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = _securityDescriptor.DiscretionaryAcl; } if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0) { securityInfo = unchecked((SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl)); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl); } } if (securityInfo == 0) { // // Nothing to persist // return; } error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (_exceptionFromErrorCode != null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException( SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_INVALID_HANDLE) { exception = new NotSupportedException(SR.AccessControl_InvalidHandle); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Assert(false, string.Format(CultureInfo.InvariantCulture, "Unexpected error code {0}", error)); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } // // Everything goes well, let us clean the modified flags. // We are in proper write lock, so just go ahead // this.OwnerModified = false; this.GroupModified = false; this.AccessRulesModified = false; this.AuditRulesModified = false; } finally { WriteUnlock(); } } #endregion #region Protected Methods // // Persists the changes made to the object // by calling the underlying Windows API // // This overloaded method takes a name of an existing object // protected sealed override void Persist(string name, AccessControlSections includeSections) { Persist(name, includeSections, _exceptionContext); } protected void Persist(string name, AccessControlSections includeSections, object exceptionContext) { if (name == null) { throw new ArgumentNullException(nameof(name)); } Contract.EndContractBlock(); Persist(name, null, includeSections, exceptionContext); } // // Persists the changes made to the object // by calling the underlying Windows API // // This overloaded method takes a handle to an existing object // protected sealed override void Persist(SafeHandle handle, AccessControlSections includeSections) { Persist(handle, includeSections, _exceptionContext); } protected void Persist(SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { if (handle == null) { throw new ArgumentNullException(nameof(handle)); } Contract.EndContractBlock(); Persist(null, handle, includeSections, exceptionContext); } #endregion } }
// // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Collections.Generic; using Mono.Collections.Generic; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using RVA = System.UInt32; #if !READ_ONLY namespace Mono.Cecil.Cil { sealed class CodeWriter : ByteBuffer { readonly RVA code_base; internal readonly MetadataBuilder metadata; readonly Dictionary<uint, MetadataToken> standalone_signatures; readonly Dictionary<ByteBuffer, RVA> tiny_method_bodies; MethodBody body; public CodeWriter (MetadataBuilder metadata) : base (0) { this.code_base = metadata.text_map.GetNextRVA (TextSegment.CLIHeader); this.metadata = metadata; this.standalone_signatures = new Dictionary<uint, MetadataToken> (); this.tiny_method_bodies = new Dictionary<ByteBuffer, RVA> (new ByteBufferEqualityComparer ()); } public RVA WriteMethodBody (MethodDefinition method) { RVA rva; if (IsUnresolved (method)) { if (method.rva == 0) return 0; rva = WriteUnresolvedMethodBody (method); } else { if (IsEmptyMethodBody (method.Body)) return 0; rva = WriteResolvedMethodBody (method); } return rva; } static bool IsEmptyMethodBody (MethodBody body) { return body.instructions.IsNullOrEmpty () && body.variables.IsNullOrEmpty (); } static bool IsUnresolved (MethodDefinition method) { return method.HasBody && method.HasImage && method.body == null; } RVA WriteUnresolvedMethodBody (MethodDefinition method) { var code_reader = metadata.module.reader.code; int code_size; MetadataToken local_var_token; var raw_body = code_reader.PatchRawMethodBody (method, this, out code_size, out local_var_token); var fat_header = (raw_body.buffer [0] & 0x3) == 0x3; if (fat_header) Align (4); var rva = BeginMethod (); if (fat_header || !GetOrMapTinyMethodBody (raw_body, ref rva)) { WriteBytes (raw_body); } if (method.debug_info == null) return rva; var symbol_writer = metadata.symbol_writer; if (symbol_writer != null) { method.debug_info.code_size = code_size; method.debug_info.local_var_token = local_var_token; symbol_writer.Write (method.debug_info); } return rva; } RVA WriteResolvedMethodBody(MethodDefinition method) { RVA rva; body = method.Body; ComputeHeader (); if (RequiresFatHeader ()) { Align (4); rva = BeginMethod (); WriteFatHeader (); WriteInstructions (); if (body.HasExceptionHandlers) WriteExceptionHandlers (); } else { rva = BeginMethod (); WriteByte ((byte) (0x2 | (body.CodeSize << 2))); // tiny WriteInstructions (); var start_position = (int) (rva - code_base); var body_size = position - start_position; var body_bytes = new byte [body_size]; Array.Copy (buffer, start_position, body_bytes, 0, body_size); if (GetOrMapTinyMethodBody (new ByteBuffer (body_bytes), ref rva)) position = start_position; } var symbol_writer = metadata.symbol_writer; if (symbol_writer != null && method.debug_info != null) { method.debug_info.code_size = body.CodeSize; method.debug_info.local_var_token = body.local_var_token; symbol_writer.Write (method.debug_info); } return rva; } bool GetOrMapTinyMethodBody (ByteBuffer body, ref RVA rva) { RVA existing_rva; if (tiny_method_bodies.TryGetValue (body, out existing_rva)) { rva = existing_rva; return true; } tiny_method_bodies.Add (body, rva); return false; } void WriteFatHeader () { var body = this.body; byte flags = 0x3; // fat if (body.InitLocals) flags |= 0x10; // init locals if (body.HasExceptionHandlers) flags |= 0x8; // more sections WriteByte (flags); WriteByte (0x30); WriteInt16 ((short) body.max_stack_size); WriteInt32 (body.code_size); body.local_var_token = body.HasVariables ? GetStandAloneSignature (body.Variables) : MetadataToken.Zero; WriteMetadataToken (body.local_var_token); } void WriteInstructions () { var instructions = body.Instructions; var items = instructions.items; var size = instructions.size; for (int i = 0; i < size; i++) { var instruction = items [i]; WriteOpCode (instruction.opcode); WriteOperand (instruction); } } void WriteOpCode (OpCode opcode) { if (opcode.Size == 1) { WriteByte (opcode.Op2); } else { WriteByte (opcode.Op1); WriteByte (opcode.Op2); } } void WriteOperand (Instruction instruction) { var opcode = instruction.opcode; var operand_type = opcode.OperandType; if (operand_type == OperandType.InlineNone) return; var operand = instruction.operand; if (operand == null && !(operand_type == OperandType.InlineBrTarget || operand_type == OperandType.ShortInlineBrTarget)) { throw new ArgumentException (); } switch (operand_type) { case OperandType.InlineSwitch: { var targets = (Instruction []) operand; WriteInt32 (targets.Length); var diff = instruction.Offset + opcode.Size + (4 * (targets.Length + 1)); for (int i = 0; i < targets.Length; i++) WriteInt32 (GetTargetOffset (targets [i]) - diff); break; } case OperandType.ShortInlineBrTarget: { var target = (Instruction) operand; var offset = target != null ? GetTargetOffset (target) : body.code_size; WriteSByte ((sbyte) (offset - (instruction.Offset + opcode.Size + 1))); break; } case OperandType.InlineBrTarget: { var target = (Instruction) operand; var offset = target != null ? GetTargetOffset (target) : body.code_size; WriteInt32 (offset - (instruction.Offset + opcode.Size + 4)); break; } case OperandType.ShortInlineVar: WriteByte ((byte) GetVariableIndex ((VariableDefinition) operand)); break; case OperandType.ShortInlineArg: WriteByte ((byte) GetParameterIndex ((ParameterDefinition) operand)); break; case OperandType.InlineVar: WriteInt16 ((short) GetVariableIndex ((VariableDefinition) operand)); break; case OperandType.InlineArg: WriteInt16 ((short) GetParameterIndex ((ParameterDefinition) operand)); break; case OperandType.InlineSig: WriteMetadataToken (GetStandAloneSignature ((CallSite) operand)); break; case OperandType.ShortInlineI: if (opcode == OpCodes.Ldc_I4_S) WriteSByte ((sbyte) operand); else WriteByte ((byte) operand); break; case OperandType.InlineI: WriteInt32 ((int) operand); break; case OperandType.InlineI8: WriteInt64 ((long) operand); break; case OperandType.ShortInlineR: WriteSingle ((float) operand); break; case OperandType.InlineR: WriteDouble ((double) operand); break; case OperandType.InlineString: WriteMetadataToken ( new MetadataToken ( TokenType.String, GetUserStringIndex ((string) operand))); break; case OperandType.InlineType: case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineTok: WriteMetadataToken (metadata.LookupToken ((IMetadataTokenProvider) operand)); break; default: throw new ArgumentException (); } } int GetTargetOffset (Instruction instruction) { if (instruction == null) { var last = body.instructions [body.instructions.size - 1]; return last.offset + last.GetSize (); } return instruction.offset; } uint GetUserStringIndex (string @string) { if (@string == null) return 0; return metadata.user_string_heap.GetStringIndex (@string); } static int GetVariableIndex (VariableDefinition variable) { return variable.Index; } int GetParameterIndex (ParameterDefinition parameter) { if (body.method.HasThis) { if (parameter == body.this_parameter) return 0; return parameter.Index + 1; } return parameter.Index; } bool RequiresFatHeader () { var body = this.body; return body.CodeSize >= 64 || body.InitLocals || body.HasVariables || body.HasExceptionHandlers || body.MaxStackSize > 8; } void ComputeHeader () { int offset = 0; var instructions = body.instructions; var items = instructions.items; var count = instructions.size; var stack_size = 0; var max_stack = 0; Dictionary<Instruction, int> stack_sizes = null; if (body.HasExceptionHandlers) ComputeExceptionHandlerStackSize (ref stack_sizes); for (int i = 0; i < count; i++) { var instruction = items [i]; instruction.offset = offset; offset += instruction.GetSize (); ComputeStackSize (instruction, ref stack_sizes, ref stack_size, ref max_stack); } body.code_size = offset; body.max_stack_size = max_stack; } void ComputeExceptionHandlerStackSize (ref Dictionary<Instruction, int> stack_sizes) { var exception_handlers = body.ExceptionHandlers; for (int i = 0; i < exception_handlers.Count; i++) { var exception_handler = exception_handlers [i]; switch (exception_handler.HandlerType) { case ExceptionHandlerType.Catch: AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes); break; case ExceptionHandlerType.Filter: AddExceptionStackSize (exception_handler.FilterStart, ref stack_sizes); AddExceptionStackSize (exception_handler.HandlerStart, ref stack_sizes); break; } } } static void AddExceptionStackSize (Instruction handler_start, ref Dictionary<Instruction, int> stack_sizes) { if (handler_start == null) return; if (stack_sizes == null) stack_sizes = new Dictionary<Instruction, int> (); stack_sizes [handler_start] = 1; } static void ComputeStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, ref int stack_size, ref int max_stack) { int computed_size; if (stack_sizes != null && stack_sizes.TryGetValue (instruction, out computed_size)) stack_size = computed_size; max_stack = System.Math.Max (max_stack, stack_size); ComputeStackDelta (instruction, ref stack_size); max_stack = System.Math.Max (max_stack, stack_size); CopyBranchStackSize (instruction, ref stack_sizes, stack_size); ComputeStackSize (instruction, ref stack_size); } static void CopyBranchStackSize (Instruction instruction, ref Dictionary<Instruction, int> stack_sizes, int stack_size) { if (stack_size == 0) return; switch (instruction.opcode.OperandType) { case OperandType.ShortInlineBrTarget: case OperandType.InlineBrTarget: CopyBranchStackSize (ref stack_sizes, (Instruction) instruction.operand, stack_size); break; case OperandType.InlineSwitch: var targets = (Instruction []) instruction.operand; for (int i = 0; i < targets.Length; i++) CopyBranchStackSize (ref stack_sizes, targets [i], stack_size); break; } } static void CopyBranchStackSize (ref Dictionary<Instruction, int> stack_sizes, Instruction target, int stack_size) { if (stack_sizes == null) stack_sizes = new Dictionary<Instruction, int> (); int branch_stack_size = stack_size; int computed_size; if (stack_sizes.TryGetValue (target, out computed_size)) branch_stack_size = System.Math.Max (branch_stack_size, computed_size); stack_sizes [target] = branch_stack_size; } static void ComputeStackSize (Instruction instruction, ref int stack_size) { switch (instruction.opcode.FlowControl) { case FlowControl.Branch: case FlowControl.Break: case FlowControl.Throw: case FlowControl.Return: stack_size = 0; break; } } static void ComputeStackDelta (Instruction instruction, ref int stack_size) { switch (instruction.opcode.FlowControl) { case FlowControl.Call: { var method = (IMethodSignature) instruction.operand; // pop 'this' argument if (method.HasImplicitThis() && instruction.opcode.Code != Code.Newobj) stack_size--; // pop normal arguments if (method.HasParameters) stack_size -= method.Parameters.Count; // pop function pointer if (instruction.opcode.Code == Code.Calli) stack_size--; // push return value if (method.ReturnType.etype != ElementType.Void || instruction.opcode.Code == Code.Newobj) stack_size++; break; } default: ComputePopDelta (instruction.opcode.StackBehaviourPop, ref stack_size); ComputePushDelta (instruction.opcode.StackBehaviourPush, ref stack_size); break; } } static void ComputePopDelta (StackBehaviour pop_behavior, ref int stack_size) { switch (pop_behavior) { case StackBehaviour.Popi: case StackBehaviour.Popref: case StackBehaviour.Pop1: stack_size--; break; case StackBehaviour.Pop1_pop1: case StackBehaviour.Popi_pop1: case StackBehaviour.Popi_popi: case StackBehaviour.Popi_popi8: case StackBehaviour.Popi_popr4: case StackBehaviour.Popi_popr8: case StackBehaviour.Popref_pop1: case StackBehaviour.Popref_popi: stack_size -= 2; break; case StackBehaviour.Popi_popi_popi: case StackBehaviour.Popref_popi_popi: case StackBehaviour.Popref_popi_popi8: case StackBehaviour.Popref_popi_popr4: case StackBehaviour.Popref_popi_popr8: case StackBehaviour.Popref_popi_popref: stack_size -= 3; break; case StackBehaviour.PopAll: stack_size = 0; break; } } static void ComputePushDelta (StackBehaviour push_behaviour, ref int stack_size) { switch (push_behaviour) { case StackBehaviour.Push1: case StackBehaviour.Pushi: case StackBehaviour.Pushi8: case StackBehaviour.Pushr4: case StackBehaviour.Pushr8: case StackBehaviour.Pushref: stack_size++; break; case StackBehaviour.Push1_push1: stack_size += 2; break; } } void WriteExceptionHandlers () { Align (4); var handlers = body.ExceptionHandlers; if (handlers.Count < 0x15 && !RequiresFatSection (handlers)) WriteSmallSection (handlers); else WriteFatSection (handlers); } static bool RequiresFatSection (Collection<ExceptionHandler> handlers) { for (int i = 0; i < handlers.Count; i++) { var handler = handlers [i]; if (IsFatRange (handler.TryStart, handler.TryEnd)) return true; if (IsFatRange (handler.HandlerStart, handler.HandlerEnd)) return true; if (handler.HandlerType == ExceptionHandlerType.Filter && IsFatRange (handler.FilterStart, handler.HandlerStart)) return true; } return false; } static bool IsFatRange (Instruction start, Instruction end) { if (start == null) throw new ArgumentException (); if (end == null) return true; return end.Offset - start.Offset > 255 || start.Offset > 65535; } void WriteSmallSection (Collection<ExceptionHandler> handlers) { const byte eh_table = 0x1; WriteByte (eh_table); WriteByte ((byte) (handlers.Count * 12 + 4)); WriteBytes (2); WriteExceptionHandlers ( handlers, i => WriteUInt16 ((ushort) i), i => WriteByte ((byte) i)); } void WriteFatSection (Collection<ExceptionHandler> handlers) { const byte eh_table = 0x1; const byte fat_format = 0x40; WriteByte (eh_table | fat_format); int size = handlers.Count * 24 + 4; WriteByte ((byte) (size & 0xff)); WriteByte ((byte) ((size >> 8) & 0xff)); WriteByte ((byte) ((size >> 16) & 0xff)); WriteExceptionHandlers (handlers, WriteInt32, WriteInt32); } void WriteExceptionHandlers (Collection<ExceptionHandler> handlers, Action<int> write_entry, Action<int> write_length) { for (int i = 0; i < handlers.Count; i++) { var handler = handlers [i]; write_entry ((int) handler.HandlerType); write_entry (handler.TryStart.Offset); write_length (GetTargetOffset (handler.TryEnd) - handler.TryStart.Offset); write_entry (handler.HandlerStart.Offset); write_length (GetTargetOffset (handler.HandlerEnd) - handler.HandlerStart.Offset); WriteExceptionHandlerSpecific (handler); } } void WriteExceptionHandlerSpecific (ExceptionHandler handler) { switch (handler.HandlerType) { case ExceptionHandlerType.Catch: WriteMetadataToken (metadata.LookupToken (handler.CatchType)); break; case ExceptionHandlerType.Filter: WriteInt32 (handler.FilterStart.Offset); break; default: WriteInt32 (0); break; } } public MetadataToken GetStandAloneSignature (Collection<VariableDefinition> variables) { var signature = metadata.GetLocalVariableBlobIndex (variables); return GetStandAloneSignatureToken (signature); } public MetadataToken GetStandAloneSignature (CallSite call_site) { var signature = metadata.GetCallSiteBlobIndex (call_site); var token = GetStandAloneSignatureToken (signature); call_site.MetadataToken = token; return token; } MetadataToken GetStandAloneSignatureToken (uint signature) { MetadataToken token; if (standalone_signatures.TryGetValue (signature, out token)) return token; token = new MetadataToken (TokenType.Signature, metadata.AddStandAloneSignature (signature)); standalone_signatures.Add (signature, token); return token; } RVA BeginMethod () { return (RVA)(code_base + position); } void WriteMetadataToken (MetadataToken token) { WriteUInt32 (token.ToUInt32 ()); } void Align (int align) { align--; WriteBytes (((position + align) & ~align) - position); } } } #endif
using System; using System.Collections; using Org.BouncyCastle.Bcpg.Sig; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Bcpg.OpenPgp { /// <remarks>Container for a list of signature subpackets.</remarks> public class PgpSignatureSubpacketVector { private readonly SignatureSubpacket[] packets; internal PgpSignatureSubpacketVector( SignatureSubpacket[] packets) { this.packets = packets; } public SignatureSubpacket GetSubpacket( SignatureSubpacketTag type) { for (int i = 0; i != packets.Length; i++) { if (packets[i].SubpacketType == type) { return packets[i]; } } return null; } /** * Return true if a particular subpacket type exists. * * @param type type to look for. * @return true if present, false otherwise. */ public bool HasSubpacket( SignatureSubpacketTag type) { return GetSubpacket(type) != null; } /** * Return all signature subpackets of the passed in type. * @param type subpacket type code * @return an array of zero or more matching subpackets. */ public SignatureSubpacket[] GetSubpackets( SignatureSubpacketTag type) { int count = 0; for (int i = 0; i < packets.Length; ++i) { if (packets[i].SubpacketType == type) { ++count; } } SignatureSubpacket[] result = new SignatureSubpacket[count]; int pos = 0; for (int i = 0; i < packets.Length; ++i) { if (packets[i].SubpacketType == type) { result[pos++] = packets[i]; } } return result; } public NotationData[] GetNotationDataOccurences() { SignatureSubpacket[] notations = GetSubpackets(SignatureSubpacketTag.NotationData); NotationData[] vals = new NotationData[notations.Length]; for (int i = 0; i < notations.Length; i++) { vals[i] = (NotationData) notations[i]; } return vals; } public long GetIssuerKeyId() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.IssuerKeyId); return p == null ? 0 : ((IssuerKeyId) p).KeyId; } public bool HasSignatureCreationTime() { return GetSubpacket(SignatureSubpacketTag.CreationTime) != null; } public DateTime GetSignatureCreationTime() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.CreationTime); if (p == null) { throw new PgpException("SignatureCreationTime not available"); } return ((SignatureCreationTime)p).GetTime(); } /// <summary> /// Return the number of seconds a signature is valid for after its creation date. /// A value of zero means the signature never expires. /// </summary> /// <returns>Seconds a signature is valid for.</returns> public long GetSignatureExpirationTime() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.ExpireTime); return p == null ? 0 : ((SignatureExpirationTime) p).Time; } /// <summary> /// Return the number of seconds a key is valid for after its creation date. /// A value of zero means the key never expires. /// </summary> /// <returns>Seconds a signature is valid for.</returns> public long GetKeyExpirationTime() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.KeyExpireTime); return p == null ? 0 : ((KeyExpirationTime) p).Time; } public int[] GetPreferredHashAlgorithms() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.PreferredHashAlgorithms); return p == null ? null : ((PreferredAlgorithms) p).GetPreferences(); } public int[] GetPreferredSymmetricAlgorithms() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.PreferredSymmetricAlgorithms); return p == null ? null : ((PreferredAlgorithms) p).GetPreferences(); } public int[] GetPreferredCompressionAlgorithms() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.PreferredCompressionAlgorithms); return p == null ? null : ((PreferredAlgorithms) p).GetPreferences(); } public int GetKeyFlags() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.KeyFlags); return p == null ? 0 : ((KeyFlags) p).Flags; } public string GetSignerUserId() { SignatureSubpacket p = GetSubpacket(SignatureSubpacketTag.SignerUserId); return p == null ? null : ((SignerUserId) p).GetId(); } public bool IsPrimaryUserId() { PrimaryUserId primaryId = (PrimaryUserId) this.GetSubpacket(SignatureSubpacketTag.PrimaryUserId); if (primaryId != null) { return primaryId.IsPrimaryUserId(); } return false; } public SignatureSubpacketTag[] GetCriticalTags() { int count = 0; for (int i = 0; i != packets.Length; i++) { if (packets[i].IsCritical()) { count++; } } SignatureSubpacketTag[] list = new SignatureSubpacketTag[count]; count = 0; for (int i = 0; i != packets.Length; i++) { if (packets[i].IsCritical()) { list[count++] = packets[i].SubpacketType; } } return list; } [Obsolete("Use 'Count' property instead")] public int Size { get { return packets.Length; } } /// <summary>Return the number of packets this vector contains.</summary> public int Count { get { return packets.Length; } } internal SignatureSubpacket[] ToSubpacketArray() { return packets; } } }
// <copyright file="ChromiumDriver.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.Collections.Generic; using System.Collections.ObjectModel; using OpenQA.Selenium.DevTools; using OpenQA.Selenium.Remote; namespace OpenQA.Selenium.Chromium { /// <summary> /// Provides an abstract way to access Chromium-based browsers to run tests. /// </summary> public class ChromiumDriver : WebDriver, ISupportsLogs, IDevTools { /// <summary> /// Accept untrusted SSL Certificates /// </summary> public static readonly bool AcceptUntrustedCertificates = true; /// <summary> /// Command for executing a Chrome DevTools Protocol command in a driver for a Chromium-based browser. /// </summary> public static readonly string ExecuteCdp = "executeCdpCommand"; /// <summary> /// Command for getting cast sinks in a driver for a Chromium-based browser. /// </summary> public static readonly string GetCastSinksCommand = "getCastSinks"; /// <summary> /// Command for selecting a cast sink in a driver for a Chromium-based browser. /// </summary> public static readonly string SelectCastSinkCommand = "selectCastSink"; /// <summary> /// Command for starting cast tab mirroring in a driver for a Chromium-based browser. /// </summary> public static readonly string StartCastTabMirroringCommand = "startCastTabMirroring"; /// <summary> /// Command for starting cast desktop mirroring in a driver for a Chromium-based browser. /// </summary> public static readonly string StartCastDesktopMirroringCommand = "startCastDesktopMirroring"; /// <summary> /// Command for getting a cast issued message in a driver for a Chromium-based browser. /// </summary> public static readonly string GetCastIssueMessageCommand = "getCastIssueMessage"; /// <summary> /// Command for stopping casting in a driver for a Chromium-based browser. /// </summary> public static readonly string StopCastingCommand = "stopCasting"; /// <summary> /// Command for getting the simulated network conditions in a driver for a Chromium-based browser. /// </summary> public static readonly string GetNetworkConditionsCommand = "getNetworkConditions"; /// <summary> /// Command for setting the simulated network conditions in a driver for a Chromium-based browser. /// </summary> public static readonly string SetNetworkConditionsCommand = "setNetworkConditions"; /// <summary> /// Command for deleting the simulated network conditions in a driver for a Chromium-based browser. /// </summary> public static readonly string DeleteNetworkConditionsCommand = "deleteNetworkConditions"; /// <summary> /// Command for executing a Chrome DevTools Protocol command in a driver for a Chromium-based browser. /// </summary> public static readonly string SendChromeCommand = "sendChromeCommand"; /// <summary> /// Command for executing a Chrome DevTools Protocol command that returns a result in a driver for a Chromium-based browser. /// </summary> public static readonly string SendChromeCommandWithResult = "sendChromeCommandWithResult"; /// <summary> /// Command for launching an app in a driver for a Chromium-based browser. /// </summary> public static readonly string LaunchAppCommand = "launchAppCommand"; /// <summary> /// Command for setting permissions in a driver for a Chromium-based browser. /// </summary> public static readonly string SetPermissionCommand = "setPermission"; private readonly string optionsCapabilityName; private DevToolsSession devToolsSession; private static Dictionary<string, CommandInfo> chromiumCustomCommands = new Dictionary<string, CommandInfo>() { { GetNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.GetCommand, "/session/{sessionId}/chromium/network_conditions") }, { SetNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/network_conditions") }, { DeleteNetworkConditionsCommand, new HttpCommandInfo(HttpCommandInfo.DeleteCommand, "/session/{sessionId}/chromium/network_conditions") }, { SendChromeCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command") }, { SendChromeCommandWithResult, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/send_command_and_get_result") }, { LaunchAppCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/chromium/launch_app") }, { SetPermissionCommand, new HttpCommandInfo(HttpCommandInfo.PostCommand, "/session/{sessionId}/permissions") } }; /// <summary> /// Initializes a new instance of the <see cref="ChromiumDriver"/> class using the specified <see cref="ChromiumDriverService"/>. /// </summary> /// <param name="service">The <see cref="ChromiumDriverService"/> to use.</param> /// <param name="options">The <see cref="ChromiumOptions"/> to be used with the ChromiumDriver.</param> /// <param name="commandTimeout">The maximum amount of time to wait for each command.</param> protected ChromiumDriver(ChromiumDriverService service, ChromiumOptions options, TimeSpan commandTimeout) : base(new DriverServiceCommandExecutor(service, commandTimeout), ConvertOptionsToCapabilities(options)) { this.optionsCapabilityName = options.CapabilityName; } protected static IReadOnlyDictionary<string, CommandInfo> ChromiumCustomCommands { get { return new ReadOnlyDictionary<string, CommandInfo>(chromiumCustomCommands); } } /// <summary> /// Gets or sets the <see cref="IFileDetector"/> responsible for detecting /// sequences of keystrokes representing file paths and names. /// </summary> /// <remarks>The Chromium driver does not allow a file detector to be set, /// as the server component of the Chromium driver only /// allows uploads from the local computer environment. Attempting to set /// this property has no effect, but does not throw an exception. If you /// are attempting to run the Chromium driver remotely, use <see cref="RemoteWebDriver"/> /// in conjunction with a standalone WebDriver server.</remarks> public override IFileDetector FileDetector { get { return base.FileDetector; } set { } } /// <summary> /// Gets a value indicating whether a DevTools session is active. /// </summary> public bool HasActiveDevToolsSession { get { return this.devToolsSession != null; } } /// <summary> /// Gets or sets the network condition emulation for Chromium. /// </summary> public ChromiumNetworkConditions NetworkConditions { get { Response response = this.Execute(GetNetworkConditionsCommand, null); return ChromiumNetworkConditions.FromDictionary(response.Value as Dictionary<string, object>); } set { if (value == null) { throw new ArgumentNullException(nameof(value), "value must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["network_conditions"] = value; this.Execute(SetNetworkConditionsCommand, parameters); } } /// <summary> /// Launches a Chromium based application. /// </summary> /// <param name="id">ID of the chromium app to launch.</param> public void LaunchApp(string id) { if (id == null) { throw new ArgumentNullException(nameof(id), "id must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["id"] = id; this.Execute(LaunchAppCommand, parameters); } /// <summary> /// Set supported permission on browser. /// </summary> /// <param name="permissionName">Name of item to set the permission on.</param> /// <param name="permissionValue">Value to set the permission to.</param> public void SetPermission(string permissionName, string permissionValue) { if (permissionName == null) { throw new ArgumentNullException(nameof(permissionName), "name must not be null"); } if (permissionValue == null) { throw new ArgumentNullException(nameof(permissionValue), "value must not be null"); } Dictionary<string, object> nameParameter = new Dictionary<string, object>(); nameParameter["name"] = permissionName; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["descriptor"] = nameParameter; parameters["state"] = permissionValue; this.Execute(SetPermissionCommand, parameters); } /// <summary> /// Executes a custom Chrome Dev Tools Protocol Command. /// </summary> /// <param name="commandName">Name of the command to execute.</param> /// <param name="commandParameters">Parameters of the command to execute.</param> /// <returns>An object representing the result of the command, if applicable.</returns> public object ExecuteCdpCommand(string commandName, Dictionary<string, object> commandParameters) { if (commandName == null) { throw new ArgumentNullException(nameof(commandName), "commandName must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["cmd"] = commandName; parameters["params"] = commandParameters; Response response = this.Execute(ExecuteCdp, parameters); return response.Value; } /// <summary> /// Executes a custom Chrome command. /// </summary> /// <param name="commandName">Name of the command to execute.</param> /// <param name="commandParameters">Parameters of the command to execute.</param> [Obsolete("ExecuteChromeCommand is deprecated in favor of ExecuteCdpCommand.")] public void ExecuteChromeCommand(string commandName, Dictionary<string, object> commandParameters) { ExecuteCdpCommand(commandName, commandParameters); } /// <summary> /// Executes a custom Chrome command. /// </summary> /// <param name="commandName">Name of the command to execute.</param> /// <param name="commandParameters">Parameters of the command to execute.</param> /// <returns>An object representing the result of the command.</returns> [Obsolete("ExecuteChromeCommandWithResult is deprecated in favor of ExecuteCdpCommand.")] public object ExecuteChromeCommandWithResult(string commandName, Dictionary<string, object> commandParameters) { return ExecuteCdpCommand(commandName, commandParameters); } /// <summary> /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol. /// </summary> /// <param name="devToolsProtocolVersion">The version of the Chromium Developer Tools protocol to use. Defaults to autodetect the protocol version.</param> /// <returns>The active session to use to communicate with the Chromium Developer Tools debugging protocol.</returns> public DevToolsSession GetDevToolsSession() { return GetDevToolsSession(DevToolsSession.AutoDetectDevToolsProtocolVersion); } /// <summary> /// Creates a session to communicate with a browser using the Chromium Developer Tools debugging protocol. /// </summary> /// <param name="devToolsProtocolVersion">The version of the Chromium Developer Tools protocol to use. Defaults to autodetect the protocol version.</param> /// <returns>The active session to use to communicate with the Chromium Developer Tools debugging protocol.</returns> public DevToolsSession GetDevToolsSession(int devToolsProtocolVersion) { if (this.devToolsSession == null) { if (!this.Capabilities.HasCapability(this.optionsCapabilityName)) { throw new WebDriverException("Cannot find " + this.optionsCapabilityName + " capability for driver"); } Dictionary<string, object> options = this.Capabilities.GetCapability(this.optionsCapabilityName) as Dictionary<string, object>; if (options == null) { throw new WebDriverException("Found " + this.optionsCapabilityName + " capability, but is not an object"); } if (!options.ContainsKey("debuggerAddress")) { throw new WebDriverException("Did not find debuggerAddress capability in " + this.optionsCapabilityName); } string debuggerAddress = options["debuggerAddress"].ToString(); try { DevToolsSession session = new DevToolsSession(debuggerAddress); session.StartSession(devToolsProtocolVersion).ConfigureAwait(false).GetAwaiter().GetResult(); this.devToolsSession = session; } catch (Exception e) { throw new WebDriverException("Unexpected error creating WebSocket DevTools session.", e); } } return this.devToolsSession; } /// <summary> /// Closes a DevTools session. /// </summary> public void CloseDevToolsSession() { if (this.devToolsSession != null) { this.devToolsSession.StopSession(true).ConfigureAwait(false).GetAwaiter().GetResult(); } } /// <summary> /// Clears simulated network conditions. /// </summary> public void ClearNetworkConditions() { this.Execute(DeleteNetworkConditionsCommand, null); } /// <summary> /// Returns the list of cast sinks (Cast devices) available to the Chrome media router. /// </summary> /// <returns>The list of available sinks.</returns> public List<Dictionary<string, string>> GetCastSinks() { List<Dictionary<string, string>> returnValue = new List<Dictionary<string, string>>(); Response response = this.Execute(GetCastSinksCommand, null); object[] responseValue = response.Value as object[]; if (responseValue != null) { foreach (object entry in responseValue) { Dictionary<string, object> entryValue = entry as Dictionary<string, object>; if (entryValue != null) { Dictionary<string, string> sink = new Dictionary<string, string>(); foreach (KeyValuePair<string, object> pair in entryValue) { sink[pair.Key] = pair.Value.ToString(); } returnValue.Add(sink); } } } return returnValue; } /// <summary> /// Selects a cast sink (Cast device) as the recipient of media router intents (connect or play). /// </summary> /// <param name="deviceName">Name of the target sink (device).</param> public void SelectCastSink(string deviceName) { if (deviceName == null) { throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["sinkName"] = deviceName; this.Execute(SelectCastSinkCommand, parameters); } /// <summary> /// Initiates tab mirroring for the current browser tab on the specified device. /// </summary> /// <param name="deviceName">Name of the target sink (device).</param> public void StartTabMirroring(string deviceName) { if (deviceName == null) { throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["sinkName"] = deviceName; this.Execute(StartCastTabMirroringCommand, parameters); } /// <summary> /// Initiates mirroring of the desktop on the specified device. /// </summary> /// <param name="deviceName">Name of the target sink (device).</param> public void StartDesktopMirroring(string deviceName) { if (deviceName == null) { throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["sinkName"] = deviceName; this.Execute(StartCastDesktopMirroringCommand, parameters); } /// <summary> /// Returns the error message if there is any issue in a Cast session. /// </summary> /// <returns>An error message.</returns> public String GetCastIssueMessage() { Response response = this.Execute(GetCastIssueMessageCommand, null); return (string)response.Value; } /// <summary> /// Stops casting from media router to the specified device, if connected. /// </summary> /// <param name="deviceName">Name of the target sink (device).</param> public void StopCasting(string deviceName) { if (deviceName == null) { throw new ArgumentNullException(nameof(deviceName), "deviceName must not be null"); } Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters["sinkName"] = deviceName; this.Execute(StopCastingCommand, parameters); } protected override void Dispose(bool disposing) { if (disposing) { if (this.devToolsSession != null) { this.devToolsSession.Dispose(); this.devToolsSession = null; } } base.Dispose(disposing); } private static ICapabilities ConvertOptionsToCapabilities(ChromiumOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options), "options must not be null"); } return options.ToCapabilities(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WebApiSample.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.CurtainSystem.CS.UI { partial class CurtainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.createCSButton = new System.Windows.Forms.Button(); this.cgCheckedListBox = new System.Windows.Forms.CheckedListBox(); this.addCGButton = new System.Windows.Forms.Button(); this.cgLabel = new System.Windows.Forms.Label(); this.removeCGButton = new System.Windows.Forms.Button(); this.facesLabel = new System.Windows.Forms.Label(); this.facesCheckedListBox = new System.Windows.Forms.CheckedListBox(); this.exitButton = new System.Windows.Forms.Button(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.operationStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.deleteCSButton = new System.Windows.Forms.Button(); this.csListBox = new System.Windows.Forms.CheckedListBox(); this.mainPanel = new System.Windows.Forms.Panel(); this.csLabel = new System.Windows.Forms.Label(); this.statusStrip.SuspendLayout(); this.mainPanel.SuspendLayout(); this.SuspendLayout(); // // createCSButton // this.createCSButton.Image = global::Revit.SDK.Samples.CurtainSystem.CS.Properties.Resources._new; this.createCSButton.Location = new System.Drawing.Point(16, 192); this.createCSButton.Margin = new System.Windows.Forms.Padding(4); this.createCSButton.Name = "createCSButton"; this.createCSButton.Size = new System.Drawing.Size(32, 30); this.createCSButton.TabIndex = 2; this.createCSButton.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.createCSButton.UseVisualStyleBackColor = true; this.createCSButton.Click += new System.EventHandler(this.createCSButton_Click); // // cgCheckedListBox // this.cgCheckedListBox.CheckOnClick = true; this.cgCheckedListBox.FormattingEnabled = true; this.cgCheckedListBox.Location = new System.Drawing.Point(454, 27); this.cgCheckedListBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 4); this.cgCheckedListBox.Name = "cgCheckedListBox"; this.cgCheckedListBox.Size = new System.Drawing.Size(144, 157); this.cgCheckedListBox.TabIndex = 7; this.cgCheckedListBox.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.cgCheckedListBox_ItemCheck); // // addCGButton // this.addCGButton.Location = new System.Drawing.Point(348, 67); this.addCGButton.Margin = new System.Windows.Forms.Padding(4); this.addCGButton.Name = "addCGButton"; this.addCGButton.Size = new System.Drawing.Size(98, 32); this.addCGButton.TabIndex = 5; this.addCGButton.Text = "&Add >>"; this.addCGButton.UseVisualStyleBackColor = true; this.addCGButton.Click += new System.EventHandler(this.addCGButton_Click); // // cgLabel // this.cgLabel.AutoSize = true; this.cgLabel.Location = new System.Drawing.Point(451, 7); this.cgLabel.Margin = new System.Windows.Forms.Padding(4, 7, 4, 0); this.cgLabel.Name = "cgLabel"; this.cgLabel.Size = new System.Drawing.Size(95, 17); this.cgLabel.TabIndex = 8; this.cgLabel.Text = "Curtain Grids:"; // // removeCGButton // this.removeCGButton.Location = new System.Drawing.Point(348, 107); this.removeCGButton.Margin = new System.Windows.Forms.Padding(4); this.removeCGButton.Name = "removeCGButton"; this.removeCGButton.Size = new System.Drawing.Size(98, 32); this.removeCGButton.TabIndex = 6; this.removeCGButton.Text = "<< &Remove"; this.removeCGButton.UseVisualStyleBackColor = true; this.removeCGButton.Click += new System.EventHandler(this.removeCGButton_Click); // // facesLabel // this.facesLabel.AutoSize = true; this.facesLabel.Location = new System.Drawing.Point(193, 7); this.facesLabel.Margin = new System.Windows.Forms.Padding(4, 7, 4, 0); this.facesLabel.Name = "facesLabel"; this.facesLabel.Size = new System.Drawing.Size(123, 17); this.facesLabel.TabIndex = 0; this.facesLabel.Text = "Uncovered Faces:"; // // facesCheckedListBox // this.facesCheckedListBox.CheckOnClick = true; this.facesCheckedListBox.FormattingEnabled = true; this.facesCheckedListBox.Location = new System.Drawing.Point(196, 27); this.facesCheckedListBox.Margin = new System.Windows.Forms.Padding(4, 3, 4, 4); this.facesCheckedListBox.Name = "facesCheckedListBox"; this.facesCheckedListBox.Size = new System.Drawing.Size(144, 157); this.facesCheckedListBox.TabIndex = 4; this.facesCheckedListBox.SelectedIndexChanged += new System.EventHandler(this.facesCheckedListBox_SelectedIndexChanged); // // exitButton // this.exitButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.exitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.exitButton.Location = new System.Drawing.Point(510, 241); this.exitButton.Margin = new System.Windows.Forms.Padding(7); this.exitButton.Name = "exitButton"; this.exitButton.Size = new System.Drawing.Size(88, 28); this.exitButton.TabIndex = 8; this.exitButton.Text = "&Close"; this.exitButton.UseVisualStyleBackColor = true; // // statusStrip // this.statusStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.operationStatusLabel}); this.statusStrip.Location = new System.Drawing.Point(0, 276); this.statusStrip.Name = "statusStrip"; this.statusStrip.Padding = new System.Windows.Forms.Padding(1, 0, 19, 0); this.statusStrip.Size = new System.Drawing.Size(614, 22); this.statusStrip.SizingGrip = false; this.statusStrip.Stretch = false; this.statusStrip.TabIndex = 12; // // operationStatusLabel // this.operationStatusLabel.Name = "operationStatusLabel"; this.operationStatusLabel.Size = new System.Drawing.Size(0, 17); // // deleteCSButton // this.deleteCSButton.Image = global::Revit.SDK.Samples.CurtainSystem.CS.Properties.Resources.delete; this.deleteCSButton.Location = new System.Drawing.Point(56, 192); this.deleteCSButton.Margin = new System.Windows.Forms.Padding(4); this.deleteCSButton.Name = "deleteCSButton"; this.deleteCSButton.Size = new System.Drawing.Size(32, 30); this.deleteCSButton.TabIndex = 3; this.deleteCSButton.UseVisualStyleBackColor = true; this.deleteCSButton.Click += new System.EventHandler(this.deleteCSButton_Click); // // csListBox // this.csListBox.FormattingEnabled = true; this.csListBox.Location = new System.Drawing.Point(16, 27); this.csListBox.Margin = new System.Windows.Forms.Padding(7, 3, 7, 4); this.csListBox.Name = "csListBox"; this.csListBox.Size = new System.Drawing.Size(169, 157); this.csListBox.TabIndex = 1; this.csListBox.SelectedIndexChanged += new System.EventHandler(this.csListBox_SelectedIndexChanged); // // mainPanel // this.mainPanel.Controls.Add(this.csListBox); this.mainPanel.Controls.Add(this.deleteCSButton); this.mainPanel.Controls.Add(this.statusStrip); this.mainPanel.Controls.Add(this.exitButton); this.mainPanel.Controls.Add(this.facesCheckedListBox); this.mainPanel.Controls.Add(this.facesLabel); this.mainPanel.Controls.Add(this.removeCGButton); this.mainPanel.Controls.Add(this.cgLabel); this.mainPanel.Controls.Add(this.addCGButton); this.mainPanel.Controls.Add(this.csLabel); this.mainPanel.Controls.Add(this.cgCheckedListBox); this.mainPanel.Controls.Add(this.createCSButton); this.mainPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.mainPanel.Location = new System.Drawing.Point(0, 0); this.mainPanel.Margin = new System.Windows.Forms.Padding(4); this.mainPanel.Name = "mainPanel"; this.mainPanel.Size = new System.Drawing.Size(614, 298); this.mainPanel.TabIndex = 0; this.mainPanel.Paint += new System.Windows.Forms.PaintEventHandler(this.mainPanel_Paint); // // csLabel // this.csLabel.AutoSize = true; this.csLabel.Location = new System.Drawing.Point(13, 7); this.csLabel.Margin = new System.Windows.Forms.Padding(4, 7, 4, 0); this.csLabel.Name = "csLabel"; this.csLabel.Size = new System.Drawing.Size(114, 17); this.csLabel.TabIndex = 0; this.csLabel.Text = "Curtain Systems:"; this.csLabel.Click += new System.EventHandler(this.csLabel_Click); // // CurtainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.exitButton; this.ClientSize = new System.Drawing.Size(614, 298); this.Controls.Add(this.mainPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Margin = new System.Windows.Forms.Padding(4); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CurtainForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Curtain System"; this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.mainPanel.ResumeLayout(false); this.mainPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button createCSButton; private System.Windows.Forms.CheckedListBox cgCheckedListBox; private System.Windows.Forms.Button addCGButton; private System.Windows.Forms.Label cgLabel; private System.Windows.Forms.Button removeCGButton; private System.Windows.Forms.Label facesLabel; private System.Windows.Forms.CheckedListBox facesCheckedListBox; private System.Windows.Forms.Button exitButton; private System.Windows.Forms.StatusStrip statusStrip; private System.Windows.Forms.ToolStripStatusLabel operationStatusLabel; private System.Windows.Forms.Button deleteCSButton; private System.Windows.Forms.CheckedListBox csListBox; private System.Windows.Forms.Panel mainPanel; private System.Windows.Forms.Label csLabel; } }
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. using System; using System.Collections.Generic; using System.IO; using OpenTK; using OpenTK.Graphics.OpenGL; using Util3d; namespace SimpleScene { public class SSMesh_wfOBJ : SSAbstractMesh { protected List<SSMeshOBJSubsetData> geometrySubsets = new List<SSMeshOBJSubsetData>(); SSAssetManager.Context ctx; public readonly string srcFilename; public struct SSMeshOBJSubsetData { public SSTexture diffuseTexture; public SSTexture specularTexture; public SSTexture ambientTexture; public SSTexture bumpTexture; // raw geometry public SSVertex_PosNormDiffTex1[] vertices; public UInt16[] indicies; public UInt16[] wireframe_indicies; // handles to OpenTK/OpenGL Vertex-buffer and index-buffer objects // these are buffers stored on the videocard for higher performance rendering public SSVertexBuffer<SSVertex_PosNormDiffTex1> vbo; public SSIndexBuffer ibo; public SSIndexBuffer ibo_wireframe; } public override string ToString () { return string.Format ("[SSMesh_FromOBJ:{0}]", this.srcFilename); } #region Constructor public SSMesh_wfOBJ(SSAssetManager.Context ctx, string filename) { this.srcFilename = filename; this.ctx = ctx; Console.WriteLine("SSMesh_wfOBJ: loading wff {0}",filename); WavefrontObjLoader wff_data = new WavefrontObjLoader(filename, delegate(string resourceName) { return ctx.Open(resourceName); }); Console.WriteLine("wff vertex count = {0}",wff_data.positions.Count); Console.WriteLine("wff face count = {0}",wff_data.numFaces); _loadData(ctx, wff_data); } #endregion private void _renderSetupGLSL(ref SSRenderConfig renderConfig, SSMeshOBJSubsetData subset) { // Step 1: setup GL rendering modes... // GL.Enable(EnableCap.Lighting); // GL.Enable(EnableCap.Blend); // GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); // GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); // Step 2: setup our material mode and paramaters... GL.Color3(System.Drawing.Color.White); // clear the vertex color to white.. SSMainShaderProgram shaderPgm = renderConfig.MainShader; if (renderConfig.drawingShadowMap) { // assume SSObject.Render has setup our materials properly for the shadowmap Pass // TODO: find a better way to do this! return; } if (shaderPgm == null) { SSShaderProgram.DeactivateAll (); // fixed function single-texture if (subset.diffuseTexture != null) { GL.ActiveTexture(TextureUnit.Texture0); GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, subset.diffuseTexture.TextureID); } } else { // bind our texture-images to GL texture-units // http://adriangame.blogspot.com/2010/05/glsl-multitexture-checklist.html // these texture-unit assignments are hard-coded in the shader setup shaderPgm.Activate (); GL.ActiveTexture(TextureUnit.Texture0); if (subset.diffuseTexture != null) { GL.BindTexture(TextureTarget.Texture2D, subset.diffuseTexture.TextureID); shaderPgm.UniDiffTexEnabled = true; } else { GL.BindTexture(TextureTarget.Texture2D, 0); shaderPgm.UniDiffTexEnabled = false; } GL.ActiveTexture(TextureUnit.Texture1); if (subset.specularTexture != null) { GL.BindTexture(TextureTarget.Texture2D, subset.specularTexture.TextureID); shaderPgm.UniSpecTexEnabled = true; } else { GL.BindTexture(TextureTarget.Texture2D, 0); shaderPgm.UniSpecTexEnabled = false; } GL.ActiveTexture(TextureUnit.Texture2); if (subset.ambientTexture != null) { GL.BindTexture(TextureTarget.Texture2D, subset.ambientTexture.TextureID); shaderPgm.UniAmbTexEnabled = true; } else { GL.BindTexture(TextureTarget.Texture2D, 0); shaderPgm.UniAmbTexEnabled = false; } GL.ActiveTexture(TextureUnit.Texture3); if (subset.bumpTexture != null) { GL.BindTexture(TextureTarget.Texture2D, subset.bumpTexture.TextureID); shaderPgm.UniBumpTexEnabled = true; } else { GL.BindTexture(TextureTarget.Texture2D, 0); shaderPgm.UniBumpTexEnabled = false; } // reset to texture-unit 0 to be friendly.. GL.ActiveTexture(TextureUnit.Texture0); } } private void _renderSetupWireframe() { SSShaderProgram.DeactivateAll (); GL.Disable(EnableCap.Texture2D); GL.Disable(EnableCap.Blend); GL.Disable(EnableCap.Lighting); } public override IEnumerable<Vector3> EnumeratePoints () { foreach (var subset in geometrySubsets) { foreach (var vtx in subset.vertices) { yield return vtx.Position; } } } public override bool TraverseTriangles<T>(T state, traverseFn<T> fn) { foreach(var subset in geometrySubsets) { for(int idx=0;idx < subset.indicies.Length;idx+=3) { var V1 = subset.vertices[subset.indicies[idx]].Position; var V2 = subset.vertices[subset.indicies[idx+1]].Position; var V3 = subset.vertices[subset.indicies[idx+2]].Position; bool finished = fn(state, V1, V2, V3); if (finished) { return true; } } } return false; } private void _renderSendVBOTriangles(SSMeshOBJSubsetData subset) { subset.ibo.DrawElements(PrimitiveType.Triangles); } private void _renderSendTriangles(SSMeshOBJSubsetData subset) { // Step 3: draw faces.. here we use the "old school" manual method of drawing // note: programs written for modern OpenGL & D3D don't do this! // instead, they hand the vertex-buffer and index-buffer to the // GPU and let it do this.. GL.Begin(PrimitiveType.Triangles); foreach(var idx in subset.indicies) { var vertex = subset.vertices[idx]; // retrieve the vertex // draw the vertex.. GL.Color3(System.Drawing.Color.FromArgb(vertex.DiffuseColor)); GL.TexCoord2(vertex.Tu,vertex.Tv); GL.Normal3(vertex.Normal); GL.Vertex3(vertex.Position); } GL.End(); } private void _renderSendVBOLines(SSMeshOBJSubsetData subset) { // TODO: this currently has classic problems with z-fighting between the model and the wireframe // it is customary to "bump" the wireframe slightly towards the camera to prevent this. GL.LineWidth(1.5f); GL.Color4(0.8f, 0.5f, 0.5f, 0.5f); subset.ibo.DrawElements(PrimitiveType.Lines); } private void _renderSendLines(SSMeshOBJSubsetData subset) { // Step 3: draw faces.. here we use the "old school" manual method of drawing // note: programs written for modern OpenGL & D3D don't do this! // instead, they hand the vertex-buffer and index-buffer to the // GPU and let it do this.. for(int i=2;i<subset.indicies.Length;i+=3) { var v1 = subset.vertices [subset.indicies[i - 2]]; var v2 = subset.vertices [subset.indicies[i - 1]]; var v3 = subset.vertices [subset.indicies[i]]; // draw the vertex.. GL.Color3(System.Drawing.Color.FromArgb(v1.DiffuseColor)); GL.Begin(PrimitiveType.LineLoop); GL.Vertex3 (v1.Position); GL.Vertex3 (v2.Position); GL.Vertex3 (v3.Position); GL.End(); } } public override void RenderMesh(ref SSRenderConfig renderConfig) { foreach (SSMeshOBJSubsetData subset in this.geometrySubsets) { if (renderConfig.drawingShadowMap) { _renderSendVBOTriangles(subset); } else { if (renderConfig.drawGLSL) { _renderSetupGLSL(ref renderConfig, subset); if (renderConfig.useVBO && renderConfig.MainShader != null) { _renderSendVBOTriangles(subset); } else { _renderSendTriangles(subset); } } if (renderConfig.drawWireframeMode == WireframeMode.GL_Lines) { _renderSetupWireframe(); if (renderConfig.useVBO && renderConfig.MainShader != null) { _renderSendVBOLines(subset); } else { _renderSendLines(subset); } } } } } #region Load Data private void _loadData(SSAssetManager.Context ctx ,WavefrontObjLoader m) { foreach (var srcmat in m.materials) { if (srcmat.faces.Count != 0) { this.geometrySubsets.Add(_loadMaterialSubset(ctx, m, srcmat)); } } } private SSMeshOBJSubsetData _loadMaterialSubset(SSAssetManager.Context ctx, WavefrontObjLoader wff, WavefrontObjLoader.MaterialFromObj objMatSubset) { // create new mesh subset-data SSMeshOBJSubsetData subsetData = new SSMeshOBJSubsetData(); // setup the material... // load and link every texture present if (objMatSubset.diffuseTextureResourceName != null) { subsetData.diffuseTexture = SSAssetManager.GetInstance<SSTexture>(ctx, objMatSubset.diffuseTextureResourceName); } if (objMatSubset.ambientTextureResourceName != null) { subsetData.ambientTexture = SSAssetManager.GetInstance<SSTexture>(ctx, objMatSubset.ambientTextureResourceName); } if (objMatSubset.bumpTextureResourceName != null) { subsetData.bumpTexture = SSAssetManager.GetInstance<SSTexture>(ctx, objMatSubset.bumpTextureResourceName); } if (objMatSubset.specularTextureResourceName != null) { subsetData.specularTexture = SSAssetManager.GetInstance<SSTexture>(ctx, objMatSubset.specularTextureResourceName); } // generate renderable geometry data... VertexSoup_VertexFormatBinder.generateDrawIndexBuffer(wff, out subsetData.indicies, out subsetData.vertices); // TODO: setup VBO/IBO buffers // http://www.opentk.com/doc/graphics/geometry/vertex-buffer-objects subsetData.wireframe_indicies = OpenTKHelper.generateLineIndicies (subsetData.indicies); subsetData.vbo = new SSVertexBuffer<SSVertex_PosNormDiffTex1>(subsetData.vertices); subsetData.ibo = new SSIndexBuffer(subsetData.indicies, subsetData.vbo); subsetData.ibo_wireframe = new SSIndexBuffer (subsetData.wireframe_indicies, subsetData.vbo); return subsetData; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.TypeParsing; using Internal.LowLevelLinq; using Internal.Reflection.Core; using Internal.Runtime.Augments; using Internal.Metadata.NativeFormat; namespace System.Reflection.Runtime.General { // // Collect various metadata reading tasks for better chunking... // internal static class MetadataReaderExtensions { public static string GetString(this ConstantStringValueHandle handle, MetadataReader reader) { return reader.GetConstantStringValue(handle).Value; } // Useful for namespace Name string which can be a null handle. public static String GetStringOrNull(this ConstantStringValueHandle handle, MetadataReader reader) { if (reader.IsNull(handle)) return null; return reader.GetConstantStringValue(handle).Value; } public static bool StringOrNullEquals(this ConstantStringValueHandle handle, String valueOrNull, MetadataReader reader) { if (valueOrNull == null) return handle.IsNull(reader); if (handle.IsNull(reader)) return false; return handle.StringEquals(valueOrNull, reader); } // Needed for RuntimeMappingTable access public static int AsInt(this TypeDefinitionHandle typeDefinitionHandle) { unsafe { return *(int*)&typeDefinitionHandle; } } public static TypeDefinitionHandle AsTypeDefinitionHandle(this int i) { unsafe { return *(TypeDefinitionHandle*)&i; } } public static int AsInt(this MethodHandle methodHandle) { unsafe { return *(int*)&methodHandle; } } public static MethodHandle AsMethodHandle(this int i) { unsafe { return *(MethodHandle*)&i; } } public static int AsInt(this FieldHandle fieldHandle) { unsafe { return *(int*)&fieldHandle; } } public static FieldHandle AsFieldHandle(this int i) { unsafe { return *(FieldHandle*)&i; } } public static bool IsTypeDefRefOrSpecHandle(this Handle handle, MetadataReader reader) { HandleType handleType = handle.HandleType; return handleType == HandleType.TypeDefinition || handleType == HandleType.TypeReference || handleType == HandleType.TypeSpecification; } public static bool IsNamespaceDefinitionHandle(this Handle handle, MetadataReader reader) { HandleType handleType = handle.HandleType; return handleType == HandleType.NamespaceDefinition; } public static bool IsNamespaceReferenceHandle(this Handle handle, MetadataReader reader) { HandleType handleType = handle.HandleType; return handleType == HandleType.NamespaceReference; } // Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller. public static ScopeReferenceHandle ToExpectedScopeReferenceHandle(this Handle handle, MetadataReader reader) { try { return handle.ToScopeReferenceHandle(reader); } catch (ArgumentException) { throw new BadImageFormatException(); } } // Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller. public static NamespaceReferenceHandle ToExpectedNamespaceReferenceHandle(this Handle handle, MetadataReader reader) { try { return handle.ToNamespaceReferenceHandle(reader); } catch (ArgumentException) { throw new BadImageFormatException(); } } // Conversion where a invalid handle type indicates bad metadata rather a mistake by the caller. public static TypeDefinitionHandle ToExpectedTypeDefinitionHandle(this Handle handle, MetadataReader reader) { try { return handle.ToTypeDefinitionHandle(reader); } catch (ArgumentException) { throw new BadImageFormatException(); } } public static MethodSignature ParseMethodSignature(this Handle handle, MetadataReader reader) { return handle.ToMethodSignatureHandle(reader).GetMethodSignature(reader); } public static FieldSignature ParseFieldSignature(this Handle handle, MetadataReader reader) { return handle.ToFieldSignatureHandle(reader).GetFieldSignature(reader); } public static PropertySignature ParsePropertySignature(this Handle handle, MetadataReader reader) { return handle.ToPropertySignatureHandle(reader).GetPropertySignature(reader); } // // Used to split methods between DeclaredMethods and DeclaredConstructors. // public static bool IsConstructor(this MethodHandle methodHandle, MetadataReader reader) { Method method = methodHandle.GetMethod(reader); return IsConstructor(ref method, reader); } // This is specially designed for a hot path so we make some compromises in the signature: // // - "method" is passed by reference even though no side-effects are intended. // public static bool IsConstructor(ref Method method, MetadataReader reader) { if ((method.Flags & (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName)) != (MethodAttributes.RTSpecialName | MethodAttributes.SpecialName)) return false; ConstantStringValueHandle nameHandle = method.Name; return nameHandle.StringEquals(ConstructorInfo.ConstructorName, reader) || nameHandle.StringEquals(ConstructorInfo.TypeConstructorName, reader); } private static Exception ParseBoxedEnumConstantValue(this ConstantBoxedEnumValueHandle handle, MetadataReader reader, out Object value) { ConstantBoxedEnumValue record = handle.GetConstantBoxedEnumValue(reader); Exception exception = null; Type enumType = record.Type.TryResolve(reader, new TypeContext(null, null), ref exception); if (enumType == null) { value = null; return exception; } if (!enumType.GetTypeInfo().IsEnum) throw new BadImageFormatException(); Type underlyingType = Enum.GetUnderlyingType(enumType); // Now box the value as the specified enum type. unsafe { switch (record.Value.HandleType) { case HandleType.ConstantByteValue: { if (underlyingType != typeof(byte)) throw new BadImageFormatException(); byte v = record.Value.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantSByteValue: { if (underlyingType != typeof(sbyte)) throw new BadImageFormatException(); sbyte v = record.Value.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantInt16Value: { if (underlyingType != typeof(short)) throw new BadImageFormatException(); short v = record.Value.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantUInt16Value: { if (underlyingType != typeof(ushort)) throw new BadImageFormatException(); ushort v = record.Value.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantInt32Value: { if (underlyingType != typeof(int)) throw new BadImageFormatException(); int v = record.Value.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantUInt32Value: { if (underlyingType != typeof(uint)) throw new BadImageFormatException(); uint v = record.Value.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantInt64Value: { if (underlyingType != typeof(long)) throw new BadImageFormatException(); long v = record.Value.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } case HandleType.ConstantUInt64Value: { if (underlyingType != typeof(ulong)) throw new BadImageFormatException(); ulong v = record.Value.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value; value = RuntimeAugments.Box(enumType.TypeHandle, (IntPtr)(&v)); return null; } default: throw new BadImageFormatException(); } } } public static Object ParseConstantValue(this Handle handle, MetadataReader reader) { Object value; Exception exception = handle.TryParseConstantValue(reader, out value); if (exception != null) throw exception; return value; } public static Exception TryParseConstantValue(this Handle handle, MetadataReader reader, out Object value) { HandleType handleType = handle.HandleType; switch (handleType) { case HandleType.ConstantBooleanValue: value = handle.ToConstantBooleanValueHandle(reader).GetConstantBooleanValue(reader).Value; return null; case HandleType.ConstantStringValue: value = handle.ToConstantStringValueHandle(reader).GetConstantStringValue(reader).Value; return null; case HandleType.ConstantCharValue: value = handle.ToConstantCharValueHandle(reader).GetConstantCharValue(reader).Value; return null; case HandleType.ConstantByteValue: value = handle.ToConstantByteValueHandle(reader).GetConstantByteValue(reader).Value; return null; case HandleType.ConstantSByteValue: value = handle.ToConstantSByteValueHandle(reader).GetConstantSByteValue(reader).Value; return null; case HandleType.ConstantInt16Value: value = handle.ToConstantInt16ValueHandle(reader).GetConstantInt16Value(reader).Value; return null; case HandleType.ConstantUInt16Value: value = handle.ToConstantUInt16ValueHandle(reader).GetConstantUInt16Value(reader).Value; return null; case HandleType.ConstantInt32Value: value = handle.ToConstantInt32ValueHandle(reader).GetConstantInt32Value(reader).Value; return null; case HandleType.ConstantUInt32Value: value = handle.ToConstantUInt32ValueHandle(reader).GetConstantUInt32Value(reader).Value; return null; case HandleType.ConstantInt64Value: value = handle.ToConstantInt64ValueHandle(reader).GetConstantInt64Value(reader).Value; return null; case HandleType.ConstantUInt64Value: value = handle.ToConstantUInt64ValueHandle(reader).GetConstantUInt64Value(reader).Value; return null; case HandleType.ConstantSingleValue: value = handle.ToConstantSingleValueHandle(reader).GetConstantSingleValue(reader).Value; return null; case HandleType.ConstantDoubleValue: value = handle.ToConstantDoubleValueHandle(reader).GetConstantDoubleValue(reader).Value; return null; case HandleType.TypeDefinition: case HandleType.TypeReference: case HandleType.TypeSpecification: { Exception exception = null; Type type = handle.TryResolve(reader, new TypeContext(null, null), ref exception); value = type; return (value == null) ? exception : null; } case HandleType.ConstantReferenceValue: value = null; return null; case HandleType.ConstantBoxedEnumValue: { return handle.ToConstantBoxedEnumValueHandle(reader).ParseBoxedEnumConstantValue(reader, out value); } default: { Exception exception; value = handle.TryParseConstantArray(reader, out exception); if (value == null) return exception; return null; } } } public static IEnumerable TryParseConstantArray(this Handle handle, MetadataReader reader, out Exception exception) { exception = null; HandleType handleType = handle.HandleType; switch (handleType) { case HandleType.ConstantBooleanArray: return handle.ToConstantBooleanArrayHandle(reader).GetConstantBooleanArray(reader).Value; case HandleType.ConstantStringArray: return handle.ToConstantStringArrayHandle(reader).GetConstantStringArray(reader).Value; case HandleType.ConstantCharArray: return handle.ToConstantCharArrayHandle(reader).GetConstantCharArray(reader).Value; case HandleType.ConstantByteArray: return handle.ToConstantByteArrayHandle(reader).GetConstantByteArray(reader).Value; case HandleType.ConstantSByteArray: return handle.ToConstantSByteArrayHandle(reader).GetConstantSByteArray(reader).Value; case HandleType.ConstantInt16Array: return handle.ToConstantInt16ArrayHandle(reader).GetConstantInt16Array(reader).Value; case HandleType.ConstantUInt16Array: return handle.ToConstantUInt16ArrayHandle(reader).GetConstantUInt16Array(reader).Value; case HandleType.ConstantInt32Array: return handle.ToConstantInt32ArrayHandle(reader).GetConstantInt32Array(reader).Value; case HandleType.ConstantUInt32Array: return handle.ToConstantUInt32ArrayHandle(reader).GetConstantUInt32Array(reader).Value; case HandleType.ConstantInt64Array: return handle.ToConstantInt64ArrayHandle(reader).GetConstantInt64Array(reader).Value; case HandleType.ConstantUInt64Array: return handle.ToConstantUInt64ArrayHandle(reader).GetConstantUInt64Array(reader).Value; case HandleType.ConstantSingleArray: return handle.ToConstantSingleArrayHandle(reader).GetConstantSingleArray(reader).Value; case HandleType.ConstantDoubleArray: return handle.ToConstantDoubleArrayHandle(reader).GetConstantDoubleArray(reader).Value; case HandleType.ConstantHandleArray: { Handle[] constantHandles = handle.ToConstantHandleArrayHandle(reader).GetConstantHandleArray(reader).Value.ToArray(); object[] elements = new object[constantHandles.Length]; for (int i = 0; i < constantHandles.Length; i++) { exception = constantHandles[i].TryParseConstantValue(reader, out elements[i]); if (exception != null) return null; } return elements; } default: throw new BadImageFormatException(); } } public static Handle GetAttributeTypeHandle(this CustomAttribute customAttribute, MetadataReader reader) { HandleType constructorHandleType = customAttribute.Constructor.HandleType; if (constructorHandleType == HandleType.QualifiedMethod) return customAttribute.Constructor.ToQualifiedMethodHandle(reader).GetQualifiedMethod(reader).EnclosingType; else if (constructorHandleType == HandleType.MemberReference) return customAttribute.Constructor.ToMemberReferenceHandle(reader).GetMemberReference(reader).Parent; else throw new BadImageFormatException(); } // // Lightweight check to see if a custom attribute's is of a well-known type. // // This check performs without instantating the Type object and bloating memory usage. On the flip side, // it doesn't check on whether the type is defined in a paricular assembly. The desktop CLR typically doesn't // check this either so this is useful from a compat persective as well. // public static bool IsCustomAttributeOfType(this CustomAttributeHandle customAttributeHandle, MetadataReader reader, String ns, String name) { String[] namespaceParts = ns.Split('.'); Handle typeHandle = customAttributeHandle.GetCustomAttribute(reader).GetAttributeTypeHandle(reader); HandleType handleType = typeHandle.HandleType; if (handleType == HandleType.TypeDefinition) { TypeDefinition typeDefinition = typeHandle.ToTypeDefinitionHandle(reader).GetTypeDefinition(reader); if (!typeDefinition.Name.StringEquals(name, reader)) return false; NamespaceDefinitionHandle nsHandle = typeDefinition.NamespaceDefinition; int idx = namespaceParts.Length; while (idx-- != 0) { String namespacePart = namespaceParts[idx]; NamespaceDefinition namespaceDefinition = nsHandle.GetNamespaceDefinition(reader); if (!namespaceDefinition.Name.StringOrNullEquals(namespacePart, reader)) return false; if (!namespaceDefinition.ParentScopeOrNamespace.IsNamespaceDefinitionHandle(reader)) return false; nsHandle = namespaceDefinition.ParentScopeOrNamespace.ToNamespaceDefinitionHandle(reader); } if (!nsHandle.GetNamespaceDefinition(reader).Name.StringOrNullEquals(null, reader)) return false; return true; } else if (handleType == HandleType.TypeReference) { TypeReference typeReference = typeHandle.ToTypeReferenceHandle(reader).GetTypeReference(reader); if (!typeReference.TypeName.StringEquals(name, reader)) return false; if (!typeReference.ParentNamespaceOrType.IsNamespaceReferenceHandle(reader)) return false; NamespaceReferenceHandle nsHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(reader); int idx = namespaceParts.Length; while (idx-- != 0) { String namespacePart = namespaceParts[idx]; NamespaceReference namespaceReference = nsHandle.GetNamespaceReference(reader); if (!namespaceReference.Name.StringOrNullEquals(namespacePart, reader)) return false; if (!namespaceReference.ParentScopeOrNamespace.IsNamespaceReferenceHandle(reader)) return false; nsHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader); } if (!nsHandle.GetNamespaceReference(reader).Name.StringOrNullEquals(null, reader)) return false; return true; } else throw new NotSupportedException(); } public static String ToNamespaceName(this NamespaceDefinitionHandle namespaceDefinitionHandle, MetadataReader reader) { String ns = ""; for (;;) { NamespaceDefinition currentNamespaceDefinition = namespaceDefinitionHandle.GetNamespaceDefinition(reader); String name = currentNamespaceDefinition.Name.GetStringOrNull(reader); if (name != null) { if (ns.Length != 0) ns = "." + ns; ns = name + ns; } Handle nextHandle = currentNamespaceDefinition.ParentScopeOrNamespace; HandleType handleType = nextHandle.HandleType; if (handleType == HandleType.ScopeDefinition) break; if (handleType == HandleType.NamespaceDefinition) { namespaceDefinitionHandle = nextHandle.ToNamespaceDefinitionHandle(reader); continue; } throw new BadImageFormatException(SR.Bif_InvalidMetadata); } return ns; } public static IEnumerable<NamespaceDefinitionHandle> GetTransitiveNamespaces(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles) { foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles) { yield return namespaceHandle; NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); foreach (NamespaceDefinitionHandle childNamespaceHandle in GetTransitiveNamespaces(reader, namespaceDefinition.NamespaceDefinitions)) yield return childNamespaceHandle; } } public static IEnumerable<TypeDefinitionHandle> GetTopLevelTypes(this MetadataReader reader, IEnumerable<NamespaceDefinitionHandle> namespaceHandles) { foreach (NamespaceDefinitionHandle namespaceHandle in namespaceHandles) { NamespaceDefinition namespaceDefinition = namespaceHandle.GetNamespaceDefinition(reader); foreach (TypeDefinitionHandle typeDefinitionHandle in namespaceDefinition.TypeDefinitions) { yield return typeDefinitionHandle; } } } public static IEnumerable<TypeDefinitionHandle> GetTransitiveTypes(this MetadataReader reader, IEnumerable<TypeDefinitionHandle> typeDefinitionHandles, bool publicOnly) { foreach (TypeDefinitionHandle typeDefinitionHandle in typeDefinitionHandles) { TypeDefinition typeDefinition = typeDefinitionHandle.GetTypeDefinition(reader); if (publicOnly) { TypeAttributes visibility = typeDefinition.Flags & TypeAttributes.VisibilityMask; if (visibility != TypeAttributes.Public && visibility != TypeAttributes.NestedPublic) continue; } yield return typeDefinitionHandle; foreach (TypeDefinitionHandle nestedTypeDefinitionHandle in GetTransitiveTypes(reader, typeDefinition.NestedTypes, publicOnly)) yield return nestedTypeDefinitionHandle; } } public static AssemblyQualifiedTypeName ToAssemblyQualifiedTypeName(this NamespaceReferenceHandle namespaceReferenceHandle, String typeName, MetadataReader reader) { LowLevelList<String> namespaceParts = new LowLevelList<String>(8); NamespaceReference namespaceReference; for (;;) { namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader); String namespacePart = namespaceReference.Name.GetStringOrNull(reader); if (namespacePart == null) break; namespaceParts.Add(namespacePart); namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedNamespaceReferenceHandle(reader); } ScopeReferenceHandle scopeReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToExpectedScopeReferenceHandle(reader); RuntimeAssemblyName assemblyName = scopeReferenceHandle.ToRuntimeAssemblyName(reader); return new AssemblyQualifiedTypeName(new NamespaceTypeName(namespaceParts.ToArray(), typeName), assemblyName); } public static RuntimeAssemblyName ToRuntimeAssemblyName(this ScopeDefinitionHandle scopeDefinitionHandle, MetadataReader reader) { ScopeDefinition scopeDefinition = scopeDefinitionHandle.GetScopeDefinition(reader); return CreateRuntimeAssemblyNameFromMetadata( reader, scopeDefinition.Name, scopeDefinition.MajorVersion, scopeDefinition.MinorVersion, scopeDefinition.BuildNumber, scopeDefinition.RevisionNumber, scopeDefinition.Culture, scopeDefinition.PublicKey, scopeDefinition.Flags ); } public static RuntimeAssemblyName ToRuntimeAssemblyName(this ScopeReferenceHandle scopeReferenceHandle, MetadataReader reader) { ScopeReference scopeReference = scopeReferenceHandle.GetScopeReference(reader); return CreateRuntimeAssemblyNameFromMetadata( reader, scopeReference.Name, scopeReference.MajorVersion, scopeReference.MinorVersion, scopeReference.BuildNumber, scopeReference.RevisionNumber, scopeReference.Culture, scopeReference.PublicKeyOrToken, scopeReference.Flags ); } private static RuntimeAssemblyName CreateRuntimeAssemblyNameFromMetadata( MetadataReader reader, ConstantStringValueHandle name, ushort majorVersion, ushort minorVersion, ushort buildNumber, ushort revisionNumber, ConstantStringValueHandle culture, IEnumerable<byte> publicKeyOrToken, AssemblyFlags assemblyFlags) { AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None; if (0 != (assemblyFlags & AssemblyFlags.PublicKey)) assemblyNameFlags |= AssemblyNameFlags.PublicKey; if (0 != (assemblyFlags & AssemblyFlags.Retargetable)) assemblyNameFlags |= AssemblyNameFlags.Retargetable; int contentType = ((int)assemblyFlags) & 0x00000E00; assemblyNameFlags |= (AssemblyNameFlags)contentType; return new RuntimeAssemblyName( name.GetString(reader), new Version(majorVersion, minorVersion, buildNumber, revisionNumber), culture.GetStringOrNull(reader), assemblyNameFlags, publicKeyOrToken.ToArray() ); } } }
// $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 System.Runtime.CompilerServices; using System.Threading; namespace Org.Apache.Etch.Bindings.Csharp.Util { /// <summary> /// A standalone version of a processor for todo items /// </summary> public class TodoManager : AbstractStartable { /// <summary> /// Constructs the TodoManager /// </summary> /// <param name="maxEntries">the maximum number of entries in the queue</param> /// <param name="entryDelay">milliseconds to delay a caller who tries to /// add a entry over the limit.</param> /// <param name="minWorkers">the minimum number of workers to keep waiting</param> /// <param name="maxWorkers">the maximum number of workers to allow.</param> /// <param name="workerLinger">milliseconds a worker will wait for a Todo /// before considering quitting.</param> /// <param name="threshold">the per worker threshold for queue length. if /// queue length exceeds this amount, a new worker is added if allowed.</param> /// public TodoManager( int maxEntries, int entryDelay, int minWorkers, int maxWorkers, int workerLinger, int threshold ) { if ( maxEntries < 1 ) throw new ArgumentException( "maxEntries < 1" ); if ( minWorkers < 0 ) throw new ArgumentException( "minWorkers < 0" ); if ( maxWorkers < minWorkers ) throw new ArgumentException( "maxWorkers < minWorkers" ); if ( maxWorkers < 1 ) throw new ArgumentException( "maxWorkers < 1" ); if ( workerLinger < 1 ) throw new ArgumentException( "workerLinger < 1" ); this.maxEntries = maxEntries; this.entryDelay = entryDelay; this.minWorkers = minWorkers; this.maxWorkers = maxWorkers; this.workerLinger = workerLinger; this.threshold = threshold; } private int maxEntries; private int entryDelay; private int minWorkers; private int maxWorkers; private int workerLinger; private int threshold; protected override void Start0() { // nothing to do } protected override void Stop0() { lock (this) { Monitor.PulseAll(this); } } /// <summary> /// /// </summary> /// <param name="todo"></param> /// Exception: /// throws ThreadInterruptedException [ MethodImpl ( MethodImplOptions.Synchronized ) ] public void Add( Todo todo ) { CheckIsStarted(); int n = AddEntry( todo ); Monitor.Pulse( this ); ConsiderStartingAWorker( n ) ; if ( n > maxEntries ) Thread.Sleep( entryDelay ); } public void Run() { bool needAdjust = true; try { Todo todo; while ( ( todo = GetNextTodo() ) != null ) { try { todo.Doit( this ); } catch ( Exception e ) { todo.Exception( this, e ); } } needAdjust = false; } finally { if ( needAdjust ) workers.Adjust( -1 ); } } # region Workers /// <summary> /// /// </summary> /// <returns>number of workers</returns> public int NumWorkers() { return workers.Get(); } [MethodImpl( MethodImplOptions.Synchronized )] private void ConsiderStartingAWorker( int qlen ) { int n = NumWorkers(); if ( n >= maxWorkers ) return; // Start a new worker if there are none or if the // queue length per worker has exceeded the threshold if ( n == 0 || ( (qlen + n-1) / n ) > threshold ) StartAWorker(); } private void StartAWorker() { workers.Adjust( 1 ); Thread t = new Thread(Run); t.Start(); } private IntCounter workers = new IntCounter(); # endregion Workers # region Queue private Entry head; private Entry tail; private IntCounter entries = new IntCounter(); /// <summary> /// Adds the todo to the tail of the queue. /// </summary> /// <param name="todo">the todo to add.</param> /// <returns>the current queue length.</returns> /// [MethodImpl( MethodImplOptions.Synchronized )] private int AddEntry( Todo todo ) { Entry e = new Entry(); e.todo = todo; if ( tail != null ) tail.next = e; else head = e; // first instance tail = e; return entries.Adjust( 1 ); } /// <summary> /// Remove an entry from the queue. /// </summary> /// <returns>a todo from the head of the queue, or /// null if empty</returns> /// [MethodImpl( MethodImplOptions.Synchronized )] private Todo RemoveEntry() { if ( head == null ) return null; Entry e = head; head = e.next; if ( head == null ) tail = null; entries.Adjust( -1 ); return e.todo; } /// <summary> /// /// </summary> /// <returns>number of TODOs</returns> public int NumEntries() { return entries.Get(); } /// <summary> /// An entry in the todo queue /// </summary> public class Entry { /// <summary> /// The todo to be performed /// </summary> public Todo todo; /// <summary> /// The next todo in the queue /// </summary> public Entry next; } # endregion Queue # region BLAH [MethodImpl( MethodImplOptions.Synchronized )] private Todo GetNextTodo() { Todo todo = null; bool lingered = false; while ( IsStarted() && ( todo = RemoveEntry() ) == null ) { try { if ( lingered && workers.Get() > minWorkers ) { workers.Adjust( -1 ); return null; } Monitor.Wait( this, workerLinger ); // we lingered. we might have been woken because // we're stopping, or a todo might have been // queued. lingered = true; } catch ( ThreadInterruptedException ) { workers.Adjust( -1 ); return null; } } return todo; } # endregion BLAH # region Static Stuff /// <summary> /// /// </summary> /// <param name="todo"></param> /// Exception: /// throws Exception /// public static void AddTodo( Todo todo ) { try { GetTodoManager().Add(todo); } catch(Exception e) { todo.Exception(null,e); } } /// <summary> /// /// </summary> /// <returns>the configured TodoManager. If there isn't one, it makes /// one with one worker thread.</returns> /// Exception: /// if there is a problem creating the TodoManager public static TodoManager GetTodoManager() { if ( todomanager == null ) { lock ( lockObject ) { if ( todomanager == null ) { todomanager = new TodoManager( 50, 10, 0, 5, 5000, 0 ); todomanager.Start(); } } } return todomanager; } /// <summary> /// /// </summary> /// <param name="newTodoManager"></param> /// <returns>the old todo manager</returns> /// [MethodImpl( MethodImplOptions.Synchronized )] public static TodoManager SetTodoManager( TodoManager newTodoManager ) { TodoManager oldTodoManager = todomanager; todomanager = newTodoManager; return oldTodoManager; } /// <summary> /// Shuts down the currently configured static todo manager if any. /// </summary> /// Exception: /// throws Exception public static void ShutDown() { TodoManager oldTodoManager = SetTodoManager( null ); if ( oldTodoManager != null ) oldTodoManager.Stop(); } /// <summary> /// Shuts down the given todo manager if any. /// </summary> /// Exception: /// throws Exception public static void ShutDown(TodoManager toDoManager) { if ( toDoManager != null ) toDoManager.Stop(); } private static TodoManager todomanager; /// <summary> /// Since C# doesn't allow locking on an entire class, the substitute /// here is locking a static variable of the class. /// </summary> private static object lockObject = new Object() ; # endregion Static Stuff } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Instrumentation; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static readonly CSharpCommandLineParser Default = new CSharpCommandLineParser(); public static readonly CSharpCommandLineParser Interactive = new CSharpCommandLineParser(isInteractive: true); internal CSharpCommandLineParser(bool isInteractive = false) : base(CSharp.MessageProvider.Instance, isInteractive) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string additionalReferencePaths) { return Parse(args, baseDirectory, additionalReferencePaths); } public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string additionalReferencePaths = null) { using (Logger.LogBlock(FunctionId.CSharp_CommandLineParser_Parse)) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsInteractive ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool emitPdb = false; string pdbPath = null; bool noStdLib = false; string outputDirectory = baseDirectory; string outputFileName = null; string documentationPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; CultureInfo preferredUILang = null; string touchedFilesPath = null; var sqmSessionGuid = Guid.Empty; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsInteractive) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(!arg.StartsWith("@")); string name, value; if (!TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); sourceFilesSpecified = true; continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(value, out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); } catch (CultureNotFoundException) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsInteractive) { switch (name) { // interactive: case "rp": case "referencepath": // TODO: should it really go to libPaths? ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports inrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports inrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); } else if (!string.Equals(value, "full", StringComparison.OrdinalIgnoreCase) && !string.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; continue; case "debug-": if (value != null) break; emitPdb = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Default, ParseWarnings(value)); } continue; case "w": case "warn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveAllQuotes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behaviour as MSBuild can return quoted or // unquoted main. unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "filealign": ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "lib": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "appconfig": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveAllQuotes(arg)); } else { appConfigPath = ParseGenericPathToFile( unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsInteractive && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib) { metadataReferences.Insert(0, new CommandLineReference(typeof(object).Assembly.Location, MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferencePaths)) { ParseAndResolveReferencePaths(null, additionalReferencePaths, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } if (!emitPdb) { if (pdbPath != null) { // Can't give a PDB file name and turn off debug information AddDiagnostic(diagnostics, ErrorCode.ERR_MissingDebugSwitch); } } string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions ).WithFeatures(features.AsImmutable()); var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: DebugInformationFormat.Pdb, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsInteractive = IsInteractive, BaseDirectory = baseDirectory, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsInteractive ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, SqmSessionGuid = sqmSessionGuid }; } } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveAllQuotes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsInteractive && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsInteractive); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // SDK path is specified or current runtime directory builder.Add(RuntimeEnvironment.GetRuntimeDirectory()); // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); // Lock the entire content to prevent others from modifying it while we are reading. try { stream.Lock(0, long.MaxValue); return stream; } catch { stream.Dispose(); throw; } }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version) { if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "default": version = defaultVersion; return true; default: int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.Data; using System.Data.SqlClient; using System.Threading.Tasks; namespace SourceCode.Clay.Data.SqlClient { /// <summary> /// Represents extensions for <see cref="SqlConnection"/> instances. /// </summary> /// <seealso cref="SqlConnection"/> public static class SqlConnectionExtensions { /// <summary> /// Create a <see cref="SqlCommand"/> using the provided parameters. /// </summary> /// <param name="sqlCon">The <see cref="SqlConnection"/> to use.</param> /// <param name="commandText">The sql command text to use.</param> /// <param name="commandType">The type of command.</param> public static SqlCommand CreateCommand(this SqlConnection sqlCon, string commandText, CommandType commandType) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); if (string.IsNullOrWhiteSpace(commandText)) throw new ArgumentNullException(nameof(commandText)); #pragma warning disable CA2100 // Review SQL queries for security vulnerabilities var cmd = new SqlCommand(commandText, sqlCon) { CommandType = commandType }; #pragma warning restore CA2100 // Review SQL queries for security vulnerabilities return cmd; } /// <summary> /// Create a <see cref="SqlCommand"/> using the provided parameters. /// </summary> /// <param name="sqlCon">The <see cref="SqlConnection"/> to use.</param> /// <param name="commandText">The sql command text to use.</param> /// <param name="commandType">The type of command.</param> /// <param name="timeoutSeconds">The command timeout in seconds.</param> public static SqlCommand CreateCommand(this SqlConnection sqlCon, string commandText, CommandType commandType, int timeoutSeconds) { if (timeoutSeconds < 0) throw new ArgumentOutOfRangeException(nameof(timeoutSeconds)); // 0 means infinite timeout in SqlCommand SqlCommand cmd = CreateCommand(sqlCon, commandText, commandType); cmd.CommandTimeout = timeoutSeconds; return cmd; } /// <summary> /// Create a <see cref="SqlCommand"/> using the provided parameters. /// </summary> /// <param name="sqlCon">The <see cref="SqlConnection"/> to use.</param> /// <param name="commandText">The sql command text to use.</param> /// <param name="commandType">The type of command.</param> /// <param name="timeout">The command timeout.</param> public static SqlCommand CreateCommand(this SqlConnection sqlCon, string commandText, CommandType commandType, TimeSpan timeout) => CreateCommand(sqlCon, commandText, commandType, (int)timeout.TotalSeconds); /// <summary> /// Reopens the specified <see cref="SqlConnection"/>. /// </summary> /// <param name="sqlCon">The connection.</param> public static void Reopen(this SqlConnection sqlCon) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); switch (sqlCon.State) { case ConnectionState.Broken: sqlCon.Close(); goto case ConnectionState.Closed; case ConnectionState.Closed: sqlCon.Open(); return; } } /// <summary> /// Reopens the specified <see cref="SqlConnection"/>. /// </summary> /// <param name="sqlCon">The connection.</param> public static async Task ReopenAsync(this SqlConnection sqlCon) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); switch (sqlCon.State) { case ConnectionState.Broken: sqlCon.Close(); goto case ConnectionState.Closed; case ConnectionState.Closed: await sqlCon.OpenAsync().ConfigureAwait(false); return; } } /// <summary> /// Opens the specified <see cref="SqlConnection"/> using impersonation. /// </summary> /// <param name="sqlCon">The SqlConnection to use.</param> /// <param name="impersonatedUsername">The username to be impersonated.</param> /// <returns>Cookie value that will be required to close the connection</returns> public static byte[] OpenImpersonated(this SqlConnection sqlCon, string impersonatedUsername) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); // Open the underlying connection sqlCon.Reopen(); // If username is null, empty or whitespace-only then don't try impersonate if (string.IsNullOrEmpty(impersonatedUsername)) return null; // Set impersonation context using EXECUTE AS try { string user = impersonatedUsername; // We need to properly-quote the username in order to avoid injection attacks const string sql = "SELECT QUOTENAME(@username, N'''') AS [username];"; using (SqlCommand cmd = sqlCon.CreateCommand(sql, CommandType.Text)) { cmd.Parameters.AddWithValue("username", user); object o = cmd.ExecuteScalar(); // Check that the result is non-empty if (o is null) throw new ArgumentNullException(nameof(impersonatedUsername)); user = o.ToString(); if (string.IsNullOrEmpty(user)) throw new ArgumentNullException(nameof(impersonatedUsername)); } // If we successfully quoted the username, then execute the impersonation switch // Remember to use the cookie option so we can deterministically undo the impersonation // and put the connection back in the connection pool when we are done with it string sql1 = $@" DECLARE @cookie VARBINARY(100); EXECUTE AS LOGIN = {user} WITH COOKIE INTO @cookie; SELECT @cookie;"; using (SqlCommand cmd = sqlCon.CreateCommand(sql1, CommandType.Text)) { // Do not use ExecuteNonQuery(), it doesn't like the COOKIE option object oc = cmd.ExecuteScalar(); byte[] cookie = (byte[])oc; return cookie; } } catch { sqlCon.Close(); throw; } } /// <summary> /// Opens the specified <see cref="SqlConnection"/> using impersonation. /// </summary> /// <param name="sqlCon">The SqlConnection to use.</param> /// <param name="impersonatedUsername">The username to be impersonated.</param> /// <returns>Cookie value that will be required to close the connection</returns> public static async Task<byte[]> OpenImpersonatedAsync(this SqlConnection sqlCon, string impersonatedUsername) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); // Open the underlying connection await sqlCon.ReopenAsync().ConfigureAwait(false); // If username is null, empty or whitespace-only then don't try impersonate if (string.IsNullOrEmpty(impersonatedUsername)) return null; // Set impersonation context using EXECUTE AS try { string user = impersonatedUsername; // We need to properly-quote the username in order to avoid injection attacks const string sql = "SELECT QUOTENAME(@username, N'''') AS [username];"; using (SqlCommand cmd = sqlCon.CreateCommand(sql, CommandType.Text)) { cmd.Parameters.AddWithValue("username", user); object o = await cmd.ExecuteScalarAsync().ConfigureAwait(false); // Check that the result is non-empty if (o is null) throw new ArgumentNullException(nameof(impersonatedUsername)); user = o.ToString(); if (string.IsNullOrEmpty(user)) throw new ArgumentNullException(nameof(impersonatedUsername)); } // If we successfully quoted the username, then execute the impersonation switch // Remember to use the cookie option so we can deterministically undo the impersonation // and put the connection back in the connection pool when we are done with it string sql1 = $@" DECLARE @cookie VARBINARY(100); EXECUTE AS LOGIN = {user} WITH COOKIE INTO @cookie; SELECT @cookie;"; using (SqlCommand cmd = sqlCon.CreateCommand(sql1, CommandType.Text)) { // Do not use ExecuteNonQuery(), it doesn't like the COOKIE option object oc = await cmd.ExecuteScalarAsync().ConfigureAwait(false); byte[] cookie = (byte[])oc; return cookie; } } catch { sqlCon.Close(); throw; } } /// <summary> /// Close the specified <see cref="SqlConnection"/> and revert any impersonation. /// </summary> /// <param name="sqlCon">The SqlConnection to use.</param> /// <param name="cookie">The impersonation cookie returned from the Open() method</param> public static void CloseImpersonated(this SqlConnection sqlCon, byte[] cookie) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); // Check that the underlying connection is still open if (sqlCon.State == ConnectionState.Open) { try { // Only revert the cookie if it is provided if (!(cookie is null) && cookie.Length > 0) // @COOKIE is VARBINARY(100) { const string sql = "REVERT WITH COOKIE = @cookie;"; using (SqlCommand cmd = sqlCon.CreateCommand(sql, CommandType.Text)) { SqlParameter p = cmd.Parameters.Add("cookie", SqlDbType.VarBinary, 100); p.Value = cookie; cmd.ExecuteNonQuery(); } } } finally { sqlCon.Close(); } } } /// <summary> /// Close the specified <see cref="SqlConnection"/> and revert any impersonation. /// </summary> /// <param name="sqlCon">The SqlConnection to use.</param> /// <param name="cookie">The impersonation cookie returned from the Open() method</param> public static async Task CloseImpersonatedAsync(this SqlConnection sqlCon, byte[] cookie) { if (sqlCon is null) throw new ArgumentNullException(nameof(sqlCon)); // Check that the underlying connection is still open if (sqlCon.State == ConnectionState.Open) { try { // Only revert the cookie if it is provided if (!(cookie is null) && cookie.Length > 0) { const string sql = "REVERT WITH COOKIE = @cookie;"; using (SqlCommand cmd = sqlCon.CreateCommand(sql, CommandType.Text)) { SqlParameter p = cmd.Parameters.Add("cookie", SqlDbType.VarBinary, 100); // @COOKIE is VARBINARY(100) p.Value = cookie; await cmd.ExecuteNonQueryAsync().ConfigureAwait(false); } } } finally { sqlCon.Close(); } } } /// <summary> /// Returns true if the specified DataSource is on AzureDb, else returns false. /// </summary> /// <param name="sqlCon">The sql connection.</param> public static bool IsAzureSql(this SqlConnection sqlCon) => sqlCon == null ? false : SqlConnectionStringBuilderExtensions.IsAzureSql(sqlCon.DataSource); } }
/// <summary> /// Dvornik /// </summary> using UnityEngine; using UnityEditor; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Collections.Generic; /// <summary> /// Split terrain. /// </summary> public class SplitTerrain : EditorWindow { string num = "4"; List<TerrainData> terrainData = new List<TerrainData>(); List<GameObject> terrainGo = new List<GameObject>(); Terrain parentTerrain; const int terrainsCount = 4; // Add submenu [MenuItem("Dvornik/Terrain/Split Terrain")] static void Init() { // Get existing open window or if none, make a new one: SplitTerrain window = (SplitTerrain)EditorWindow.GetWindow(typeof(SplitTerrain)); window.minSize = new Vector2( 100f,100f ); window.maxSize = new Vector2( 200f,200f ); window.autoRepaintOnSceneChange = true; window.title = "Resize terrain"; window.Show(); } /// <summary> /// Determines whether this instance is power of two the specified x. /// </summary> /// <returns> /// <c>true</c> if this instance is power of two the specified x; otherwise, <c>false</c>. /// </returns> /// <param name='x'> /// If set to <c>true</c> x. /// </param> bool IsPowerOfTwo(int x) { return (x & (x - 1)) == 0; } void SplitIt() { if ( Selection.activeGameObject == null ) { Debug.LogWarning("No terrain was selected"); return; } parentTerrain = Selection.activeGameObject.GetComponent(typeof(Terrain)) as Terrain; if ( parentTerrain == null ) { Debug.LogWarning("Current selection is not a terrain"); return; } //Split terrain for ( int i=0; i< terrainsCount; i++) { EditorUtility.DisplayProgressBar("Split terrain","Process " + i, (float) i / terrainsCount ); TerrainData td = new TerrainData(); GameObject tgo = Terrain.CreateTerrainGameObject( td ); tgo.name = parentTerrain.name + " " + i; terrainData.Add( td ); terrainGo.Add ( tgo ); Terrain genTer = tgo.GetComponent(typeof(Terrain)) as Terrain; genTer.terrainData = td; AssetDatabase.CreateAsset(td, "Assets/" + genTer.name+ ".asset"); // Assign splatmaps genTer.terrainData.splatPrototypes = parentTerrain.terrainData.splatPrototypes; // Assign detail prototypes genTer.terrainData.detailPrototypes = parentTerrain.terrainData.detailPrototypes; // Assign tree information genTer.terrainData.treePrototypes = parentTerrain.terrainData.treePrototypes; // Copy parent terrain propeties #region parent properties genTer.basemapDistance = parentTerrain.basemapDistance; genTer.castShadows = parentTerrain.castShadows; genTer.detailObjectDensity = parentTerrain.detailObjectDensity; genTer.detailObjectDistance = parentTerrain.detailObjectDistance; genTer.heightmapMaximumLOD = parentTerrain.heightmapMaximumLOD; genTer.heightmapPixelError = parentTerrain.heightmapPixelError; genTer.treeBillboardDistance = parentTerrain.treeBillboardDistance; genTer.treeCrossFadeLength = parentTerrain.treeCrossFadeLength; genTer.treeDistance = parentTerrain.treeDistance; genTer.treeMaximumFullLODCount = parentTerrain.treeMaximumFullLODCount; #endregion //Start processing it // Translate peace to position #region translate peace to right position Vector3 parentPosition = parentTerrain.GetPosition(); int terraPeaces = (int) Mathf.Sqrt( terrainsCount ); float spaceShiftX = parentTerrain.terrainData.size.z / terraPeaces; float spaceShiftY = parentTerrain.terrainData.size.x / terraPeaces; float xWShift = (i % terraPeaces ) * spaceShiftX; float zWShift = ( i / terraPeaces ) * spaceShiftY; tgo.transform.position = new Vector3( tgo.transform.position.x + zWShift, tgo.transform.position.y, tgo.transform.position.z + xWShift ); // Shift last position tgo.transform.position = new Vector3( tgo.transform.position.x + parentPosition.x, tgo.transform.position.y + parentPosition.y, tgo.transform.position.z + parentPosition.z ); #endregion // Split height #region split height Debug.Log ( "Split height" ); //Copy heightmap td.heightmapResolution = parentTerrain.terrainData.heightmapResolution / terraPeaces; //Keep y same td.size = new Vector3( parentTerrain.terrainData.size.x / terraPeaces, parentTerrain.terrainData.size.y, parentTerrain.terrainData.size.z / terraPeaces ); float[,] parentHeight = parentTerrain.terrainData.GetHeights(0,0, parentTerrain.terrainData.heightmapResolution, parentTerrain.terrainData.heightmapResolution ); float[,] peaceHeight = new float[ parentTerrain.terrainData.heightmapResolution / terraPeaces + 1, parentTerrain.terrainData.heightmapResolution / terraPeaces + 1 ]; // Shift calc int heightShift = parentTerrain.terrainData.heightmapResolution / terraPeaces; int startX = 0; int startY = 0; int endX = 0; int endY = 0; if ( i==0 ) { startX = startY = 0; endX = endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } if ( i==1 ) { startX = startY = 0; endX = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } if ( i==2 ) { startX = startY = 0; endX = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } if ( i==3 ) { startX = startY = 0; endX = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; endY = parentTerrain.terrainData.heightmapResolution / terraPeaces + 1; } // iterate for ( int x=startX;x< endX;x++) { EditorUtility.DisplayProgressBar("Split terrain","Split height", (float) x / ( endX - startX )); for ( int y=startY;y< endY;y++) { int xShift=0; int yShift=0; // if ( i==0 ) { xShift = 0; yShift = 0; } // if ( i==1 ) { xShift = heightShift; yShift = 0; } // if ( i==2 ) { xShift = 0; yShift = heightShift; } if ( i==3 ) { xShift = heightShift; yShift = heightShift; } float ph = parentHeight[ x + xShift,y + yShift]; peaceHeight[x ,y ] = ph; } } EditorUtility.ClearProgressBar(); // Set heightmap to child genTer.terrainData.SetHeights( 0,0, peaceHeight ); #endregion // Split splat map #region split splat map td.alphamapResolution = parentTerrain.terrainData.alphamapResolution / terraPeaces; float[,,] parentSplat = parentTerrain.terrainData.GetAlphamaps(0,0, parentTerrain.terrainData.alphamapResolution, parentTerrain.terrainData.alphamapResolution ); float[,,] peaceSplat = new float[ parentTerrain.terrainData.alphamapResolution / terraPeaces , parentTerrain.terrainData.alphamapResolution / terraPeaces, parentTerrain.terrainData.alphamapLayers ]; // Shift calc int splatShift = parentTerrain.terrainData.alphamapResolution / terraPeaces; if ( i==0 ) { startX = startY = 0; endX = endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } if ( i==1 ) { startX = startY = 0; endX = parentTerrain.terrainData.alphamapResolution / terraPeaces; endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } if ( i==2 ) { startX = startY = 0; endX = parentTerrain.terrainData.alphamapResolution / terraPeaces; endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } if ( i==3 ) { startX = startY = 0; endX = parentTerrain.terrainData.alphamapResolution / terraPeaces; endY = parentTerrain.terrainData.alphamapResolution / terraPeaces; } // iterate for ( int s=0;s<parentTerrain.terrainData.alphamapLayers;s++) { for ( int x=startX;x< endX;x++) { EditorUtility.DisplayProgressBar("Split terrain","Split splat", (float) x / ( endX - startX )); for ( int y=startY;y< endY;y++) { int xShift=0; int yShift=0; // if ( i==0 ) { xShift = 0; yShift = 0; } // if ( i==1 ) { xShift = splatShift; yShift = 0; } // if ( i==2 ) { xShift = 0; yShift = splatShift; } if ( i==3 ) { xShift = splatShift; yShift = splatShift; } float ph = parentSplat[x + xShift,y + yShift, s]; peaceSplat[x ,y, s] = ph; } } } EditorUtility.ClearProgressBar(); // Set heightmap to child genTer.terrainData.SetAlphamaps( 0,0, peaceSplat ); #endregion // Split detail map #region split detail map td.SetDetailResolution( parentTerrain.terrainData.detailResolution / terraPeaces, 8 ); for ( int detLay=0; detLay< parentTerrain.terrainData.detailPrototypes.Length; detLay++) { int[,] parentDetail = parentTerrain.terrainData.GetDetailLayer(0,0, parentTerrain.terrainData.detailResolution, parentTerrain.terrainData.detailResolution, detLay ); int[,] peaceDetail = new int[ parentTerrain.terrainData.detailResolution / terraPeaces, parentTerrain.terrainData.detailResolution / terraPeaces ]; // Shift calc int detailShift = parentTerrain.terrainData.detailResolution / terraPeaces; if ( i==0 ) { startX = startY = 0; endX = endY = parentTerrain.terrainData.detailResolution / terraPeaces; } if ( i==1 ) { startX = startY = 0; endX = parentTerrain.terrainData.detailResolution / terraPeaces; endY = parentTerrain.terrainData.detailResolution / terraPeaces; } if ( i==2 ) { startX = startY = 0; endX = parentTerrain.terrainData.detailResolution / terraPeaces; endY = parentTerrain.terrainData.detailResolution / terraPeaces; } if ( i==3 ) { startX = startY = 0; endX = parentTerrain.terrainData.detailResolution / terraPeaces; endY = parentTerrain.terrainData.detailResolution / terraPeaces; } // iterate for ( int x=startX;x< endX;x++) { EditorUtility.DisplayProgressBar("Split terrain","Split detail", (float) x / (endX - startX )); for ( int y=startY;y< endY;y++) { int xShift=0; int yShift=0; // if ( i==0 ) { xShift = 0; yShift = 0; } // if ( i==1 ) { xShift = detailShift; yShift = 0; } // if ( i==2 ) { xShift = 0; yShift = detailShift; } if ( i==3 ) { xShift = detailShift; yShift = detailShift; } int ph = parentDetail[x + xShift,y + yShift]; peaceDetail[x ,y] = ph; } } EditorUtility.ClearProgressBar(); // Set heightmap to child genTer.terrainData.SetDetailLayer( 0,0, detLay, peaceDetail ); } #endregion // Split tree data #region split tree data for( int t=0; t< parentTerrain.terrainData.treeInstances.Length;t++) { EditorUtility.DisplayProgressBar("Split terrain","Split trees " , (float) t / parentTerrain.terrainData.treeInstances.Length ); // Get tree instance TreeInstance ti = parentTerrain.terrainData.treeInstances[t]; // First section if ( i==0 && ti.position.x > 0f && ti.position.x < 0.5f && ti.position.z > 0f && ti.position.z < 0.5f ) { // Recalculate new tree position ti.position = new Vector3( ti.position.x * 2f, ti.position.y, ti.position.z * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } // Second section if ( i==1 && ti.position.x > 0.0f &&ti.position.x < 0.5f && ti.position.z >= 0.5f && ti.position.z <= 1.0f ) { // Recalculate new tree position ti.position = new Vector3( (ti.position.x ) * 2f, ti.position.y, ( ti.position.z - 0.5f ) * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } // Third section if ( i==2 && ti.position.x >= 0.5f && ti.position.x <= 1.0f && ti.position.z > 0.0f && ti.position.z < 0.5f ) { // Recalculate new tree position ti.position = new Vector3( (ti.position.x - 0.5f ) * 2f, ti.position.y, ( ti.position.z ) * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } // Fourth section if ( i==3 && ti.position.x >= 0.5f && ti.position.x <= 1.0f && ti.position.z >= 0.5f && ti.position.z <= 1.0f ) { // Recalculate new tree position ti.position = new Vector3( (ti.position.x - 0.5f ) * 2f, ti.position.y, ( ti.position.z - 0.5f ) * 2f ); // Add tree instance genTer.AddTreeInstance( ti ); } } #endregion AssetDatabase.SaveAssets(); } EditorUtility.ClearProgressBar(); } void OnGUI() { if(GUILayout.Button("Split terrain")) { SplitIt(); } } }
// 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.Threading; // This tests CompareExchange<object>. // It just casts a bunch of different types to object, // then makes sure CompareExchange<object> works on those objects. public class InterlockedCompareExchange7 { private const int c_NUM_LOOPS = 100; private const int c_MIN_STRING_LEN = 5; private const int c_MAX_STRING_LEN = 128; public static int Main() { InterlockedCompareExchange7 test = new InterlockedCompareExchange7(); TestLibrary.TestFramework.BeginTestCase("InterlockedCompareExchange7"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; return retVal; } // This particular test is for when the comparands are equal and the // switch should take place. public bool PosTest1() { bool retVal = true; object location; TestLibrary.TestFramework.BeginScenario("PosTest1: object Interlocked.CompareExchange<object>(object&,object, object) where comparand is equal"); try { TestLibrary.TestFramework.BeginScenario("PosTest1: object == Byte"); location = (object)TestLibrary.Generator.GetByte(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetByte(-55) ) && retVal; // Note that (&&) performs a logical-AND of // its bool operands, but only evaluates its second // operand if necessary. When ExchangeObjects is first // called (above), retVal (RHS) // is true, as it was initialized above. If ExchangeObjects // returns true, then it checks retVal (RHS), it is also true, // so retVal (LHS) gets set to true. This stays this // way so long as ExchangeObjects returns true in this and // subsequent calls. // If some time ExchangeObjects returns false (0), this // expression does not check retVal (RHS), and instead // retVal (LHS) becomes false. Next call to ExchangeObjects, // retVal (RHS) is false even if ExchangeObjects returns true, so // retVal (both RHS and LHS) remains false for all // subsequent calls to ExchangeObjects. As such, if any one of // the many calls to ExchangeObjects fails, retVal returns false TestLibrary.TestFramework.BeginScenario("PosTest1: object == Byte[]"); byte[] bArr1 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)]; byte[] bArr2 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)]; TestLibrary.Generator.GetBytes(-55, bArr1); TestLibrary.Generator.GetBytes(-55, bArr2); location = (object)bArr1; retVal = ExchangeObjects( true, location, location, (object)bArr2 ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int16"); location = (object)TestLibrary.Generator.GetInt16(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetInt16(-55) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int32"); location = (object)TestLibrary.Generator.GetInt32(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetInt32(-55) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Int64"); location = (object)(object)TestLibrary.Generator.GetInt64(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetInt64(-55) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Single"); location = (object)(object)TestLibrary.Generator.GetSingle(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetSingle(-55) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == Double"); location = (object)(object)TestLibrary.Generator.GetDouble(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetDouble(-55) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == string"); location = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == char"); location = TestLibrary.Generator.GetChar(-55); retVal = ExchangeObjects( true, location, location, (object)TestLibrary.Generator.GetChar(-55) ) && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } // This particular test is for when the comparands are not equal and the // switch should not take place. public bool PosTest2() { bool retVal = true; object location; object other; TestLibrary.TestFramework.BeginScenario("PosTest2: object Interlocked.CompareExchange<object>(object&,object, object) where comparand are not equal"); try { TestLibrary.TestFramework.BeginScenario("PosTest2: object == Byte"); location = (object)TestLibrary.Generator.GetByte(-55); other = (object)TestLibrary.Generator.GetByte(-55); retVal = ExchangeObjects( false, location, (object)((byte)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Byte[]"); byte[] bArr1 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)]; byte[] bArr2 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)]; byte[] bArr3 = new Byte[5 + (TestLibrary.Generator.GetInt32(-55) % 1024)]; TestLibrary.Generator.GetBytes(-55, bArr1); TestLibrary.Generator.GetBytes(-55, bArr2); TestLibrary.Generator.GetBytes(-55, bArr3); location = (object)bArr1; retVal = ExchangeObjects( false, location, (object)bArr2, (object)bArr3 ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Int16"); location = (object)TestLibrary.Generator.GetInt16(-55); other = (object)TestLibrary.Generator.GetInt16(-55); retVal = ExchangeObjects( false, location, (object)((Int16)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Int32"); location = (object)TestLibrary.Generator.GetInt32(-55); other = (object)TestLibrary.Generator.GetInt32(-55); retVal = ExchangeObjects( false, location, (object)((Int32)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Int64"); location = (object)(object)TestLibrary.Generator.GetInt64(-55); other = (object)TestLibrary.Generator.GetInt64(-55); retVal = ExchangeObjects( false, location, (object)((Int64)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Single"); location = (object)(object)TestLibrary.Generator.GetSingle(-55); other = (object)TestLibrary.Generator.GetSingle(-55); retVal = ExchangeObjects( false, location, (object)((Single)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest2: object == Double"); location = (object)(object)TestLibrary.Generator.GetDouble(-55); other = (object)TestLibrary.Generator.GetDouble(-55); retVal = ExchangeObjects( false, location, (object)((Double)location+1), other ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == string"); location = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); retVal = ExchangeObjects( false, location, (string)location+TestLibrary.Generator.GetChar(-55), (object)TestLibrary.Generator.GetDouble(-55) ) && retVal; TestLibrary.TestFramework.BeginScenario("PosTest1: object == char"); location = TestLibrary.Generator.GetChar(-55); object comparand; do { comparand = TestLibrary.Generator.GetChar(-55); } while(comparand == location); retVal = ExchangeObjects( false, location, comparand, (object)TestLibrary.Generator.GetChar(-55) ) && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool ExchangeObjects(bool exchange, object location, object comparand, object value) { bool retVal = true; object oldLocation; object originalLocation = location; if (!exchange && comparand == location) { TestLibrary.TestFramework.LogError("003", "Comparand and location are equal unexpectedly!!!!"); retVal = false; } if (exchange && comparand != location) { TestLibrary.TestFramework.LogError("004", "Comparand and location are not equal unexpectadly!!!!"); retVal = false; } // this is the only significant difference between this test // and InterlockedCompareExchange7.cs - here we use the // generic overload, passing it T=object. oldLocation = Interlocked.CompareExchange<object>(ref location, value, comparand); // if exchange=true, then the exchange was supposed to take place. // as a result, assuming value did not equal comparand initially, // and location did equal comparand initially, then we should // expect the following: // oldLoc holds locations old value,oldLocation == comparand, because oldLocation equals what // location equaled before the exchange, and that // equaled comparand // location == value, because the exchange took place if (exchange) { if (!Object.ReferenceEquals(value,location)) { TestLibrary.TestFramework.LogError("005", "Interlocked.CompareExchange() did not do the exchange correctly: Expected location(" + location + ") to equal value(" + value + ")"); retVal = false; } if (!Object.ReferenceEquals(oldLocation,originalLocation)) { TestLibrary.TestFramework.LogError("006", "Interlocked.CompareExchange() did not return the expected value: Expected oldLocation(" + oldLocation + ") to equal originalLocation(" + originalLocation + ")"); retVal = false; } } // if exchange!=true, then the exchange was supposed to NOT take place. // expect the following: // location == originalLocation, because the exchange did not happen // oldLocation == originalLocation, because the exchange did not happen else { if (!Object.ReferenceEquals(location,originalLocation)) { TestLibrary.TestFramework.LogError("007", "Interlocked.CompareExchange() should not change the location: Expected location(" + location + ") to equal originalLocation(" + originalLocation + ")"); retVal = false; } if (!Object.ReferenceEquals(oldLocation,originalLocation)) { TestLibrary.TestFramework.LogError("008", "Interlocked.CompareExchange() did not return the expected value: Expected oldLocation(" + oldLocation + ") to equal originalLocation(" + originalLocation + ")"); retVal = false; } } return retVal; } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email [email protected] | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.IO; namespace Reporting.RdlDesign { /// <summary> /// Summary description for StyleCtl. /// </summary> internal class VisibilityCtl : System.Windows.Forms.UserControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; // flags for controlling whether syntax changed for a particular property private bool fHidden, fToggle; private System.Windows.Forms.GroupBox grpBoxVisibility; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox tbHidden; private System.Windows.Forms.ComboBox cbToggle; private System.Windows.Forms.Button bHidden; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal VisibilityCtl(DesignXmlDraw dxDraw, List<XmlNode> reportItems) { _ReportItems = reportItems; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(_ReportItems[0]); } private void InitValues(XmlNode node) { // Handle Visiblity definition XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility"); if (visNode != null) { XmlNode hNode = _Draw.GetNamedChildNode(node, "Visibility"); this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", ""); this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", ""); } IEnumerable list = _Draw.GetReportItems("//Textbox"); if (list != null) { foreach (XmlNode tNode in list) { XmlAttribute name = tNode.Attributes["Name"]; if (name != null && name.Value != null && name.Value.Length > 0) cbToggle.Items.Add(name.Value); } } // nothing has changed now fHidden = fToggle = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.grpBoxVisibility = new System.Windows.Forms.GroupBox(); this.bHidden = new System.Windows.Forms.Button(); this.cbToggle = new System.Windows.Forms.ComboBox(); this.tbHidden = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.grpBoxVisibility.SuspendLayout(); this.SuspendLayout(); // // grpBoxVisibility // this.grpBoxVisibility.Controls.Add(this.bHidden); this.grpBoxVisibility.Controls.Add(this.cbToggle); this.grpBoxVisibility.Controls.Add(this.tbHidden); this.grpBoxVisibility.Controls.Add(this.label3); this.grpBoxVisibility.Controls.Add(this.label2); this.grpBoxVisibility.Location = new System.Drawing.Point(3, 3); this.grpBoxVisibility.Name = "grpBoxVisibility"; this.grpBoxVisibility.Size = new System.Drawing.Size(432, 80); this.grpBoxVisibility.TabIndex = 1; this.grpBoxVisibility.TabStop = false; this.grpBoxVisibility.Text = "Visibility"; // // bHidden // this.bHidden.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bHidden.Location = new System.Drawing.Point(400, 24); this.bHidden.Name = "bHidden"; this.bHidden.Size = new System.Drawing.Size(24, 21); this.bHidden.TabIndex = 1; this.bHidden.Tag = "visibility"; this.bHidden.Text = "fx"; this.bHidden.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bHidden.Click += new System.EventHandler(this.bExpr_Click); // // cbToggle // this.cbToggle.Location = new System.Drawing.Point(168, 48); this.cbToggle.Name = "cbToggle"; this.cbToggle.Size = new System.Drawing.Size(224, 21); this.cbToggle.TabIndex = 2; this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged); this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged); // // tbHidden // this.tbHidden.Location = new System.Drawing.Point(168, 24); this.tbHidden.Name = "tbHidden"; this.tbHidden.Size = new System.Drawing.Size(224, 20); this.tbHidden.TabIndex = 0; this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged); // // label3 // this.label3.Location = new System.Drawing.Point(16, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(152, 23); this.label3.TabIndex = 1; this.label3.Text = "Toggle Item (Textbox name)"; // // label2 // this.label2.Location = new System.Drawing.Point(16, 24); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(120, 23); this.label2.TabIndex = 0; this.label2.Text = "Hidden (initial visibility)"; // // VisibilityCtl // this.Controls.Add(this.grpBoxVisibility); this.Name = "VisibilityCtl"; this.Size = new System.Drawing.Size(454, 104); this.grpBoxVisibility.ResumeLayout(false); this.grpBoxVisibility.PerformLayout(); this.ResumeLayout(false); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); // nothing has changed now fHidden = fToggle = false; } private void ApplyChanges(XmlNode rNode) { if (fHidden || fToggle) { XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null); if (fHidden) { if (tbHidden.Text.Length == 0) _Draw.RemoveElement(visNode, "Hidden"); else _Draw.SetElement(visNode, "Hidden", tbHidden.Text); } if (fToggle) _Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text); } } private void tbHidden_TextChanged(object sender, System.EventArgs e) { fHidden = true; } private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e) { fToggle = true; } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; switch (b.Tag as string) { case "visibility": c = tbHidden; break; } if (c == null) return; XmlNode sNode = _ReportItems[0]; using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, sNode)) { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; return; } } } }
using System; using System.Collections.Generic; using NUnit.Framework; using Python.Runtime; namespace Python.EmbeddingTest { public class Inheritance { [OneTimeSetUp] public void SetUp() { PythonEngine.Initialize(); using var locals = new PyDict(); PythonEngine.Exec(InheritanceTestBaseClassWrapper.ClassSourceCode, locals: locals); ExtraBaseTypeProvider.ExtraBase = new PyType(locals[InheritanceTestBaseClassWrapper.ClassName]); var baseTypeProviders = PythonEngine.InteropConfiguration.PythonBaseTypeProviders; baseTypeProviders.Add(new ExtraBaseTypeProvider()); baseTypeProviders.Add(new NoEffectBaseTypeProvider()); } [OneTimeTearDown] public void Dispose() { ExtraBaseTypeProvider.ExtraBase.Dispose(); PythonEngine.Shutdown(); } [Test] public void ExtraBase_PassesInstanceCheck() { var inherited = new Inherited(); bool properlyInherited = PyIsInstance(inherited, ExtraBaseTypeProvider.ExtraBase); Assert.IsTrue(properlyInherited); } static dynamic PyIsInstance => PythonEngine.Eval("isinstance"); [Test] public void InheritingWithExtraBase_CreatesNewClass() { PyObject a = ExtraBaseTypeProvider.ExtraBase; var inherited = new Inherited(); PyObject inheritedClass = inherited.ToPython().GetAttr("__class__"); Assert.IsFalse(PythonReferenceComparer.Instance.Equals(a, inheritedClass)); } [Test] public void InheritedFromInheritedClassIsSelf() { using var scope = Py.CreateScope(); scope.Exec($"from {typeof(Inherited).Namespace} import {nameof(Inherited)}"); scope.Exec($"class B({nameof(Inherited)}): pass"); PyObject b = scope.Eval("B"); PyObject bInstance = b.Invoke(); PyObject bInstanceClass = bInstance.GetAttr("__class__"); Assert.IsTrue(PythonReferenceComparer.Instance.Equals(b, bInstanceClass)); } // https://github.com/pythonnet/pythonnet/issues/1420 [Test] public void CallBaseMethodFromContainerInNestedClass() { using var nested = new ContainerClass.InnerClass().ToPython(); nested.InvokeMethod(nameof(ContainerClass.BaseMethod)); } [Test] public void Grandchild_PassesExtraBaseInstanceCheck() { using var scope = Py.CreateScope(); scope.Exec($"from {typeof(Inherited).Namespace} import {nameof(Inherited)}"); scope.Exec($"class B({nameof(Inherited)}): pass"); PyObject b = scope.Eval("B"); PyObject bInst = b.Invoke(); bool properlyInherited = PyIsInstance(bInst, ExtraBaseTypeProvider.ExtraBase); Assert.IsTrue(properlyInherited); } [Test] public void CallInheritedClrMethod_WithExtraPythonBase() { var instance = new Inherited().ToPython(); string result = instance.InvokeMethod(nameof(PythonWrapperBase.WrapperBaseMethod)).As<string>(); Assert.AreEqual(result, nameof(PythonWrapperBase.WrapperBaseMethod)); } [Test] public void CallExtraBaseMethod() { var instance = new Inherited(); using var scope = Py.CreateScope(); scope.Set(nameof(instance), instance); int actual = instance.ToPython().InvokeMethod("callVirt").As<int>(); Assert.AreEqual(expected: Inherited.OverridenVirtValue, actual); } [Test] public void SetAdHocAttributes_WhenExtraBasePresent() { var instance = new Inherited(); using var scope = Py.CreateScope(); scope.Set(nameof(instance), instance); scope.Exec($"super({nameof(instance)}.__class__, {nameof(instance)}).set_x_to_42()"); int actual = scope.Eval<int>($"{nameof(instance)}.{nameof(Inherited.XProp)}"); Assert.AreEqual(expected: Inherited.X, actual); } // https://github.com/pythonnet/pythonnet/issues/1476 [Test] public void BaseClearIsCalled() { using var scope = Py.CreateScope(); scope.Set("exn", new Exception("42")); var msg = scope.Eval("exn.args[0]"); Assert.AreEqual(2, msg.Refcount); scope.Set("exn", null); Assert.AreEqual(1, msg.Refcount); } // https://github.com/pythonnet/pythonnet/issues/1455 [Test] public void PropertyAccessorOverridden() { using var derived = new PropertyAccessorDerived().ToPython(); derived.SetAttr(nameof(PropertyAccessorDerived.VirtualProp), "hi".ToPython()); Assert.AreEqual("HI", derived.GetAttr(nameof(PropertyAccessorDerived.VirtualProp)).As<string>()); } } class ExtraBaseTypeProvider : IPythonBaseTypeProvider { internal static PyType ExtraBase; public IEnumerable<PyType> GetBaseTypes(Type type, IList<PyType> existingBases) { if (type == typeof(InheritanceTestBaseClassWrapper)) { return new[] { PyType.Get(type.BaseType), ExtraBase }; } return existingBases; } } class NoEffectBaseTypeProvider : IPythonBaseTypeProvider { public IEnumerable<PyType> GetBaseTypes(Type type, IList<PyType> existingBases) => existingBases; } public class PythonWrapperBase { public string WrapperBaseMethod() => nameof(WrapperBaseMethod); } public class InheritanceTestBaseClassWrapper : PythonWrapperBase { public const string ClassName = "InheritanceTestBaseClass"; public const string ClassSourceCode = "class " + ClassName + @": def virt(self): return 42 def set_x_to_42(self): self.XProp = 42 def callVirt(self): return self.virt() def __getattr__(self, name): return '__getattr__:' + name def __setattr__(self, name, value): value[name] = name " + ClassName + " = " + ClassName + "\n"; } public class Inherited : InheritanceTestBaseClassWrapper { public const int OverridenVirtValue = -42; public const int X = 42; readonly Dictionary<string, object> extras = new Dictionary<string, object>(); public int virt() => OverridenVirtValue; public int XProp { get { using (var scope = Py.CreateScope()) { scope.Set("this", this); try { return scope.Eval<int>($"super(this.__class__, this).{nameof(XProp)}"); } catch (PythonException ex) when (PythonReferenceComparer.Instance.Equals(ex.Type, Exceptions.AttributeError)) { if (this.extras.TryGetValue(nameof(this.XProp), out object value)) return (int)value; throw; } } } set => this.extras[nameof(this.XProp)] = value; } } public class PropertyAccessorBase { public virtual string VirtualProp { get; set; } } public class PropertyAccessorIntermediate: PropertyAccessorBase { } public class PropertyAccessorDerived: PropertyAccessorIntermediate { public override string VirtualProp { set => base.VirtualProp = value.ToUpperInvariant(); } } public class ContainerClass { public void BaseMethod() { } public class InnerClass: ContainerClass { } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using OpenMetaverse; using OpenSim.Region.Framework.Scenes; namespace OpenSim.ApplicationPlugins.Rest.Inventory.Tests { public class Remote : ITest { private static readonly int PARM_TESTID = 0; private static readonly int PARM_COMMAND = 1; private static readonly int PARM_MOVE_AVATAR = 2; private static readonly int PARM_MOVE_X = 3; private static readonly int PARM_MOVE_Y = 4; private static readonly int PARM_MOVE_Z = 5; private bool enabled = false; // No constructor code is required. public Remote() { Rest.Log.InfoFormat("{0} Remote services constructor", MsgId); } // Post-construction, pre-enabled initialization opportunity // Not currently exploited. public void Initialize() { enabled = true; Rest.Log.InfoFormat("{0} Remote services initialized", MsgId); } // Called by the plug-in to halt REST processing. Local processing is // disabled, and control blocks until all current processing has // completed. No new processing will be started public void Close() { enabled = false; Rest.Log.InfoFormat("{0} Remote services closing down", MsgId); } // Properties internal string MsgId { get { return Rest.MsgId; } } // Remote Handler // Key information of interest here is the Parameters array, each // entry represents an element of the URI, with element zero being // the public void Execute(RequestData rdata) { if (!enabled) return; // If we can't relate to what's there, leave it for others. if (rdata.Parameters.Length == 0 || rdata.Parameters[PARM_TESTID] != "remote") return; Rest.Log.DebugFormat("{0} REST Remote handler ENTRY", MsgId); // Remove the prefix and what's left are the parameters. If we don't have // the parameters we need, fail the request. Parameters do NOT include // any supplied query values. if (rdata.Parameters.Length > 1) { switch (rdata.Parameters[PARM_COMMAND].ToLower()) { case "move" : DoMove(rdata); break; default : DoHelp(rdata); break; } } else { DoHelp(rdata); } } private void DoHelp(RequestData rdata) { rdata.body = Help; rdata.Complete(); rdata.Respond("Help"); } private void DoMove(RequestData rdata) { if (rdata.Parameters.Length < 6) { Rest.Log.WarnFormat("{0} Move: No movement information provided", MsgId); rdata.Fail(Rest.HttpStatusCodeBadRequest, "no movement information provided"); } else { string[] names = rdata.Parameters[PARM_MOVE_AVATAR].Split(Rest.CA_SPACE); ScenePresence presence = null; Scene scene = null; if (names.Length != 2) { rdata.Fail(Rest.HttpStatusCodeBadRequest, String.Format("invalid avatar name: <{0}>",rdata.Parameters[PARM_MOVE_AVATAR])); } Rest.Log.WarnFormat("{0} '{1}' command received for {2} {3}", MsgId, rdata.Parameters[0], names[0], names[1]); // The first parameter should be an avatar name, look for the // avatar in the known regions first. Rest.main.SceneManager.ForEachScene(delegate(Scene s) { s.ForEachScenePresence(delegate(ScenePresence sp) { if (sp.Firstname == names[0] && sp.Lastname == names[1]) { scene = s; presence = sp; } }); }); if (presence != null) { Rest.Log.DebugFormat("{0} Move : Avatar {1} located in region {2}", MsgId, rdata.Parameters[PARM_MOVE_AVATAR], scene.RegionInfo.RegionName); try { float x = Convert.ToSingle(rdata.Parameters[PARM_MOVE_X]); float y = Convert.ToSingle(rdata.Parameters[PARM_MOVE_Y]); float z = Convert.ToSingle(rdata.Parameters[PARM_MOVE_Z]); Vector3 vector = new Vector3(x,y,z); presence.DoAutoPilot(0,vector,presence.ControllingClient); } catch (Exception e) { rdata.Fail(Rest.HttpStatusCodeBadRequest, String.Format("invalid parameters: {0}", e.Message)); } } else { rdata.Fail(Rest.HttpStatusCodeBadRequest, String.Format("avatar {0} not present", rdata.Parameters[PARM_MOVE_AVATAR])); } rdata.Complete(); rdata.Respond("OK"); } } private static readonly string Help = "<html>" + "<head><title>Remote Command Usage</title></head>" + "<body>" + "<p>Supported commands are:</p>" + "<dl>" + "<dt>move/avatar-name/x/y/z</dt>" + "<dd>moves the specified avatar to another location</dd>" + "</dl>" + "</body>" + "</html>" ; } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); readonly Func<TWrite, byte[]> serializer; readonly Func<byte[], TRead> deserializer; protected readonly object myLock = new object(); protected CallSafeHandle call; protected bool disposed; protected bool started; protected bool errorOccured; protected bool cancelRequested; protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null. protected AsyncCompletionDelegate<TRead> readCompletionDelegate; // Completion of a pending send or sendclose if not null. protected bool readingDone; protected bool halfcloseRequested; protected bool halfclosed; protected bool finished; // True if close has been received from the peer. public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer) { this.serializer = Preconditions.CheckNotNull(serializer); this.deserializer = Preconditions.CheckNotNull(deserializer); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { Preconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> public void CancelWithStatus(Status status) { lock (myLock) { Preconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(CallSafeHandle call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartSendMessageInternal(TWrite msg, AsyncCompletionDelegate<object> completionDelegate) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendMessage(payload, HandleSendFinished); sendCompletionDelegate = completionDelegate; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartReadMessageInternal(AsyncCompletionDelegate<TRead> completionDelegate) { lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckReadingAllowed(); call.StartReceiveMessage(HandleReadFinished); readCompletionDelegate = completionDelegate; } } // TODO(jtattermusch): find more fitting name for this method. /// <summary> /// Default behavior just completes the read observer, but more sofisticated behavior might be required /// by subclasses. /// </summary> protected virtual void ProcessLastRead(AsyncCompletionDelegate<TRead> completionDelegate) { FireCompletion(completionDelegate, default(TRead), null); } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { if (!disposed && call != null) { bool noMoreSendCompletions = halfclosed || (cancelRequested && sendCompletionDelegate == null); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } private void ReleaseResources() { OnReleaseResources(); if (call != null) { call.Dispose(); } disposed = true; } protected virtual void OnReleaseResources() { } protected void CheckSendingAllowed() { Preconditions.CheckState(started); Preconditions.CheckState(!errorOccured); CheckNotCancelled(); Preconditions.CheckState(!disposed); Preconditions.CheckState(!halfcloseRequested, "Already halfclosed."); Preconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time"); } protected void CheckReadingAllowed() { Preconditions.CheckState(started); Preconditions.CheckState(!disposed); Preconditions.CheckState(!errorOccured); Preconditions.CheckState(!readingDone, "Stream has already been closed."); Preconditions.CheckState(readCompletionDelegate == null, "Only one read can be pending at a time"); } protected void CheckNotCancelled() { if (cancelRequested) { throw new OperationCanceledException("Remote call has been cancelled."); } } protected byte[] UnsafeSerialize(TWrite msg) { return serializer(msg); } protected bool TrySerialize(TWrite msg, out byte[] payload) { try { payload = serializer(msg); return true; } catch (Exception e) { Logger.Error(e, "Exception occured while trying to serialize message"); payload = null; return false; } } protected bool TryDeserialize(byte[] payload, out TRead msg) { try { msg = deserializer(payload); return true; } catch (Exception e) { Logger.Error(e, "Exception occured while trying to deserialize message."); msg = default(TRead); return false; } } protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error) { try { completionDelegate(value, error); } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } /// <summary> /// Handles send completion. /// </summary> protected void HandleSendFinished(bool success, BatchContextSafeHandle ctx) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new OperationFailedException("Send failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles halfclose completion. /// </summary> protected void HandleHalfclosed(bool success, BatchContextSafeHandle ctx) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { halfclosed = true; origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new OperationFailedException("Halfclose failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, BatchContextSafeHandle ctx) { var payload = ctx.GetReceivedMessage(); AsyncCompletionDelegate<TRead> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = readCompletionDelegate; if (payload != null) { readCompletionDelegate = null; } else { // This was the last read. Keeping the readCompletionDelegate // to be either fired by this handler or by client-side finished // handler. readingDone = true; } ReleaseResourcesIfPossible(); } // TODO: handle the case when error occured... if (payload != null) { // TODO: handle deserialization error TRead msg; TryDeserialize(payload, out msg); FireCompletion(origCompletionDelegate, msg, null); } else { ProcessLastRead(origCompletionDelegate); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.SymbolMapping; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService))] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new SemaphoreSlim(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo>(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new Dictionary<string, MetadataAsSourceGeneratedFileInfo>(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex _mutex; private string _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; public MetadataAsSourceFileService() { _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); } private static string CreateMutexName(string directoryName) { return "MetadataAsSource-" + directoryName; } private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, CancellationToken cancellationToken = default(CancellationToken)) { if (project == null) { throw new ArgumentNullException("project"); } if (symbol == null) { throw new ArgumentNullException("symbol"); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(EditorFeaturesResources.SymbolCannotBeNamespace, "symbol"); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false), cancellationToken); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); var infoKey = await GetUniqueDocumentKey(project, topLevelNamedType, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, symbol, cancellationToken).ConfigureAwait(false); // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath); while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: fileInfo.Encoding)) { text.Write(textWriter); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLock(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, EditorFeaturesResources.FromMetadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. DocumentId openDocumentId; if (_openedDocumentIds.TryGetValue(fileInfo, out openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, ITextBuffer buffer) { using (_gate.DisposableWait()) { MetadataAsSourceGeneratedFileInfo fileInfo; if (_generatedFilenameToInformation.TryGetValue(filePath, out fileInfo)) { Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, buffer.AsTextContainer()); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { MetadataAsSourceGeneratedFileInfo fileInfo; if (_generatedFilenameToInformation.TryGetValue(filePath, out fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, fileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private async Task<UniqueDocumentKey> GetUniqueDocumentKey(Project project, INamedTypeSymbol topLevelNamedType, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, project.Language, SymbolKey.Create(topLevelNamedType, compilation, cancellationToken)); } else { return new UniqueDocumentKey(topLevelNamedType.ContainingAssembly.Identity, project.Language, SymbolKey.Create(topLevelNamedType, compilation, cancellationToken)); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } internal async Task<SymbolMappingResult> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARANING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); if (project == null) { return null; } var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) { return null; } return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { bool deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { Mutex acquiredMutex; // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string _filePath; /// <summary> /// Assembly identity. Only non-null if filePath is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity _assemblyIdentity; private readonly string _language; private readonly SymbolKey _symbolId; public UniqueDocumentKey(string filePath, string language, SymbolKey symbolId) { Contract.ThrowIfNull(filePath); _filePath = filePath; _language = language; _symbolId = symbolId; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, string language, SymbolKey symbolId) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _language = language; _symbolId = symbolId; } public bool Equals(UniqueDocumentKey other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId); } public override bool Equals(object obj) { return Equals(obj as UniqueDocumentKey); } public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity != null ? _assemblyIdentity.GetHashCode() : 0, Hash.Combine(_language.GetHashCode(), s_symbolIdComparer.GetHashCode(_symbolId)))); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Security; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.OptionalModules.Scripting.Minimodule.Object; using OpenSim.Region.Physics.Manager; using PrimType=OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.PrimType; using SculptType=OpenSim.Region.OptionalModules.Scripting.Minimodule.Object.SculptType; namespace OpenSim.Region.OptionalModules.Scripting.Minimodule { class SOPObject : MarshalByRefObject, IObject, IObjectPhysics, IObjectShape, IObjectSound { private readonly Scene m_rootScene; private readonly uint m_localID; private readonly ISecurityCredential m_security; [Obsolete("Replace with 'credential' constructor [security]")] public SOPObject(Scene rootScene, uint localID) { m_rootScene = rootScene; m_localID = localID; } public SOPObject(Scene rootScene, uint localID, ISecurityCredential credential) { m_rootScene = rootScene; m_localID = localID; m_security = credential; } /// <summary> /// This needs to run very, very quickly. /// It is utilized in nearly every property and method. /// </summary> /// <returns></returns> private SceneObjectPart GetSOP() { return m_rootScene.GetSceneObjectPart(m_localID); } private bool CanEdit() { if (!m_security.CanEditObject(this)) { throw new SecurityException("Insufficient Permission to edit object with UUID [" + GetSOP().UUID + "]"); } return true; } #region OnTouch private event OnTouchDelegate _OnTouch; private bool _OnTouchActive = false; public event OnTouchDelegate OnTouch { add { if (CanEdit()) { if (!_OnTouchActive) { GetSOP().Flags |= PrimFlags.Touch; _OnTouchActive = true; m_rootScene.EventManager.OnObjectGrab += EventManager_OnObjectGrab; } _OnTouch += value; } } remove { _OnTouch -= value; if (_OnTouch == null) { GetSOP().Flags &= ~PrimFlags.Touch; _OnTouchActive = false; m_rootScene.EventManager.OnObjectGrab -= EventManager_OnObjectGrab; } } } void EventManager_OnObjectGrab(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { if (_OnTouchActive && m_localID == localID) { TouchEventArgs e = new TouchEventArgs(); e.Avatar = new SPAvatar(m_rootScene, remoteClient.AgentId, m_security); e.TouchBiNormal = surfaceArgs.Binormal; e.TouchMaterialIndex = surfaceArgs.FaceIndex; e.TouchNormal = surfaceArgs.Normal; e.TouchPosition = surfaceArgs.Position; e.TouchST = new Vector2(surfaceArgs.STCoord.X, surfaceArgs.STCoord.Y); e.TouchUV = new Vector2(surfaceArgs.UVCoord.X, surfaceArgs.UVCoord.Y); IObject sender = this; if (_OnTouch != null) _OnTouch(sender, e); } } #endregion public bool Exists { get { return GetSOP() != null; } } public uint LocalID { get { return m_localID; } } public UUID GlobalID { get { return GetSOP().UUID; } } public string Name { get { return GetSOP().Name; } set { if (CanEdit()) GetSOP().Name = value; } } public string Description { get { return GetSOP().Description; } set { if (CanEdit()) GetSOP().Description = value; } } public UUID OwnerId { get { return GetSOP().OwnerID;} } public UUID CreatorId { get { return GetSOP().CreatorID;} } public IObject[] Children { get { SceneObjectPart my = GetSOP(); IObject[] rets = null; int total = my.ParentGroup.PrimCount; rets = new IObject[total]; int i = 0; foreach (SceneObjectPart part in my.ParentGroup.Parts) { rets[i++] = new SOPObject(m_rootScene, part.LocalId, m_security); } return rets; } } public IObject Root { get { return new SOPObject(m_rootScene, GetSOP().ParentGroup.RootPart.LocalId, m_security); } } public IObjectMaterial[] Materials { get { SceneObjectPart sop = GetSOP(); IObjectMaterial[] rets = new IObjectMaterial[getNumberOfSides(sop)]; for (int i = 0; i < rets.Length; i++) { rets[i] = new SOPObjectMaterial(i, sop); } return rets; } } public Vector3 Scale { get { return GetSOP().Scale; } set { if (CanEdit()) GetSOP().Scale = value; } } public Quaternion WorldRotation { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Quaternion OffsetRotation { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Vector3 WorldPosition { get { return GetSOP().AbsolutePosition; } set { if (CanEdit()) { SceneObjectPart pos = GetSOP(); pos.UpdateOffSet(value - pos.AbsolutePosition); } } } public Vector3 OffsetPosition { get { return GetSOP().OffsetPosition; } set { if (CanEdit()) { GetSOP().OffsetPosition = value; } } } public Vector3 SitTarget { get { return GetSOP().SitTargetPosition; } set { if (CanEdit()) { GetSOP().SitTargetPosition = value; } } } public string SitTargetText { get { return GetSOP().SitName; } set { if (CanEdit()) { GetSOP().SitName = value; } } } public string TouchText { get { return GetSOP().TouchName; } set { if (CanEdit()) { GetSOP().TouchName = value; } } } public string Text { get { return GetSOP().Text; } set { if (CanEdit()) { GetSOP().SetText(value,new Vector3(1.0f,1.0f,1.0f),1.0f); } } } public bool IsRotationLockedX { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsRotationLockedY { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsRotationLockedZ { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsSandboxed { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsImmotile { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsAlwaysReturned { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsTemporary { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsFlexible { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public PhysicsMaterial PhysicsMaterial { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public IObjectPhysics Physics { get { return this; } } public IObjectShape Shape { get { return this; } } public IObjectInventory Inventory { get { return new SOPObjectInventory(m_rootScene, GetSOP().TaskInventory); } } #region Public Functions public void Say(string msg) { if (!CanEdit()) return; SceneObjectPart sop = GetSOP(); m_rootScene.SimChat(msg, ChatTypeEnum.Say, sop.AbsolutePosition, sop.Name, sop.UUID, false); } public void Say(string msg,int channel) { if (!CanEdit()) return; SceneObjectPart sop = GetSOP(); m_rootScene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say,channel, sop.AbsolutePosition, sop.Name, sop.UUID, false); } public void Dialog(UUID avatar, string message, string[] buttons, int chat_channel) { if (!CanEdit()) return; IDialogModule dm = m_rootScene.RequestModuleInterface<IDialogModule>(); if (dm == null) return; if (buttons.Length < 1) { Say("ERROR: No less than 1 button can be shown",2147483647); return; } if (buttons.Length > 12) { Say("ERROR: No more than 12 buttons can be shown",2147483647); return; } foreach (string button in buttons) { if (button == String.Empty) { Say("ERROR: button label cannot be blank",2147483647); return; } if (button.Length > 24) { Say("ERROR: button label cannot be longer than 24 characters",2147483647); return; } } dm.SendDialogToUser( avatar, GetSOP().Name, GetSOP().UUID, GetSOP().OwnerID, message, new UUID("00000000-0000-2222-3333-100000001000"), chat_channel, buttons); } #endregion #region Supporting Functions // Helper functions to understand if object has cut, hollow, dimple, and other affecting number of faces private static void hasCutHollowDimpleProfileCut(int primType, PrimitiveBaseShape shape, out bool hasCut, out bool hasHollow, out bool hasDimple, out bool hasProfileCut) { if (primType == (int)PrimType.Box || primType == (int)PrimType.Cylinder || primType == (int)PrimType.Prism) hasCut = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); else hasCut = (shape.PathBegin > 0) || (shape.PathEnd > 0); hasHollow = shape.ProfileHollow > 0; hasDimple = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); // taken from llSetPrimitiveParms hasProfileCut = hasDimple; // is it the same thing? } private static int getScriptPrimType(PrimitiveBaseShape primShape) { if (primShape.SculptEntry) return (int) PrimType.Sculpt; if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Square) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Box; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Tube; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Circle) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Cylinder; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Torus; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.HalfCircle) { if (primShape.PathCurve == (byte) Extrusion.Curve1 || primShape.PathCurve == (byte) Extrusion.Curve2) return (int) PrimType.Sphere; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.EquilateralTriangle) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Prism; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Ring; } return (int) PrimType.NotPrimitive; } private static int getNumberOfSides(SceneObjectPart part) { int ret; bool hasCut; bool hasHollow; bool hasDimple; bool hasProfileCut; int primType = getScriptPrimType(part.Shape); hasCutHollowDimpleProfileCut(primType, part.Shape, out hasCut, out hasHollow, out hasDimple, out hasProfileCut); switch (primType) { default: case (int) PrimType.Box: ret = 6; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Cylinder: ret = 3; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Prism: ret = 5; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Sphere: ret = 1; if (hasCut) ret += 2; if (hasDimple) ret += 2; if (hasHollow) ret += 1; // GOTCHA: LSL shows 2 additional sides here. // This has been fixed, but may cause porting issues. break; case (int) PrimType.Torus: ret = 1; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Tube: ret = 4; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Ring: ret = 3; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Sculpt: ret = 1; break; } return ret; } #endregion #region IObjectPhysics public bool Enabled { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool Phantom { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool PhantomCollisions { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public double Density { get { return (GetSOP().PhysActor.Mass/Scale.X*Scale.Y/Scale.Z); } set { throw new NotImplementedException(); } } public double Mass { get { return GetSOP().PhysActor.Mass; } set { throw new NotImplementedException(); } } public double Buoyancy { get { return GetSOP().PhysActor.Buoyancy; } set { GetSOP().PhysActor.Buoyancy = (float)value; } } public Vector3 GeometricCenter { get { Vector3 tmp = GetSOP().PhysActor.GeometricCenter; return tmp; } } public Vector3 CenterOfMass { get { Vector3 tmp = GetSOP().PhysActor.CenterOfMass; return tmp; } } public Vector3 RotationalVelocity { get { Vector3 tmp = GetSOP().PhysActor.RotationalVelocity; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.RotationalVelocity = value; } } public Vector3 Velocity { get { Vector3 tmp = GetSOP().PhysActor.Velocity; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Velocity = value; } } public Vector3 Torque { get { Vector3 tmp = GetSOP().PhysActor.Torque; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Torque = value; } } public Vector3 Acceleration { get { Vector3 tmp = GetSOP().PhysActor.Acceleration; return tmp; } } public Vector3 Force { get { Vector3 tmp = GetSOP().PhysActor.Force; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Force = value; } } public bool FloatOnWater { set { if (!CanEdit()) return; GetSOP().PhysActor.FloatOnWater = value; } } public void AddForce(Vector3 force, bool pushforce) { if (!CanEdit()) return; GetSOP().PhysActor.AddForce(force, pushforce); } public void AddAngularForce(Vector3 force, bool pushforce) { if (!CanEdit()) return; GetSOP().PhysActor.AddAngularForce(force, pushforce); } public void SetMomentum(Vector3 momentum) { if (!CanEdit()) return; GetSOP().PhysActor.SetMomentum(momentum); } #endregion #region Implementation of IObjectShape private UUID m_sculptMap = UUID.Zero; public UUID SculptMap { get { return m_sculptMap; } set { if (!CanEdit()) return; m_sculptMap = value; SetPrimitiveSculpted(SculptMap, (byte) SculptType); } } private SculptType m_sculptType = Object.SculptType.Default; public SculptType SculptType { get { return m_sculptType; } set { if (!CanEdit()) return; m_sculptType = value; SetPrimitiveSculpted(SculptMap, (byte) SculptType); } } public HoleShape HoleType { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public double HoleSize { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public PrimType PrimType { get { return (PrimType)getScriptPrimType(GetSOP().Shape); } set { throw new System.NotImplementedException(); } } private void SetPrimitiveSculpted(UUID map, byte type) { ObjectShapePacket.ObjectDataBlock shapeBlock = new ObjectShapePacket.ObjectDataBlock(); SceneObjectPart part = GetSOP(); UUID sculptId = map; shapeBlock.ObjectLocalID = part.LocalId; shapeBlock.PathScaleX = 100; shapeBlock.PathScaleY = 150; // retain pathcurve shapeBlock.PathCurve = part.Shape.PathCurve; part.Shape.SetSculptProperties((byte)type, sculptId); part.Shape.SculptEntry = true; part.UpdateShape(shapeBlock); } #endregion #region Implementation of IObjectSound public IObjectSound Sound { get { return this; } } public void Play(UUID asset, double volume) { if (!CanEdit()) return; ISoundModule module = m_rootScene.RequestModuleInterface<ISoundModule>(); if (module != null) { module.SendSound(GetSOP().UUID, asset, volume, true, 0, 0, false, false); } } #endregion } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ScreenRecordingAdPlatform /// </summary> [DataContract] public partial class ScreenRecordingAdPlatform : IEquatable<ScreenRecordingAdPlatform>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ScreenRecordingAdPlatform" /> class. /// </summary> /// <param name="fbc">Facebook Click Id (Cookie).</param> /// <param name="fbclid">Facebook Click Id Parameter (Parameter).</param> /// <param name="fbp">Facebook Browser Id (Cookie).</param> /// <param name="gacid">Google Analytics CID (Cookie).</param> /// <param name="glcid">Google Adwords Click Id (Parameter).</param> /// <param name="msclkid">Bing Click Id (Parameter.</param> /// <param name="ttclid">TikTok Click Id (Parameter.</param> public ScreenRecordingAdPlatform(string fbc = default(string), string fbclid = default(string), string fbp = default(string), string gacid = default(string), string glcid = default(string), string msclkid = default(string), string ttclid = default(string)) { this.Fbc = fbc; this.Fbclid = fbclid; this.Fbp = fbp; this.Gacid = gacid; this.Glcid = glcid; this.Msclkid = msclkid; this.Ttclid = ttclid; } /// <summary> /// Facebook Click Id (Cookie) /// </summary> /// <value>Facebook Click Id (Cookie)</value> [DataMember(Name="fbc", EmitDefaultValue=false)] public string Fbc { get; set; } /// <summary> /// Facebook Click Id Parameter (Parameter) /// </summary> /// <value>Facebook Click Id Parameter (Parameter)</value> [DataMember(Name="fbclid", EmitDefaultValue=false)] public string Fbclid { get; set; } /// <summary> /// Facebook Browser Id (Cookie) /// </summary> /// <value>Facebook Browser Id (Cookie)</value> [DataMember(Name="fbp", EmitDefaultValue=false)] public string Fbp { get; set; } /// <summary> /// Google Analytics CID (Cookie) /// </summary> /// <value>Google Analytics CID (Cookie)</value> [DataMember(Name="gacid", EmitDefaultValue=false)] public string Gacid { get; set; } /// <summary> /// Google Adwords Click Id (Parameter) /// </summary> /// <value>Google Adwords Click Id (Parameter)</value> [DataMember(Name="glcid", EmitDefaultValue=false)] public string Glcid { get; set; } /// <summary> /// Bing Click Id (Parameter /// </summary> /// <value>Bing Click Id (Parameter</value> [DataMember(Name="msclkid", EmitDefaultValue=false)] public string Msclkid { get; set; } /// <summary> /// TikTok Click Id (Parameter /// </summary> /// <value>TikTok Click Id (Parameter</value> [DataMember(Name="ttclid", EmitDefaultValue=false)] public string Ttclid { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ScreenRecordingAdPlatform {\n"); sb.Append(" Fbc: ").Append(Fbc).Append("\n"); sb.Append(" Fbclid: ").Append(Fbclid).Append("\n"); sb.Append(" Fbp: ").Append(Fbp).Append("\n"); sb.Append(" Gacid: ").Append(Gacid).Append("\n"); sb.Append(" Glcid: ").Append(Glcid).Append("\n"); sb.Append(" Msclkid: ").Append(Msclkid).Append("\n"); sb.Append(" Ttclid: ").Append(Ttclid).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ScreenRecordingAdPlatform); } /// <summary> /// Returns true if ScreenRecordingAdPlatform instances are equal /// </summary> /// <param name="input">Instance of ScreenRecordingAdPlatform to be compared</param> /// <returns>Boolean</returns> public bool Equals(ScreenRecordingAdPlatform input) { if (input == null) return false; return ( this.Fbc == input.Fbc || (this.Fbc != null && this.Fbc.Equals(input.Fbc)) ) && ( this.Fbclid == input.Fbclid || (this.Fbclid != null && this.Fbclid.Equals(input.Fbclid)) ) && ( this.Fbp == input.Fbp || (this.Fbp != null && this.Fbp.Equals(input.Fbp)) ) && ( this.Gacid == input.Gacid || (this.Gacid != null && this.Gacid.Equals(input.Gacid)) ) && ( this.Glcid == input.Glcid || (this.Glcid != null && this.Glcid.Equals(input.Glcid)) ) && ( this.Msclkid == input.Msclkid || (this.Msclkid != null && this.Msclkid.Equals(input.Msclkid)) ) && ( this.Ttclid == input.Ttclid || (this.Ttclid != null && this.Ttclid.Equals(input.Ttclid)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Fbc != null) hashCode = hashCode * 59 + this.Fbc.GetHashCode(); if (this.Fbclid != null) hashCode = hashCode * 59 + this.Fbclid.GetHashCode(); if (this.Fbp != null) hashCode = hashCode * 59 + this.Fbp.GetHashCode(); if (this.Gacid != null) hashCode = hashCode * 59 + this.Gacid.GetHashCode(); if (this.Glcid != null) hashCode = hashCode * 59 + this.Glcid.GetHashCode(); if (this.Msclkid != null) hashCode = hashCode * 59 + this.Msclkid.GetHashCode(); if (this.Ttclid != null) hashCode = hashCode * 59 + this.Ttclid.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using Org.Apache.REEF.Common.Metrics.Api; using Org.Apache.REEF.Tang.Annotations; using Org.Apache.REEF.Utilities.Attributes; namespace Org.Apache.REEF.Common.Metrics.MutableMetricsLayer { /// <summary> /// Default implementation of <see cref="IMetricsSource"/>. Contains user friendly aceess to /// add and update metrics. Can be extended or totally ignored by the user. /// </summary> [Unstable("0.16", "Contract may change.")] public class DefaultMetricsSourceImpl : IMetricsSource, IDisposable { private readonly IMetricContainer<ICounter> _counters; private readonly IMetricContainer<ILongGauge> _longGauges; private readonly IMetricContainer<IDoubleGauge> _doubleGauges; private readonly IMetricContainer<IRate> _rates; private readonly Dictionary<string, MetricsTag> _tags = new Dictionary<string, MetricsTag>(); private readonly IList<IObserver<SnapshotRequest>> _observers = new List<IObserver<SnapshotRequest>>(); private readonly object _lock = new object(); private readonly string _contextOrTaskName; private readonly string _evaluatorId; private readonly string _sourceContext; private readonly string _recordName; private readonly IMetricsFactory _metricsFactory; [Inject] private DefaultMetricsSourceImpl( [Parameter(typeof(DefaultMetricsSourceParameters.ContextOrTaskName))] string contextOrTaskName, [Parameter(typeof(DefaultMetricsSourceParameters.EvaluatorId))] string evaluatorId, [Parameter(typeof(DefaultMetricsSourceParameters.SourceContext))] string sourceContext, [Parameter(typeof(DefaultMetricsSourceParameters.RecordName))] string recordName, IMetricsFactory metricsFactory) { _contextOrTaskName = contextOrTaskName; _evaluatorId = evaluatorId; _sourceContext = sourceContext; _recordName = recordName; _metricsFactory = metricsFactory; _counters = new MutableMetricContainer<ICounter>( (name, desc) => metricsFactory.CreateCounter(name, desc), this); _longGauges = new MutableMetricContainer<ILongGauge>( (name, desc) => metricsFactory.CreateLongGauge(name, desc), this); _doubleGauges = new MutableMetricContainer<IDoubleGauge>( (name, desc) => metricsFactory.CreateDoubleGauge(name, desc), this); _rates = new MutableMetricContainer<IRate>( (name, desc) => metricsFactory.CreateRateMetric(name, desc), this); } /// <summary> /// Returns indexable counters container. /// </summary> public IMetricContainer<ICounter> Counters { get { return _counters; } } /// <summary> /// Returns indexable long guage container. /// </summary> public IMetricContainer<ILongGauge> LongGauges { get { return _longGauges; } } /// <summary> /// Returns indexable double gauge container. /// </summary> public IMetricContainer<IDoubleGauge> DoubleGauges { get { return _doubleGauges; } } /// <summary> /// Returns indexable double gauge container. /// </summary> public IMetricContainer<IRate> Rates { get { return _rates; } } /// <summary> /// Adds a tag to the source. Replaces old one if it exists. /// </summary> /// <param name="name">Name of the tag.</param> /// <param name="desc">Description of the tag.</param> /// <param name="value">Value of the tag.</param> public void AddTag(string name, string desc, string value) { lock (_lock) { _tags[name] = _metricsFactory.CreateTag(new MetricsInfoImpl(name, desc), value); } } /// <summary> /// Returns tag by name. /// </summary> /// <param name="name">Name of the tag.</param> /// <returns>Tag if it exists, null otherwise.</returns> public MetricsTag GetTag(string name) { lock (_lock) { MetricsTag tag; _tags.TryGetValue(name, out tag); return tag; } } /// <summary> /// Subscribes the <see cref="MutableMetricBase"/> whose snapshot /// will be taken. This function will be used if user has its own metric types except /// from the ones used in this class. For example, a ML algorithm can subscribe itself /// as observer, and directly add metric vlaues like iterations, loss function etc. in the /// record. /// </summary> /// <param name="observer">Observer that takes snapshot of the metric.</param> /// <returns>A disposable handler used to unsubscribe the observer.</returns> public IDisposable Subscribe(IObserver<SnapshotRequest> observer) { lock (_lock) { if (!_observers.Contains(observer)) { _observers.Add(observer); } return new Unsubscriber(_observers, observer, _lock); } } /// <summary> /// Gets metrics from the source. /// </summary> /// <param name="collector">Collector that stores the resulting metrics snapshot as records.</param> /// <param name="all">If true, gets metric values even if they are unchanged.</param> public void GetMetrics(IMetricsCollector collector, bool all) { lock (_lock) { var rb = collector.CreateRecord(_recordName) .SetContext(_sourceContext) .AddTag("TaskOrContextName", _contextOrTaskName) .AddTag("EvaluatorId", _evaluatorId) .AddTag("SourceType", "DefaultSource"); var request = new SnapshotRequest(rb, all); foreach (var entry in _observers) { entry.OnNext(request); } foreach (var entry in _tags) { rb.Add(entry.Value); } } } /// <summary> /// Diposes the <see cref="DefaultMetricsSourceImpl"/>. /// Removes all the observers. /// </summary> public void Dispose() { foreach (var observer in _observers) { observer.OnCompleted(); } } private class Unsubscriber : IDisposable { private readonly IList<IObserver<SnapshotRequest>> _observers; private readonly IObserver<SnapshotRequest> _observer; private readonly object _lock; public Unsubscriber(IList<IObserver<SnapshotRequest>> observers, IObserver<SnapshotRequest> observer, object lockObject) { _observers = observers; _observer = observer; _lock = lockObject; } public void Dispose() { lock (_lock) { if (_observer != null && _observers.Contains(_observer)) { _observers.Remove(_observer); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MinDouble() { var test = new SimpleBinaryOpTest__MinDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinDouble { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__MinDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__MinDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.Min( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.Min( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.Min( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.Min), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Min(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__MinDouble(); var result = Avx.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(Math.Min(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Math.Min(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Min)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Runtime.x86; namespace Mosa.Kernel.x86.Smbios { /// <summary> /// /// </summary> public static class SmbiosManager { /// <summary> /// Holds the smbios entry point /// </summary> private static uint entryPoint = 0u; /// <summary> /// /// </summary> private static uint tableAddress = 0u; /// <summary> /// /// </summary> private static uint tableLength = 0u; /// <summary> /// /// </summary> private static uint numberOfStructures = 0u; /// <summary> /// /// </summary> private static uint majorVersion = 0u; /// <summary> /// /// </summary> private static uint minorVersion = 0u; /// <summary> /// Checks if SMBIOS is available /// </summary> public static bool IsAvailable { get { return EntryPoint != 0x100000u; } } /// <summary> /// Gets the table's entry point /// </summary> public static uint EntryPoint { get { return entryPoint; } } /// <summary> /// /// </summary> public static uint MajorVersion { get { return majorVersion; } } /// <summary> /// /// </summary> public static uint MinorVersion { get { return minorVersion; } } /// <summary> /// Gets the table's length /// </summary> public static uint TableLength { get { return tableLength; } } /// <summary> /// Gets the entry address for smbios structures /// </summary> public static uint TableAddress { get { return tableAddress; } } /// <summary> /// Gets the total number of available structures /// </summary> public static uint NumberOfStructures { get { return numberOfStructures; } } /// <summary> /// /// </summary> public static void Setup() { LocateEntryPoint(); if (!IsAvailable) return; GetTableAddress(); GetTableLength(); GetNumberOfStructures(); GetMajorVersion(); GetMinorVersion(); } /// <summary> /// /// </summary> public static uint GetStructureOfType(byte type) { uint address = TableAddress; while (GetType(address) != 127u) { if (GetType(address) == type) return address; address = GetAddressOfNextStructure(address); } return 0xFFFFu; } /// <summary> /// /// </summary> private static byte GetType(uint address) { return Native.Get8(address); } /// <summary> /// /// </summary> private static uint GetAddressOfNextStructure(uint address) { byte length = Native.Get8(address + 0x01u); uint endOfFormattedArea = address + length; while (Native.Get16(endOfFormattedArea) != 0x0000u) ++endOfFormattedArea; endOfFormattedArea += 0x02u; return endOfFormattedArea; } /// <summary> /// /// </summary> /// <returns> /// /// </returns> private static void LocateEntryPoint() { uint memory = 0xF0000u; while (memory < 0x100000u) { char a = (char)Native.Get8(memory); char s = (char)Native.Get8(memory + 1u); char m = (char)Native.Get8(memory + 2u); char b = (char)Native.Get8(memory + 3u); if (a == '_' && s == 'S' && m == 'M' && b == '_') { entryPoint = memory; return; } memory += 0x10u; } entryPoint = memory; } /// <summary> /// /// </summary> private static void GetMajorVersion() { majorVersion = Native.Get8(EntryPoint + 0x06u); } /// <summary> /// /// </summary> private static void GetMinorVersion() { minorVersion = Native.Get8(EntryPoint + 0x07u); } /// <summary> /// /// </summary> private static void GetTableAddress() { tableAddress = Native.Get32(EntryPoint + 0x18u); } /// <summary> /// /// </summary> private static void GetTableLength() { tableLength = Native.Get16(EntryPoint + 0x16u); } /// <summary> /// /// </summary> private static void GetNumberOfStructures() { numberOfStructures = Native.Get16(EntryPoint + 0x1Cu); } } }
using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace ForSerial.Objects { public class DynamicMethodProvider : ObjectInterfaceProvider { public GetMethod GetPropertyGetter(PropertyInfo property) { if (property.DeclaringType.IsInterface) return null; GetMethod compiledGet = null; return source => (compiledGet ?? (compiledGet = CompilePropertyGetter(property)))(source); } private static GetMethod CompilePropertyGetter(PropertyInfo property) { const int instanceArg = 1; DynamicMethod dynamicGet = CreateDynamicFunc(property.DeclaringType, "dynamicGet_" + property.Name, instanceArg); dynamicGet.GetILGenerator() .LoadObjectInstance(property.DeclaringType) .CallMethod(property.GetGetMethod(true)) .BoxIfNeeded(property.PropertyType) .Return(); return (GetMethod)dynamicGet.CreateDelegate(typeof(GetMethod)); } public SetMethod GetPropertySetter(PropertyInfo property) { if (property.DeclaringType.IsInterface) return null; SetMethod compiledSet = null; return (target, value) => (compiledSet ?? (compiledSet = CompilePropertySetter(property)))(target, value); } private static SetMethod CompilePropertySetter(PropertyInfo property) { const int instanceAndValueArgs = 2; DynamicMethod dynamicSet = CreateDynamicAction(property.DeclaringType, "dynamicSet_" + property.Name, instanceAndValueArgs); dynamicSet.GetILGenerator() .LoadObjectInstance(property.DeclaringType) .LoadArg(1) .UnboxIfNeeded(property.PropertyType) .CallMethod(property.GetSetMethod(true)) .Return(); return (SetMethod)dynamicSet.CreateDelegate(typeof(SetMethod)); } public GetMethod GetFieldGetter(FieldInfo field) { GetMethod compiledGet = null; return source => (compiledGet ?? (compiledGet = CompileFieldGetter(field)))(source); } private static GetMethod CompileFieldGetter(FieldInfo field) { const int instanceArg = 1; DynamicMethod dynamicGet = CreateDynamicFunc(field.DeclaringType, "dynamicGet_" + field.Name, instanceArg); dynamicGet.GetILGenerator() .LoadObjectInstance(field.DeclaringType) .LoadField(field) .BoxIfNeeded(field.FieldType) .Return(); return (GetMethod)dynamicGet.CreateDelegate(typeof(GetMethod)); } public SetMethod GetFieldSetter(FieldInfo field) { SetMethod compiledSet = null; return (target, value) => (compiledSet ?? (compiledSet = CompileFieldSetter(field)))(target, value); } private static SetMethod CompileFieldSetter(FieldInfo field) { const int instanceAndValueArgs = 2; DynamicMethod dynamicSet = CreateDynamicAction(field.DeclaringType, "dynamicSet_" + field.Name, instanceAndValueArgs); dynamicSet.GetILGenerator() .LoadObjectInstance(field.DeclaringType) .LoadArg(1) .UnboxIfNeeded(field.FieldType) .SetField(field) .Return(); return (SetMethod)dynamicSet.CreateDelegate(typeof(SetMethod)); } public StaticFuncMethod GetStaticFunc(MethodInfo method) { StaticFuncMethod compiledFuncCall = null; return (args) => (compiledFuncCall ?? (compiledFuncCall = CompileStaticFuncCall(method)))(args); } private static StaticFuncMethod CompileStaticFuncCall(MethodInfo method) { const int objectArrayArg = 1; DynamicMethod dynamicMethod = CreateDynamicFunc(method.DeclaringType, "dynamicCall_" + method.Name, objectArrayArg); dynamicMethod.GetILGenerator() .LoadParamsFromObjectArrayArg(0, method) .CallMethod(method) .Return(); return (StaticFuncMethod)dynamicMethod.CreateDelegate(typeof(StaticFuncMethod)); } public ActionMethod GetAction(MethodInfo method) { if (method.DeclaringType.IsInterface) return null; ActionMethod compiledActionCall = null; return (target, args) => (compiledActionCall ?? (compiledActionCall = CompileActionCall(method)))(target, args); } private static ActionMethod CompileActionCall(MethodInfo method) { const int instanceAndObjectArrayArgs = 2; DynamicMethod dynamicMethod = CreateDynamicAction(method.DeclaringType, "dynamicCall_" + method.Name, instanceAndObjectArrayArgs); dynamicMethod.GetILGenerator() .LoadObjectInstance(method.DeclaringType) .LoadParamsFromObjectArrayArg(1, method) .CallMethod(method) .IgnoreReturnValue(method) .Return(); return (ActionMethod)dynamicMethod.CreateDelegate(typeof(ActionMethod)); } public ConstructorMethod GetConstructor(ConstructorInfo constructor) { DynamicMethod dynamicConstructor = CreateDynamicConstructor(constructor); ILGenerator il = dynamicConstructor.GetILGenerator(); ParameterInfo[] parameters = constructor.GetParameters(); for (int i = 0; i < parameters.Length; i++) { il.Emit(OpCodes.Ldarg_0); switch (i) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: il.Emit(OpCodes.Ldc_I4, i); break; } il.Emit(OpCodes.Ldelem_Ref); Type paramType = parameters[i].ParameterType; il.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } il.Emit(OpCodes.Newobj, constructor); il.BoxIfNeeded(constructor.DeclaringType); il.Emit(OpCodes.Ret); return (ConstructorMethod)dynamicConstructor.CreateDelegate(typeof(ConstructorMethod)); } private static DynamicMethod CreateDynamicFunc(Type type, string name, int argCount) { return CreateDynamicMethod(type, name, argCount, typeof(object)); } private static DynamicMethod CreateDynamicAction(Type type, string name, int argCount) { return CreateDynamicMethod(type, name, argCount, typeof(void)); } private static DynamicMethod CreateDynamicMethod(Type type, string name, int argCount, Type returnType) { return new DynamicMethod(name, returnType, Enumerable.Repeat(typeof(object), argCount).ToArray(), type, true); } private static DynamicMethod CreateDynamicConstructor(ConstructorInfo constructor) { Type type = constructor.DeclaringType; string methodName = "construct_" + type.Name; Type returnType = typeof(object); Type[] methodParameterTypes = new[] { typeof(object[]) }; return type.IsPrimitive || type.IsArray // FIXME primitives and arrays simply shouldn't get getting in here ? new DynamicMethod(methodName, returnType, methodParameterTypes) : new DynamicMethod(methodName, returnType, methodParameterTypes, type, true); } } internal static class IlGeneratorExtensions { public static ILGenerator LoadObjectInstance(this ILGenerator il, Type type) { il.Emit(OpCodes.Ldarg_0); if (type.IsValueType) il.UnboxAndLoadValue(type); return il; } private static void UnboxAndLoadValue(this ILGenerator il, Type type) { il.DeclareLocal(type); il.Emit(OpCodes.Unbox_Any, type); il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloca_S, 0); } public static ILGenerator LoadParamsFromObjectArrayArg(this ILGenerator il, int objectArrayIndex, MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); for (int i = 0; i < parameters.Length; i++) { il.LoadArg(objectArrayIndex); switch (i) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: il.Emit(OpCodes.Ldc_I4, i); break; } il.Emit(OpCodes.Ldelem_Ref); Type paramType = parameters[i].ParameterType; il.Emit(paramType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, paramType); } return il; } public static ILGenerator LoadArg(this ILGenerator il, int index) { switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: il.Emit(OpCodes.Ldarg_S, index); break; } return il; } public static ILGenerator LoadField(this ILGenerator il, FieldInfo field) { il.Emit(OpCodes.Ldfld, field); return il; } public static ILGenerator SetField(this ILGenerator il, FieldInfo field) { il.Emit(OpCodes.Stfld, field); return il; } public static ILGenerator CallMethod(this ILGenerator il, MethodInfo method) { OpCode call = method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call; il.Emit(call, method); return il; } public static ILGenerator BoxIfNeeded(this ILGenerator il, Type type) { if (type.IsValueType) il.Emit(OpCodes.Box, type); return il; } public static ILGenerator UnboxIfNeeded(this ILGenerator il, Type type) { if (type.IsValueType) il.Emit(OpCodes.Unbox_Any, type); return il; } public static ILGenerator IgnoreReturnValue(this ILGenerator il, MethodInfo method) { if (method.ReturnType != typeof(void)) il.Emit(OpCodes.Pop); return il; } public static void Return(this ILGenerator il) { il.Emit(OpCodes.Ret); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Linq.JsonPath; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Linq.JsonPath { [TestFixture] public class JPathParseTests : TestFixtureBase { [Test] public void SingleProperty() { JPath path = new JPath("Blah"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedProperty() { JPath path = new JPath("['Blah']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedPropertyWithWhitespace() { JPath path = new JPath("[ 'Blah' ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedPropertyWithDots() { JPath path = new JPath("['Blah.Ha']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah.Ha", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleQuotedPropertyWithBrackets() { JPath path = new JPath("['[*]']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("[*]", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SinglePropertyWithRoot() { JPath path = new JPath("$.Blah"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SinglePropertyWithRootWithStartAndEndWhitespace() { JPath path = new JPath(" $.Blah "); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); } [Test] public void RootWithBadWhitespace() { ExceptionAssert.Throws<JsonException>( @"Unexpected character while parsing path: ", () => { new JPath("$ .Blah"); }); } [Test] public void NoFieldNameAfterDot() { ExceptionAssert.Throws<JsonException>( @"Unexpected end while parsing path.", () => { new JPath("$.Blah."); }); } [Test] public void RootWithBadWhitespace2() { ExceptionAssert.Throws<JsonException>( @"Unexpected character while parsing path: ", () => { new JPath("$. Blah"); }); } [Test] public void WildcardPropertyWithRoot() { JPath path = new JPath("$.*"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((FieldFilter)path.Filters[0]).Name); } [Test] public void WildcardArrayWithRoot() { JPath path = new JPath("$.[*]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void RootArrayNoDot() { JPath path = new JPath("$[1]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void WildcardArray() { JPath path = new JPath("[*]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void WildcardArrayWithProperty() { JPath path = new JPath("[ * ].derp"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual(null, ((ArrayIndexFilter)path.Filters[0]).Index); Assert.AreEqual("derp", ((FieldFilter)path.Filters[1]).Name); } [Test] public void QuotedWildcardPropertyWithRoot() { JPath path = new JPath("$.['*']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("*", ((FieldFilter)path.Filters[0]).Name); } [Test] public void SingleScanWithRoot() { JPath path = new JPath("$..Blah"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual("Blah", ((ScanFilter)path.Filters[0]).Name); } [Test] public void WildcardScanWithRoot() { JPath path = new JPath("$..*"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ScanFilter)path.Filters[0]).Name); } [Test] public void WildcardScanWithRootWithWhitespace() { JPath path = new JPath("$..* "); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ScanFilter)path.Filters[0]).Name); } [Test] public void TwoProperties() { JPath path = new JPath("Blah.Two"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual("Two", ((FieldFilter)path.Filters[1]).Name); } [Test] public void OnePropertyOneScan() { JPath path = new JPath("Blah..Two"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual("Two", ((ScanFilter)path.Filters[1]).Name); } [Test] public void SinglePropertyAndIndexer() { JPath path = new JPath("Blah[0]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[1]).Index); } [Test] public void SinglePropertyAndExistsQuery() { JPath path = new JPath("Blah[ ?( @..name ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Exists, expressions.Operator); Assert.AreEqual(1, expressions.Path.Count); Assert.AreEqual("name", ((ScanFilter)expressions.Path[0]).Name); } [Test] public void SinglePropertyAndFilterWithWhitespace() { JPath path = new JPath("Blah[ ?( @.name=='hi' ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual("hi", (string)expressions.Value); } [Test] public void SinglePropertyAndFilterWithEscapeQuote() { JPath path = new JPath(@"Blah[ ?( @.name=='h\'i' ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual("h'i", (string)expressions.Value); } [Test] public void SinglePropertyAndFilterWithDoubleEscape() { JPath path = new JPath(@"Blah[ ?( @.name=='h\\i' ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual("h\\i", (string)expressions.Value); } [Test] public void SinglePropertyAndFilterWithUnknownEscape() { ExceptionAssert.Throws<JsonException>( @"Unknown escape chracter: \i", () => { new JPath(@"Blah[ ?( @.name=='h\i' ) ]"); }); } [Test] public void SinglePropertyAndFilterWithFalse() { JPath path = new JPath("Blah[ ?( @.name==false ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual(false, (bool)expressions.Value); } [Test] public void SinglePropertyAndFilterWithTrue() { JPath path = new JPath("Blah[ ?( @.name==true ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual(true, (bool)expressions.Value); } [Test] public void SinglePropertyAndFilterWithNull() { JPath path = new JPath("Blah[ ?( @.name==null ) ]"); Assert.AreEqual(2, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter)path.Filters[0]).Name); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[1]).Expression; Assert.AreEqual(QueryOperator.Equals, expressions.Operator); Assert.AreEqual(null, expressions.Value.Value); } [Test] public void FilterWithScan() { JPath path = new JPath("[?(@..name<>null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual("name", ((ScanFilter)expressions.Path[0]).Name); } [Test] public void FilterWithNotEquals() { JPath path = new JPath("[?(@.name<>null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.NotEquals, expressions.Operator); } [Test] public void FilterWithNotEquals2() { JPath path = new JPath("[?(@.name!=null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.NotEquals, expressions.Operator); } [Test] public void FilterWithLessThan() { JPath path = new JPath("[?(@.name<null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.LessThan, expressions.Operator); } [Test] public void FilterWithLessThanOrEquals() { JPath path = new JPath("[?(@.name<=null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.LessThanOrEquals, expressions.Operator); } [Test] public void FilterWithGreaterThan() { JPath path = new JPath("[?(@.name>null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.GreaterThan, expressions.Operator); } [Test] public void FilterWithGreaterThanOrEquals() { JPath path = new JPath("[?(@.name>=null)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.GreaterThanOrEquals, expressions.Operator); } [Test] public void FilterWithInteger() { JPath path = new JPath("[?(@.name>=12)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(12, (int)expressions.Value); } [Test] public void FilterWithNegativeInteger() { JPath path = new JPath("[?(@.name>=-12)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(-12, (int)expressions.Value); } [Test] public void FilterWithFloat() { JPath path = new JPath("[?(@.name>=12.1)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(12.1d, (double)expressions.Value); } [Test] public void FilterExistWithAnd() { JPath path = new JPath("[?(@.name&&@.title)]"); CompositeExpression expressions = (CompositeExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.And, expressions.Operator); Assert.AreEqual(2, expressions.Expressions.Count); Assert.AreEqual("name", ((FieldFilter)((BooleanQueryExpression)expressions.Expressions[0]).Path[0]).Name); Assert.AreEqual(QueryOperator.Exists, expressions.Expressions[0].Operator); Assert.AreEqual("title", ((FieldFilter)((BooleanQueryExpression)expressions.Expressions[1]).Path[0]).Name); Assert.AreEqual(QueryOperator.Exists, expressions.Expressions[1].Operator); } [Test] public void FilterExistWithAndOr() { JPath path = new JPath("[?(@.name&&@.title||@.pie)]"); CompositeExpression andExpression = (CompositeExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(QueryOperator.And, andExpression.Operator); Assert.AreEqual(2, andExpression.Expressions.Count); Assert.AreEqual("name", ((FieldFilter)((BooleanQueryExpression)andExpression.Expressions[0]).Path[0]).Name); Assert.AreEqual(QueryOperator.Exists, andExpression.Expressions[0].Operator); CompositeExpression orExpression = (CompositeExpression)andExpression.Expressions[1]; Assert.AreEqual(2, orExpression.Expressions.Count); Assert.AreEqual("title", ((FieldFilter)((BooleanQueryExpression)orExpression.Expressions[0]).Path[0]).Name); Assert.AreEqual(QueryOperator.Exists, orExpression.Expressions[0].Operator); Assert.AreEqual("pie", ((FieldFilter)((BooleanQueryExpression)orExpression.Expressions[1]).Path[0]).Name); Assert.AreEqual(QueryOperator.Exists, orExpression.Expressions[1].Operator); } [Test] public void BadOr1() { ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: )", () => new JPath("[?(@.name||)]")); } [Test] public void BaddOr2() { ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: |", () => new JPath("[?(@.name|)]")); } [Test] public void BaddOr3() { ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: |", () => new JPath("[?(@.name|")); } [Test] public void BaddOr4() { ExceptionAssert.Throws<JsonException>("Path ended with open query.", () => new JPath("[?(@.name||")); } [Test] public void NoAtAfterOr() { ExceptionAssert.Throws<JsonException>("Unexpected character while parsing path query: s", () => new JPath("[?(@.name||s")); } [Test] public void NoPathAfterAt() { ExceptionAssert.Throws<JsonException>(@"Path ended with open query.", () => new JPath("[?(@.name||@")); } [Test] public void NoPathAfterDot() { ExceptionAssert.Throws<JsonException>(@"Unexpected end while parsing path.", () => new JPath("[?(@.name||@.")); } [Test] public void NoPathAfterDot2() { ExceptionAssert.Throws<JsonException>(@"Unexpected end while parsing path.", () => new JPath("[?(@.name||@.)]")); } [Test] public void FilterWithFloatExp() { JPath path = new JPath("[?(@.name>=5.56789e+0)]"); BooleanQueryExpression expressions = (BooleanQueryExpression)((QueryFilter)path.Filters[0]).Expression; Assert.AreEqual(5.56789e+0, (double)expressions.Value); } [Test] public void MultiplePropertiesAndIndexers() { JPath path = new JPath("Blah[0]..Two.Three[1].Four"); Assert.AreEqual(6, path.Filters.Count); Assert.AreEqual("Blah", ((FieldFilter) path.Filters[0]).Name); Assert.AreEqual(0, ((ArrayIndexFilter) path.Filters[1]).Index); Assert.AreEqual("Two", ((ScanFilter)path.Filters[2]).Name); Assert.AreEqual("Three", ((FieldFilter)path.Filters[3]).Name); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[4]).Index); Assert.AreEqual("Four", ((FieldFilter)path.Filters[5]).Name); } [Test] public void BadCharactersInIndexer() { ExceptionAssert.Throws<JsonException>( @"Unexpected character while parsing path indexer: [", () => { new JPath("Blah[[0]].Two.Three[1].Four"); }); } [Test] public void UnclosedIndexer() { ExceptionAssert.Throws<JsonException>( @"Path ended with open indexer.", () => { new JPath("Blah[0"); }); } [Test] public void IndexerOnly() { JPath path = new JPath("[111119990]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(111119990, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void IndexerOnlyWithWhitespace() { JPath path = new JPath("[ 10 ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(10, ((ArrayIndexFilter)path.Filters[0]).Index); } [Test] public void MultipleIndexes() { JPath path = new JPath("[111119990,3]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes.Count); Assert.AreEqual(111119990, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[0]); Assert.AreEqual(3, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[1]); } [Test] public void MultipleIndexesWithWhitespace() { JPath path = new JPath("[ 111119990 , 3 ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes.Count); Assert.AreEqual(111119990, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[0]); Assert.AreEqual(3, ((ArrayMultipleIndexFilter)path.Filters[0]).Indexes[1]); } [Test] public void MultipleQuotedIndexes() { JPath path = new JPath("['111119990','3']"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((FieldMultipleFilter)path.Filters[0]).Names.Count); Assert.AreEqual("111119990", ((FieldMultipleFilter)path.Filters[0]).Names[0]); Assert.AreEqual("3", ((FieldMultipleFilter)path.Filters[0]).Names[1]); } [Test] public void MultipleQuotedIndexesWithWhitespace() { JPath path = new JPath("[ '111119990' , '3' ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(2, ((FieldMultipleFilter)path.Filters[0]).Names.Count); Assert.AreEqual("111119990", ((FieldMultipleFilter)path.Filters[0]).Names[0]); Assert.AreEqual("3", ((FieldMultipleFilter)path.Filters[0]).Names[1]); } [Test] public void SlicingIndexAll() { JPath path = new JPath("[111119990:3:2]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(2, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndex() { JPath path = new JPath("[111119990:3]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexNegative() { JPath path = new JPath("[-111119990:-3:-2]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(-111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(-3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(-2, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexEmptyStop() { JPath path = new JPath("[ -3 : ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(-3, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexEmptyStart() { JPath path = new JPath("[ : 1 : ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(1, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(null, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void SlicingIndexWhitespace() { JPath path = new JPath("[ -111119990 : -3 : -2 ]"); Assert.AreEqual(1, path.Filters.Count); Assert.AreEqual(-111119990, ((ArraySliceFilter)path.Filters[0]).Start); Assert.AreEqual(-3, ((ArraySliceFilter)path.Filters[0]).End); Assert.AreEqual(-2, ((ArraySliceFilter)path.Filters[0]).Step); } [Test] public void EmptyIndexer() { ExceptionAssert.Throws<JsonException>( "Array index expected.", () => { new JPath("[]"); }); } [Test] public void IndexerCloseInProperty() { ExceptionAssert.Throws<JsonException>( "Unexpected character while parsing path: ]", () => { new JPath("]"); }); } [Test] public void AdjacentIndexers() { JPath path = new JPath("[1][0][0][" + int.MaxValue + "]"); Assert.AreEqual(4, path.Filters.Count); Assert.AreEqual(1, ((ArrayIndexFilter)path.Filters[0]).Index); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[1]).Index); Assert.AreEqual(0, ((ArrayIndexFilter)path.Filters[2]).Index); Assert.AreEqual(int.MaxValue, ((ArrayIndexFilter)path.Filters[3]).Index); } [Test] public void MissingDotAfterIndexer() { ExceptionAssert.Throws<JsonException>( "Unexpected character following indexer: B", () => { new JPath("[1]Blah"); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute; using EditorBrowsableState = System.ComponentModel.EditorBrowsableState; using Internal.Runtime.CompilerServices; #pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)' #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { /// <summary> /// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed /// or native memory, or to memory allocated on the stack. It is type- and memory-safe. /// </summary> [NonVersionable] public readonly ref partial struct ReadOnlySpan<T> { /// <summary>A byref or a native ptr.</summary> internal readonly ByReference<T> _pointer; /// <summary>The number of elements this ReadOnlySpan contains.</summary> #if PROJECTN [Bound] #endif private readonly int _length; /// <summary> /// Creates a new read-only span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array) { if (array == null) { this = default; return; // returns default } _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData())); _length = array.Length; } /// <summary> /// Creates a new read-only span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the read-only span.</param> /// <param name="length">The number of items in the read-only span.</param> /// <remarks>Returns default when <paramref name="array"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); this = default; return; // returns default } #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start)); _length = length; } /// <summary> /// Creates a new read-only span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="pointer">An unmanaged pointer to memory.</param> /// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param> /// <exception cref="System.ArgumentException"> /// Thrown when <typeparamref name="T"/> is reference type or contains pointers and hence cannot be stored in unmanaged memory. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="length"/> is negative. /// </exception> [CLSCompliant(false)] [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ReadOnlySpan(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences<T>()) ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); if (length < 0) ThrowHelper.ThrowArgumentOutOfRangeException(); _pointer = new ByReference<T>(ref Unsafe.As<byte, T>(ref *(byte*)pointer)); _length = length; } // Constructor for internal use only. [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(ref T ptr, int length) { Debug.Assert(length >= 0); _pointer = new ByReference<T>(ref ptr); _length = length; } /// <summary> /// Returns the specified element of the read-only span. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <exception cref="System.IndexOutOfRangeException"> /// Thrown when index less than 0 or index greater than or equal to Length /// </exception> public ref readonly T this[int index] { #if PROJECTN [BoundsChecking] get { return ref Unsafe.Add(ref _pointer.Value, index); } #else [Intrinsic] [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] get { if ((uint)index >= (uint)_length) ThrowHelper.ThrowIndexOutOfRangeException(); return ref Unsafe.Add(ref _pointer.Value, index); } #endif } /// <summary> /// Returns a reference to the 0th element of the Span. If the Span is empty, returns null reference. /// It can be used for pinning and is required to support the use of span within a fixed statement. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public unsafe ref readonly T GetPinnableReference() { // Ensure that the native code has just one forward branch that is predicted-not-taken. ref T ret = ref Unsafe.AsRef<T>(null); if (_length != 0) ret = ref _pointer.Value; return ref ret; } /// <summary> /// Copies the contents of this read-only span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// /// <param name="destination">The span to copy items into.</param> /// <exception cref="System.ArgumentException"> /// Thrown when the destination Span is shorter than the source Span. /// </exception> /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span<T> destination) { // Using "if (!TryCopyTo(...))" results in two branches: one for the length // check, and one for the result of TryCopyTo. Since these checks are equivalent, // we can optimize by performing the check once ourselves then calling Memmove directly. if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } /// <summary> /// Copies the contents of this read-only span into destination span. If the source /// and destinations overlap, this method behaves as if the original values in /// a temporary location before the destination is overwritten. /// </summary> /// <returns>If the destination span is shorter than the source span, this method /// return false and no data is written to the destination.</returns> /// <param name="destination">The span to copy items into.</param> public bool TryCopyTo(Span<T> destination) { bool retVal = false; if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (nuint)_length); retVal = true; } return retVal; } /// <summary> /// Returns true if left and right point at the same memory and have the same length. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public static bool operator ==(ReadOnlySpan<T> left, ReadOnlySpan<T> right) { return left._length == right._length && Unsafe.AreSame<T>(ref left._pointer.Value, ref right._pointer.Value); } /// <summary> /// For <see cref="ReadOnlySpan{Char}"/>, returns a new instance of string that represents the characters pointed to by the span. /// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements. /// </summary> public override string ToString() { if (typeof(T) == typeof(char)) { return new string(new ReadOnlySpan<char>(ref Unsafe.As<T, char>(ref _pointer.Value), _length)); } #if FEATURE_UTF8STRING else if (typeof(T) == typeof(Char8)) { // TODO_UTF8STRING: Call into optimized transcoding routine when it's available. return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref _pointer.Value), _length)); } #endif // FEATURE_UTF8STRING return string.Format("System.ReadOnlySpan<{0}>[{1}]", typeof(T).Name, _length); } /// <summary> /// Forms a slice out of the given read-only span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start) { if ((uint)start > (uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), _length - start); } /// <summary> /// Forms a slice out of the given read-only span, beginning at 'start', of given length /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<T> Slice(int start, int length) { #if BIT64 // See comment in Span<T>.Slice for how this works. if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length) ThrowHelper.ThrowArgumentOutOfRangeException(); #else if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(); #endif return new ReadOnlySpan<T>(ref Unsafe.Add(ref _pointer.Value, start), length); } /// <summary> /// Copies the contents of this read-only span into a new array. This heap /// allocates, so should generally be avoided, however it is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] ToArray() { if (_length == 0) return Array.Empty<T>(); var destination = new T[_length]; Buffer.Memmove(ref Unsafe.As<byte, T>(ref destination.GetRawSzArrayData()), ref _pointer.Value, (nuint)_length); return destination; } } }
#region License // Distributed under the MIT License // ============================================================ // Copyright (c) 2019 Hotcakes Commerce, LLC // Copyright (c) 2020 Upendo Ventures, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Hotcakes.Commerce.Contacts; using Hotcakes.Commerce.Content; using Hotcakes.Commerce.Utilities; using Hotcakes.CommerceDTO.v1.Membership; namespace Hotcakes.Commerce.Membership { /// <summary> /// This is the primary class used to manage customer accounts. Many of these properties are duplicated in the CMS. /// </summary> [Serializable] public class CustomerAccount : IReplaceable { // Constructor public CustomerAccount() { Bvin = string.Empty; StoreId = 0; Email = string.Empty; FirstName = string.Empty; LastName = string.Empty; Password = string.Empty; TaxExempt = false; Notes = string.Empty; PricingGroupId = string.Empty; Locked = false; LockedUntilUtc = DateTime.UtcNow; FailedLoginCount = 0; LastUpdatedUtc = DateTime.UtcNow; CreationDateUtc = DateTime.UtcNow; LastLoginDateUtc = DateTime.UtcNow; BillingAddress = new Address(); ShippingAddress = new Address(); } /// <summary> /// The unique ID of the customer account /// </summary> public string Bvin { get; set; } /// <summary> /// This is the ID of the Hotcakes store. Typically, this is 1, except in multi-tenant environments. /// </summary> public long StoreId { get; set; } /// <summary> /// The primary email address for the customer and it is used to get their avatar from gravatar. /// </summary> public string Email { get; set; } /// <summary> /// The username of the customer in the CMS /// </summary> public string Username { get; set; } /// <summary> /// First name of the customer /// </summary> public string FirstName { get; set; } /// <summary> /// Last or surname of the customer /// </summary> public string LastName { get; set; } /// <summary> /// Encrypted password of the customer /// </summary> public string Password { get; set; } /// <summary> /// Address details for the primary shipping address /// </summary> public Address ShippingAddress { get; set; } /// <summary> /// Address details for billing the customer /// </summary> public Address BillingAddress { get; set; } /// <summary> /// Addresses from the customer's address book /// </summary> public AddressList Addresses { get { return _Addresses; } set { _Addresses = value; } } /// <summary> /// Culture that was used when placing last order /// </summary> public string LastUsedCulture { get; set; } /// <summary> /// Contains a list of phones for the customer /// </summary> /// <remarks>This doesn't appear to be populated anywhere. Might not be in use, or legacy code.</remarks> public PhoneNumberList Phones { get { return _Phones; } set { _Phones = value; } } // Other /// <summary> /// Defines whether the customer is exempt from paying taxes /// </summary> public bool TaxExempt { get; set; } /// <summary> /// If the customer is tax exempt, this number is used for tax reporting /// </summary> public string TaxExemptionNumber { get; set; } /// <summary> /// Notes about the customer /// </summary> public string Notes { get; set; } /// <summary> /// The unique ID (bvin) of the price group that this customer belongs to. /// </summary> /// <remarks>Enmpty string means that they are not part of any price group.</remarks> public string PricingGroupId { get; set; } // Security /// <summary> /// Defines whether the customer is locked out or the site or not /// </summary> /// <remarks>This normally happens due to too many invalid login attempts</remarks> public bool Locked { get; set; } /// <summary> /// The date that the user will become unlocked automatically /// </summary> public DateTime LockedUntilUtc { get; set; } /// <summary> /// The number of times that the customer failed to login /// </summary> public int FailedLoginCount { get; set; } // Tracking /// <summary> /// The date/time stamp of the last time the customer was updated /// </summary> public DateTime LastUpdatedUtc { get; set; } /// <summary> /// The date/time stamp of when the customer was created /// </summary> public DateTime CreationDateUtc { get; set; } /// <summary> /// The date/time stamp of the last time the customer logged in /// </summary> public DateTime LastLoginDateUtc { get; set; } /// <summary> /// Provides a listing of the tokens that the customer information can be replaced with in email templates /// </summary> /// <param name="context">An instance of the Hotcakes Request context object</param> /// <returns>List of name/value pairs of the tokens and replacement content</returns> public List<HtmlTemplateTag> GetReplaceableTags(HccRequestContext context) { var result = new List<HtmlTemplateTag>(); result.Add(new HtmlTemplateTag("[[User.Bvin]]", Bvin)); result.Add(new HtmlTemplateTag("[[User.Notes]]", Notes)); result.Add(new HtmlTemplateTag("[[User.CreationDate]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, CreationDateUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.Email]]", Email)); result.Add(new HtmlTemplateTag("[[User.UserName]]", Username)); result.Add(new HtmlTemplateTag("[[User.FirstName]]", FirstName)); result.Add(new HtmlTemplateTag("[[User.LastLoginDate]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, LastLoginDateUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.LastName]]", LastName)); result.Add(new HtmlTemplateTag("[[User.LastUpdated]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, LastUpdatedUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.Locked]]", Locked.ToString())); result.Add(new HtmlTemplateTag("[[User.LockedUntil]]", DateHelper.ConvertUtcToStoreTime(context.CurrentStore, LockedUntilUtc).ToString())); result.Add(new HtmlTemplateTag("[[User.Password]]", Password)); return result; } /// <summary> /// Verifies the passed address for the customer, and if new, updates the customer record with it /// </summary> /// <param name="address">New address object to compare against the customer's current address</param> /// <returns>Boolean - if true, the address was created</returns> public bool CheckIfNewAddressAndAddNoUpdate(Address address) { var addressFound = false; foreach (var currAddress in Addresses) { if (currAddress.IsEqualTo(address)) { addressFound = true; break; } } var createdAddress = false; if (!addressFound) { address.Bvin = Guid.NewGuid().ToString(); _Addresses.Add(address); createdAddress = true; } return createdAddress; } /// <summary> /// Finds the specified address and deletes it from the customer record /// </summary> /// <param name="bvin"></param> /// <returns></returns> public bool DeleteAddress(string bvin) { var result = false; var index = -1; for (var i = 0; i < _Addresses.Count; i++) { if (_Addresses[i].Bvin == bvin) { index = i; break; } } if (index >= 0) { _Addresses.RemoveAt(index); return true; } return result; } /// <summary> /// Updates the customer record with the given address /// </summary> /// <param name="a">The new address you want the customer to have</param> /// <returns>Boolean - if true, the update was successful</returns> public bool UpdateAddress(Address a) { var result = false; var index = -1; for (var i = 0; i < _Addresses.Count; i++) { if (_Addresses[i].Bvin == a.Bvin) { index = i; break; } } if (index >= 0) { _Addresses[index] = a; return true; } return result; } //DTO /// <summary> /// Allows you to convert the current customer account object to the DTO equivalent for use with the REST API /// </summary> /// <returns>A new instance of CustomerAccountDTO</returns> public CustomerAccountDTO ToDto() { var dto = new CustomerAccountDTO(); dto.Bvin = Bvin; dto.Email = Email; dto.FirstName = FirstName; dto.LastName = LastName; dto.Password = Password; dto.TaxExempt = TaxExempt; dto.Notes = Notes; dto.PricingGroupId = PricingGroupId; dto.FailedLoginCount = FailedLoginCount; dto.LastUpdatedUtc = LastUpdatedUtc; dto.CreationDateUtc = CreationDateUtc; dto.LastLoginDateUtc = LastLoginDateUtc; foreach (var a in Addresses) { dto.Addresses.Add(a.ToDto()); } dto.ShippingAddress = ShippingAddress.ToDto(); dto.BillingAddress = BillingAddress.ToDto(); return dto; } /// <summary> /// Allows you to populate the current customer account object using a CustomerAccount instance /// </summary> /// <param name="dto">An instance of the customer account from the REST API</param> public void FromDto(CustomerAccountDTO dto) { Bvin = dto.Bvin; Email = dto.Email; FirstName = dto.FirstName; LastName = dto.LastName; Password = dto.Password; TaxExempt = dto.TaxExempt; Notes = dto.Notes; PricingGroupId = dto.PricingGroupId; FailedLoginCount = dto.FailedLoginCount; LastUpdatedUtc = dto.LastUpdatedUtc; CreationDateUtc = dto.CreationDateUtc; LastLoginDateUtc = dto.LastLoginDateUtc; foreach (var a in dto.Addresses) { var addr = new Address(); addr.FromDto(a); Addresses.Add(addr); } ShippingAddress.FromDto(dto.ShippingAddress); BillingAddress.FromDto(dto.BillingAddress); } #region Fields // Addresses private AddressList _Addresses = new AddressList(); private PhoneNumberList _Phones = new PhoneNumberList(); #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="DistanceViewServiceClient"/> instances.</summary> public sealed partial class DistanceViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="DistanceViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="DistanceViewServiceSettings"/>.</returns> public static DistanceViewServiceSettings GetDefault() => new DistanceViewServiceSettings(); /// <summary>Constructs a new <see cref="DistanceViewServiceSettings"/> object with default settings.</summary> public DistanceViewServiceSettings() { } private DistanceViewServiceSettings(DistanceViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetDistanceViewSettings = existing.GetDistanceViewSettings; OnCopy(existing); } partial void OnCopy(DistanceViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>DistanceViewServiceClient.GetDistanceView</c> and <c>DistanceViewServiceClient.GetDistanceViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetDistanceViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="DistanceViewServiceSettings"/> object.</returns> public DistanceViewServiceSettings Clone() => new DistanceViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="DistanceViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class DistanceViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<DistanceViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public DistanceViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public DistanceViewServiceClientBuilder() { UseJwtAccessWithScopes = DistanceViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref DistanceViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<DistanceViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override DistanceViewServiceClient Build() { DistanceViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<DistanceViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<DistanceViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private DistanceViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return DistanceViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<DistanceViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return DistanceViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => DistanceViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => DistanceViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => DistanceViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>DistanceViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch distance views. /// </remarks> public abstract partial class DistanceViewServiceClient { /// <summary> /// The default endpoint for the DistanceViewService service, which is a host of "googleads.googleapis.com" and /// a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default DistanceViewService scopes.</summary> /// <remarks> /// The default DistanceViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="DistanceViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="DistanceViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="DistanceViewServiceClient"/>.</returns> public static stt::Task<DistanceViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new DistanceViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="DistanceViewServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use /// <see cref="DistanceViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="DistanceViewServiceClient"/>.</returns> public static DistanceViewServiceClient Create() => new DistanceViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="DistanceViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="DistanceViewServiceSettings"/>.</param> /// <returns>The created <see cref="DistanceViewServiceClient"/>.</returns> internal static DistanceViewServiceClient Create(grpccore::CallInvoker callInvoker, DistanceViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } DistanceViewService.DistanceViewServiceClient grpcClient = new DistanceViewService.DistanceViewServiceClient(callInvoker); return new DistanceViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC DistanceViewService client</summary> public virtual DistanceViewService.DistanceViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::DistanceView GetDistanceView(GetDistanceViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::DistanceView> GetDistanceViewAsync(GetDistanceViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::DistanceView> GetDistanceViewAsync(GetDistanceViewRequest request, st::CancellationToken cancellationToken) => GetDistanceViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the distance view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::DistanceView GetDistanceView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetDistanceView(new GetDistanceViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the distance view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::DistanceView> GetDistanceViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetDistanceViewAsync(new GetDistanceViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the distance view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::DistanceView> GetDistanceViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetDistanceViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the distance view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::DistanceView GetDistanceView(gagvr::DistanceViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetDistanceView(new GetDistanceViewRequest { ResourceNameAsDistanceViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the distance view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::DistanceView> GetDistanceViewAsync(gagvr::DistanceViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetDistanceViewAsync(new GetDistanceViewRequest { ResourceNameAsDistanceViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the distance view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::DistanceView> GetDistanceViewAsync(gagvr::DistanceViewName resourceName, st::CancellationToken cancellationToken) => GetDistanceViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>DistanceViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch distance views. /// </remarks> public sealed partial class DistanceViewServiceClientImpl : DistanceViewServiceClient { private readonly gaxgrpc::ApiCall<GetDistanceViewRequest, gagvr::DistanceView> _callGetDistanceView; /// <summary> /// Constructs a client wrapper for the DistanceViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="DistanceViewServiceSettings"/> used within this client.</param> public DistanceViewServiceClientImpl(DistanceViewService.DistanceViewServiceClient grpcClient, DistanceViewServiceSettings settings) { GrpcClient = grpcClient; DistanceViewServiceSettings effectiveSettings = settings ?? DistanceViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetDistanceView = clientHelper.BuildApiCall<GetDistanceViewRequest, gagvr::DistanceView>(grpcClient.GetDistanceViewAsync, grpcClient.GetDistanceView, effectiveSettings.GetDistanceViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetDistanceView); Modify_GetDistanceViewApiCall(ref _callGetDistanceView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetDistanceViewApiCall(ref gaxgrpc::ApiCall<GetDistanceViewRequest, gagvr::DistanceView> call); partial void OnConstruction(DistanceViewService.DistanceViewServiceClient grpcClient, DistanceViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC DistanceViewService client</summary> public override DistanceViewService.DistanceViewServiceClient GrpcClient { get; } partial void Modify_GetDistanceViewRequest(ref GetDistanceViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::DistanceView GetDistanceView(GetDistanceViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetDistanceViewRequest(ref request, ref callSettings); return _callGetDistanceView.Sync(request, callSettings); } /// <summary> /// Returns the attributes of the requested distance view. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::DistanceView> GetDistanceViewAsync(GetDistanceViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetDistanceViewRequest(ref request, ref callSettings); return _callGetDistanceView.Async(request, callSettings); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A sports location, such as a playing field. /// </summary> public class SportsActivityLocation_Core : TypeCore, ILocalBusiness { public SportsActivityLocation_Core() { this._TypeId = 246; this._Id = "SportsActivityLocation"; this._Schema_Org_Url = "http://schema.org/SportsActivityLocation"; string label = ""; GetLabel(out label, "SportsActivityLocation", typeof(SportsActivityLocation_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155}; this._SubTypes = new int[]{44,100,115,124,218,243,247,250,263}; this._SuperTypes = new int[]{155}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
//------------------------------------------------------------------------------ // <copyright file="XmlAttributes.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.Reflection; using System.Collections; using System.ComponentModel; internal enum XmlAttributeFlags { Enum = 0x1, Array = 0x2, Text = 0x4, ArrayItems = 0x8, Elements = 0x10, Attribute = 0x20, Root = 0x40, Type = 0x80, AnyElements = 0x100, AnyAttribute = 0x200, ChoiceIdentifier = 0x400, XmlnsDeclarations = 0x800, } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlAttributes { XmlElementAttributes xmlElements = new XmlElementAttributes(); XmlArrayItemAttributes xmlArrayItems = new XmlArrayItemAttributes(); XmlAnyElementAttributes xmlAnyElements = new XmlAnyElementAttributes(); XmlArrayAttribute xmlArray; XmlAttributeAttribute xmlAttribute; XmlTextAttribute xmlText; XmlEnumAttribute xmlEnum; bool xmlIgnore; bool xmlns; object xmlDefaultValue = null; XmlRootAttribute xmlRoot; XmlTypeAttribute xmlType; XmlAnyAttributeAttribute xmlAnyAttribute; XmlChoiceIdentifierAttribute xmlChoiceIdentifier; static volatile Type ignoreAttributeType; /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlAttributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes() { } internal XmlAttributeFlags XmlFlags { get { XmlAttributeFlags flags = 0; if (xmlElements.Count > 0) flags |= XmlAttributeFlags.Elements; if (xmlArrayItems.Count > 0) flags |= XmlAttributeFlags.ArrayItems; if (xmlAnyElements.Count > 0) flags |= XmlAttributeFlags.AnyElements; if (xmlArray != null) flags |= XmlAttributeFlags.Array; if (xmlAttribute != null) flags |= XmlAttributeFlags.Attribute; if (xmlText != null) flags |= XmlAttributeFlags.Text; if (xmlEnum != null) flags |= XmlAttributeFlags.Enum; if (xmlRoot != null) flags |= XmlAttributeFlags.Root; if (xmlType != null) flags |= XmlAttributeFlags.Type; if (xmlAnyAttribute != null) flags |= XmlAttributeFlags.AnyAttribute; if (xmlChoiceIdentifier != null) flags |= XmlAttributeFlags.ChoiceIdentifier; if (xmlns) flags |= XmlAttributeFlags.XmlnsDeclarations; return flags; } } private static Type IgnoreAttribute { get { if (ignoreAttributeType == null) { ignoreAttributeType = typeof(object).Assembly.GetType("System.XmlIgnoreMemberAttribute"); if (ignoreAttributeType == null) { ignoreAttributeType = typeof(XmlIgnoreAttribute); } } return ignoreAttributeType; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlAttributes1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributes(ICustomAttributeProvider provider) { object[] attrs = provider.GetCustomAttributes(false); // most generic <any/> matches everithig XmlAnyElementAttribute wildcard = null; for (int i = 0; i < attrs.Length; i++) { if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute) { xmlIgnore = true; break; } else if (attrs[i] is XmlElementAttribute) { this.xmlElements.Add((XmlElementAttribute)attrs[i]); } else if (attrs[i] is XmlArrayItemAttribute) { this.xmlArrayItems.Add((XmlArrayItemAttribute)attrs[i]); } else if (attrs[i] is XmlAnyElementAttribute) { XmlAnyElementAttribute any = (XmlAnyElementAttribute)attrs[i]; if ((any.Name == null || any.Name.Length == 0) && any.NamespaceSpecified && any.Namespace == null) { // ignore duplicate wildcards wildcard = any; } else { this.xmlAnyElements.Add((XmlAnyElementAttribute)attrs[i]); } } else if (attrs[i] is DefaultValueAttribute) { this.xmlDefaultValue = ((DefaultValueAttribute)attrs[i]).Value; } else if (attrs[i] is XmlAttributeAttribute) { this.xmlAttribute = (XmlAttributeAttribute)attrs[i]; } else if (attrs[i] is XmlArrayAttribute) { this.xmlArray = (XmlArrayAttribute)attrs[i]; } else if (attrs[i] is XmlTextAttribute) { this.xmlText = (XmlTextAttribute)attrs[i]; } else if (attrs[i] is XmlEnumAttribute) { this.xmlEnum = (XmlEnumAttribute)attrs[i]; } else if (attrs[i] is XmlRootAttribute) { this.xmlRoot = (XmlRootAttribute)attrs[i]; } else if (attrs[i] is XmlTypeAttribute) { this.xmlType = (XmlTypeAttribute)attrs[i]; } else if (attrs[i] is XmlAnyAttributeAttribute) { this.xmlAnyAttribute = (XmlAnyAttributeAttribute)attrs[i]; } else if (attrs[i] is XmlChoiceIdentifierAttribute) { this.xmlChoiceIdentifier = (XmlChoiceIdentifierAttribute)attrs[i]; } else if (attrs[i] is XmlNamespaceDeclarationsAttribute) { this.xmlns = true; } } if (xmlIgnore) { this.xmlElements.Clear(); this.xmlArrayItems.Clear(); this.xmlAnyElements.Clear(); this.xmlDefaultValue = null; this.xmlAttribute = null; this.xmlArray = null; this.xmlText = null; this.xmlEnum = null; this.xmlType = null; this.xmlAnyAttribute = null; this.xmlChoiceIdentifier = null; this.xmlns = false; } else { if (wildcard != null) { this.xmlAnyElements.Add(wildcard); } } } internal static object GetAttr(ICustomAttributeProvider provider, Type attrType) { object[] attrs = provider.GetCustomAttributes(attrType, false); if (attrs.Length == 0) return null; return attrs[0]; } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlElements"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlElementAttributes XmlElements { get { return xmlElements; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAttributeAttribute XmlAttribute { get { return xmlAttribute; } set { xmlAttribute = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlEnum"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlEnumAttribute XmlEnum { get { return xmlEnum; } set { xmlEnum = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlText"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTextAttribute XmlText { get { return xmlText; } set { xmlText = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlArray"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlArrayAttribute XmlArray { get { return xmlArray; } set { xmlArray = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlArrayItems"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlArrayItemAttributes XmlArrayItems { get { return xmlArrayItems; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlDefaultValue"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public object XmlDefaultValue { get { return xmlDefaultValue; } set { xmlDefaultValue = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlIgnore"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool XmlIgnore { get { return xmlIgnore; } set { xmlIgnore = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlType"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlTypeAttribute XmlType { get { return xmlType; } set { xmlType = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlRoot"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlRootAttribute XmlRoot { get { return xmlRoot; } set { xmlRoot = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlAnyElement"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAnyElementAttributes XmlAnyElements { get { return xmlAnyElements; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlAnyAttribute"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlAnyAttributeAttribute XmlAnyAttribute { get { return xmlAnyAttribute; } set { xmlAnyAttribute = value; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.XmlChoiceIdentifier"]/*' /> public XmlChoiceIdentifierAttribute XmlChoiceIdentifier { get { return xmlChoiceIdentifier; } } /// <include file='doc\XmlAttributes.uex' path='docs/doc[@for="XmlAttributes.Xmlns"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Xmlns { get { return xmlns; } set { xmlns = value; } } } }
namespace Cronofy { using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Class representing an event. /// </summary> public sealed class Event { /// <summary> /// Gets or sets the ID of the calendar the event is within. /// </summary> /// <value> /// The ID of the calendar the event is within. /// </value> public string CalendarId { get; set; } /// <summary> /// Gets or sets the OAuth application's ID for the event, if it is /// an event the OAuth application is managing. /// </summary> /// <value> /// The OAuth application's ID for the event, <c>null</c> if the /// OAuth application is not managing this event. /// </value> public string EventId { get; set; } /// <summary> /// Gets or sets the UID of the event. /// </summary> /// <value> /// The UID of the event. /// </value> public string EventUid { get; set; } /// <summary> /// Gets or sets the Google event ID of the event. /// </summary> /// <value> /// The Google event ID of the event. /// </value> public string GoogleEventId { get; set; } /// <summary> /// Gets or sets the event's summary. /// </summary> /// <value> /// The event's summary. /// </value> public string Summary { get; set; } /// <summary> /// Gets or sets the event's description. /// </summary> /// <value> /// The event's description. /// </value> public string Description { get; set; } /// <summary> /// Gets or sets the start time of the event. /// </summary> /// <value> /// The start time of the event. /// </value> public EventTime Start { get; set; } /// <summary> /// Gets or sets the end time of the event. /// </summary> /// <value> /// The end time of the event. /// </value> public EventTime End { get; set; } /// <summary> /// Gets or sets the location of the event. /// </summary> /// <value> /// The location of the event. /// </value> public Location Location { get; set; } /// <summary> /// Gets or sets a value indicating whether this event has been /// deleted. /// </summary> /// <value> /// <c>true</c> if the event has been deleted; otherwise, /// <c>false</c>. /// </value> public bool Deleted { get; set; } /// <summary> /// Gets or sets the account's participation status. /// </summary> /// <value> /// The account's participation status. /// </value> /// <remarks> /// See <see cref="Cronofy.AttendeeStatus"/> for potential values. /// </remarks> public string ParticipationStatus { get; set; } /// <summary> /// Gets or sets the transparency of the event. /// </summary> /// <value> /// The transparency of the event. /// </value> /// <remarks> /// See <see cref="Cronofy.Transparency"/> for potential values. /// </remarks> public string Transparency { get; set; } /// <summary> /// Gets or sets the status of the event. /// </summary> /// <value> /// The status of the event. /// </value> /// <remarks> /// See <see cref="Cronofy.EventStatus"/> for potential values. /// </remarks> public string EventStatus { get; set; } /// <summary> /// Gets or sets the categories assigned to the event. /// </summary> /// <value> /// The categories assigned to the event. /// </value> public string[] Categories { get; set; } /// <summary> /// Gets or sets the time the event was created. /// </summary> /// <value> /// The time the event was created. /// </value> public DateTime Created { get; set; } /// <summary> /// Gets or sets the time the event was last updated. /// </summary> /// <value> /// The time the event was last updated. /// </value> public DateTime Updated { get; set; } /// <summary> /// Gets or sets the event's attendees. /// </summary> /// <value> /// The event's attendees. /// </value> public Attendee[] Attendees { get; set; } /// <summary> /// Gets or sets the event's organizer. /// </summary> /// <value> /// The event's Organizer. /// </value> public Organizer Organizer { get; set; } /// <summary> /// Gets or sets a value indicating whether this event is a /// recurring event. /// </summary> /// <value> /// <c>true</c> if the event is a recurring event; otherwise, /// <c>false</c>. /// </value> public bool Recurring { get; set; } /// <summary> /// Gets or sets a value indicating whether this event is private. /// </summary> /// <value> /// The event is private only set on event creation. /// </value> public bool EventPrivate { get; set; } /// <summary> /// Gets or sets the permissable options for this event. /// </summary> /// <value> /// The event's options. /// </value> public EventOptions Options { get; set; } /// <summary> /// Gets or sets a value for the event's meeting URL. /// </summary> /// <value> /// The event's meeting URL. /// </value> public string MeetingUrl { get; set; } /// <inheritdoc/> public override int GetHashCode() { return this.EventUid.GetHashCode(); } /// <inheritdoc/> public override bool Equals(object obj) { var other = obj as Event; if (other == null) { return false; } return this.Equals(other); } /// <summary> /// Determines whether the specified <see cref="Cronofy.Event"/> is /// equal to the current <see cref="Cronofy.Event"/>. /// </summary> /// <param name="other"> /// The <see cref="Cronofy.Event"/> to compare with the current /// <see cref="Cronofy.Event"/>. /// </param> /// <returns> /// <c>true</c> if the specified <see cref="Cronofy.Event"/> is equal to /// the current <see cref="Cronofy.Event"/>; otherwise, <c>false</c>. /// </returns> public bool Equals(Event other) { return other != null && this.EventUid == other.EventUid && this.GoogleEventId == other.GoogleEventId && this.EventId == other.EventId && this.CalendarId == other.CalendarId && this.Created == other.Created && this.Updated == other.Updated && this.Deleted == other.Deleted && this.Summary == other.Summary && this.Description == other.Description && this.ParticipationStatus == other.ParticipationStatus && this.Transparency == other.Transparency && this.EventStatus == other.EventStatus && this.Recurring == other.Recurring && this.MeetingUrl == other.MeetingUrl && object.Equals(this.Organizer, other.Organizer) && object.Equals(this.Location, other.Location) && object.Equals(this.Start, other.Start) && object.Equals(this.End, other.End) && EnumerableUtils.NullTolerantSequenceEqual(this.Attendees, other.Attendees) && EnumerableUtils.NullTolerantSequenceEqual(this.Categories, other.Categories); } /// <inheritdoc/> public override string ToString() { return string.Format( "<{0} CalendarId={1}, EventId={2}, EventUid={3}, Summary={4}, Start={5}, End={6}, Deleted={7}, Recurring={8}, Attendees={9}, Organizer={10}>", this.GetType(), this.CalendarId, this.EventId, this.EventUid, this.Summary, this.Start, this.End, this.Deleted, this.Recurring, this.Attendees, this.Organizer); } } }
#if !NETFX_CORE && !(ANDROID || IOS) //----------------------------------------------------------------------- // <copyright file="ConnectionManager.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>Provides an automated way to reuse open</summary> //----------------------------------------------------------------------- using System; using System.Configuration; using System.Data; using System.Data.Common; using Csla.Properties; namespace Csla.Data { /// <summary> /// Provides an automated way to reuse open /// database connections within the context /// of a single data portal operation. /// </summary> /// <remarks> /// This type stores the open database connection /// in <see cref="Csla.ApplicationContext.LocalContext" /> /// and uses reference counting through /// <see cref="IDisposable" /> to keep the connection /// open for reuse by child objects, and to automatically /// dispose the connection when the last consumer /// has called Dispose." /// </remarks> public class ConnectionManager : IDisposable { private static object _lock = new object(); private IDbConnection _connection; private string _connectionString; private string _label; /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// Database name as shown in the config file. /// </param> public static ConnectionManager GetManager(string database) { return GetManager(database, true); } /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// Database name as shown in the config file. /// </param> /// <param name="label">Label for this connection.</param> public static ConnectionManager GetManager(string database, string label) { return GetManager(database, true, label); } /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// The database name or connection string. /// </param> /// <param name="isDatabaseName"> /// True to indicate that the connection string /// should be retrieved from the config file. If /// False, the database parameter is directly /// used as a connection string. /// </param> /// <returns>ConnectionManager object for the name.</returns> public static ConnectionManager GetManager(string database, bool isDatabaseName) { return GetManager(database, isDatabaseName, "default"); } /// <summary> /// Gets the ConnectionManager object for the /// specified database. /// </summary> /// <param name="database"> /// The database name or connection string. /// </param> /// <param name="isDatabaseName"> /// True to indicate that the connection string /// should be retrieved from the config file. If /// False, the database parameter is directly /// used as a connection string. /// </param> /// <param name="label">Label for this connection.</param> /// <returns>ConnectionManager object for the name.</returns> public static ConnectionManager GetManager(string database, bool isDatabaseName, string label) { if (isDatabaseName) { var connection = ConfigurationManager.ConnectionStrings[database]; if (connection == null) throw new ConfigurationErrorsException(String.Format(Resources.DatabaseNameNotFound, database)); var conn = ConfigurationManager.ConnectionStrings[database].ConnectionString; if (string.IsNullOrEmpty(conn)) throw new ConfigurationErrorsException(String.Format(Resources.DatabaseNameNotFound, database)); database = conn; } lock (_lock) { var ctxName = GetContextName(database, label); ConnectionManager mgr = null; if (ApplicationContext.LocalContext.Contains(ctxName)) { mgr = (ConnectionManager)(ApplicationContext.LocalContext[ctxName]); } else { mgr = new ConnectionManager(database, label); ApplicationContext.LocalContext[ctxName] = mgr; } mgr.AddRef(); return mgr; } } private ConnectionManager(string connectionString, string label) { _label = label; _connectionString = connectionString; string provider = ConfigurationManager.AppSettings["dbProvider"]; if (string.IsNullOrEmpty(provider)) provider = "System.Data.SqlClient"; DbProviderFactory factory = DbProviderFactories.GetFactory(provider); // open connection _connection = factory.CreateConnection(); _connection.ConnectionString = connectionString; _connection.Open(); } private static string GetContextName(string connectionString, string label) { return "__db:" + label + "-" + connectionString; } /// <summary> /// Dispose object, dereferencing or /// disposing the connection it is /// managing. /// </summary> public IDbConnection Connection { get { return _connection; } } #region Reference counting private int _refCount; /// <summary> /// Gets the current reference count for this /// object. /// </summary> public int RefCount { get { return _refCount; } } private void AddRef() { _refCount += 1; } private void DeRef() { lock (_lock) { _refCount -= 1; if (_refCount == 0) { _connection.Dispose(); ApplicationContext.LocalContext.Remove(GetContextName(_connectionString, _label)); } } } #endregion #region IDisposable /// <summary> /// Dispose object, dereferencing or /// disposing the connection it is /// managing. /// </summary> public void Dispose() { DeRef(); } #endregion } } #endif
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using Fungus; namespace Fungus { /** * Controller for main camera. * Supports several types of camera transition including snap, pan & fade. */ public class CameraController : MonoBehaviour { Game game; Camera mainCamera; float fadeAlpha = 0f; void Start() { game = Game.GetInstance(); GameObject cameraObject = GameObject.FindGameObjectWithTag("MainCamera"); if (cameraObject == null) { Debug.LogError("Failed to find game object with tag 'MainCamera'"); return; } mainCamera = cameraObject.GetComponent<Camera>(); if (mainCamera == null) { Debug.LogError("Failed to find camera component"); return; } } void OnGUI() { int drawDepth = -1000; if (fadeAlpha < 1f) { // 1 = scene fully visible // 0 = scene fully obscured GUI.color = new Color(1,1,1, 1f - fadeAlpha); GUI.depth = drawDepth; GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), game.fadeTexture); } } public void Fade(float targetAlpha, float fadeDuration, Action fadeAction) { StartCoroutine(FadeInternal(targetAlpha, fadeDuration, fadeAction)); } public void FadeToView(View view, float fadeDuration, Action fadeAction) { // Fade out Fade(0f, fadeDuration / 2f, delegate { // Snap to new view PanToView(view, 0f, null); // Fade in Fade(1f, fadeDuration / 2f, delegate { if (fadeAction != null) { fadeAction(); } }); }); } IEnumerator FadeInternal(float targetAlpha, float fadeDuration, Action fadeAction) { float startAlpha = fadeAlpha; float timer = 0; while (timer < fadeDuration) { float t = timer / fadeDuration; timer += Time.deltaTime; t = Mathf.Clamp01(t); fadeAlpha = Mathf.Lerp(startAlpha, targetAlpha, t); yield return null; } fadeAlpha = targetAlpha; if (fadeAction != null) { fadeAction(); } } /** * Positions camera so sprite is centered and fills the screen. * @param spriteRenderer The sprite to center the camera on */ public void CenterOnSprite(SpriteRenderer spriteRenderer) { Sprite sprite = spriteRenderer.sprite; Vector3 extents = sprite.bounds.extents; float localScaleY = spriteRenderer.transform.localScale.y; mainCamera.orthographicSize = extents.y * localScaleY; Vector3 pos = spriteRenderer.transform.position; mainCamera.transform.position = new Vector3(pos.x, pos.y, 0); SetCameraZ(); } public void SnapToView(View view) { PanToView(view, 0, null); } /** * Moves camera from current position to a target View over a period of time. */ public void PanToView(View view, float duration, Action arriveAction) { if (duration == 0f) { // Move immediately mainCamera.orthographicSize = view.viewSize; mainCamera.transform.position = view.transform.position; SetCameraZ(); if (arriveAction != null) { arriveAction(); } } else { StartCoroutine(PanInternal(view, duration, arriveAction)); } } IEnumerator PanInternal(View view, float duration, Action arriveAction) { float timer = 0; float startSize = mainCamera.orthographicSize; float endSize = view.viewSize; Vector3 startPos = mainCamera.transform.position; Vector3 endPos = view.transform.position; bool arrived = false; while (!arrived) { timer += Time.deltaTime; if (timer > duration) { arrived = true; timer = duration; } // Apply smoothed lerp to camera position and orthographic size float t = timer / duration; mainCamera.orthographicSize = Mathf.Lerp(startSize, endSize, Mathf.SmoothStep(0f, 1f, t)); mainCamera.transform.position = Vector3.Lerp(startPos, endPos, Mathf.SmoothStep(0f, 1f, t)); SetCameraZ(); if (arrived && arriveAction != null) { arriveAction(); } yield return null; } } /** * Moves camera smoothly through a sequence of Views over a period of time */ public void PanToPath(View[] viewList, float duration, Action arriveAction) { List<Vector3> pathList = new List<Vector3>(); // Add current camera position as first point in path // Note: We use the z coord to tween the camera orthographic size Vector3 startPos = new Vector3(mainCamera.transform.position.x, mainCamera.transform.position.y, mainCamera.orthographicSize); pathList.Add(startPos); for (int i = 0; i < viewList.Length; ++i) { View view = viewList[i]; Vector3 viewPos = new Vector3(view.transform.position.x, view.transform.position.y, view.viewSize); pathList.Add(viewPos); } StartCoroutine(PanToPathInternal(duration, arriveAction, pathList.ToArray())); } IEnumerator PanToPathInternal(float duration, Action arriveAction, Vector3[] path) { float timer = 0; while (timer < duration) { timer += Time.deltaTime; timer = Mathf.Min(timer, duration); float percent = timer / duration; Vector3 point = iTween.PointOnPath(path, percent); mainCamera.transform.position = new Vector3(point.x, point.y, 0); mainCamera.orthographicSize = point.z; SetCameraZ(); yield return null; } if (arriveAction != null) { arriveAction(); } } void SetCameraZ() { mainCamera.transform.position = new Vector3(mainCamera.transform.position.x, mainCamera.transform.position.y, game.cameraZ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Reflection.Metadata.Ecma335 { public static class MetadataTokens { /// <summary> /// Maximum number of tables that can be present in Ecma335 metadata. /// </summary> public static readonly int TableCount = TableIndexExtensions.Count; /// <summary> /// Maximum number of tables that can be present in Ecma335 metadata. /// </summary> public static readonly int HeapCount = HeapIndexExtensions.Count; /// <summary> /// Returns the row number of a metadata table entry that corresponds /// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>One based row number.</returns> /// <exception cref="ArgumentException">The <paramref name="handle"/> is not a valid metadata table handle.</exception> public static int GetRowNumber(this MetadataReader reader, EntityHandle handle) { if (handle.IsVirtual) { return MapVirtualHandleRowId(reader, handle); } return handle.RowId; } /// <summary> /// Returns the offset of metadata heap data that corresponds /// to the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>Zero based offset, or -1 if <paramref name="handle"/> isn't a metadata heap handle.</returns> /// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="handle"/> is invalid.</exception> public static int GetHeapOffset(this MetadataReader reader, Handle handle) { if (!handle.IsHeapHandle) { Throw.HeapHandleRequired(); } if (handle.IsVirtual) { return MapVirtualHandleRowId(reader, handle); } return handle.Offset; } /// <summary> /// Returns the metadata token of the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>Metadata token.</returns> /// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception> public static int GetToken(this MetadataReader reader, EntityHandle handle) { if (handle.IsVirtual) { return (int)handle.Type | MapVirtualHandleRowId(reader, handle); } return handle.Token; } /// <summary> /// Returns the metadata token of the specified <paramref name="handle"/> in the context of <paramref name="reader"/>. /// </summary> /// <returns>Metadata token.</returns> /// <exception cref="ArgumentException"> /// Handle represents a metadata entity that doesn't have a token. /// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>. /// </exception> /// <exception cref="NotSupportedException">The operation is not supported for the specified <paramref name="handle"/>.</exception> public static int GetToken(this MetadataReader reader, Handle handle) { if (!handle.IsEntityOrUserStringHandle) { Throw.EntityOrUserStringHandleRequired(); } if (handle.IsVirtual) { return (int)handle.EntityHandleType | MapVirtualHandleRowId(reader, handle); } return handle.Token; } private static int MapVirtualHandleRowId(MetadataReader reader, Handle handle) { switch (handle.Kind) { case HandleKind.AssemblyReference: // pretend that virtual rows immediately follow real rows: return reader.AssemblyRefTable.NumberOfNonVirtualRows + 1 + handle.RowId; case HandleKind.String: case HandleKind.Blob: // We could precalculate offsets for virtual strings and blobs as we are creating them // if we wanted to implement this. throw new NotSupportedException(SR.CantGetOffsetForVirtualHeapHandle); default: throw new ArgumentException(SR.InvalidHandle, nameof(handle)); } } /// <summary> /// Returns the row number of a metadata table entry that corresponds /// to the specified <paramref name="handle"/>. /// </summary> /// <returns> /// One based row number, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetRowNumber(MetadataReader, EntityHandle)"/>. /// </returns> public static int GetRowNumber(EntityHandle handle) { return handle.IsVirtual ? -1 : handle.RowId; } /// <summary> /// Returns the offset of metadata heap data that corresponds /// to the specified <paramref name="handle"/>. /// </summary> /// <returns> /// Zero based offset, or -1 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetHeapOffset(MetadataReader, Handle)"/>. /// </returns> public static int GetHeapOffset(Handle handle) { if (!handle.IsHeapHandle) { Throw.HeapHandleRequired(); } if (handle.IsVirtual) { return -1; } return handle.Offset; } /// <summary> /// Returns the metadata token of the specified <paramref name="handle"/>. /// </summary> /// <returns> /// Metadata token, or 0 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetToken(MetadataReader, Handle)"/>. /// </returns> /// <exception cref="ArgumentException"> /// Handle represents a metadata entity that doesn't have a token. /// A token can only be retrieved for a metadata table handle or a heap handle of type <see cref="HandleKind.UserString"/>. /// </exception> public static int GetToken(Handle handle) { if (!handle.IsEntityOrUserStringHandle) { Throw.EntityOrUserStringHandleRequired(); } if (handle.IsVirtual) { return 0; } return handle.Token; } /// <summary> /// Returns the metadata token of the specified <paramref name="handle"/>. /// </summary> /// <returns> /// Metadata token, or 0 if <paramref name="handle"/> can only be interpreted in a context of a specific <see cref="MetadataReader"/>. /// See <see cref="GetToken(MetadataReader, EntityHandle)"/>. /// </returns> public static int GetToken(EntityHandle handle) { return handle.IsVirtual ? 0 : handle.Token; } /// <summary> /// Gets the <see cref="TableIndex"/> of the table corresponding to the specified <see cref="HandleKind"/>. /// </summary> /// <param name="type">Handle type.</param> /// <param name="index">Table index.</param> /// <returns>True if the handle type corresponds to an Ecma335 table, false otherwise.</returns> public static bool TryGetTableIndex(HandleKind type, out TableIndex index) { if ((int)type < TableIndexExtensions.Count) { index = (TableIndex)type; return true; } index = 0; return false; } /// <summary> /// Gets the <see cref="HeapIndex"/> of the heap corresponding to the specified <see cref="HandleKind"/>. /// </summary> /// <param name="type">Handle type.</param> /// <param name="index">Heap index.</param> /// <returns>True if the handle type corresponds to an Ecma335 heap, false otherwise.</returns> public static bool TryGetHeapIndex(HandleKind type, out HeapIndex index) { switch (type) { case HandleKind.UserString: index = HeapIndex.UserString; return true; case HandleKind.String: case HandleKind.NamespaceDefinition: index = HeapIndex.String; return true; case HandleKind.Blob: index = HeapIndex.Blob; return true; case HandleKind.Guid: index = HeapIndex.Guid; return true; default: index = 0; return false; } } #region Handle Factories /// <summary> /// Creates a handle from a token value. /// </summary> /// <exception cref="ArgumentException"> /// <paramref name="token"/> is not a valid metadata token. /// It must encode a metadata table entity or an offset in <see cref="HandleKind.UserString"/> heap. /// </exception> public static Handle Handle(int token) { if (!TokenTypeIds.IsEntityOrUserStringToken(unchecked((uint)token))) { Throw.InvalidToken(); } return Metadata.Handle.FromVToken((uint)token); } /// <summary> /// Creates an entity handle from a token value. /// </summary> /// <exception cref="ArgumentException"><paramref name="token"/> is not a valid metadata entity token.</exception> public static EntityHandle EntityHandle(int token) { if (!TokenTypeIds.IsEntityToken(unchecked((uint)token))) { Throw.InvalidToken(); } return new EntityHandle((uint)token); } /// <summary> /// Creates an <see cref="Metadata.EntityHandle"/> from a token value. /// </summary> /// <exception cref="ArgumentException"> /// <paramref name="tableIndex"/> is not a valid table index.</exception> public static EntityHandle EntityHandle(TableIndex tableIndex, int rowNumber) { return Handle(tableIndex, rowNumber); } /// <summary> /// Creates an <see cref="Metadata.EntityHandle"/> from a token value. /// </summary> /// <exception cref="ArgumentException"> /// <paramref name="tableIndex"/> is not a valid table index.</exception> public static EntityHandle Handle(TableIndex tableIndex, int rowNumber) { int token = ((int)tableIndex << TokenTypeIds.RowIdBitCount) | rowNumber; if (!TokenTypeIds.IsEntityOrUserStringToken(unchecked((uint)token))) { Throw.TableIndexOutOfRange(); } return new EntityHandle((uint)token); } private static int ToRowId(int rowNumber) { return rowNumber & (int)TokenTypeIds.RIDMask; } public static MethodDefinitionHandle MethodDefinitionHandle(int rowNumber) { return Metadata.MethodDefinitionHandle.FromRowId(ToRowId(rowNumber)); } public static MethodImplementationHandle MethodImplementationHandle(int rowNumber) { return Metadata.MethodImplementationHandle.FromRowId(ToRowId(rowNumber)); } public static MethodSpecificationHandle MethodSpecificationHandle(int rowNumber) { return Metadata.MethodSpecificationHandle.FromRowId(ToRowId(rowNumber)); } public static TypeDefinitionHandle TypeDefinitionHandle(int rowNumber) { return Metadata.TypeDefinitionHandle.FromRowId(ToRowId(rowNumber)); } public static ExportedTypeHandle ExportedTypeHandle(int rowNumber) { return Metadata.ExportedTypeHandle.FromRowId(ToRowId(rowNumber)); } public static TypeReferenceHandle TypeReferenceHandle(int rowNumber) { return Metadata.TypeReferenceHandle.FromRowId(ToRowId(rowNumber)); } public static TypeSpecificationHandle TypeSpecificationHandle(int rowNumber) { return Metadata.TypeSpecificationHandle.FromRowId(ToRowId(rowNumber)); } public static InterfaceImplementationHandle InterfaceImplementationHandle(int rowNumber) { return Metadata.InterfaceImplementationHandle.FromRowId(ToRowId(rowNumber)); } public static MemberReferenceHandle MemberReferenceHandle(int rowNumber) { return Metadata.MemberReferenceHandle.FromRowId(ToRowId(rowNumber)); } public static FieldDefinitionHandle FieldDefinitionHandle(int rowNumber) { return Metadata.FieldDefinitionHandle.FromRowId(ToRowId(rowNumber)); } public static EventDefinitionHandle EventDefinitionHandle(int rowNumber) { return Metadata.EventDefinitionHandle.FromRowId(ToRowId(rowNumber)); } public static PropertyDefinitionHandle PropertyDefinitionHandle(int rowNumber) { return Metadata.PropertyDefinitionHandle.FromRowId(ToRowId(rowNumber)); } public static StandaloneSignatureHandle StandaloneSignatureHandle(int rowNumber) { return Metadata.StandaloneSignatureHandle.FromRowId(ToRowId(rowNumber)); } public static ParameterHandle ParameterHandle(int rowNumber) { return Metadata.ParameterHandle.FromRowId(ToRowId(rowNumber)); } public static GenericParameterHandle GenericParameterHandle(int rowNumber) { return Metadata.GenericParameterHandle.FromRowId(ToRowId(rowNumber)); } public static GenericParameterConstraintHandle GenericParameterConstraintHandle(int rowNumber) { return Metadata.GenericParameterConstraintHandle.FromRowId(ToRowId(rowNumber)); } public static ModuleReferenceHandle ModuleReferenceHandle(int rowNumber) { return Metadata.ModuleReferenceHandle.FromRowId(ToRowId(rowNumber)); } public static AssemblyReferenceHandle AssemblyReferenceHandle(int rowNumber) { return Metadata.AssemblyReferenceHandle.FromRowId(ToRowId(rowNumber)); } public static CustomAttributeHandle CustomAttributeHandle(int rowNumber) { return Metadata.CustomAttributeHandle.FromRowId(ToRowId(rowNumber)); } public static DeclarativeSecurityAttributeHandle DeclarativeSecurityAttributeHandle(int rowNumber) { return Metadata.DeclarativeSecurityAttributeHandle.FromRowId(ToRowId(rowNumber)); } public static ConstantHandle ConstantHandle(int rowNumber) { return Metadata.ConstantHandle.FromRowId(ToRowId(rowNumber)); } public static ManifestResourceHandle ManifestResourceHandle(int rowNumber) { return Metadata.ManifestResourceHandle.FromRowId(ToRowId(rowNumber)); } public static AssemblyFileHandle AssemblyFileHandle(int rowNumber) { return Metadata.AssemblyFileHandle.FromRowId(ToRowId(rowNumber)); } // debug public static DocumentHandle DocumentHandle(int rowNumber) { return Metadata.DocumentHandle.FromRowId(ToRowId(rowNumber)); } public static MethodDebugInformationHandle MethodDebugInformationHandle(int rowNumber) { return Metadata.MethodDebugInformationHandle.FromRowId(ToRowId(rowNumber)); } public static LocalScopeHandle LocalScopeHandle(int rowNumber) { return Metadata.LocalScopeHandle.FromRowId(ToRowId(rowNumber)); } public static LocalVariableHandle LocalVariableHandle(int rowNumber) { return Metadata.LocalVariableHandle.FromRowId(ToRowId(rowNumber)); } public static LocalConstantHandle LocalConstantHandle(int rowNumber) { return Metadata.LocalConstantHandle.FromRowId(ToRowId(rowNumber)); } public static ImportScopeHandle ImportScopeHandle(int rowNumber) { return Metadata.ImportScopeHandle.FromRowId(ToRowId(rowNumber)); } public static CustomDebugInformationHandle CustomDebugInformationHandle(int rowNumber) { return Metadata.CustomDebugInformationHandle.FromRowId(ToRowId(rowNumber)); } // heaps public static UserStringHandle UserStringHandle(int offset) { return Metadata.UserStringHandle.FromOffset(offset & (int)TokenTypeIds.RIDMask); } public static StringHandle StringHandle(int offset) { return Metadata.StringHandle.FromOffset(offset); } public static BlobHandle BlobHandle(int offset) { return Metadata.BlobHandle.FromOffset(offset); } public static GuidHandle GuidHandle(int offset) { return Metadata.GuidHandle.FromIndex(offset); } public static DocumentNameBlobHandle DocumentNameBlobHandle(int offset) { return Metadata.DocumentNameBlobHandle.FromOffset(offset); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.ObjectModel; using System.Diagnostics; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { [Flags] internal enum GetValueFlags { None = 0x0, IncludeTypeName = 0x1, IncludeObjectId = 0x2, } // This class provides implementation for the "displaying values as strings" aspect of the default (C#) Formatter component. internal abstract partial class Formatter { internal string GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options, GetValueFlags flags) { if (value.IsError()) { return (string)value.HostObjectValue; } if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } var lmrType = value.Type.GetLmrType(); if (IsPredefinedType(lmrType) && !lmrType.IsObject()) { if (lmrType.IsString()) { var stringValue = (string)value.HostObjectValue; if (stringValue == null) { return _nullString; } return IncludeObjectId( value, FormatString(stringValue, options), flags); } else if (lmrType.IsCharacter()) { return IncludeObjectId( value, FormatLiteral((char)value.HostObjectValue, options | ObjectDisplayOptions.IncludeCodePoints), flags); } else { return IncludeObjectId( value, FormatPrimitive(value, options & ~ObjectDisplayOptions.UseQuotes, inspectionContext), flags); } } else if (value.IsNull && !lmrType.IsPointer) { return _nullString; } else if (lmrType.IsEnum) { return IncludeObjectId( value, GetEnumDisplayString(lmrType, value, options, (flags & GetValueFlags.IncludeTypeName) != 0, inspectionContext), flags); } else if (lmrType.IsArray) { return IncludeObjectId( value, GetArrayDisplayString(lmrType, value.ArrayDimensions, value.ArrayLowerBounds, options), flags); } else if (lmrType.IsPointer) { // NOTE: the HostObjectValue will have a size corresponding to the process bitness // and FormatPrimitive will adjust accordingly. var tmp = FormatPrimitive(value, ObjectDisplayOptions.UseHexadecimalNumbers, inspectionContext); // Always in hex. Debug.Assert(tmp != null); return tmp; } else if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); // It should be impossible to nest nullables, so this recursion should introduce only a single extra stack frame. return nullableValue == null ? _nullString : GetValueString(nullableValue, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } // "value.EvaluateToString()" will check "Call string-conversion function on objects in variables windows" // (Tools > Options setting) and call "value.ToString()" if appropriate. return IncludeObjectId( value, string.Format(_defaultFormat, value.EvaluateToString(inspectionContext) ?? inspectionContext.GetTypeName(value.Type, Formatter.NoFormatSpecifiers)), flags); } /// <summary> /// Gets the string representation of a character literal without including the numeric code point. /// </summary> internal string GetValueStringForCharacter(DkmClrValue value, DkmInspectionContext inspectionContext, ObjectDisplayOptions options) { Debug.Assert(value.Type.GetLmrType().IsCharacter()); if (UsesHexadecimalNumbers(inspectionContext)) { options |= ObjectDisplayOptions.UseHexadecimalNumbers; } var charTemp = FormatLiteral((char)value.HostObjectValue, options); Debug.Assert(charTemp != null); return charTemp; } internal bool HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return GetUnderlyingString(value, inspectionContext) != null; } internal string GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { RawStringDataItem dataItem = value.GetDataItem<RawStringDataItem>(); if (dataItem != null) { return dataItem.RawString; } string underlyingString = GetUnderlyingStringImpl(value, inspectionContext); dataItem = new RawStringDataItem(underlyingString); value.SetDataItem(DkmDataCreationDisposition.CreateNew, dataItem); return underlyingString; } private string GetUnderlyingStringImpl(DkmClrValue value, DkmInspectionContext inspectionContext) { Debug.Assert(!value.IsError()); if (value.IsNull) { return null; } var lmrType = value.Type.GetLmrType(); if (lmrType.IsEnum || lmrType.IsArray || lmrType.IsPointer) { return null; } if (lmrType.IsNullable()) { var nullableValue = value.GetNullableValue(inspectionContext); return nullableValue != null ? GetUnderlyingStringImpl(nullableValue, inspectionContext) : null; } if (lmrType.IsString()) { return (string)value.HostObjectValue; } else if (!IsPredefinedType(lmrType)) { // Check for special cased non-primitives that have underlying strings if (lmrType.IsType("System.Data.SqlTypes", "SqlString")) { var fieldValue = value.GetFieldValue(InternalWellKnownMemberNames.SqlStringValue, inspectionContext); return fieldValue.HostObjectValue as string; } else if (lmrType.IsOrInheritsFrom("System.Xml.Linq", "XNode")) { return value.EvaluateToString(inspectionContext); } } return null; } #pragma warning disable RS0010 /// <remarks> /// The corresponding native code is in EEUserStringBuilder::ErrTryAppendConstantEnum. /// The corresponding roslyn code is in /// <see cref="M:Microsoft.CodeAnalysis.SymbolDisplay.AbstractSymbolDisplayVisitor`1.AddEnumConstantValue(Microsoft.CodeAnalysis.INamedTypeSymbol, System.Object, System.Boolean)"/>. /// NOTE: no curlies for enum values. /// </remarks> #pragma warning restore RS0010 private string GetEnumDisplayString(Type lmrType, DkmClrValue value, ObjectDisplayOptions options, bool includeTypeName, DkmInspectionContext inspectionContext) { Debug.Assert(lmrType.IsEnum); Debug.Assert(value != null); object underlyingValue = value.HostObjectValue; Debug.Assert(underlyingValue != null); string displayString; ArrayBuilder<EnumField> fields = ArrayBuilder<EnumField>.GetInstance(); FillEnumFields(fields, lmrType); // We will normalize/extend all enum values to ulong to ensure that we are always comparing the full underlying value. ulong valueForComparison = ConvertEnumUnderlyingTypeToUInt64(underlyingValue, Type.GetTypeCode(lmrType)); var typeToDisplayOpt = includeTypeName ? lmrType : null; if (valueForComparison != 0 && IsFlagsEnum(lmrType)) { displayString = GetNamesForFlagsEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } else { displayString = GetNameForEnumValue(fields, underlyingValue, valueForComparison, options, typeToDisplayOpt); } fields.Free(); return displayString ?? FormatPrimitive(value, options, inspectionContext); } private static void FillEnumFields(ArrayBuilder<EnumField> fields, Type lmrType) { var fieldInfos = lmrType.GetFields(); var enumTypeCode = Type.GetTypeCode(lmrType); foreach (var info in fieldInfos) { if (!info.IsSpecialName) // Skip __value. { fields.Add(new EnumField(info.Name, ConvertEnumUnderlyingTypeToUInt64(info.GetRawConstantValue(), enumTypeCode))); } } fields.Sort(EnumField.Comparer); } internal static void FillUsedEnumFields(ArrayBuilder<EnumField> usedFields, ArrayBuilder<EnumField> fields, ulong underlyingValue) { var remaining = underlyingValue; foreach (var field in fields) { var fieldValue = field.Value; if (fieldValue == 0) continue; // Otherwise, we'd tack the zero flag onto everything. if ((remaining & fieldValue) == fieldValue) { remaining -= fieldValue; usedFields.Add(field); if (remaining == 0) break; } } // The value contained extra bit flags that didn't correspond to any enum field. We will // report "no fields used" here so the Formatter will just display the underlying value. if (remaining != 0) { usedFields.Clear(); } } private static bool IsFlagsEnum(Type lmrType) { Debug.Assert(lmrType.IsEnum); var attributes = lmrType.GetCustomAttributesData(); foreach (var attribute in attributes) { // NOTE: AttributeType is not available in 2.0 if (attribute.Constructor.DeclaringType.FullName == "System.FlagsAttribute") { return true; } } return false; } private static bool UsesHexadecimalNumbers(DkmInspectionContext inspectionContext) { Debug.Assert(inspectionContext != null); return inspectionContext.Radix == 16; } /// <summary> /// Convert a boxed primitive (generally of the backing type of an enum) into a ulong. /// </summary> protected static ulong ConvertEnumUnderlyingTypeToUInt64(object value, TypeCode typeCode) { Debug.Assert(value != null); unchecked { switch (typeCode) { case TypeCode.SByte: return (ulong)(sbyte)value; case TypeCode.Int16: return (ulong)(short)value; case TypeCode.Int32: return (ulong)(int)value; case TypeCode.Int64: return (ulong)(long)value; case TypeCode.Byte: return (byte)value; case TypeCode.UInt16: return (ushort)value; case TypeCode.UInt32: return (uint)value; case TypeCode.UInt64: return (ulong)value; default: throw ExceptionUtilities.UnexpectedValue(typeCode); } } } internal string GetEditableValue(DkmClrValue value, DkmInspectionContext inspectionContext) { if (value.IsError()) { return null; } if (value.EvalFlags.Includes(DkmEvaluationResultFlags.ReadOnly)) { return null; } var type = value.Type.GetLmrType(); if (type.IsEnum) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.None, GetValueFlags.IncludeTypeName); } else if (type.IsDecimal()) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.IncludeTypeSuffix, GetValueFlags.None); } // The legacy EE didn't special-case strings or chars (when ",nq" was used, // you had to manually add quotes when editing) but it makes sense to // always automatically quote (non-null) strings and chars when editing. else if (type.IsString()) { if (!value.IsNull) { return this.GetValueString(value, inspectionContext, ObjectDisplayOptions.UseQuotes, GetValueFlags.None); } } else if (type.IsCharacter()) { return this.GetValueStringForCharacter(value, inspectionContext, ObjectDisplayOptions.UseQuotes); } return null; } internal string FormatPrimitive(DkmClrValue value, ObjectDisplayOptions options, DkmInspectionContext inspectionContext) { Debug.Assert(value != null); object obj; if (value.Type.GetLmrType().IsDateTime()) { DkmClrValue dateDataValue = value.GetFieldValue(DateTimeUtilities.DateTimeDateDataFieldName, inspectionContext); Debug.Assert(dateDataValue.HostObjectValue != null); obj = DateTimeUtilities.ToDateTime((ulong)dateDataValue.HostObjectValue); } else { Debug.Assert(value.HostObjectValue != null); obj = value.HostObjectValue; } return FormatPrimitiveObject(obj, options); } private static string IncludeObjectId(DkmClrValue value, string valueStr, GetValueFlags flags) { Debug.Assert(valueStr != null); return (flags & GetValueFlags.IncludeObjectId) == 0 ? valueStr : value.IncludeObjectId(valueStr); } #region Language-specific value formatting behavior internal abstract string GetArrayDisplayString(Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options); internal abstract string GetArrayIndexExpression(int[] indices); internal abstract string GetCastExpression(string argument, string type, bool parenthesizeArgument = false /* ignored in Visual Basic */, bool parenthesizeEntireExpression = false /* ignored in Visual Basic */); internal abstract string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt); internal abstract string GetObjectCreationExpression(string type, string arguments); internal abstract string FormatLiteral(char c, ObjectDisplayOptions options); internal abstract string FormatLiteral(int value, ObjectDisplayOptions options); internal abstract string FormatPrimitiveObject(object value, ObjectDisplayOptions options); internal abstract string FormatString(string str, ObjectDisplayOptions options); #endregion } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Net; using Amazon.Util; namespace Amazon.EC2 { /// <summary> /// Configuration for accessing Amazon EC2 service /// </summary> public class AmazonEC2Config { private string serviceVersion = "2013-08-15"; private RegionEndpoint regionEndpoint; private string serviceURL = "https://ec2.amazonaws.com"; private string userAgent = Amazon.Util.AWSSDKUtils.SDKUserAgent; private string signatureVersion = "2"; private string signatureMethod = "HmacSHA256"; private string proxyHost; private int proxyPort = -1; private int maxErrorRetry = 3; private bool fUseSecureString = true; private string proxyUsername; private string proxyPassword; private int? connectionLimit; private ICredentials proxyCredentials; /// <summary> /// Gets Service Version /// </summary> public string ServiceVersion { get { return this.serviceVersion; } } /// <summary> /// Gets and sets of the signatureMethod property. /// </summary> public string SignatureMethod { get { return this.signatureMethod; } set { this.signatureMethod = value; } } /// <summary> /// Sets the SignatureMethod property /// </summary> /// <param name="signatureMethod">SignatureMethod property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithSignatureMethod(string signatureMethod) { this.signatureMethod = signatureMethod; return this; } /// <summary> /// Checks if SignatureMethod property is set /// </summary> /// <returns>true if SignatureMethod property is set</returns> public bool IsSetSignatureMethod() { return this.signatureMethod != null; } /// <summary> /// Gets and sets of the SignatureVersion property. /// </summary> public string SignatureVersion { get { return this.signatureVersion; } set { this.signatureVersion = value; } } /// <summary> /// Sets the SignatureVersion property /// </summary> /// <param name="signatureVersion">SignatureVersion property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithSignatureVersion(string signatureVersion) { this.signatureVersion = signatureVersion; return this; } /// <summary> /// Checks if SignatureVersion property is set /// </summary> /// <returns>true if SignatureVersion property is set</returns> public bool IsSetSignatureVersion() { return this.signatureVersion != null; } /// <summary> /// Gets and sets of the UserAgent property. /// </summary> public string UserAgent { get { return this.userAgent; } set { this.userAgent = value; } } /// <summary> /// Sets the UserAgent property /// </summary> /// <param name="userAgent">UserAgent property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithUserAgent(string userAgent) { this.userAgent = userAgent; return this; } /// <summary> /// Checks if UserAgent property is set /// </summary> /// <returns>true if UserAgent property is set</returns> public bool IsSetUserAgent() { return this.userAgent != null; } /// <summary> /// Gets and sets the RegionEndpoint property. The region constant to use that /// determines the endpoint to use. If this is not set /// then the client will fallback to the value of ServiceURL. /// </summary> public RegionEndpoint RegionEndpoint { get { return regionEndpoint; } set { this.regionEndpoint = value; } } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> internal string RegionEndpointServiceName { get { return "ec2"; } } /// <summary> /// Gets and sets of the ServiceURL property. /// This is an optional property; change it /// only if you want to try a different service /// endpoint or want to switch between https and http. /// </summary> public string ServiceURL { get { return this.serviceURL; } set { this.serviceURL = value; } } /// <summary> /// Sets the ServiceURL property /// </summary> /// <param name="serviceURL">ServiceURL property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithServiceURL(string serviceURL) { this.serviceURL = serviceURL; return this; } /// <summary> /// Checks if ServiceURL property is set /// </summary> /// <returns>true if ServiceURL property is set</returns> public bool IsSetServiceURL() { return this.serviceURL != null; } /// <summary> /// Gets and sets of the ProxyHost property. /// </summary> public string ProxyHost { get { return this.proxyHost; } set { this.proxyHost = value; } } /// <summary> /// Sets the ProxyHost property /// </summary> /// <param name="proxyHost">ProxyHost property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithProxyHost(string proxyHost) { this.proxyHost = proxyHost; return this; } /// <summary> /// Checks if ProxyHost property is set /// </summary> /// <returns>true if ProxyHost property is set</returns> public bool IsSetProxyHost() { return this.proxyHost != null; } /// <summary> /// Gets and sets of the ProxyPort property. /// </summary> public int ProxyPort { get { return this.proxyPort; } set { this.proxyPort = value; } } /// <summary> /// Sets the ProxyPort property /// </summary> /// <param name="proxyPort">ProxyPort property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithProxyPort(int proxyPort) { this.proxyPort = proxyPort; return this; } /// <summary> /// Checks if ProxyPort property is set /// </summary> /// <returns>true if ProxyPort property is set</returns> public bool IsSetProxyPort() { return this.proxyPort >= 0; } /// <summary> /// Credentials to use with a proxy. /// </summary> public ICredentials ProxyCredentials { get { ICredentials credentials = this.proxyCredentials; if (credentials == null && this.IsSetProxyUsername()) { credentials = new NetworkCredential(this.proxyUsername, this.proxyPassword ?? String.Empty); } return credentials; } set { this.proxyCredentials = value; } } /// <summary> /// Sets the ProxyCredentials property. /// </summary> /// <param name="proxyCredentials">ProxyCredentials property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithProxyCredentials(ICredentials proxyCredentials) { this.proxyCredentials = proxyCredentials; return this; } /// <summary> /// Checks if ProxyCredentials property is set /// </summary> /// <returns>true if ProxyCredentials property is set</returns> internal bool IsSetProxyCredentials() { return (this.ProxyCredentials != null); } /// <summary> /// Gets and sets of the MaxErrorRetry property. /// </summary> public int MaxErrorRetry { get { return this.maxErrorRetry; } set { this.maxErrorRetry = value; } } /// <summary> /// Sets the MaxErrorRetry property /// </summary> /// <param name="maxErrorRetry">MaxErrorRetry property</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithMaxErrorRetry(int maxErrorRetry) { this.maxErrorRetry = maxErrorRetry; return this; } /// <summary> /// Checks if MaxErrorRetry property is set /// </summary> /// <returns>true if MaxErrorRetry property is set</returns> public bool IsSetMaxErrorRetry() { return this.maxErrorRetry >= 0; } /// <summary> /// Gets and Sets the UseSecureStringForAwsSecretKey property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> public bool UseSecureStringForAwsSecretKey { get { return this.fUseSecureString; } set { this.fUseSecureString = value; } } /// <summary> /// Sets the UseSecureString property. /// By default, the AWS Secret Access Key is stored /// in a SecureString (true) - this is one of the secure /// ways to store a secret provided by the .NET Framework. /// But, the use of SecureStrings is not supported in Medium /// Trust Windows Hosting environments. If you are building an /// ASP.NET application that needs to run with Medium Trust, /// set this property to false, and the client will /// not save your AWS Secret Key in a secure string. Changing /// the default to false can result in the Secret Key being /// vulnerable; please use this property judiciously. /// </summary> /// <param name="fSecure"> /// Whether a secure string should be used or not. /// </param> /// <returns>The Config object with the property set</returns> /// <remarks>Storing the AWS Secret Access Key is not /// recommended unless absolutely necessary. /// </remarks> /// <seealso cref="T:System.Security.SecureString"/> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public AmazonEC2Config WithUseSecureStringForAwsSecretKey(bool fSecure) { fUseSecureString = fSecure; return this; } /// <summary> /// Gets and sets the ProxyUsername property. /// Used in conjunction with the ProxyPassword /// property to authenticate requests with the /// specified Proxy server. /// </summary> [Obsolete("Use ProxyCredentials instead")] public string ProxyUsername { get { return this.proxyUsername; } set { this.proxyUsername = value; } } /// <summary> /// Sets the ProxyUsername property /// </summary> /// <param name="userName">Value for the ProxyUsername property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonEC2Config WithProxyUsername(string userName) { this.proxyUsername = userName; return this; } /// <summary> /// Checks if ProxyUsername property is set /// </summary> /// <returns>true if ProxyUsername property is set</returns> internal bool IsSetProxyUsername() { return !System.String.IsNullOrEmpty(this.proxyUsername); } /// <summary> /// Gets and sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> [Obsolete("Use ProxyCredentials instead")] public string ProxyPassword { get { return this.proxyPassword; } set { this.proxyPassword = value; } } /// <summary> /// Sets the ProxyPassword property. /// Used in conjunction with the ProxyUsername /// property to authenticate requests with the /// specified Proxy server. /// </summary> /// <remarks> /// If this property isn't set, String.Empty is used as /// the proxy password. This property isn't /// used if ProxyUsername is null or empty. /// </remarks> /// <param name="password">ProxyPassword property</param> /// <returns>this instance</returns> [Obsolete("Use WithProxyCredentials instead")] public AmazonEC2Config WithProxyPassword(string password) { this.proxyPassword = password; return this; } /// <summary> /// Checks if ProxyPassword property is set /// </summary> /// <returns>true if ProxyPassword property is set</returns> internal bool IsSetProxyPassword() { return !System.String.IsNullOrEmpty(this.proxyPassword); } /// <summary> /// Gets and sets the connection limit set on the ServicePoint for the WebRequest. /// Default value is 50 connections unless ServicePointManager.DefaultConnectionLimit is set in /// which case ServicePointManager.DefaultConnectionLimit will be used as the default. /// </summary> public int ConnectionLimit { get { return AWSSDKUtils.GetConnectionLimit(this.connectionLimit); } set { this.connectionLimit = value; } } } }
// // SmugMugExport.cs // // Author: // Stephane Delcroix <[email protected]> // Stephen Shaw <[email protected]> // // Copyright (C) 2006-2009 Novell, Inc. // Copyright (C) 2006-2009 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /* * SmugMugExport.cs * * Authors: * Thomas Van Machelen <[email protected]> * * Based on PicasaWebExport code from Stephane Delcroix. * * Copyright (C) 2006 Thomas Van Machelen */ using System; using System.IO; using System.Collections.Generic; using Mono.Unix; using FSpot; using FSpot.Core; using FSpot.Database; using FSpot.Filters; using FSpot.Settings; using FSpot.Widgets; using FSpot.UI.Dialog; using Hyena; using SmugMugNet; using System.Linq; namespace FSpot.Exporters.SmugMug { public class SmugMugExport : FSpot.Extensions.IExporter { public SmugMugExport () {} public void Run (IBrowsableCollection selection) { builder = new GtkBeans.Builder (null, "smugmug_export_dialog.ui", null); builder.Autoconnect (this); gallery_optionmenu = Gtk.ComboBox.NewText(); album_optionmenu = Gtk.ComboBox.NewText(); (edit_button.Parent as Gtk.HBox).PackStart (gallery_optionmenu); (album_button.Parent as Gtk.HBox).PackStart (album_optionmenu); (edit_button.Parent as Gtk.HBox).ReorderChild (gallery_optionmenu, 1); (album_button.Parent as Gtk.HBox).ReorderChild (album_optionmenu, 1); gallery_optionmenu.Show (); album_optionmenu.Show (); this.items = selection.Items.ToArray (); album_button.Sensitive = false; var view = new TrayView (selection); view.DisplayDates = false; view.DisplayTags = false; Dialog.Modal = false; Dialog.TransientFor = null; Dialog.Close += HandleCloseEvent; thumb_scrolledwindow.Add (view); view.Show (); Dialog.Show (); SmugMugAccountManager manager = SmugMugAccountManager.GetInstance (); manager.AccountListChanged += PopulateSmugMugOptionMenu; PopulateSmugMugOptionMenu (manager, null); if (edit_button != null) edit_button.Clicked += HandleEditGallery; Dialog.Response += HandleResponse; connect = true; HandleSizeActive (null, null); Connect (); LoadPreference (SCALE_KEY); LoadPreference (SIZE_KEY); LoadPreference (BROWSER_KEY); } private bool scale; private int size; private bool browser; private bool connect = false; private long approx_size = 0; private long sent_bytes = 0; IPhoto [] items; int photo_index; ThreadProgressDialog progress_dialog; List<SmugMugAccount> accounts; private SmugMugAccount account; private Album album; private string dialog_name = "smugmug_export_dialog"; private GtkBeans.Builder builder; // Widgets [GtkBeans.Builder.Object] Gtk.Dialog dialog; Gtk.ComboBox gallery_optionmenu; Gtk.ComboBox album_optionmenu; #pragma warning disable 649 [GtkBeans.Builder.Object] Gtk.CheckButton browser_check; [GtkBeans.Builder.Object] Gtk.CheckButton scale_check; [GtkBeans.Builder.Object] Gtk.SpinButton size_spin; [GtkBeans.Builder.Object] Gtk.Button album_button; [GtkBeans.Builder.Object] Gtk.Button edit_button; [GtkBeans.Builder.Object] Gtk.Button export_button; [GtkBeans.Builder.Object] Gtk.ScrolledWindow thumb_scrolledwindow; #pragma warning restore 649 System.Threading.Thread command_thread; public const string EXPORT_SERVICE = "smugmug/"; public const string SCALE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "scale"; public const string SIZE_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "size"; public const string BROWSER_KEY = Preferences.APP_FSPOT_EXPORT + EXPORT_SERVICE + "browser"; private void HandleResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId != Gtk.ResponseType.Ok) { Dialog.Destroy (); return; } if (scale_check != null) { scale = scale_check.Active; size = size_spin.ValueAsInt; } else scale = false; browser = browser_check.Active; if (account != null) { album = (Album) account.SmugMug.GetAlbums() [Math.Max (0, album_optionmenu.Active)]; photo_index = 0; Dialog.Destroy (); command_thread = new System.Threading.Thread (new System.Threading.ThreadStart (this.Upload)); command_thread.Name = Mono.Unix.Catalog.GetString ("Uploading Pictures"); progress_dialog = new ThreadProgressDialog (command_thread, items.Length); progress_dialog.Start (); // Save these settings for next time Preferences.Set (SCALE_KEY, scale); Preferences.Set (SIZE_KEY, size); Preferences.Set (BROWSER_KEY, browser); } } public void HandleSizeActive (object sender, EventArgs args) { size_spin.Sensitive = scale_check.Active; } private void Upload () { sent_bytes = 0; approx_size = 0; System.Uri album_uri = null; Log.Debug ("Starting Upload to Smugmug, album " + album.Title + " - " + album.AlbumID); FilterSet filters = new FilterSet (); filters.Add (new JpegFilter ()); if (scale) filters.Add (new ResizeFilter ((uint)size)); while (photo_index < items.Length) { try { IPhoto item = items[photo_index]; FileInfo file_info; Log.Debug ("uploading " + photo_index); progress_dialog.Message = string.Format (Catalog.GetString ("Uploading picture \"{0}\" ({1} of {2})"), item.Name, photo_index+1, items.Length); progress_dialog.ProgressText = string.Empty; progress_dialog.Fraction = ((photo_index) / (double) items.Length); photo_index++; FilterRequest request = new FilterRequest (item.DefaultVersion.Uri); filters.Convert (request); file_info = new FileInfo (request.Current.LocalPath); if (approx_size == 0) //first image approx_size = file_info.Length * items.Length; else approx_size = sent_bytes * items.Length / (photo_index - 1); int image_id = account.SmugMug.Upload (request.Current.LocalPath, album.AlbumID); if (App.Instance.Database != null && item is Photo && image_id >= 0) App.Instance.Database.Exports.Create ((item as Photo).Id, (item as Photo).DefaultVersionId, ExportStore.SmugMugExportType, account.SmugMug.GetAlbumUrl (image_id).ToString ()); sent_bytes += file_info.Length; if (album_uri == null) album_uri = account.SmugMug.GetAlbumUrl (image_id); } catch (System.Exception e) { progress_dialog.Message = string.Format (Mono.Unix.Catalog.GetString ("Error Uploading To Gallery: {0}"), e.Message); progress_dialog.ProgressText = Mono.Unix.Catalog.GetString ("Error"); Log.DebugException (e); if (progress_dialog.PerformRetrySkip ()) { photo_index--; if (photo_index == 0) approx_size = 0; } } } progress_dialog.Message = Catalog.GetString ("Done Sending Photos"); progress_dialog.Fraction = 1.0; progress_dialog.ProgressText = Mono.Unix.Catalog.GetString ("Upload Complete"); progress_dialog.ButtonLabel = Gtk.Stock.Ok; if (browser && album_uri != null) { GtkBeans.Global.ShowUri (Dialog.Screen, album_uri.ToString ()); } } private void PopulateSmugMugOptionMenu (SmugMugAccountManager manager, SmugMugAccount changed_account) { this.account = changed_account; int pos = 0; accounts = manager.GetAccounts (); if (accounts == null || accounts.Count == 0) { gallery_optionmenu.AppendText (Mono.Unix.Catalog.GetString ("(No Gallery)")); gallery_optionmenu.Sensitive = false; edit_button.Sensitive = false; } else { int i = 0; foreach (SmugMugAccount account in accounts) { if (account == changed_account) pos = i; gallery_optionmenu.AppendText(account.Username); i++; } gallery_optionmenu.Sensitive = true; edit_button.Sensitive = true; } gallery_optionmenu.Active = pos; } private void Connect () { Connect (null); } private void Connect (SmugMugAccount selected) { Connect (selected, null); } private void Connect (SmugMugAccount selected, string text) { try { if (accounts.Count != 0 && connect) { if (selected == null) account = (SmugMugAccount) accounts [gallery_optionmenu.Active]; else account = selected; if (!account.Connected) account.Connect (); PopulateAlbumOptionMenu (account.SmugMug); } } catch (System.Exception) { Log.Warning ("Can not connect to SmugMug. Bad username? Password? Network connection?"); if (selected != null) account = selected; PopulateAlbumOptionMenu (account.SmugMug); album_button.Sensitive = false; new SmugMugAccountDialog (this.Dialog, account); } } private void HandleAccountSelected (object sender, System.EventArgs args) { Connect (); } public void HandleAlbumAdded (string title) { SmugMugAccount account = (SmugMugAccount) accounts [gallery_optionmenu.Active]; PopulateAlbumOptionMenu (account.SmugMug); // make the newly created album selected Album[] albums = account.SmugMug.GetAlbums(); for (int i=0; i < albums.Length; i++) { if (((Album)albums[i]).Title == title) { album_optionmenu.Active = 1; } } } private void PopulateAlbumOptionMenu (SmugMugApi smugmug) { Album[] albums = null; if (smugmug != null) { try { albums = smugmug.GetAlbums(); } catch (Exception) { Log.Debug ("Can't get the albums"); smugmug = null; } } bool disconnected = smugmug == null || !account.Connected || albums == null; if (disconnected || albums.Length == 0) { string msg = disconnected ? Mono.Unix.Catalog.GetString ("(Not Connected)") : Mono.Unix.Catalog.GetString ("(No Albums)"); album_optionmenu.AppendText(msg); export_button.Sensitive = false; album_optionmenu.Sensitive = false; album_button.Sensitive = false; } else { foreach (Album album in albums) { System.Text.StringBuilder label_builder = new System.Text.StringBuilder (); label_builder.Append (album.Title); album_optionmenu.AppendText (label_builder.ToString()); } export_button.Sensitive = items.Length > 0; album_optionmenu.Sensitive = true; album_button.Sensitive = true; } album_optionmenu.Active = 0; } public void HandleAddGallery (object sender, System.EventArgs args) { new SmugMugAccountDialog (this.Dialog); } public void HandleEditGallery (object sender, System.EventArgs args) { new SmugMugAccountDialog (this.Dialog, account); } public void HandleAddAlbum (object sender, System.EventArgs args) { if (account == null) throw new Exception (Catalog.GetString ("No account selected")); new SmugMugAddAlbum (this, account.SmugMug); } void LoadPreference (string key) { switch (key) { case SCALE_KEY: if (scale_check.Active != Preferences.Get<bool> (key)) { scale_check.Active = Preferences.Get<bool> (key); } break; case SIZE_KEY: size_spin.Value = (double) Preferences.Get<int> (key); break; case BROWSER_KEY: if (browser_check.Active != Preferences.Get<bool> (key)) browser_check.Active = Preferences.Get<bool> (key); break; } } protected void HandleCloseEvent (object sender, System.EventArgs args) { account.SmugMug.Logout (); } private Gtk.Dialog Dialog { get { if (dialog == null) dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name)); return dialog; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; namespace System.Numerics { /// <summary> /// A structure encapsulating a four-dimensional vector (x,y,z,w), /// which is used to efficiently rotate an object about the (x,y,z) vector by the angle theta, where w = cos(theta/2). /// </summary> public struct Quaternion : IEquatable<Quaternion> { /// <summary> /// Specifies the X-value of the vector component of the Quaternion. /// </summary> public float X; /// <summary> /// Specifies the Y-value of the vector component of the Quaternion. /// </summary> public float Y; /// <summary> /// Specifies the Z-value of the vector component of the Quaternion. /// </summary> public float Z; /// <summary> /// Specifies the rotation component of the Quaternion. /// </summary> public float W; /// <summary> /// Returns a Quaternion representing no rotation. /// </summary> public static Quaternion Identity { get { return new Quaternion(0, 0, 0, 1); } } /// <summary> /// Returns whether the Quaternion is the identity Quaternion. /// </summary> public bool IsIdentity { get { return X == 0f && Y == 0f && Z == 0f && W == 1f; } } /// <summary> /// Constructs a Quaternion from the given components. /// </summary> /// <param name="x">The X component of the Quaternion.</param> /// <param name="y">The Y component of the Quaternion.</param> /// <param name="z">The Z component of the Quaternion.</param> /// <param name="w">The W component of the Quaternion.</param> public Quaternion(float x, float y, float z, float w) { this.X = x; this.Y = y; this.Z = z; this.W = w; } /// <summary> /// Constructs a Quaternion from the given vector and rotation parts. /// </summary> /// <param name="vectorPart">The vector part of the Quaternion.</param> /// <param name="scalarPart">The rotation part of the Quaternion.</param> public Quaternion(Vector3 vectorPart, float scalarPart) { X = vectorPart.X; Y = vectorPart.Y; Z = vectorPart.Z; W = scalarPart; } /// <summary> /// Calculates the length of the Quaternion. /// </summary> /// <returns>The computed length of the Quaternion.</returns> public float Length() { float ls = X * X + Y * Y + Z * Z + W * W; return (float)Math.Sqrt((double)ls); } /// <summary> /// Calculates the length squared of the Quaternion. This operation is cheaper than Length(). /// </summary> /// <returns>The length squared of the Quaternion.</returns> public float LengthSquared() { return X * X + Y * Y + Z * Z + W * W; } /// <summary> /// Divides each component of the Quaternion by the length of the Quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The normalized Quaternion.</returns> public static Quaternion Normalize(Quaternion value) { Quaternion ans; float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float invNorm = 1.0f / (float)Math.Sqrt((double)ls); ans.X = value.X * invNorm; ans.Y = value.Y * invNorm; ans.Z = value.Z * invNorm; ans.W = value.W * invNorm; return ans; } /// <summary> /// Creates the conjugate of a specified Quaternion. /// </summary> /// <param name="value">The Quaternion of which to return the conjugate.</param> /// <returns>A new Quaternion that is the conjugate of the specified one.</returns> public static Quaternion Conjugate(Quaternion value) { Quaternion ans; ans.X = -value.X; ans.Y = -value.Y; ans.Z = -value.Z; ans.W = value.W; return ans; } /// <summary> /// Returns the inverse of a Quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The inverted Quaternion.</returns> public static Quaternion Inverse(Quaternion value) { // -1 ( a -v ) // q = ( ------------- ------------- ) // ( a^2 + |v|^2 , a^2 + |v|^2 ) Quaternion ans; float ls = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float invNorm = 1.0f / ls; ans.X = -value.X * invNorm; ans.Y = -value.Y * invNorm; ans.Z = -value.Z * invNorm; ans.W = value.W * invNorm; return ans; } /// <summary> /// Creates a Quaternion from a vector and an angle to rotate about the vector. /// </summary> /// <param name="axis">The vector to rotate around.</param> /// <param name="angle">The angle, in radians, to rotate around the vector.</param> /// <returns>The created Quaternion.</returns> public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) { Quaternion ans; float halfAngle = angle * 0.5f; float s = (float)Math.Sin(halfAngle); float c = (float)Math.Cos(halfAngle); ans.X = axis.X * s; ans.Y = axis.Y * s; ans.Z = axis.Z * s; ans.W = c; return ans; } /// <summary> /// Creates a new Quaternion from the given yaw, pitch, and roll, in radians. /// </summary> /// <param name="yaw">The yaw angle, in radians, around the Y-axis.</param> /// <param name="pitch">The pitch angle, in radians, around the X-axis.</param> /// <param name="roll">The roll angle, in radians, around the Z-axis.</param> /// <returns></returns> public static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll) { // Roll first, about axis the object is facing, then // pitch upward, then yaw to face into the new heading float sr, cr, sp, cp, sy, cy; float halfRoll = roll * 0.5f; sr = (float)Math.Sin(halfRoll); cr = (float)Math.Cos(halfRoll); float halfPitch = pitch * 0.5f; sp = (float)Math.Sin(halfPitch); cp = (float)Math.Cos(halfPitch); float halfYaw = yaw * 0.5f; sy = (float)Math.Sin(halfYaw); cy = (float)Math.Cos(halfYaw); Quaternion result; result.X = cy * sp * cr + sy * cp * sr; result.Y = sy * cp * cr - cy * sp * sr; result.Z = cy * cp * sr - sy * sp * cr; result.W = cy * cp * cr + sy * sp * sr; return result; } /// <summary> /// Creates a Quaternion from the given rotation matrix. /// </summary> /// <param name="matrix">The rotation matrix.</param> /// <returns>The created Quaternion.</returns> public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix) { float trace = matrix.M11 + matrix.M22 + matrix.M33; Quaternion q = new Quaternion(); if (trace > 0.0f) { float s = (float)Math.Sqrt(trace + 1.0f); q.W = s * 0.5f; s = 0.5f / s; q.X = (matrix.M23 - matrix.M32) * s; q.Y = (matrix.M31 - matrix.M13) * s; q.Z = (matrix.M12 - matrix.M21) * s; } else { if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33) { float s = (float)Math.Sqrt(1.0f + matrix.M11 - matrix.M22 - matrix.M33); float invS = 0.5f / s; q.X = 0.5f * s; q.Y = (matrix.M12 + matrix.M21) * invS; q.Z = (matrix.M13 + matrix.M31) * invS; q.W = (matrix.M23 - matrix.M32) * invS; } else if (matrix.M22 > matrix.M33) { float s = (float)Math.Sqrt(1.0f + matrix.M22 - matrix.M11 - matrix.M33); float invS = 0.5f / s; q.X = (matrix.M21 + matrix.M12) * invS; q.Y = 0.5f * s; q.Z = (matrix.M32 + matrix.M23) * invS; q.W = (matrix.M31 - matrix.M13) * invS; } else { float s = (float)Math.Sqrt(1.0f + matrix.M33 - matrix.M11 - matrix.M22); float invS = 0.5f / s; q.X = (matrix.M31 + matrix.M13) * invS; q.Y = (matrix.M32 + matrix.M23) * invS; q.Z = 0.5f * s; q.W = (matrix.M12 - matrix.M21) * invS; } } return q; } /// <summary> /// Calculates the dot product of two Quaternions. /// </summary> /// <param name="quaternion1">The first source Quaternion.</param> /// <param name="quaternion2">The second source Quaternion.</param> /// <returns>The dot product of the Quaternions.</returns> public static float Dot(Quaternion quaternion1, Quaternion quaternion2) { return quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; } /// <summary> /// Interpolates between two quaternions, using spherical linear interpolation. /// </summary> /// <param name="quaternion1">The first source Quaternion.</param> /// <param name="quaternion2">The second source Quaternion.</param> /// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param> /// <returns>The interpolated Quaternion.</returns> public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { const float epsilon = 1e-6f; float t = amount; float cosOmega = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; bool flip = false; if (cosOmega < 0.0f) { flip = true; cosOmega = -cosOmega; } float s1, s2; if (cosOmega > (1.0f - epsilon)) { // Too close, do straight linear interpolation. s1 = 1.0f - t; s2 = (flip) ? -t : t; } else { float omega = (float)Math.Acos(cosOmega); float invSinOmega = (float)(1 / Math.Sin(omega)); s1 = (float)Math.Sin((1.0f - t) * omega) * invSinOmega; s2 = (flip) ? (float)-Math.Sin(t * omega) * invSinOmega : (float)Math.Sin(t * omega) * invSinOmega; } Quaternion ans; ans.X = s1 * quaternion1.X + s2 * quaternion2.X; ans.Y = s1 * quaternion1.Y + s2 * quaternion2.Y; ans.Z = s1 * quaternion1.Z + s2 * quaternion2.Z; ans.W = s1 * quaternion1.W + s2 * quaternion2.W; return ans; } /// <summary> /// Linearly interpolates between two quaternions. /// </summary> /// <param name="quaternion1">The first source Quaternion.</param> /// <param name="quaternion2">The second source Quaternion.</param> /// <param name="amount">The relative weight of the second source Quaternion in the interpolation.</param> /// <returns>The interpolated Quaternion.</returns> public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { float t = amount; float t1 = 1.0f - t; Quaternion r = new Quaternion(); float dot = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; if (dot >= 0.0f) { r.X = t1 * quaternion1.X + t * quaternion2.X; r.Y = t1 * quaternion1.Y + t * quaternion2.Y; r.Z = t1 * quaternion1.Z + t * quaternion2.Z; r.W = t1 * quaternion1.W + t * quaternion2.W; } else { r.X = t1 * quaternion1.X - t * quaternion2.X; r.Y = t1 * quaternion1.Y - t * quaternion2.Y; r.Z = t1 * quaternion1.Z - t * quaternion2.Z; r.W = t1 * quaternion1.W - t * quaternion2.W; } // Normalize it. float ls = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W; float invNorm = 1.0f / (float)Math.Sqrt((double)ls); r.X *= invNorm; r.Y *= invNorm; r.Z *= invNorm; r.W *= invNorm; return r; } /// <summary> /// Concatenates two Quaternions; the result represents the value1 rotation followed by the value2 rotation. /// </summary> /// <param name="value1">The first Quaternion rotation in the series.</param> /// <param name="value2">The second Quaternion rotation in the series.</param> /// <returns>A new Quaternion representing the concatenation of the value1 rotation followed by the value2 rotation.</returns> public static Quaternion Concatenate(Quaternion value1, Quaternion value2) { Quaternion ans; // Concatenate rotation is actually q2 * q1 instead of q1 * q2. // So that's why value2 goes q1 and value1 goes q2. float q1x = value2.X; float q1y = value2.Y; float q1z = value2.Z; float q1w = value2.W; float q2x = value1.X; float q2y = value1.Y; float q2z = value1.Z; float q2w = value1.W; // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Flips the sign of each component of the quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The negated Quaternion.</returns> public static Quaternion Negate(Quaternion value) { Quaternion ans; ans.X = -value.X; ans.Y = -value.Y; ans.Z = -value.Z; ans.W = -value.W; return ans; } /// <summary> /// Adds two Quaternions element-by-element. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second source Quaternion.</param> /// <returns>The result of adding the Quaternions.</returns> public static Quaternion Add(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X + value2.X; ans.Y = value1.Y + value2.Y; ans.Z = value1.Z + value2.Z; ans.W = value1.W + value2.W; return ans; } /// <summary> /// Subtracts one Quaternion from another. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second Quaternion, to be subtracted from the first.</param> /// <returns>The result of the subtraction.</returns> public static Quaternion Subtract(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X - value2.X; ans.Y = value1.Y - value2.Y; ans.Z = value1.Z - value2.Z; ans.W = value1.W - value2.W; return ans; } /// <summary> /// Multiplies two Quaternions together. /// </summary> /// <param name="value1">The Quaternion on the left side of the multiplication.</param> /// <param name="value2">The Quaternion on the right side of the multiplication.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion Multiply(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; float q2x = value2.X; float q2y = value2.Y; float q2z = value2.Z; float q2w = value2.W; // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Multiplies a Quaternion by a scalar value. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The scalar value.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion Multiply(Quaternion value1, float value2) { Quaternion ans; ans.X = value1.X * value2; ans.Y = value1.Y * value2; ans.Z = value1.Z * value2; ans.W = value1.W * value2; return ans; } /// <summary> /// Divides a Quaternion by another Quaternion. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The divisor.</param> /// <returns>The result of the division.</returns> public static Quaternion Divide(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; //------------------------------------- // Inverse part. float ls = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float invNorm = 1.0f / ls; float q2x = -value2.X * invNorm; float q2y = -value2.Y * invNorm; float q2z = -value2.Z * invNorm; float q2w = value2.W * invNorm; //------------------------------------- // Multiply part. // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Flips the sign of each component of the quaternion. /// </summary> /// <param name="value">The source Quaternion.</param> /// <returns>The negated Quaternion.</returns> public static Quaternion operator -(Quaternion value) { Quaternion ans; ans.X = -value.X; ans.Y = -value.Y; ans.Z = -value.Z; ans.W = -value.W; return ans; } /// <summary> /// Adds two Quaternions element-by-element. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second source Quaternion.</param> /// <returns>The result of adding the Quaternions.</returns> public static Quaternion operator +(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X + value2.X; ans.Y = value1.Y + value2.Y; ans.Z = value1.Z + value2.Z; ans.W = value1.W + value2.W; return ans; } /// <summary> /// Subtracts one Quaternion from another. /// </summary> /// <param name="value1">The first source Quaternion.</param> /// <param name="value2">The second Quaternion, to be subtracted from the first.</param> /// <returns>The result of the subtraction.</returns> public static Quaternion operator -(Quaternion value1, Quaternion value2) { Quaternion ans; ans.X = value1.X - value2.X; ans.Y = value1.Y - value2.Y; ans.Z = value1.Z - value2.Z; ans.W = value1.W - value2.W; return ans; } /// <summary> /// Multiplies two Quaternions together. /// </summary> /// <param name="value1">The Quaternion on the left side of the multiplication.</param> /// <param name="value2">The Quaternion on the right side of the multiplication.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion operator *(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; float q2x = value2.X; float q2y = value2.Y; float q2z = value2.Z; float q2w = value2.W; // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Multiplies a Quaternion by a scalar value. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The scalar value.</param> /// <returns>The result of the multiplication.</returns> public static Quaternion operator *(Quaternion value1, float value2) { Quaternion ans; ans.X = value1.X * value2; ans.Y = value1.Y * value2; ans.Z = value1.Z * value2; ans.W = value1.W * value2; return ans; } /// <summary> /// Divides a Quaternion by another Quaternion. /// </summary> /// <param name="value1">The source Quaternion.</param> /// <param name="value2">The divisor.</param> /// <returns>The result of the division.</returns> public static Quaternion operator /(Quaternion value1, Quaternion value2) { Quaternion ans; float q1x = value1.X; float q1y = value1.Y; float q1z = value1.Z; float q1w = value1.W; //------------------------------------- // Inverse part. float ls = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float invNorm = 1.0f / ls; float q2x = -value2.X * invNorm; float q2y = -value2.Y * invNorm; float q2z = -value2.Z * invNorm; float q2w = value2.W * invNorm; //------------------------------------- // Multiply part. // cross(av, bv) float cx = q1y * q2z - q1z * q2y; float cy = q1z * q2x - q1x * q2z; float cz = q1x * q2y - q1y * q2x; float dot = q1x * q2x + q1y * q2y + q1z * q2z; ans.X = q1x * q2w + q2x * q1w + cx; ans.Y = q1y * q2w + q2y * q1w + cy; ans.Z = q1z * q2w + q2z * q1w + cz; ans.W = q1w * q2w - dot; return ans; } /// <summary> /// Returns a boolean indicating whether the two given Quaternions are equal. /// </summary> /// <param name="value1">The first Quaternion to compare.</param> /// <param name="value2">The second Quaternion to compare.</param> /// <returns>True if the Quaternions are equal; False otherwise.</returns> public static bool operator ==(Quaternion value1, Quaternion value2) { return (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z && value1.W == value2.W); } /// <summary> /// Returns a boolean indicating whether the two given Quaternions are not equal. /// </summary> /// <param name="value1">The first Quaternion to compare.</param> /// <param name="value2">The second Quaternion to compare.</param> /// <returns>True if the Quaternions are not equal; False if they are equal.</returns> public static bool operator !=(Quaternion value1, Quaternion value2) { return (value1.X != value2.X || value1.Y != value2.Y || value1.Z != value2.Z || value1.W != value2.W); } /// <summary> /// Returns a boolean indicating whether the given Quaternion is equal to this Quaternion instance. /// </summary> /// <param name="other">The Quaternion to compare this instance to.</param> /// <returns>True if the other Quaternion is equal to this instance; False otherwise.</returns> public bool Equals(Quaternion other) { return (X == other.X && Y == other.Y && Z == other.Z && W == other.W); } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Quaternion instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Quaternion; False otherwise.</returns> public override bool Equals(object obj) { if (obj is Quaternion) { return Equals((Quaternion)obj); } return false; } /// <summary> /// Returns a String representing this Quaternion instance. /// </summary> /// <returns>The string representation.</returns> public override string ToString() { CultureInfo ci = CultureInfo.CurrentCulture; return String.Format(ci, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X.ToString(ci), Y.ToString(ci), Z.ToString(ci), W.ToString(ci)); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { return X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryNullableOrTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableByteOrTest(bool useInterpreter) { byte?[] array = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableByteOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableSByteOrTest(bool useInterpreter) { sbyte?[] array = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableSByteOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUShortOrTest(bool useInterpreter) { ushort?[] array = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUShortOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableShortOrTest(bool useInterpreter) { short?[] array = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableShortOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableUIntOrTest(bool useInterpreter) { uint?[] array = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableUIntOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableIntOrTest(bool useInterpreter) { int?[] array = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableIntOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableULongOrTest(bool useInterpreter) { ulong?[] array = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableULongOr(array[i], array[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNullableLongOrTest(bool useInterpreter) { long?[] array = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyNullableLongOr(array[i], array[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyNullableByteOr(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Or( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?))), Enumerable.Empty<ParameterExpression>()); Func<byte?> f = e.Compile(useInterpreter); Assert.Equal((byte?)(a | b), f()); } private static void VerifyNullableSByteOr(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Or( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?))), Enumerable.Empty<ParameterExpression>()); Func<sbyte?> f = e.Compile(useInterpreter); Assert.Equal((sbyte?)(a | b), f()); } private static void VerifyNullableUShortOr(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Or( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?))), Enumerable.Empty<ParameterExpression>()); Func<ushort?> f = e.Compile(useInterpreter); Assert.Equal((ushort?)(a | b), f()); } private static void VerifyNullableShortOr(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Or( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?))), Enumerable.Empty<ParameterExpression>()); Func<short?> f = e.Compile(useInterpreter); Assert.Equal((short?)(a | b), f()); } private static void VerifyNullableUIntOr(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Or( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?))), Enumerable.Empty<ParameterExpression>()); Func<uint?> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyNullableIntOr(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Or( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?))), Enumerable.Empty<ParameterExpression>()); Func<int?> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyNullableULongOr(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Or( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?))), Enumerable.Empty<ParameterExpression>()); Func<ulong?> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } private static void VerifyNullableLongOr(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Or( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?))), Enumerable.Empty<ParameterExpression>()); Func<long?> f = e.Compile(useInterpreter); Assert.Equal(a | b, f()); } #endregion } }
#region Apache License, Version 2.0 // // 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. // #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Microsoft.Win32; namespace NPanday.Utils { public class GacUtility { private static readonly ILog log = LogManager.GetLogger(typeof(GacUtility)); private string gacs; private static GacUtility instance; private GacUtility() { // Used to determine which references exist in the GAC, used during VS project import // TODO: we need a better way to determine this by querying the GAC using .NET // rather than parsing command output // consider this: http://www.codeproject.com/KB/dotnet/undocumentedfusion.aspx // (works, but seems to be missing the processor architecture) // Can also use LoadWithPartialName, but it is deprecated // First, let's find gacutil.exe. For now, we use .NET 4.0 if available to list everything and let // the rest of the logic sort out the right ones - but we might want to pre-filter this to CLR 2.0 // and CLR 4.0 versions string gacutil = "gacutil.exe"; Dictionary<string, KeyValuePair<string, string>> paths = new Dictionary<string, KeyValuePair<string, string>>(); try { RegistryKey sdks = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SDKs\Windows"); foreach (string sdk in sdks.GetSubKeyNames()) { using (RegistryKey key = sdks.OpenSubKey(sdk)) { foreach (string location in key.GetSubKeyNames()) { using (RegistryKey subkey = key.OpenSubKey(location)) { object value = subkey.GetValue("InstallationFolder"); if (value != null) { string exe = Path.Combine(value.ToString(), "gacutil.exe"); if (new FileInfo(exe).Exists) { // override with later ones in the list paths.Remove(location); paths.Add(location, new KeyValuePair<string,string>(sdk, exe)); } } } } } } string[] search = new string[] { "WinSDK-NetFx40Tools", "WinSDK-NetFx40Tools-x86", "WinSDK-NetFx35Tools", "WinSDK-NetFx35Tools-x86", "WinSDK-SDKTools" }; foreach (string s in search) { if (paths.ContainsKey(s)) { KeyValuePair<string, string> pair = paths[s]; gacutil = pair.Value; log.Info("Found gacutil from SDK " + pair.Key + " at " + gacutil); break; } } } catch (Exception e) { log.Error("Unable to find gacutil in the registry due to an exception: " + e.Message); } Process p = new Process(); try { p.StartInfo.FileName = gacutil; p.StartInfo.Arguments = "/l"; p.StartInfo.UseShellExecute = false; p.StartInfo.ErrorDialog = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardOutput = true; p.Start(); System.IO.StreamReader oReader2 = p.StandardOutput; gacs = oReader2.ReadToEnd(); oReader2.Close(); p.WaitForExit(); } catch ( Exception exception ) { throw new Exception( "Unable to execute gacutil - check that your PATH has been set correctly (Message: " + exception.Message + ")" ); } } public static GacUtility GetInstance() { if (instance == null) { instance = new GacUtility(); } return instance; } public static string GetNPandayGacType(System.Reflection.Assembly a, string publicKeyToken) { ProcessorArchitecture architecture = a.GetName().ProcessorArchitecture; return GetNPandayGacType(a.ImageRuntimeVersion, architecture, publicKeyToken); } public static string GetNPandayGacType(string runtimeVersion, ProcessorArchitecture architecture, string publicKeyToken) { string type; if (architecture == ProcessorArchitecture.MSIL) { if (runtimeVersion.StartsWith("v4.0")) { type = "gac_msil4"; } else { type = "gac_msil"; } } else if (architecture == ProcessorArchitecture.X86) { if (runtimeVersion.StartsWith("v4.0")) { type = "gac_32_4"; } else { type = "gac_32"; } } else if (architecture == ProcessorArchitecture.IA64 || architecture == ProcessorArchitecture.Amd64) { if (runtimeVersion.StartsWith("v4.0")) { type = "gac_64_4"; } else { type = "gac_64"; } } else { type = "gac"; } return type; } public List<string> GetAssemblyInfo(string assemblyName, string version, string processorArchitecture) { if (string.IsNullOrEmpty(assemblyName)) { return null; } List<string> results = new List<string>(); string architecture = String.Empty; if (! string.IsNullOrEmpty(processorArchitecture)) { architecture = GetRegexProcessorArchitectureFromString(processorArchitecture); } Regex regex; if (string.IsNullOrEmpty(version)) { regex = new Regex(@"\s+" + assemblyName + @",.*processorArchitecture=" + architecture + ".*", RegexOptions.IgnoreCase); } else { regex = new Regex(@"\s+" + assemblyName + @",\s*Version=" + Regex.Escape(version) + @".*processorArchitecture=" + architecture + ".*", RegexOptions.IgnoreCase); } MatchCollection matches = regex.Matches(gacs); foreach (Match match in matches) { results.Add(match.Value.Trim()); } return results; } private static string GetRegexProcessorArchitectureFromString(string input) { switch (input) { case "x64": return "(AMD64|MSIL)"; case "Itanium": return "(IA64|MSIL)"; case "x86": return "(x86|MSIL)"; case "AnyCPU": return "(x86|MSIL)"; default: return input; } } } }
// // 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 Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetVMReimageDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetVMReimageMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); string instanceId = (string)ParseParameter(invokeMethodInputParameters[2]); var result = VirtualMachineScaleSetVMsClient.Reimage(resourceGroupName, vmScaleSetName, instanceId); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetVMReimageParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; string instanceId = string.Empty; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceId" }, new object[] { resourceGroupName, vmScaleSetName, instanceId }); } } [Cmdlet(VerbsCommon.Set, "AzureRmVmssVM", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)] public partial class SetAzureRmVmssVM : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { if (this.ParameterSetName == "InvokeByDynamicParameters") { this.MethodName = "VirtualMachineScaleSetVMReimage"; } else { this.MethodName = "VirtualMachineScaleSetVMReimageAll"; } if (ShouldProcess(this.dynamicParameters["ResourceGroupName"].Value.ToString(), VerbsCommon.Set)) { base.ProcessRecord(); } } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new AliasAttribute("Name")); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 3, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pReimage = new RuntimeDefinedParameter(); pReimage.Name = "Reimage"; pReimage.ParameterType = typeof(SwitchParameter); pReimage.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 4, Mandatory = true }); pReimage.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Reimage", pReimage); var pReimageAll = new RuntimeDefinedParameter(); pReimageAll.Name = "ReimageAll"; pReimageAll.ParameterType = typeof(SwitchParameter); pReimageAll.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 4, Mandatory = true }); pReimageAll.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ReimageAll", pReimageAll); return dynamicParameters; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PrimitiveOperations. /// </summary> public static partial class PrimitiveOperationsExtensions { /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IntWrapperInner GetInt(this IPrimitiveOperations operations) { return operations.GetIntAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IntWrapperInner> GetIntAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetIntWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> public static void PutInt(this IPrimitiveOperations operations, IntWrapperInner complexBody) { operations.PutIntAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutIntAsync(this IPrimitiveOperations operations, IntWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutIntWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LongWrapperInner GetLong(this IPrimitiveOperations operations) { return operations.GetLongAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LongWrapperInner> GetLongAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetLongWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> public static void PutLong(this IPrimitiveOperations operations, LongWrapperInner complexBody) { operations.PutLongAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLongAsync(this IPrimitiveOperations operations, LongWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutLongWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static FloatWrapperInner GetFloat(this IPrimitiveOperations operations) { return operations.GetFloatAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FloatWrapperInner> GetFloatAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> public static void PutFloat(this IPrimitiveOperations operations, FloatWrapperInner complexBody) { operations.PutFloatAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutFloatAsync(this IPrimitiveOperations operations, FloatWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutFloatWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DoubleWrapperInner GetDouble(this IPrimitiveOperations operations) { return operations.GetDoubleAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DoubleWrapperInner> GetDoubleAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> public static void PutDouble(this IPrimitiveOperations operations, DoubleWrapperInner complexBody) { operations.PutDoubleAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDoubleAsync(this IPrimitiveOperations operations, DoubleWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDoubleWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static BooleanWrapperInner GetBool(this IPrimitiveOperations operations) { return operations.GetBoolAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BooleanWrapperInner> GetBoolAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetBoolWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put true and false /// </param> public static void PutBool(this IPrimitiveOperations operations, BooleanWrapperInner complexBody) { operations.PutBoolAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put true and false /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBoolAsync(this IPrimitiveOperations operations, BooleanWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBoolWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static StringWrapperInner GetString(this IPrimitiveOperations operations) { return operations.GetStringAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StringWrapperInner> GetStringAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStringWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> public static void PutString(this IPrimitiveOperations operations, StringWrapperInner complexBody) { operations.PutStringAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutStringAsync(this IPrimitiveOperations operations, StringWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutStringWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateWrapperInner GetDate(this IPrimitiveOperations operations) { return operations.GetDateAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateWrapperInner> GetDateAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> public static void PutDate(this IPrimitiveOperations operations, DateWrapperInner complexBody) { operations.PutDateAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateAsync(this IPrimitiveOperations operations, DateWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDateWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DatetimeWrapperInner GetDateTime(this IPrimitiveOperations operations) { return operations.GetDateTimeAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DatetimeWrapperInner> GetDateTimeAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' /// </param> public static void PutDateTime(this IPrimitiveOperations operations, DatetimeWrapperInner complexBody) { operations.PutDateTimeAsync(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateTimeAsync(this IPrimitiveOperations operations, DatetimeWrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDateTimeWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Datetimerfc1123WrapperInner GetDateTimeRfc1123(this IPrimitiveOperations operations) { return operations.GetDateTimeRfc1123Async().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Datetimerfc1123WrapperInner> GetDateTimeRfc1123Async(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDateTimeRfc1123WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 /// GMT' /// </param> public static void PutDateTimeRfc1123(this IPrimitiveOperations operations, Datetimerfc1123WrapperInner complexBody) { operations.PutDateTimeRfc1123Async(complexBody).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with datetimeRfc1123 properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 /// GMT' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateTimeRfc1123Async(this IPrimitiveOperations operations, Datetimerfc1123WrapperInner complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDateTimeRfc1123WithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DurationWrapperInner GetDuration(this IPrimitiveOperations operations) { return operations.GetDurationAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DurationWrapperInner> GetDurationAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDurationWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> public static void PutDuration(this IPrimitiveOperations operations, System.TimeSpan? field = default(System.TimeSpan?)) { operations.PutDurationAsync(field).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with duration properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDurationAsync(this IPrimitiveOperations operations, System.TimeSpan? field = default(System.TimeSpan?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDurationWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ByteWrapperInner GetByte(this IPrimitiveOperations operations) { return operations.GetByteAsync().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ByteWrapperInner> GetByteAsync(this IPrimitiveOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetByteWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> public static void PutByte(this IPrimitiveOperations operations, byte[] field = default(byte[])) { operations.PutByteAsync(field).GetAwaiter().GetResult(); } /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='field'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutByteAsync(this IPrimitiveOperations operations, byte[] field = default(byte[]), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutByteWithHttpMessagesAsync(field, null, cancellationToken).ConfigureAwait(false); } } }
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFAB_STATIC_API using PlayFab.DataModels; using PlayFab.Internal; #pragma warning disable 0649 using System; // This is required for the Obsolete Attribute flag // which is not always present in all API's #pragma warning restore 0649 using System.Collections.Generic; using System.Threading.Tasks; namespace PlayFab { /// <summary> /// Store arbitrary data associated with an entity. Objects are small (~1KB) JSON-compatible objects which are stored /// directly on the entity profile. Objects are made available for use in other PlayFab contexts, such as PlayStream events /// and CloudScript functions. Files can efficiently store data of any size or format. Both objects and files support a /// flexible permissions system to control read and write access by other entities. /// </summary> public static class PlayFabDataAPI { /// <summary> /// Verify entity login. /// </summary> public static bool IsEntityLoggedIn() { return PlayFabSettings.staticPlayer.IsEntityLoggedIn(); } /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public static void ForgetAllCredentials() { PlayFabSettings.staticPlayer.ForgetAllCredentials(); } /// <summary> /// Abort pending file uploads to an entity's profile. /// </summary> public static async Task<PlayFabResult<AbortFileUploadsResponse>> AbortFileUploadsAsync(AbortFileUploadsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/File/AbortFileUploads", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<AbortFileUploadsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<AbortFileUploadsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<AbortFileUploadsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Delete files on an entity's profile. /// </summary> public static async Task<PlayFabResult<DeleteFilesResponse>> DeleteFilesAsync(DeleteFilesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/File/DeleteFiles", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<DeleteFilesResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<DeleteFilesResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<DeleteFilesResponse> { Result = result, CustomData = customData }; } /// <summary> /// Finalize file uploads to an entity's profile. /// </summary> public static async Task<PlayFabResult<FinalizeFileUploadsResponse>> FinalizeFileUploadsAsync(FinalizeFileUploadsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/File/FinalizeFileUploads", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<FinalizeFileUploadsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<FinalizeFileUploadsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<FinalizeFileUploadsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves file metadata from an entity's profile. /// </summary> public static async Task<PlayFabResult<GetFilesResponse>> GetFilesAsync(GetFilesRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/File/GetFiles", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetFilesResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetFilesResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetFilesResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves objects from an entity's profile. /// </summary> public static async Task<PlayFabResult<GetObjectsResponse>> GetObjectsAsync(GetObjectsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Object/GetObjects", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetObjectsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetObjectsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetObjectsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Initiates file uploads to an entity's profile. /// </summary> public static async Task<PlayFabResult<InitiateFileUploadsResponse>> InitiateFileUploadsAsync(InitiateFileUploadsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/File/InitiateFileUploads", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<InitiateFileUploadsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<InitiateFileUploadsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<InitiateFileUploadsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Sets objects on an entity's profile. /// </summary> public static async Task<PlayFabResult<SetObjectsResponse>> SetObjectsAsync(SetObjectsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Object/SetObjects", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SetObjectsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetObjectsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SetObjectsResponse> { Result = result, CustomData = customData }; } } } #endif
namespace XenAdmin.Dialogs { partial class AssignLicenseDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { licenseServerNameTextBox.TextChanged -= licenseServerPortTextBox_TextChanged; licenseServerPortTextBox.TextChanged -= licenseServerNameTextBox_TextChanged; components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AssignLicenseDialog)); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.mainLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.licenseServerLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.licenseServerNameLabel = new System.Windows.Forms.Label(); this.licenseServerNameTextBox = new System.Windows.Forms.TextBox(); this.licenseServerPortTextBox = new System.Windows.Forms.TextBox(); this.colonLabel = new System.Windows.Forms.Label(); this.mainLabel = new System.Windows.Forms.Label(); this.editionsGroupBox = new System.Windows.Forms.GroupBox(); this.editionLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.perSocketRadioButton = new System.Windows.Forms.RadioButton(); this.advancedRadioButton = new System.Windows.Forms.RadioButton(); this.enterpriseRadioButton = new System.Windows.Forms.RadioButton(); this.platinumRadioButton = new System.Windows.Forms.RadioButton(); this.xenDesktopEnterpriseRadioButton = new System.Windows.Forms.RadioButton(); this.enterprisePerSocketRadioButton = new System.Windows.Forms.RadioButton(); this.enterprisePerUserRadioButton = new System.Windows.Forms.RadioButton(); this.desktopRadioButton = new System.Windows.Forms.RadioButton(); this.standardPerSocketRadioButton = new System.Windows.Forms.RadioButton(); this.buttonsLayoutPanel = new System.Windows.Forms.FlowLayoutPanel(); this.desktopPlusRadioButton = new System.Windows.Forms.RadioButton(); this.mainLayoutPanel.SuspendLayout(); this.licenseServerLayoutPanel.SuspendLayout(); this.editionsGroupBox.SuspendLayout(); this.editionLayoutPanel.SuspendLayout(); this.buttonsLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // okButton // resources.ApplyResources(this.okButton, "okButton"); this.okButton.Name = "okButton"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.Name = "cancelButton"; this.cancelButton.UseVisualStyleBackColor = true; // // mainLayoutPanel // resources.ApplyResources(this.mainLayoutPanel, "mainLayoutPanel"); this.mainLayoutPanel.Controls.Add(this.licenseServerLayoutPanel, 0, 1); this.mainLayoutPanel.Controls.Add(this.mainLabel, 0, 0); this.mainLayoutPanel.Controls.Add(this.editionsGroupBox, 0, 2); this.mainLayoutPanel.Controls.Add(this.buttonsLayoutPanel, 0, 3); this.mainLayoutPanel.Name = "mainLayoutPanel"; // // licenseServerLayoutPanel // resources.ApplyResources(this.licenseServerLayoutPanel, "licenseServerLayoutPanel"); this.licenseServerLayoutPanel.Controls.Add(this.licenseServerNameLabel, 0, 0); this.licenseServerLayoutPanel.Controls.Add(this.licenseServerNameTextBox, 1, 0); this.licenseServerLayoutPanel.Controls.Add(this.licenseServerPortTextBox, 3, 0); this.licenseServerLayoutPanel.Controls.Add(this.colonLabel, 2, 0); this.licenseServerLayoutPanel.Name = "licenseServerLayoutPanel"; // // licenseServerNameLabel // resources.ApplyResources(this.licenseServerNameLabel, "licenseServerNameLabel"); this.licenseServerNameLabel.Name = "licenseServerNameLabel"; // // licenseServerNameTextBox // resources.ApplyResources(this.licenseServerNameTextBox, "licenseServerNameTextBox"); this.licenseServerNameTextBox.Name = "licenseServerNameTextBox"; // // licenseServerPortTextBox // resources.ApplyResources(this.licenseServerPortTextBox, "licenseServerPortTextBox"); this.licenseServerPortTextBox.Name = "licenseServerPortTextBox"; // // colonLabel // resources.ApplyResources(this.colonLabel, "colonLabel"); this.colonLabel.Name = "colonLabel"; // // mainLabel // resources.ApplyResources(this.mainLabel, "mainLabel"); this.mainLabel.Name = "mainLabel"; // // editionsGroupBox // resources.ApplyResources(this.editionsGroupBox, "editionsGroupBox"); this.editionsGroupBox.Controls.Add(this.editionLayoutPanel); this.editionsGroupBox.Name = "editionsGroupBox"; this.editionsGroupBox.TabStop = false; // // editionLayoutPanel // resources.ApplyResources(this.editionLayoutPanel, "editionLayoutPanel"); this.editionLayoutPanel.Controls.Add(this.perSocketRadioButton); this.editionLayoutPanel.Controls.Add(this.advancedRadioButton); this.editionLayoutPanel.Controls.Add(this.enterpriseRadioButton); this.editionLayoutPanel.Controls.Add(this.platinumRadioButton); this.editionLayoutPanel.Controls.Add(this.xenDesktopEnterpriseRadioButton); this.editionLayoutPanel.Controls.Add(this.enterprisePerSocketRadioButton); this.editionLayoutPanel.Controls.Add(this.enterprisePerUserRadioButton); this.editionLayoutPanel.Controls.Add(this.desktopPlusRadioButton); this.editionLayoutPanel.Controls.Add(this.desktopRadioButton); this.editionLayoutPanel.Controls.Add(this.standardPerSocketRadioButton); this.editionLayoutPanel.Name = "editionLayoutPanel"; // // perSocketRadioButton // resources.ApplyResources(this.perSocketRadioButton, "perSocketRadioButton"); this.perSocketRadioButton.Checked = true; this.perSocketRadioButton.Name = "perSocketRadioButton"; this.perSocketRadioButton.TabStop = true; this.perSocketRadioButton.UseVisualStyleBackColor = true; // // advancedRadioButton // resources.ApplyResources(this.advancedRadioButton, "advancedRadioButton"); this.advancedRadioButton.Name = "advancedRadioButton"; this.advancedRadioButton.UseVisualStyleBackColor = true; // // enterpriseRadioButton // resources.ApplyResources(this.enterpriseRadioButton, "enterpriseRadioButton"); this.enterpriseRadioButton.Name = "enterpriseRadioButton"; this.enterpriseRadioButton.UseVisualStyleBackColor = true; // // platinumRadioButton // resources.ApplyResources(this.platinumRadioButton, "platinumRadioButton"); this.platinumRadioButton.Name = "platinumRadioButton"; this.platinumRadioButton.UseVisualStyleBackColor = true; // // xenDesktopEnterpriseRadioButton // resources.ApplyResources(this.xenDesktopEnterpriseRadioButton, "xenDesktopEnterpriseRadioButton"); this.xenDesktopEnterpriseRadioButton.Name = "xenDesktopEnterpriseRadioButton"; this.xenDesktopEnterpriseRadioButton.UseVisualStyleBackColor = true; // // enterprisePerSocketRadioButton // resources.ApplyResources(this.enterprisePerSocketRadioButton, "enterprisePerSocketRadioButton"); this.enterprisePerSocketRadioButton.Name = "enterprisePerSocketRadioButton"; this.enterprisePerSocketRadioButton.UseVisualStyleBackColor = true; // // enterprisePerUserRadioButton // resources.ApplyResources(this.enterprisePerUserRadioButton, "enterprisePerUserRadioButton"); this.enterprisePerUserRadioButton.Name = "enterprisePerUserRadioButton"; this.enterprisePerUserRadioButton.UseVisualStyleBackColor = true; // // desktopRadioButton // resources.ApplyResources(this.desktopRadioButton, "desktopRadioButton"); this.desktopRadioButton.Name = "desktopRadioButton"; this.desktopRadioButton.UseVisualStyleBackColor = true; // // standardPerSocketRadioButton // resources.ApplyResources(this.standardPerSocketRadioButton, "standardPerSocketRadioButton"); this.standardPerSocketRadioButton.Name = "standardPerSocketRadioButton"; this.standardPerSocketRadioButton.UseVisualStyleBackColor = true; // // buttonsLayoutPanel // resources.ApplyResources(this.buttonsLayoutPanel, "buttonsLayoutPanel"); this.buttonsLayoutPanel.Controls.Add(this.okButton); this.buttonsLayoutPanel.Controls.Add(this.cancelButton); this.buttonsLayoutPanel.Name = "buttonsLayoutPanel"; // // desktopPlusRadioButton // resources.ApplyResources(this.desktopPlusRadioButton, "desktopPlusRadioButton"); this.desktopPlusRadioButton.Name = "desktopPlusRadioButton"; this.desktopPlusRadioButton.UseVisualStyleBackColor = true; // // AssignLicenseDialog // this.AcceptButton = this.okButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.cancelButton; this.Controls.Add(this.mainLayoutPanel); this.Name = "AssignLicenseDialog"; this.Shown += new System.EventHandler(this.AssignLicenseDialog_Shown); this.mainLayoutPanel.ResumeLayout(false); this.mainLayoutPanel.PerformLayout(); this.licenseServerLayoutPanel.ResumeLayout(false); this.licenseServerLayoutPanel.PerformLayout(); this.editionsGroupBox.ResumeLayout(false); this.editionsGroupBox.PerformLayout(); this.editionLayoutPanel.ResumeLayout(false); this.editionLayoutPanel.PerformLayout(); this.buttonsLayoutPanel.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.TableLayoutPanel mainLayoutPanel; private System.Windows.Forms.Label mainLabel; private System.Windows.Forms.FlowLayoutPanel buttonsLayoutPanel; private System.Windows.Forms.TableLayoutPanel licenseServerLayoutPanel; private System.Windows.Forms.Label licenseServerNameLabel; private System.Windows.Forms.TextBox licenseServerNameTextBox; private System.Windows.Forms.TextBox licenseServerPortTextBox; private System.Windows.Forms.Label colonLabel; private System.Windows.Forms.GroupBox editionsGroupBox; private System.Windows.Forms.FlowLayoutPanel editionLayoutPanel; private System.Windows.Forms.RadioButton perSocketRadioButton; private System.Windows.Forms.RadioButton advancedRadioButton; private System.Windows.Forms.RadioButton enterpriseRadioButton; private System.Windows.Forms.RadioButton platinumRadioButton; private System.Windows.Forms.RadioButton xenDesktopEnterpriseRadioButton; private System.Windows.Forms.RadioButton enterprisePerSocketRadioButton; private System.Windows.Forms.RadioButton enterprisePerUserRadioButton; private System.Windows.Forms.RadioButton desktopRadioButton; private System.Windows.Forms.RadioButton standardPerSocketRadioButton; private System.Windows.Forms.RadioButton desktopPlusRadioButton; } }
#region /* Copyright (c) 2002-2012, Bas Geertsema, Xih Solutions (http://www.xihsolutions.net), Thiago.Sayao, Pang Wu, Ethem Evlice, Andy Phan, Chang Liu. All rights reserved. http://code.google.com/p/msnp-sharp/ 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 names of Bas Geertsema or Xih Solutions nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion using System; using System.IO; using System.Web; using System.Xml; using System.Text; using System.Drawing; using System.Text.RegularExpressions; namespace MSNPSharp { using MSNPSharp.Core; using System.Globalization; [Serializable] public class PersonalMessage { private string userTileLocation = string.Empty; private string friendlyName = string.Empty; private string rum = string.Empty; private string personalMessage = string.Empty; private string ddp = string.Empty; private string scene = string.Empty; private Color colorScheme = Color.Empty; private string signatureSound = string.Empty; private MediaType mediaType = MediaType.None; private string appName = string.Empty; private string format = string.Empty; private string[] content; public PersonalMessage() { } public PersonalMessage(string personalmsg) { Message = personalmsg; } public PersonalMessage(string personalmsg, MediaType mediatype, string[] currentmediacontent) { Message = personalmsg; mediaType = mediatype; content = currentmediacontent; Format = "{0}"; } public PersonalMessage(string personalmsg, MediaType mediatype, string[] currentmediacontent, string contentformat) { Message = personalmsg; mediaType = mediatype; content = currentmediacontent; Format = contentformat; } internal PersonalMessage(XmlNodeList nodeList) { try { Handle(nodeList); } catch (Exception exception) { System.Diagnostics.Trace.WriteLineIf(Settings.TraceSwitch.TraceError, exception.Message, GetType().Name); } } public string UserTileLocation { get { return userTileLocation; } set { userTileLocation = value; } } public string FriendlyName { get { return friendlyName; } set { friendlyName = value; } } public string Message { get { return personalMessage; } set { personalMessage = value; if(MediaType != MediaType.None) MediaType = MediaType.None; } } public string RUM { get { return rum; } set { rum = value; } } public string DDP { get { return ddp; } set { ddp = value; } } public string Scene { get { return scene; } set { scene = value; } } public Color ColorScheme { get { return colorScheme; } set { colorScheme = value; } } public string SignatureSound { get { return signatureSound; } private set { signatureSound = value; } } public MediaType MediaType { get { return mediaType; } private set { mediaType = value; } } public string AppName { get { return appName; } } public string Format { get { return format; } set { format = value; } } //This is used in conjunction with format public string[] CurrentMediaContent { get { return content; } set { content = value; } } public string CurrentMedia { get { string currentmedia = String.Empty; if (mediaType != MediaType.None) { foreach (string media in content) { currentmedia = currentmedia + media + @"\0"; } if (String.IsNullOrEmpty(Format)) Format = "{0}"; currentmedia = @"\0" + mediaType.ToString() + @"\01\0" + Format + @"\0" + currentmedia; } return currentmedia; } } public string Payload { get { // I think we need a serializer for PersonalMessage. XmlDocument xdoc = new XmlDocument(); XmlNode rootNode = xdoc.CreateElement("root"); xdoc.AppendChild(rootNode); XmlNode userTileLocationNode = xdoc.CreateElement("UserTileLocation"); userTileLocationNode.InnerText = UserTileLocation; rootNode.AppendChild(userTileLocationNode); XmlNode friendlyNameNode = xdoc.CreateElement("FriendlyName"); friendlyNameNode.InnerText = FriendlyName; rootNode.AppendChild(friendlyNameNode); XmlNode rumNode = xdoc.CreateElement("RUM"); rumNode.InnerText = RUM; rootNode.AppendChild(rumNode); XmlNode personalMessageNode = xdoc.CreateElement("PSM"); personalMessageNode.InnerText = Message; rootNode.AppendChild(personalMessageNode); XmlNode ddpNode = xdoc.CreateElement("DDP"); ddpNode.InnerText = DDP; rootNode.AppendChild(ddpNode); XmlNode colorSchemeNode = xdoc.CreateElement("ColorScheme"); colorSchemeNode.InnerText = ColorScheme.ToArgb().ToString(CultureInfo.InvariantCulture); rootNode.AppendChild(colorSchemeNode); XmlNode sceneNode = xdoc.CreateElement("Scene"); sceneNode.InnerText = Scene; rootNode.AppendChild(sceneNode); XmlNode signatureSoundNode = xdoc.CreateElement("SignatureSound"); signatureSoundNode.InnerText = HttpUtility.UrlEncode(SignatureSound); rootNode.AppendChild(signatureSoundNode); XmlNode currentMediaNode = xdoc.CreateElement("CurrentMedia"); currentMediaNode.InnerText = CurrentMedia; rootNode.AppendChild(currentMediaNode); return rootNode.InnerXml; } } public string ToDebugString() { return Payload; } public override string ToString() { return Payload; } public void SetListeningAlbum(string artist, string song, string album) { this.mediaType = MediaType.Music; this.content = new string[] { artist, song, album, String.Empty }; } private void Handle(XmlNodeList nodeList) { if (nodeList == null || nodeList.Count == 0) return; foreach (XmlNode node in nodeList) { if (!String.IsNullOrEmpty(node.InnerText)) { // REMARK: All the MSNObject must use MSNObject.GetDecodeString(string) to get the decoded conext. switch (node.Name) { case "UserTileLocation": UserTileLocation = MSNObject.GetDecodeString(node.InnerText); break; case "FriendlyName": FriendlyName = node.InnerText; break; case "RUM": RUM = System.Web.HttpUtility.UrlDecode(node.InnerText, System.Text.Encoding.UTF8); break; case "PSM": Message = System.Web.HttpUtility.UrlDecode(node.InnerText, System.Text.Encoding.UTF8); break; case "DDP": DDP = System.Web.HttpUtility.UrlDecode(node.InnerText, System.Text.Encoding.UTF8); break; case "ColorScheme": ColorScheme = ColorTranslator.FromOle(int.Parse(node.InnerText)); break; case "Scene": Scene = MSNObject.GetDecodeString(node.InnerText); break; case "SignatureSound": SignatureSound = System.Web.HttpUtility.UrlDecode(node.InnerText, System.Text.Encoding.UTF8); break; case "CurrentMedia": string mediaString = System.Web.HttpUtility.UrlDecode(node.InnerText, System.Text.Encoding.UTF8); if (mediaString.Length > 0) { string[] vals = mediaString.Split(new string[] { @"\0" }, StringSplitOptions.None); if (!String.IsNullOrEmpty(vals[0])) appName = vals[0]; switch (vals[1]) { case "Music": MediaType = MediaType.Music; break; case "Games": MediaType = MediaType.Games; break; case "Office": MediaType = MediaType.Office; break; } /* 0 1 Music 2 1 3 {0} - {1} 4 Evanescence 5 Call Me When You're Sober 6 Album 7 WMContentID 8 */ //vals[2] = Enabled/Disabled Format = vals[3]; int size = vals.Length - 4; CurrentMediaContent = new String[size]; for (int i = 0; i < size; i++) CurrentMediaContent[i] = vals[i + 4]; } break; } } } } public static bool operator ==(PersonalMessage psm1, PersonalMessage psm2) { if (((object)psm1) == null && ((object)psm2) == null) return true; if (((object)psm1) == null || ((object)psm2) == null) return false; return psm1.Payload.Equals(psm2.Payload); } public static bool operator !=(PersonalMessage psm1, PersonalMessage psm2) { return !(psm1 == psm2); } public override bool Equals(object obj) { if (obj == null || obj.GetType() != GetType()) return false; return this.Payload == ((PersonalMessage)obj).Payload; } public override int GetHashCode() { return Payload.GetHashCode(); } } };
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Cats.Models.Hubs; using Cats.Services.Hub; using Cats.Models.Hubs.ViewModels.Common; using Cats.Models.Hubs.ViewModels.Report; using Cats.Web.Hub.Controllers.Reports; using Moq; using NUnit.Framework; namespace Cats.Web.Hub.Tests { [TestFixture] public class StockManagementControllerTests { #region SetUp / TearDown private StockManagementController _stockManagementController; [SetUp] public void Init() { var userProfiles = new List<UserProfile> { new UserProfile {UserProfileID = 1, UserName = "Nathnael", Password = "passWord", Email = "[email protected]"}, new UserProfile {UserProfileID = 2, UserName = "Banty", Password="passWord", Email = "[email protected]"}, }; var userProfileService = new Mock<IUserProfileService>(); userProfileService.Setup(t => t.GetAllUserProfile()).Returns(userProfiles); var programs = new List<Program> { new Program{ProgramID = 1, Name = "Relief"}, new Program{ProgramID = 2, Name = "PSNP"} }; var programService = new Mock<IProgramService>(); programService.Setup(t => t.GetAllProgram()).Returns(programs); var commodityTypes = new List<CommodityType> { new CommodityType{ CommodityTypeID = 1, Name = "Food"}, new CommodityType{ CommodityTypeID = 2, Name = "Non Food"} }; var commodityTypeService = new Mock<ICommodityTypeService>(); commodityTypeService.Setup(t => t.GetAllCommodityType()).Returns(commodityTypes); var commoditySource = new List<CommoditySource> { new CommoditySource {CommoditySourceID = 1, Name = "Donation"}, new CommoditySource {CommoditySourceID = 2, Name = "Loan"}, new CommoditySource {CommoditySourceID = 3, Name = "Local Purchase"}, }; var commoditySourceService = new Mock<ICommoditySourceService>(); commoditySourceService.Setup(t => t.GetAllCommoditySource()).Returns(commoditySource); var projectCodes = new List<ProjectCode> { new ProjectCode{ProjectCodeID = 76, Value = "10685 MT"}, new ProjectCode{ProjectCodeID = 77, Value = "1314.3"} }; var projectCodeService = new Mock<IProjectCodeService>(); projectCodeService.Setup(t => t.GetAllProjectCode()).Returns(projectCodes); var shippingInstructions = new List<ShippingInstruction> { new ShippingInstruction{ShippingInstructionID = 104, Value = "00013753"}, new ShippingInstruction{ShippingInstructionID = 102, Value = "00014110"} }; var shippingInstructionService = new Mock<IShippingInstructionService>(); shippingInstructionService.Setup(t => t.GetAllShippingInstruction()).Returns(shippingInstructions); var receiveService = new Mock<IReceiveService>(); var storeService = new Mock<IStoreService>(); var hubService = new Mock<IHubService>(); var adminUnitService = new Mock<IAdminUnitService>(); var dispatchAllocationServie = new Mock<IDispatchAllocationService>(); var donorService = new Mock<IDonorService>(); _stockManagementController = new StockManagementController( userProfileService.Object, programService.Object, commodityTypeService.Object, commoditySourceService.Object, projectCodeService.Object, shippingInstructionService.Object, receiveService.Object, storeService.Object, hubService.Object, adminUnitService.Object, dispatchAllocationServie.Object, donorService.Object); } [TearDown] public void Dispose() { _stockManagementController.Dispose(); } #endregion #region Tests [Test] public void CanViewArrivalsVsReceipts() { //ACT var viewResult = _stockManagementController.ArrivalsVsReceipts() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<ArrivalsVsReceiptsViewModel>(model); } [Test] public void CanArrivalsVsReceiptsReport() { //ACT //TODO: Seed data into ArrivalsVsReceiptsViewModel before proceding with testing var viewModel = new ArrivalsVsReceiptsViewModel {}; var viewResult = _stockManagementController.ArrivalsVsReceiptsReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); Assert.IsInstanceOf<IEnumerable<CommoditySource>>(viewResult.ViewBag.CommoditySources); } [Test] public void CanViewReceipts() { //ACT var viewResult = _stockManagementController.Receipts() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<ReceiptsViewModel>(model); } [Test] public void CanReceiptsReport() { //ACT //TODO: Seed data into ReceiptsViewModel before proceding with testing var viewModel = new ReceiptsViewModel { }; var viewResult = _stockManagementController.ReceiptsReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); Assert.IsInstanceOf<IEnumerable<CommoditySource>>(viewResult.ViewBag.CommoditySources); } [Test] public void CanViewStockBalance() { //ACT var viewResult = _stockManagementController.StockBalance() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<StockBalanceViewModel>(model); } [Test] public void CanBackPostStockBalanceReport() { //ACT //TODO: Seed data into StockBalanceViewModel before proceding with testing var viewModel = new StockBalanceViewModel { }; var viewResult = _stockManagementController.StockBalanceReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewDispatches() { //ACT var viewResult = _stockManagementController.Dispatches() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<DispatchesViewModel>(model); } [Test] public void CanBackPostDispatchesReport() { //ACT //TODO: Seed data into DispatchesViewModel before proceding with testing var viewModel = new DispatchesViewModel { }; var viewResult = _stockManagementController.DispatchesReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewCommittedVsDispatched() { //ACT var viewResult = _stockManagementController.CommittedVsDispatched() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<CommittedVsDispatchedViewModel>(model); } [Test] public void CanBackPostCommittedVsDispatchedReport() { //ACT //TODO: Seed data into CommittedVsDispatchedViewModel before proceding with testing var viewModel = new CommittedVsDispatchedViewModel { }; var viewResult = _stockManagementController.CommittedVsDispatchedReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewInTransit() { //ACT var viewResult = _stockManagementController.InTransit() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<InTransitViewModel>(model); } [Test] public void CanBackPostInTransitReprot() { //ACT //TODO: Seed data into InTransitViewModel before proceding with testing var viewModel = new InTransitViewModel { }; var viewResult = _stockManagementController.InTransitReprot(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewDeliveryAgainstDispatch() { //ACT var viewResult = _stockManagementController.DeliveryAgainstDispatch() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<DeliveryAgainstDispatchViewModel>(model); } [Test] public void CanBackPostDeliveryAgainstDispatchReport() { //ACT //TODO: Seed data into DeliveryAgainstDispatchViewModel before proceding with testing var viewModel = new DeliveryAgainstDispatchViewModel { }; var viewResult = _stockManagementController.DeliveryAgainstDispatchReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewDistributionDeliveryDispatch() { //ACT var viewResult = _stockManagementController.DistributionDeliveryDispatch() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<DistributionDeliveryDispatchViewModel>(model); } [Test] public void CanBackPostDistributionDeliveryDispatchReport() { //ACT //TODO: Seed data into DistributionDeliveryDispatchViewModel before proceding with testing var viewModel = new DistributionDeliveryDispatchViewModel { }; var viewResult = _stockManagementController.DistributionDeliveryDispatchReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewDistributionByOwner() { //ACT var viewResult = _stockManagementController.DistributionByOwner() as ViewResult; //ASSERT Assert.NotNull(viewResult); var model = viewResult.Model; Assert.IsInstanceOf<DistributionByOwnerViewModel>(model); } [Test] public void CanBackPostDistributionByOwnerReport() { //ACT //TODO: Seed data into DistributionByOwnerViewModel before proceding with testing var viewModel = new DistributionByOwnerViewModel { }; var viewResult = _stockManagementController.DistributionByOwnerReport(viewModel) as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<Program>>(viewResult.ViewBag.Program); Assert.IsInstanceOf<IEnumerable<CommodityType>>(viewResult.ViewBag.CommodityTypes); } [Test] public void CanViewProjectCode() { //ACT var viewResult = _stockManagementController.ProjectCode() as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<SelectList>>(viewResult.ViewBag.ProjectCode); Assert.AreEqual("ProjectCodeId", ((SelectList)viewResult.ViewBag.ProjectCode).DataValueField); Assert.AreEqual("ProjectName", ((SelectList)viewResult.ViewBag.ProjectCode).DataTextField); Assert.IsInstanceOf<IEnumerable<ProjectCodeViewModel>>(((SelectList)viewResult.ViewBag.ProjectCode).Items); } [Test] public void CanViewShippingInstruction () { //ACT var viewResult = _stockManagementController.ShippingInstruction() as ViewResult; //ASSERT Assert.NotNull(viewResult); Assert.IsInstanceOf<IEnumerable<SelectList>>(viewResult.ViewBag.ShippingInstruction); Assert.AreEqual("ShippingInstructionId", ((SelectList)viewResult.ViewBag.ShippingInstruction).DataValueField); Assert.AreEqual("ShippingInstructionName", ((SelectList)viewResult.ViewBag.ShippingInstruction).DataTextField); Assert.IsInstanceOf<IEnumerable<ShippingInstructionViewModel>>(((SelectList)viewResult.ViewBag.ShippingInstruction).Items); } #endregion } }
using System; using System.Drawing; using System.Linq; using System.Windows.Forms; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.Routing; using Microsoft.Msagl.Layout.Layered; using P = Microsoft.Msagl.Core.Geometry.Point; using System.Drawing.Drawing2D; using Edge = Microsoft.Msagl.Core.Layout.Edge; using Node = Microsoft.Msagl.Core.Layout.Node; namespace DrawingFromMsaglGraph { public partial class Form1 : Form { GeometryGraph geometryGraph; static Random r = new Random(1); public Form1() { // Microsoft.Msagl.GraphViewerGdi.DisplayGeometryGraph.SetShowFunctions(); InitializeComponent(); SizeChanged += Form1_SizeChanged; // the magic calls for invoking doublebuffering SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); } void Form1_SizeChanged(object sender, EventArgs e) { Invalidate(); } protected override void OnPaint(PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; base.OnPaint(e); if (geometryGraph == null) { geometryGraph = CreateAndLayoutGraph(); } DrawFromGraph(e.Graphics); } private void DrawFromGraph(Graphics graphics) { SetGraphTransform(); var pen = new Pen(Brushes.Black); DrawNodes(pen, graphics); DrawEdges(pen, graphics); } private void SetGraphTransform() { //instead of setting transormation for graphics we are going to transform the geometry graph, just to test that GeometryGraph.Transform() works RectangleF clientRectangle = ClientRectangle; var gr = geometryGraph.BoundingBox; if (clientRectangle.Height > 1 && clientRectangle.Width > 1) { var scale = Math.Min(clientRectangle.Width * 0.9 / gr.Width, clientRectangle.Height * 0.9 / gr.Height); var g0 = (gr.Left + gr.Right) / 2; var g1 = (gr.Top + gr.Bottom) / 2; var c0 = (clientRectangle.Left + clientRectangle.Right) / 2; var c1 = (clientRectangle.Top + clientRectangle.Bottom) / 2; var dx = c0 - scale * g0; var dy = c1 - scale * g1; var planeTransformation=new PlaneTransformation(scale,0,dx, 0, scale, dy); geometryGraph.Transform(planeTransformation); } } private void DrawEdges(Pen pen, Graphics graphics) { foreach (Edge e in geometryGraph.Edges) DrawEdge(e, pen, graphics); } private void DrawEdge(Edge e, Pen pen, Graphics graphics) { graphics.DrawPath(pen, CreateGraphicsPath(e.Curve)); if (e.EdgeGeometry != null && e.EdgeGeometry.SourceArrowhead != null) DrawArrow(e, pen, graphics, e.Curve.Start, e.EdgeGeometry.SourceArrowhead.TipPosition); if (e.EdgeGeometry != null && e.EdgeGeometry.TargetArrowhead != null) DrawArrow(e, pen, graphics, e.Curve.End, e.EdgeGeometry.TargetArrowhead.TipPosition); } internal static GraphicsPath CreateGraphicsPath(ICurve iCurve) { GraphicsPath graphicsPath = new GraphicsPath(); if (iCurve == null) return null; Curve c = iCurve as Curve; if (c != null) { foreach (ICurve seg in c.Segments) { CubicBezierSegment cubic = seg as CubicBezierSegment; if (cubic != null) graphicsPath.AddBezier(PointF(cubic.B(0)), PointF(cubic.B(1)), PointF(cubic.B(2)), PointF(cubic.B(3))); else { LineSegment ls = seg as LineSegment; if (ls != null) graphicsPath.AddLine(PointF(ls.Start), PointF(ls.End)); else { Ellipse el = seg as Ellipse; if (el != null) { graphicsPath.AddArc((float)(el.Center.X - el.AxisA.X), (float)(el.Center.Y - el.AxisB.Y), (float)(el.AxisA.X * 2), Math.Abs((float)el.AxisB.Y * 2), EllipseStartAngle(el), EllipseSweepAngle(el)); } } } } } else { var ls = iCurve as LineSegment; if (ls != null) graphicsPath.AddLine(PointF(ls.Start), PointF(ls.End)); } return graphicsPath; } private static System.Drawing.PointF PointF(Microsoft.Msagl.Core.Geometry.Point point) { return new System.Drawing.PointF((float)point.X, (float)point.Y); } private void DrawArrow(Edge e, Pen pen, Graphics graphics, P start, P end) { PointF[] points; float arrowAngle = 30; P dir = end - start; P h = dir; dir /= dir.Length; P s = new P(-dir.Y, dir.X); s *= h.Length * ((float)Math.Tan(arrowAngle * 0.5f * (Math.PI / 180.0))); points = new PointF[] { MsaglPointToDrawingPoint(start + s), MsaglPointToDrawingPoint(end), MsaglPointToDrawingPoint(start - s) }; graphics.FillPolygon(pen.Brush, points); } private void DrawNodes(Pen pen, Graphics graphics) { foreach (Node n in geometryGraph.Nodes) DrawNode(n, pen, graphics); } private static float EllipseSweepAngle(Ellipse el) { return (float)((el.ParEnd - el.ParStart) / Math.PI * 180); } private static float EllipseStartAngle(Ellipse el) { return (float)(el.ParStart / Math.PI * 180); } private void DrawNode(Node n, Pen pen, Graphics graphics) { ICurve curve = n.BoundaryCurve; Ellipse el = curve as Ellipse; if (el != null) { graphics.DrawEllipse(pen, new RectangleF((float)el.BoundingBox.Left, (float)el.BoundingBox.Bottom, (float)el.BoundingBox.Width, (float)el.BoundingBox.Height)); } else graphics.DrawPath(pen, CreateGraphicsPath(curve)); } private System.Drawing.Point MsaglPointToDrawingPoint(P point) { return new System.Drawing.Point((int)point.X, (int)point.Y); } static internal GeometryGraph CreateAndLayoutGraph() { GeometryGraph graph = new GeometryGraph(); double width = 40; double height = 10; foreach (string id in "0 1 2 3 4 5 6 A B C D E F G a b c d e".Split(' ')) { AddNode(id, graph, width, height); } graph.Edges.Add(new Edge(graph.FindNodeByUserData("A"), graph.FindNodeByUserData("B"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("A"), graph.FindNodeByUserData("C"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("A"), graph.FindNodeByUserData("D"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("D"), graph.FindNodeByUserData("E"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("B"), graph.FindNodeByUserData("E"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("D"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("0"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("1"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("2"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("3"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("4"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("5"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("6"), graph.FindNodeByUserData("F"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("a"), graph.FindNodeByUserData("b"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("b"), graph.FindNodeByUserData("c"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("c"), graph.FindNodeByUserData("d"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("d"), graph.FindNodeByUserData("e"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("A"), graph.FindNodeByUserData("a"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("B"), graph.FindNodeByUserData("a"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("C"), graph.FindNodeByUserData("a"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("D"), graph.FindNodeByUserData("a"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("E"), graph.FindNodeByUserData("a"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("F"), graph.FindNodeByUserData("a"))); graph.Edges.Add(new Edge(graph.FindNodeByUserData("G"), graph.FindNodeByUserData("a"))); var settings = new SugiyamaLayoutSettings(); settings.Transformation = PlaneTransformation.Rotation(Math.PI/2); settings.EdgeRoutingSettings.EdgeRoutingMode = EdgeRoutingMode.Spline; var layout = new LayeredLayout(graph, settings); layout.Run(); return graph; // double w = 40; // double h = 10; // GeometryGraph graph = new GeometryGraph(); //columns // var col0 = new[] { "a", "b", "c" }; // var col1 = new[] { "d", "e", "f", "g" }; // var col2 = new[] { "k", "l", "m", "n" }; // var col3 = new[] { "w", "y", "z" }; // // var settings = new SugiyamaLayoutSettings(); // // foreach (var id in col0) // AddNode(id, graph, w, h); // foreach (var id in col1) // AddNode(id, graph, w, h); // foreach (var id in col2) // AddNode(id, graph, w, h); // foreach (var id in col3) // AddNode(id, graph, w, h); // //pinning columns // settings.PinNodesToSameLayer(col0.Select(s=>graph.FindNodeByUserData(s)).ToArray()); // settings.PinNodesToSameLayer(col1.Select(s => graph.FindNodeByUserData(s)).ToArray()); // settings.PinNodesToSameLayer(col2.Select(s => graph.FindNodeByUserData(s)).ToArray()); // settings.PinNodesToSameLayer(col3.Select(s => graph.FindNodeByUserData(s)).ToArray()); // // AddEdgesBetweenColumns(col0, col1, graph); // AddEdgesBetweenColumns(col1, col2, graph); // AddEdgesBetweenColumns(col2, col3, graph); //rotate layer to columns // graph.Transformation = PlaneTransformation.Rotation(Math.PI / 2); // settings.NodeSeparation = 5; // settings.LayerSeparation = 100; // var ll = new LayeredLayout(graph, settings); // ll.Run(); // return graph; } private static void AddNode(string id, GeometryGraph graph, double w, double h) { graph.Nodes.Add(new Node(CreateCurve(w, h), id)); } private static ICurve CreateCurve(double w, double h) { return CurveFactory.CreateRectangle(w, h, new Microsoft.Msagl.Core.Geometry.Point()) ; } static void AddEdgesBetweenColumns(string[] col0, string[] col1, GeometryGraph graph) { foreach (var id in col0) { Edge edge = new Edge(graph.FindNodeByUserData(id), graph.FindNodeByUserData(col1[r.Next(col1.Length)])); edge.EdgeGeometry.TargetArrowhead = null; graph.Edges.Add(edge); edge = new Edge(graph.FindNodeByUserData(id), graph.FindNodeByUserData(col1[r.Next(col1.Length)])); graph.Edges.Add(edge); } } } }
namespace AngleSharp.Dom { using AngleSharp.Css.Dom; using AngleSharp.Css.Parser; using AngleSharp.Text; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Extensions for performing QuerySelector operations. /// </summary> public static class QueryExtensions { #region Text Selector /// <summary> /// Returns the first element within the document (using depth-first pre-order traversal /// of the document's nodes) that matches the specified group of selectors. /// Requires either a non-empty nodelist or a valid scope node. /// </summary> /// <param name="nodes">The nodes to take as source.</param> /// <param name="selectorText">A string containing one or more CSS selectors separated by commas.</param> /// <param name="scopeNode">The optional node to take as scope.</param> /// <returns>An element object.</returns> public static IElement? QuerySelector(this INodeList nodes, String selectorText, INode? scopeNode = null) { var scope = GetScope(scopeNode); var sg = CreateSelector(nodes, scope, selectorText); if (sg != null) { return sg.MatchAny(nodes.OfType<IElement>(), scope); } return null; } /// <summary> /// Returns a list of the elements within the document (using depth-first pre-order traversal /// of the document's nodes) that match the specified group of selectors. /// Requires either a non-empty nodelist or a valid scope node. /// </summary> /// <param name="nodes">The nodes to take as source.</param> /// <param name="selectorText">A string containing one or more CSS selectors separated by commas.</param> /// <param name="scopeNode">The optional node to take as scope.</param> /// <returns>A HTMLCollection with all elements that match the selection.</returns> public static IHtmlCollection<IElement> QuerySelectorAll(this INodeList nodes, String selectorText, INode? scopeNode = null) { var scope = GetScope(scopeNode); var sg = CreateSelector(nodes, scope, selectorText); if (sg != null) { return sg.MatchAll(nodes.OfType<IElement>(), scope); } return new HtmlCollection<IElement>(Array.Empty<IElement>()); } /// <summary> /// Returns a set of elements which have all the given class names. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="classNames">A string representing the list of class names to match; class names are separated by whitespace.</param> /// <returns>A collection of HTML elements.</returns> public static IHtmlCollection<IElement> GetElementsByClassName(this INodeList elements, String classNames) { var result = new List<IElement>(); var names = classNames.SplitSpaces(); if (names.Length > 0) { elements.GetElementsByClassName(names, result); } return new HtmlCollection<IElement>(result); } /// <summary> /// Returns a NodeList of elements with the given tag name. The complete document is searched, including the root node. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="tagName">A string representing the name of the elements. The special string "*" represents all elements.</param> /// <returns>A NodeList of found elements in the order they appear in the tree.</returns> public static IHtmlCollection<IElement> GetElementsByTagName(this INodeList elements, String tagName) { var result = new List<IElement>(); elements.GetElementsByTagName(tagName is "*" ? null : tagName, result); return new HtmlCollection<IElement>(result); } /// <summary> /// Returns a list of elements with the given tag name belonging to the given namespace. /// The complete document is searched, including the root node. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="namespaceUri">The namespace URI of elements to look for.</param> /// <param name="localName">Either the local name of elements to look for or the special value "*", which matches all elements.</param> /// <returns>A NodeList of found elements in the order they appear in the tree.</returns> public static IHtmlCollection<IElement> GetElementsByTagName(this INodeList elements, String? namespaceUri, String localName) { var result = new List<IElement>(); elements.GetElementsByTagName(namespaceUri, localName is "*" ? null : localName, result); return new HtmlCollection<IElement>(result); } #endregion #region Object Selector /// <summary> /// Returns the first element within the document (using depth-first pre-order traversal /// of the document's nodes) that matches the given selector. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="selectors">A selector object.</param> /// <returns>An element object.</returns> public static T? QuerySelector<T>(this INodeList elements, ISelector selectors) where T : class, IElement { return elements.QuerySelector(selectors) as T; } /// <summary> /// Returns the first element within the document (using depth-first pre-order traversal /// of the document's nodes) that matches the specified group of selectors. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="selector">A selector object.</param> /// <returns>An element object.</returns> public static IElement? QuerySelector(this INodeList elements, ISelector selector) { for (var i = 0; i < elements.Length; i++) { if (elements[i] is IElement element) { if (selector.Match(element)) { return element; } if (element.HasChildNodes) { element = QuerySelector(element.ChildNodes, selector)!; if (element != null) { return element; } } } } return null; } /// <summary> /// Returns a list of the elements within the document (using depth-first pre-order traversal /// of the document's nodes) that matches the selector. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="selector">A selector object.</param> /// <returns>A HTMLCollection with all elements that match the selection.</returns> public static IHtmlCollection<IElement> QuerySelectorAll(this INodeList elements, ISelector selector) { var result = new List<IElement>(); elements.QuerySelectorAll(selector, result); return new HtmlCollection<IElement>(result); } /// <summary> /// Returns a list of the elements within the document (using depth-first pre-order traversal /// of the document's nodes) that match the specified group of selectors. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="selector">A selector object.</param> /// <param name="result">A reference to the list where to store the results.</param> public static void QuerySelectorAll(this INodeList elements, ISelector selector, List<IElement> result) { for (var i = 0; i < elements.Length; i++) { if (elements[i] is IElement element) { foreach (var descendentAndSelf in element.DescendentsAndSelf<IElement>()) { if (selector.Match(descendentAndSelf)) { result.Add(descendentAndSelf); } } } } } /// <summary> /// Returns true if the underlying string contains all of the tokens, otherwise false. /// </summary> /// <param name="list">The list that is considered.</param> /// <param name="tokens">The tokens to consider.</param> /// <returns>True if the string contained all tokens, otherwise false.</returns> public static Boolean Contains(this ITokenList list, String[] tokens) { for (var i = 0; i < tokens.Length; i++) { if (!list.Contains(tokens[i])) { return false; } } return true; } #endregion #region Helpers /// <summary> /// Returns a set of elements which have all the given class names. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="classNames">An array with class names to consider.</param> /// <param name="result">A reference to the list where to store the results.</param> private static void GetElementsByClassName(this INodeList elements, String[] classNames, List<IElement> result) { for (var i = 0; i < elements.Length; i++) { if (elements[i] is IElement element) { if (element.ClassList.Contains(classNames)) { result.Add(element); } if (element.ChildElementCount != 0) { GetElementsByClassName(element.ChildNodes, classNames, result); } } } } /// <summary> /// Returns a NodeList of elements with the given tag name. The complete document is searched, including the root node. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="tagName">A string representing the name of the elements. The special string "*" represents all elements.</param> /// <param name="result">A reference to the list where to store the results.</param> private static void GetElementsByTagName(this INodeList elements, String? tagName, List<IElement> result) { for (var i = 0; i < elements.Length; i++) { if (elements[i] is IElement element) { if (tagName is null || tagName.Isi(element.LocalName)) { result.Add(element); } if (element.ChildElementCount != 0) { GetElementsByTagName(element.ChildNodes, tagName!, result); } } } } /// <summary> /// Returns a list of elements with the given tag name belonging to the given namespace. /// The complete document is searched, including the root node. /// </summary> /// <param name="elements">The elements to take as source.</param> /// <param name="namespaceUri">The namespace URI of elements to look for.</param> /// <param name="localName">Either the local name of elements to look for or the special value "*", which matches all elements.</param> /// <param name="result">A reference to the list where to store the results.</param> private static void GetElementsByTagName(this INodeList elements, String? namespaceUri, String? localName, List<IElement> result) { for (var i = 0; i < elements.Length; i++) { if (elements[i] is IElement element) { if (element.NamespaceUri.Is(namespaceUri) && (localName is null || localName.Isi(element.LocalName))) { result.Add(element); } if (element.ChildElementCount != 0) { GetElementsByTagName(element.ChildNodes, namespaceUri, localName, result); } } } } private static IElement? GetScope(INode? scopeNode) => scopeNode as IElement ?? (scopeNode as IDocument)?.DocumentElement ?? (scopeNode as IShadowRoot)?.Host; private static ISelector? CreateSelector(INodeList nodes, INode? scope, String selectorText) { var node = nodes.Length > 0 ? nodes[0] : scope; var sg = default(ISelector); if (node != null) { var parser = node.Owner!.Context.GetService<ICssSelectorParser>()!; sg = parser.ParseSelector(selectorText) ?? throw new DomException(DomError.Syntax); } return sg; } #endregion } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Logging; using osu.Framework.Screens; using osu.Game.Input; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Components; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Screens.OnlinePlay.Match.Components; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osu.Game.Users; using osuTK; namespace osu.Game.Screens.OnlinePlay.Playlists { public class PlaylistsRoomSubScreen : RoomSubScreen { public override string Title { get; } public override string ShortTitle => "playlist"; private readonly IBindable<bool> isIdle = new BindableBool(); private MatchLeaderboard leaderboard; private SelectionPollingComponent selectionPollingComponent; private FillFlowContainer progressSection; public PlaylistsRoomSubScreen(Room room) : base(room, false) // Editing is temporarily not allowed. { Title = room.RoomID.Value == null ? "New playlist" : room.Name.Value; Activity.Value = new UserActivity.InLobby(room); } [BackgroundDependencyLoader(true)] private void load([CanBeNull] IdleTracker idleTracker) { if (idleTracker != null) isIdle.BindTo(idleTracker.IsIdle); AddInternal(selectionPollingComponent = new SelectionPollingComponent(Room)); } protected override void LoadComplete() { base.LoadComplete(); isIdle.BindValueChanged(_ => updatePollingRate(), true); RoomId.BindValueChanged(id => { if (id.NewValue != null) { // Set the first playlist item. // This is scheduled since updating the room and playlist may happen in an arbitrary order (via Room.CopyFrom()). Schedule(() => SelectedItem.Value = Room.Playlist.FirstOrDefault()); } }, true); Room.MaxAttempts.BindValueChanged(attempts => progressSection.Alpha = Room.MaxAttempts.Value != null ? 1 : 0, true); } protected override Drawable CreateMainContent() => new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Horizontal = 5, Vertical = 10 }, Child = new GridContainer { RelativeSizeAxes = Axes.Both, ColumnDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.Absolute, 10), new Dimension(), new Dimension(GridSizeMode.Absolute, 10), new Dimension(), }, Content = new[] { new Drawable[] { // Playlist items column new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Right = 5 }, Child = new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new OverlinedPlaylistHeader(), }, new Drawable[] { new DrawableRoomPlaylist { RelativeSizeAxes = Axes.Both, Items = { BindTarget = Room.Playlist }, SelectedItem = { BindTarget = SelectedItem }, AllowSelection = true, AllowShowingResults = true, RequestResults = item => { Debug.Assert(RoomId.Value != null); ParentScreen?.Push(new PlaylistsResultsScreen(null, RoomId.Value.Value, item, false)); } } }, }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(), } } }, // Spacer null, // Middle column (mods and leaderboard) new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new[] { UserModsSection = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Alpha = 0, Margin = new MarginPadding { Bottom = 10 }, Children = new Drawable[] { new OverlinedHeader("Extra mods"), new FillFlowContainer { AutoSizeAxes = Axes.Both, Direction = FillDirection.Horizontal, Spacing = new Vector2(10, 0), Children = new Drawable[] { new UserModSelectButton { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Width = 90, Text = "Select", Action = ShowUserModSelect, }, new ModDisplay { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Current = UserMods, Scale = new Vector2(0.8f), }, } } } }, }, new Drawable[] { progressSection = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Alpha = 0, Margin = new MarginPadding { Bottom = 10 }, Direction = FillDirection.Vertical, Children = new Drawable[] { new OverlinedHeader("Progress"), new RoomLocalUserInfo(), } }, }, new Drawable[] { new OverlinedHeader("Leaderboard") }, new Drawable[] { leaderboard = new MatchLeaderboard { RelativeSizeAxes = Axes.Both }, }, }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), new Dimension(), } }, // Spacer null, // Main right column new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { new OverlinedHeader("Chat") }, new Drawable[] { new MatchChatDisplay(Room) { RelativeSizeAxes = Axes.Both } } }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(), } }, }, }, } }; protected override Drawable CreateFooter() => new PlaylistsRoomFooter { OnStart = StartPlay }; protected override RoomSettingsOverlay CreateRoomSettingsOverlay(Room room) => new PlaylistsRoomSettingsOverlay(room) { EditPlaylist = () => { if (this.IsCurrentScreen()) this.Push(new PlaylistsSongSelect(Room)); }, }; private void updatePollingRate() { selectionPollingComponent.TimeBetweenPolls.Value = isIdle.Value ? 30000 : 5000; Logger.Log($"Polling adjusted (selection: {selectionPollingComponent.TimeBetweenPolls.Value})"); } protected override Screen CreateGameplayScreen() => new PlayerLoader(() => new PlaylistsPlayer(Room, SelectedItem.Value) { Exited = () => leaderboard.RefetchScores() }); } }