context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Windows.Controls.Primitives; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Input; using MahApps.Metro.Automation.Peers; using MahApps.Metro.ValueBoxes; namespace MahApps.Metro.Controls { /// <summary> /// The MetroThumbContentControl control can be used for titles or something else and enables basic drag movement functionality. /// </summary> public class MetroThumbContentControl : ContentControlEx, IMetroThumb { private TouchDevice currentDevice = null; private Point startDragPoint; private Point startDragScreenPoint; private Point oldDragScreenPoint; static MetroThumbContentControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(MetroThumbContentControl), new FrameworkPropertyMetadata(typeof(MetroThumbContentControl))); FocusableProperty.OverrideMetadata(typeof(MetroThumbContentControl), new FrameworkPropertyMetadata(default(bool))); EventManager.RegisterClassHandler(typeof(MetroThumbContentControl), Mouse.LostMouseCaptureEvent, new MouseEventHandler(OnLostMouseCapture)); } public static readonly RoutedEvent DragStartedEvent = EventManager.RegisterRoutedEvent(nameof(DragStarted), RoutingStrategy.Bubble, typeof(DragStartedEventHandler), typeof(MetroThumbContentControl)); public static readonly RoutedEvent DragDeltaEvent = EventManager.RegisterRoutedEvent(nameof(DragDelta), RoutingStrategy.Bubble, typeof(DragDeltaEventHandler), typeof(MetroThumbContentControl)); public static readonly RoutedEvent DragCompletedEvent = EventManager.RegisterRoutedEvent(nameof(DragCompleted), RoutingStrategy.Bubble, typeof(DragCompletedEventHandler), typeof(MetroThumbContentControl)); /// <summary> /// Adds or remove a DragStartedEvent handler /// </summary> public event DragStartedEventHandler DragStarted { add { this.AddHandler(DragStartedEvent, value); } remove { this.RemoveHandler(DragStartedEvent, value); } } /// <summary> /// Adds or remove a DragDeltaEvent handler /// </summary> public event DragDeltaEventHandler DragDelta { add { this.AddHandler(DragDeltaEvent, value); } remove { this.RemoveHandler(DragDeltaEvent, value); } } /// <summary> /// Adds or remove a DragCompletedEvent handler /// </summary> public event DragCompletedEventHandler DragCompleted { add { this.AddHandler(DragCompletedEvent, value); } remove { this.RemoveHandler(DragCompletedEvent, value); } } private static readonly DependencyPropertyKey IsDraggingPropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsDragging), typeof(bool), typeof(MetroThumbContentControl), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// DependencyProperty for the IsDragging property. /// </summary> public static readonly DependencyProperty IsDraggingProperty = IsDraggingPropertyKey.DependencyProperty; /// <summary> /// Indicates that the left mouse button is pressed and is over the MetroThumbContentControl. /// </summary> public bool IsDragging { get { return (bool)this.GetValue(IsDraggingProperty); } protected set { this.SetValue(IsDraggingPropertyKey, BooleanBoxes.Box(value)); } } public void CancelDragAction() { if (!this.IsDragging) { return; } if (this.IsMouseCaptured) { this.ReleaseMouseCapture(); } this.ClearValue(IsDraggingPropertyKey); var horizontalChange = this.oldDragScreenPoint.X - this.startDragScreenPoint.X; var verticalChange = this.oldDragScreenPoint.Y - this.startDragScreenPoint.Y; this.RaiseEvent(new MetroThumbContentControlDragCompletedEventArgs(horizontalChange, verticalChange, true)); } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { if (!this.IsDragging) { e.Handled = true; try { // focus me this.Focus(); // now capture the mouse for the drag action this.CaptureMouse(); // so now we are in dragging mode this.SetValue(IsDraggingPropertyKey, BooleanBoxes.TrueBox); // get the mouse points this.startDragPoint = e.GetPosition(this); this.oldDragScreenPoint = this.startDragScreenPoint = this.PointToScreen(this.startDragPoint); this.RaiseEvent(new MetroThumbContentControlDragStartedEventArgs(this.startDragPoint.X, this.startDragPoint.Y)); } catch (Exception exception) { Trace.TraceError($"{this}: Something went wrong here: {exception} {Environment.NewLine} {exception.StackTrace}"); this.CancelDragAction(); } } base.OnMouseLeftButtonDown(e); } protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { if (this.IsMouseCaptured && this.IsDragging) { e.Handled = true; // now we are in normal mode this.ClearValue(IsDraggingPropertyKey); // release the captured mouse this.ReleaseMouseCapture(); // get the current mouse position and call the completed event with the horizontal/vertical change Point currentMouseScreenPoint = this.PointToScreen(e.MouseDevice.GetPosition(this)); var horizontalChange = currentMouseScreenPoint.X - this.startDragScreenPoint.X; var verticalChange = currentMouseScreenPoint.Y - this.startDragScreenPoint.Y; this.RaiseEvent(new MetroThumbContentControlDragCompletedEventArgs(horizontalChange, verticalChange, false)); } base.OnMouseLeftButtonUp(e); } private static void OnLostMouseCapture(object sender, MouseEventArgs e) { // Cancel the drag action if we lost capture MetroThumbContentControl thumb = (MetroThumbContentControl)sender; if (Mouse.Captured != thumb) { thumb.CancelDragAction(); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (!this.IsDragging) { return; } if (e.MouseDevice.LeftButton == MouseButtonState.Pressed) { Point currentDragPoint = e.GetPosition(this); // Get client point and convert it to screen point Point currentDragScreenPoint = this.PointToScreen(currentDragPoint); if (currentDragScreenPoint != this.oldDragScreenPoint) { this.oldDragScreenPoint = currentDragScreenPoint; e.Handled = true; var horizontalChange = currentDragPoint.X - this.startDragPoint.X; var verticalChange = currentDragPoint.Y - this.startDragPoint.Y; this.RaiseEvent(new DragDeltaEventArgs(horizontalChange, verticalChange) { RoutedEvent = MetroThumbContentControl.DragDeltaEvent }); } } else { // clear some saved stuff if (e.MouseDevice.Captured == this) { this.ReleaseMouseCapture(); } this.ClearValue(IsDraggingPropertyKey); this.startDragPoint.X = 0; this.startDragPoint.Y = 0; } } protected override void OnPreviewTouchDown(TouchEventArgs e) { // Release any previous capture this.ReleaseCurrentDevice(); // Capture the new touch this.CaptureCurrentDevice(e); } protected override void OnPreviewTouchUp(TouchEventArgs e) { this.ReleaseCurrentDevice(); } protected override void OnLostTouchCapture(TouchEventArgs e) { // Only re-capture if the reference is not null // This way we avoid re-capturing after calling ReleaseCurrentDevice() if (this.currentDevice != null) { this.CaptureCurrentDevice(e); } } private void ReleaseCurrentDevice() { if (this.currentDevice != null) { // Set the reference to null so that we don't re-capture in the OnLostTouchCapture() method var temp = this.currentDevice; this.currentDevice = null; this.ReleaseTouchCapture(temp); } } private void CaptureCurrentDevice(TouchEventArgs e) { bool gotTouch = this.CaptureTouch(e.TouchDevice); if (gotTouch) { this.currentDevice = e.TouchDevice; } } protected override AutomationPeer OnCreateAutomationPeer() { return new MetroThumbContentControlAutomationPeer(this); } } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ using System; using System.Data; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using GemFireXDDBI.DBObjects; using GemFireXDDBI.DBI; using GemFireXDDBI.Util; namespace GemFireXDDBI.DBMigrate { /// <summary> /// Automates the migration process per user options /// </summary> class Migrator { public delegate void MigrateEventHandler(MigrateEventArgs e); public static event MigrateEventHandler MigrateEvent; public static String SourceDBConnName { get; set; } public static String DestDBConnName { get; set; } public static bool MigrateTables { get; set; } public static bool MigrateViews { get; set; } public static bool MigrateProcedures { get; set; } public static bool MigrateFunctions { get; set; } public static bool MigrateTriggers { get; set; } public static bool MigrateIndexes { get; set; } public static bool Errorred { get; set; } public static Result Result { get; set; } private static IDictionary<String, DbTable> dbTableList = new Dictionary<String, DbTable>(); public static void MigrateDB() { SQLSvrDbi.DbConnectionString = Configuration.Configurator.GetDBConnString(SourceDBConnName); GemFireXDDbi.DbConnectionString = Configuration.Configurator.GetDBConnString(DestDBConnName); try { if (MigrateTables) MigrateDbTables(); if (MigrateViews) MigrateDbViews(); if (MigrateIndexes) MigrateDbIndexes(); if (MigrateProcedures) MigrateDbStoredProcedures(); if (MigrateFunctions) MigrateDbFunctions(); if (MigrateTriggers) MigrateDbTriggers(); } catch (ThreadAbortException e) { Result = Result.Aborted; OnMigrateEvent(new MigrateEventArgs(Result.Aborted, "Operation aborted!")); } catch (Exception e) { Helper.Log(e); } finally { dbTableList.Clear(); } } public static DbTable GetTableFromList(String tableFullName) { return dbTableList[tableFullName]; } public static String GetTableFullName(String tableName) { foreach (DbTable table in dbTableList.Values) { if (table.TableName == tableName.ToUpper()) return table.TableFullName; } return tableName; } private static void MigrateDbTables() { Helper.Log("Start migrating database tables"); DataTable dt = SQLSvrDbi.GetTableNames(); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { DbTable table = new DbTable( row["SchemaName"].ToString().ToUpper(), row["TableName"].ToString().ToUpper()); dbTableList.Add(table.TableFullName, table); } foreach (DbTable table in dbTableList.Values) table.Migrate(); } Helper.Log("Finished migrating database tables"); } private static void MigrateDbIndexes() { Helper.Log("Start migrating database indexes"); DataTable dt = SQLSvrDbi.GetIndexes(); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { DbIndex index = new DbIndex( row["SchemaName"].ToString().ToUpper(), row["TableName"].ToString().ToUpper(), row["IndexName"].ToString().ToUpper(), row["ColumnName"].ToString().ToUpper(), bool.Parse(row["IsUnique"].ToString())); index.Migrate(); } } Helper.Log("Finished migrating database indexes"); } private static void MigrateDbStoredProcedures() { Helper.Log("Start migrating stored procedures"); DataTable dt = SQLSvrDbi.GetStoredProcedures(); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { DbModule module = new DbModule( row["SchemaName"].ToString(), row["ProcedureName"].ToString(), row["ProcedureDefinition"].ToString(), ModuleType.StoredProcedure); module.Migrate(); } } Helper.Log("Finished migrating stored procedures"); } private static void MigrateDbFunctions() { Helper.Log("Start migrating database functions"); DataTable dt = SQLSvrDbi.GetFunctions(); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { DbModule module = new DbModule( row["SchemaName"].ToString(), row["FunctionName"].ToString(), row["FunctionDefinition"].ToString(), ModuleType.Function); module.Migrate(); } } Helper.Log("Finished migrating database functions"); } private static void MigrateDbTriggers() { Helper.Log("Start migrating database triggers"); DataTable dt = SQLSvrDbi.GetTriggers(); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { DbModule module = new DbModule( row["SchemaName"].ToString(), row["TriggerName"].ToString(), row["TriggerDefinition"].ToString(), ModuleType.Trigger); module.Migrate(); } } Helper.Log("Finished migrating database triggers"); } private static void MigrateDbViews() { Helper.Log("Start migrating database views"); DataTable dt = SQLSvrDbi.GetViews(); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { DbModule module = new DbModule(row["SchemaName"].ToString(), row["ViewName"].ToString(), row["ViewDefinition"].ToString(), ModuleType.View); module.Migrate(); } } Helper.Log("Finished migrating database views"); } private static void ValidateTableCreation() { foreach (DbTable table in dbTableList.Values) { if (!table.Validate()) Helper.Log(String.Format("Failed to create table {0}", table.TableFullName)); } } private static void ListTables() { foreach (DbTable table in dbTableList.Values) Helper.Log(table.GetCreateTableSql()); } public static void OnMigrateEvent(MigrateEventArgs e) { if (MigrateEvent != null) MigrateEvent(e); } } }
using AutoBogus.Conventions; using AutoBogus.Playground.Model; using FluentAssertions; using NSubstitute; using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; namespace AutoBogus.Playground { public abstract class ServiceFixture { private class TestProduct : Product<int> { public Exception Error { get; set; } public IEnumerable<string> GetNotes() { return Notes; } } private class ProductGeneratorOverride : AutoGeneratorOverride { public override bool CanOverride(AutoGenerateContext context) { return context.GenerateType.IsGenericType && context.GenerateType.GetGenericTypeDefinition() == typeof(Product<>); } public override void Generate(AutoGenerateOverrideContext context) { // Get the code and apply a serial number value var serialNumber = AutoFaker.Generate<string>(); var codeProperty = context.GenerateType.GetProperty("Code"); var codeInstance = codeProperty.GetValue(context.Instance); var serialNumberProperty = codeProperty.PropertyType.GetProperty("SerialNumber"); serialNumberProperty.SetValue(codeInstance, serialNumber); } } private class ProductCodeOverride : AutoGeneratorOverride { public ProductCodeOverride() { Code = AutoFaker.Generate<string>(); } public string Code { get; set; } public override bool CanOverride(AutoGenerateContext context) { return context.GenerateType.IsGenericType && context.GenerateType.GetGenericTypeDefinition() == typeof(Product<>); } public override void Generate(AutoGenerateOverrideContext context) { var type = typeof(ProductCode); var productCodeProperty = context.GenerateType.GetProperty("Code"); var productCode = productCodeProperty.GetValue(context.Instance); var serialNoProperty = type.GetProperty("SerialNumber"); serialNoProperty.SetValue(productCode, Code); } } protected IAutoFaker _faker; protected Item _item; protected IEnumerable<Item> _items; protected IRepository _repository; protected Service _service; protected ITestOutputHelper _output; protected ServiceFixture(ITestOutputHelper output, IAutoBinder binder) { _faker = AutoFaker.Create(builder => { builder.WithOverride(new ProductGeneratorOverride()); if (binder != null) { builder.WithBinder(binder); } }); // Setup var id = _faker.Generate<Guid>(); var generator = new AutoFaker<Item>(binder) .RuleFor(item => item.Id, () => id) .RuleFor(item => item.Name, faker => faker.Person.FullName) .RuleFor(item => item.Amendments, faker => new HashSet<string> { "1", "2", "3" }); _item = generator; _items = generator.Generate(5); _repository = Substitute.For<IRepository>(); _repository.Get(id).Returns(_item); _repository.GetAll().Returns(_items); _service = new Service(_repository); _output = output; } [Fact] public void Should_Set_Timestamp() { _item.Timestamp.Should().NotBeNull(); } [Fact] public void Should_Set_Product_Notes() { var product = AutoFaker.Generate<TestProduct>(); product.GetNotes().Should().NotBeEmpty(); } [Fact] public void Should_Not_Set_Product_Code() { var product = AutoFaker.Generate<TestProduct>(builder => { builder.WithSkip<Exception>(); }); product.Error.Should().BeNull(); } [Fact] public void Should_Not_Set_Product_Notes() { var product = AutoFaker.Generate<TestProduct>(builder => { builder.WithSkip<TestProduct>("Notes"); }); product.GetNotes().Should().BeEmpty(); } [Fact] public void Service_Get_Should_Call_Repository_Get() { _service.Get(_item.Id); _repository.Received().Get(_item.Id); } [Fact] public void Service_Get_Should_Return_Item() { _service.Get(_item.Id).Should().Be(_item); } [Fact] public void Service_GetAll_Should_Call_Repository_GetAll() { _service.GetAll(); _repository.Received().GetAll(); } [Fact] public void Service_GetAll_Should_Return_Items() { _service.GetAll().Should().BeSameAs(_items); } [Fact] public void Service_GetPending_Should_Call_Repository_GetFiltered() { _service.GetPending(); _repository.Received().GetFiltered(Service.PendingFilter); } [Fact] public void Service_GetPending_Should_Return_Items() { var id = _faker.Generate<Guid>(); var item = AutoFaker.Generate<Item>(); var item1Override = new ProductCodeOverride(); var item2Override = new ProductCodeOverride(); var items = new List<Item> { _faker.Generate<Item, ItemFaker>(builder => builder.WithArgs(id).WithOverride(item1Override)), AutoFaker.Generate<Item, ItemFaker>(builder => builder.WithArgs(id).WithOverride(item2Override)), AutoFaker.Generate<Item>(builder => builder.WithSkip<Item>(i => i.ProcessedBy)), AutoFaker.Generate<Item>(builder => builder.WithConventions(c => c.Email.Aliases("SupplierEmail"))) }; item.Status = ItemStatus.Pending; items.Add(item); _repository.GetFiltered(Service.PendingFilter).Returns(items); _service.GetPending().Should().BeSameAs(items); items.ElementAt(0).ProcessedBy.Email.Should().NotContain("@"); items.ElementAt(0).SupplierEmail.Should().NotContain("@"); items.ElementAt(0).ProductInt.Code.SerialNumber.Should().Be(item1Override.Code); items.ElementAt(0).ProductString.Code.SerialNumber.Should().Be(item1Override.Code); items.ElementAt(1).ProcessedBy.Email.Should().NotContain("@"); items.ElementAt(1).SupplierEmail.Should().NotContain("@"); items.ElementAt(1).ProductInt.Code.SerialNumber.Should().Be(item2Override.Code); items.ElementAt(1).ProductString.Code.SerialNumber.Should().Be(item2Override.Code); items.ElementAt(2).ProcessedBy.Should().BeNull(); items.ElementAt(2).SupplierEmail.Should().NotContain("@"); items.ElementAt(2).ProductInt.Code.SerialNumber.Should().BeNull(); items.ElementAt(2).ProductString.Code.SerialNumber.Should().BeNull(); items.ElementAt(3).ProcessedBy.Email.Should().Contain("@"); items.ElementAt(3).SupplierEmail.Should().Contain("@"); items.ElementAt(3).ProductInt.Code.SerialNumber.Should().BeNull(); items.ElementAt(3).ProductString.Code.SerialNumber.Should().BeNull(); items.ElementAt(4).ProcessedBy.Email.Should().NotContain("@"); items.ElementAt(4).SupplierEmail.Should().NotContain("@"); items.ElementAt(4).ProductInt.Code.SerialNumber.Should().BeNull(); items.ElementAt(4).ProductString.Code.SerialNumber.Should().BeNull(); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.Text; using System.Text.RegularExpressions; using ASC.ActiveDirectory.Base.Data; using ASC.Common.Logging; using ASC.Core; using ASC.Core.Users; using Monocert = Mono.Security.X509; using Syscert = System.Security.Cryptography.X509Certificates; namespace ASC.ActiveDirectory { public static class LdapUtils { private static readonly Regex DcRegex = new Regex("dc=([^,]+)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); public static string DistinguishedNameToDomain(string distinguishedName) { if (string.IsNullOrEmpty(distinguishedName)) return null; var matchList = DcRegex.Matches(distinguishedName); var dcList = matchList.Cast<Match>().Select(match => match.Groups[1].Value).ToList(); return !dcList.Any() ? null : string.Join(".", dcList); } public static bool IsLoginAccepted(LdapLogin ldapLogin, UserInfo ldapUser, string ldapDomain) { if (ldapLogin == null || string.IsNullOrEmpty(ldapLogin.ToString()) || string.IsNullOrEmpty(ldapDomain) || ldapUser == null || ldapUser.Equals(Constants.LostUser) || string.IsNullOrEmpty(ldapUser.Email) || string.IsNullOrEmpty(ldapUser.UserName)) { return false; } var hasDomain = !string.IsNullOrEmpty(ldapLogin.Domain); if (!hasDomain) { return ldapLogin.Username.Equals(ldapUser.UserName, StringComparison.InvariantCultureIgnoreCase); } var fullLogin = ldapLogin.ToString(); if (fullLogin.Equals(ldapUser.Email, StringComparison.InvariantCultureIgnoreCase)) return true; if (!ldapDomain.StartsWith(ldapLogin.Domain)) return false; var alterEmail = ldapUser.UserName.Contains("@") ? ldapUser.UserName : string.Format("{0}@{1}", ldapUser.UserName, ldapDomain); return IsLoginAndEmailSuitable(fullLogin, alterEmail); } private static string GetLdapAccessableEmail(string email) { try { if (string.IsNullOrEmpty(email)) return null; var login = LdapLogin.ParseLogin(email); if (string.IsNullOrEmpty(login.Domain)) return email; var dotIndex = login.Domain.LastIndexOf(".", StringComparison.Ordinal); var accessableEmail = dotIndex > -1 ? string.Format("{0}@{1}", login.Username, login.Domain.Remove(dotIndex)) : email; return accessableEmail; } catch (Exception) { return null; } } private static bool IsLoginAndEmailSuitable(string login, string email) { try { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(email)) return false; var accessableLogin = GetLdapAccessableEmail(login); if (string.IsNullOrEmpty(accessableLogin)) return false; var accessableEmail = GetLdapAccessableEmail(email); if (string.IsNullOrEmpty(accessableEmail)) return false; return accessableLogin.Equals(accessableEmail, StringComparison.InvariantCultureIgnoreCase); } catch (Exception) { return false; } } public static string GeneratePassword() { return Guid.NewGuid().ToString(); } public static bool IsCertInstalled(Syscert.X509Certificate certificate, ILog log = null) { try { var monoX509 = new Monocert.X509Certificate(certificate.GetRawCertData()); var store = WorkContext.IsMono ? Monocert.X509StoreManager.CurrentUser.TrustedRoot : Monocert.X509StoreManager.LocalMachine.TrustedRoot; return store.Certificates.Contains(monoX509); } catch (Exception ex) { if (log != null) log.ErrorFormat("IsCertInstalled() failed. Error: {0}", ex); } return false; } public static bool TryInstallCert(Syscert.X509Certificate certificate, ILog log = null) { try { var monoX509 = new Monocert.X509Certificate(certificate.GetRawCertData()); var store = WorkContext.IsMono ? Monocert.X509StoreManager.CurrentUser.TrustedRoot : Monocert.X509StoreManager.LocalMachine.TrustedRoot; // Add the certificate to the store. store.Import(monoX509); store.Certificates.Add(monoX509); return true; } catch (Exception ex) { if (log != null) log.ErrorFormat("TryInstallCert() failed. Error: {0}", ex); } return false; } public static void SkipErrors(Action method, ILog log = null) { try { method(); } catch (Exception ex) { if (log != null) log.ErrorFormat("SkipErrors() failed. Error: {0}", ex); } } public static string GetContactsString(this UserInfo userInfo) { if (userInfo.Contacts.Count == 0) return null; var sBuilder = new StringBuilder(); foreach (var contact in userInfo.Contacts) { sBuilder.AppendFormat("{0}|", contact); } return sBuilder.ToString(); } public static string GetUserInfoString(this UserInfo userInfo) { return string.Format( "{{ ID: '{0}' SID: '{1}' Email '{2}' UserName: '{3}' FirstName: '{4}' LastName: '{5}' Title: '{6}' Location: '{7}' Contacts: '{8}' Status: '{9}' }}", userInfo.ID, userInfo.Sid, userInfo.Email, userInfo.UserName, userInfo.FirstName, userInfo.LastName, userInfo.Title, userInfo.Location, userInfo.GetContactsString(), Enum.GetName(typeof(EmployeeStatus), userInfo.Status)); } public static string UnescapeLdapString(string ldapString) { var sb = new StringBuilder(); for (var i = 0; i < ldapString.Length; i++) { var ch = ldapString[i]; if (ch == '\\') { if (i + 1 < ldapString.Length && ldapString[i + 1] == ch) { sb.Append(ch); i++; } } else { sb.Append(ch); } } return sb.ToString(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NodaTime; using System.Linq; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Algorithm; using QuantConnect.Interfaces; using QuantConnect.Data.Market; using System.Collections.Generic; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Tests.Engine.DataFeeds; using QuantConnect.Data.Custom.AlphaStreams; using QuantConnect.Lean.Engine.HistoricalData; using QuantConnect.Securities; using HistoryRequest = QuantConnect.Data.HistoryRequest; namespace QuantConnect.Tests.Algorithm { [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class AlgorithmHistoryTests { private QCAlgorithm _algorithm; private TestHistoryProvider _testHistoryProvider; private IDataProvider _dataProvider; private IMapFileProvider _mapFileProvider; private IFactorFileProvider _factorFileProvider; [SetUp] public void Setup() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.HistoryProvider = _testHistoryProvider = new TestHistoryProvider(); _dataProvider = TestGlobals.DataProvider; _mapFileProvider = TestGlobals.MapFileProvider; _factorFileProvider = TestGlobals.FactorFileProvider; } [Test] public void TickResolutionHistoryRequest() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.HistoryProvider = new SubscriptionDataReaderHistoryProvider(); var zipCacheProvider = new ZipDataCacheProvider(_dataProvider); _algorithm.HistoryProvider.Initialize(new HistoryProviderInitializeParameters( null, null, _dataProvider, zipCacheProvider, _mapFileProvider, _factorFileProvider, null, false, new DataPermissionManager())); _algorithm.SetStartDate(2013, 10, 08); var start = new DateTime(2013, 10, 07); // Trades and quotes var result = _algorithm.History(new [] { Symbols.SPY }, start.AddHours(9.8), start.AddHours(10), Resolution.Tick).ToList(); // Just Trades var result2 = _algorithm.History<Tick>(Symbols.SPY, start.AddHours(9.8), start.AddHours(10), Resolution.Tick).ToList(); zipCacheProvider.DisposeSafely(); Assert.IsNotEmpty(result); Assert.IsNotEmpty(result2); Assert.IsTrue(result2.All(tick => tick.TickType == TickType.Trade)); // (Trades and quotes).Count > Trades * 2 Assert.Greater(result.Count, result2.Count * 2); } [Test] public void ImplicitTickResolutionHistoryRequestTradeBarApiThrowsException() { var spy = _algorithm.AddEquity("SPY", Resolution.Tick).Symbol; Assert.Throws<InvalidOperationException>(() => _algorithm.History(spy, 1).ToList()); } [Test] public void TickResolutionHistoryRequestTradeBarApiThrowsException() { Assert.Throws<InvalidOperationException>( () => _algorithm.History(Symbols.SPY, 1, Resolution.Tick).ToList()); Assert.Throws<InvalidOperationException>( () => _algorithm.History(Symbols.SPY, TimeSpan.FromSeconds(2), Resolution.Tick).ToList()); Assert.Throws<InvalidOperationException>( () => _algorithm.History(Symbols.SPY, DateTime.UtcNow.AddDays(-1), DateTime.UtcNow, Resolution.Tick).ToList()); } [TestCase(Resolution.Second)] [TestCase(Resolution.Minute)] [TestCase(Resolution.Hour)] [TestCase(Resolution.Daily)] public void TimeSpanHistoryRequestIsCorrectlyBuilt(Resolution resolution) { _algorithm.SetStartDate(2013, 10, 07); _algorithm.History(Symbols.SPY, TimeSpan.FromSeconds(2), resolution); Resolution? fillForwardResolution = null; if (resolution != Resolution.Tick) { fillForwardResolution = resolution; } var expectedCount = resolution == Resolution.Hour || resolution == Resolution.Daily ? 1 : 2; Assert.AreEqual(expectedCount, _testHistoryProvider.HistryRequests.Count); Assert.AreEqual(Symbols.SPY, _testHistoryProvider.HistryRequests.First().Symbol); Assert.AreEqual(resolution, _testHistoryProvider.HistryRequests.First().Resolution); Assert.IsFalse(_testHistoryProvider.HistryRequests.First().IncludeExtendedMarketHours); Assert.IsFalse(_testHistoryProvider.HistryRequests.First().IsCustomData); Assert.AreEqual(fillForwardResolution, _testHistoryProvider.HistryRequests.First().FillForwardResolution); Assert.AreEqual(DataNormalizationMode.Adjusted, _testHistoryProvider.HistryRequests.First().DataNormalizationMode); Assert.AreEqual(TickType.Trade, _testHistoryProvider.HistryRequests.First().TickType); } [TestCase(Resolution.Second)] [TestCase(Resolution.Minute)] [TestCase(Resolution.Hour)] [TestCase(Resolution.Daily)] public void BarCountHistoryRequestIsCorrectlyBuilt(Resolution resolution) { _algorithm.SetStartDate(2013, 10, 07); _algorithm.History(Symbols.SPY, 10, resolution); Resolution? fillForwardResolution = null; if (resolution != Resolution.Tick) { fillForwardResolution = resolution; } var expectedCount = resolution == Resolution.Hour || resolution == Resolution.Daily ? 1 : 2; Assert.AreEqual(expectedCount, _testHistoryProvider.HistryRequests.Count); Assert.AreEqual(Symbols.SPY, _testHistoryProvider.HistryRequests.First().Symbol); Assert.AreEqual(resolution, _testHistoryProvider.HistryRequests.First().Resolution); Assert.IsFalse(_testHistoryProvider.HistryRequests.First().IncludeExtendedMarketHours); Assert.IsFalse(_testHistoryProvider.HistryRequests.First().IsCustomData); Assert.AreEqual(fillForwardResolution, _testHistoryProvider.HistryRequests.First().FillForwardResolution); Assert.AreEqual(DataNormalizationMode.Adjusted, _testHistoryProvider.HistryRequests.First().DataNormalizationMode); Assert.AreEqual(TickType.Trade, _testHistoryProvider.HistryRequests.First().TickType); } [Test] public void TickHistoryRequestIgnoresFillForward() { _algorithm.SetStartDate(2013, 10, 07); _algorithm.History(new [] {Symbols.SPY}, new DateTime(1,1,1,1,1,1), new DateTime(1, 1, 1, 1, 1, 2), Resolution.Tick, fillForward: true); Assert.AreEqual(2, _testHistoryProvider.HistryRequests.Count); Assert.AreEqual(Symbols.SPY, _testHistoryProvider.HistryRequests.First().Symbol); Assert.AreEqual(Resolution.Tick, _testHistoryProvider.HistryRequests.First().Resolution); Assert.IsFalse(_testHistoryProvider.HistryRequests.First().IncludeExtendedMarketHours); Assert.IsFalse(_testHistoryProvider.HistryRequests.First().IsCustomData); Assert.AreEqual(null, _testHistoryProvider.HistryRequests.First().FillForwardResolution); Assert.AreEqual(DataNormalizationMode.Adjusted, _testHistoryProvider.HistryRequests.First().DataNormalizationMode); Assert.AreEqual(TickType.Trade, _testHistoryProvider.HistryRequests.First().TickType); } [Test] public void GetLastKnownPriceOfIlliquidAsset_RealData() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider,new DateTime(2014, 6, 6, 11, 0, 0)); //20140606_twx_minute_quote_american_call_230000_20150117.csv var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 23, new DateTime(2015,1,17)); var option = algorithm.AddOptionContract(optionSymbol); var lastKnownPrice = algorithm.GetLastKnownPrice(option); Assert.IsNotNull(lastKnownPrice); // Data gap of more than 15 minutes Assert.Greater((algorithm.Time - lastKnownPrice.EndTime).TotalMinutes, 15); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPriceOfIlliquidAsset_TestData() { // Set the start date on Tuesday _algorithm.SetStartDate(2014, 6, 10); var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 23, new DateTime(2015, 1, 17)); var option = _algorithm.AddOptionContract(optionSymbol); // The last known price is on Friday, so we missed data from Monday and no data during Weekend var barTime = new DateTime(2014, 6, 6, 15, 0, 0, 0); _testHistoryProvider.Slices = new[] { new Slice(barTime, new[] { new TradeBar(barTime, optionSymbol, 100, 100, 100, 100, 1) }) }.ToList(); var lastKnownPrice = _algorithm.GetLastKnownPrice(option); Assert.IsNotNull(lastKnownPrice); Assert.AreEqual(barTime.AddMinutes(1), lastKnownPrice.EndTime); } [Test] public void GetLastKnownPriceOfCustomData() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2018, 4, 4)); var alpha = algorithm.AddData<AlphaStreamsPortfolioState>("9fc8ef73792331b11dbd5429a"); var lastKnownPrice = algorithm.GetLastKnownPrice(alpha); Assert.IsNotNull(lastKnownPrice); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPricesEquity() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2013, 10, 8)); var equity = algorithm.AddEquity("SPY"); var lastKnownPrices = algorithm.GetLastKnownPrices(equity.Symbol).ToList(); Assert.AreEqual(2, lastKnownPrices.Count); Assert.AreEqual(1, lastKnownPrices.Count(data => data.GetType() == typeof(TradeBar))); Assert.AreEqual(1, lastKnownPrices.Count(data => data.GetType() == typeof(QuoteBar))); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPriceEquity() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2013, 10, 8)); var equity = algorithm.AddEquity("SPY"); var lastKnownPrice = algorithm.GetLastKnownPrice(equity); Assert.AreEqual(typeof(TradeBar), lastKnownPrice.GetType()); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPriceOption() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2014, 06, 09)); var option = algorithm.AddOptionContract(Symbols.CreateOptionSymbol("AAPL", OptionRight.Call, 250m, new DateTime(2016, 01, 15))); var lastKnownPrice = algorithm.GetLastKnownPrice(option); Assert.AreEqual(typeof(QuoteBar), lastKnownPrice.GetType()); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPricesOption() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2014, 06, 09)); var option = algorithm.AddOptionContract(Symbols.CreateOptionSymbol("AAPL", OptionRight.Call, 250m, new DateTime(2016, 01, 15))); var lastKnownPrices = algorithm.GetLastKnownPrices(option).ToList();; Assert.AreEqual(2, lastKnownPrices.Count); Assert.AreEqual(1, lastKnownPrices.Count(data => data.GetType() == typeof(TradeBar))); Assert.AreEqual(1, lastKnownPrices.Count(data => data.GetType() == typeof(QuoteBar))); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPriceFuture() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2013, 10, 8)); var future = algorithm.AddSecurity(Symbols.CreateFutureSymbol(Futures.Indices.SP500EMini, new DateTime(2013, 12, 20))); var lastKnownPrice = algorithm.GetLastKnownPrice(future); Assert.AreEqual(typeof(QuoteBar), lastKnownPrice.GetType()); cacheProvider.DisposeSafely(); } [Test] public void GetLastKnownPricesFuture() { var cacheProvider = new ZipDataCacheProvider(_dataProvider); var algorithm = GetAlgorithm(cacheProvider, new DateTime(2013, 10, 8)); var future = algorithm.AddSecurity(Symbols.CreateFutureSymbol(Futures.Indices.SP500EMini, new DateTime(2013, 12, 20))); var lastKnownPrices = algorithm.GetLastKnownPrices(future).ToList(); Assert.AreEqual(2, lastKnownPrices.Count); Assert.AreEqual(1, lastKnownPrices.Count(data => data.GetType() == typeof(TradeBar))); Assert.AreEqual(1, lastKnownPrices.Count(data => data.GetType() == typeof(QuoteBar))); cacheProvider.DisposeSafely(); } [Test] public void TickResolutionOpenInterestHistoryRequestIsNotFilteredWhenRequestedExplicitly() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.HistoryProvider = new SubscriptionDataReaderHistoryProvider(); var zipCacheProvider = new ZipDataCacheProvider(_dataProvider); _algorithm.HistoryProvider.Initialize(new HistoryProviderInitializeParameters( null, null, _dataProvider, zipCacheProvider, _mapFileProvider, _factorFileProvider, null, false, new DataPermissionManager())); var start = new DateTime(2014, 6, 05); _algorithm.SetStartDate(start); _algorithm.SetDateTime(start.AddDays(2)); _algorithm.UniverseSettings.FillForward = false; var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 23, new DateTime(2015, 1, 17)); var openInterests = _algorithm.History<OpenInterest>(optionSymbol, start, start.AddDays(2), Resolution.Minute).ToList(); zipCacheProvider.DisposeSafely(); Assert.IsNotEmpty(openInterests); Assert.AreEqual(2, openInterests.Count); Assert.AreEqual(new DateTime(2014, 06, 05, 6, 32, 0), openInterests[0].Time); Assert.AreEqual(optionSymbol, openInterests[0].Symbol); Assert.AreEqual(new DateTime(2014, 06, 06, 6, 32, 0), openInterests[1].Time); Assert.AreEqual(optionSymbol, openInterests[1].Symbol); } [Test] public void TickResolutionOpenInterestHistoryRequestIsFilteredByDefault_SingleSymbol() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.HistoryProvider = new SubscriptionDataReaderHistoryProvider(); var zipCacheProvider = new ZipDataCacheProvider(_dataProvider); _algorithm.HistoryProvider.Initialize(new HistoryProviderInitializeParameters( null, null, _dataProvider, zipCacheProvider, _mapFileProvider, _factorFileProvider, null, false, new DataPermissionManager())); var start = new DateTime(2014, 6, 05); _algorithm.SetStartDate(start); _algorithm.SetDateTime(start.AddDays(2)); var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 23, new DateTime(2015, 1, 17)); var result = _algorithm.History(new[] { optionSymbol }, start, start.AddDays(2), Resolution.Minute, fillForward:false).ToList(); zipCacheProvider.DisposeSafely(); Assert.IsNotEmpty(result); Assert.IsTrue(result.Any(slice => slice.ContainsKey(optionSymbol))); var openInterests = result.Select(slice => slice.Get(typeof(OpenInterest)) as DataDictionary<OpenInterest>).Where(dataDictionary => dataDictionary.Count > 0).ToList(); Assert.AreEqual(0, openInterests.Count); } [Test] public void TickResolutionOpenInterestHistoryRequestIsFilteredByDefault_MultipleSymbols() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _algorithm.HistoryProvider = new SubscriptionDataReaderHistoryProvider(); var zipCacheProvider = new ZipDataCacheProvider(_dataProvider); _algorithm.HistoryProvider.Initialize(new HistoryProviderInitializeParameters( null, null, _dataProvider, zipCacheProvider, _mapFileProvider, _factorFileProvider, null, false, new DataPermissionManager())); var start = new DateTime(2014, 6, 05); _algorithm.SetStartDate(start); _algorithm.SetDateTime(start.AddDays(2)); var optionSymbol = Symbol.CreateOption("TWX", Market.USA, OptionStyle.American, OptionRight.Call, 23, new DateTime(2015, 1, 17)); var optionSymbol2 = Symbol.CreateOption("AAPL", Market.USA, OptionStyle.American, OptionRight.Call, 500, new DateTime(2015, 1, 17)); var result = _algorithm.History(new[] { optionSymbol, optionSymbol2 }, start, start.AddDays(2), Resolution.Minute, fillForward: false).ToList(); zipCacheProvider.DisposeSafely(); Assert.IsNotEmpty(result); Assert.IsTrue(result.Any(slice => slice.ContainsKey(optionSymbol))); Assert.IsTrue(result.Any(slice => slice.ContainsKey(optionSymbol2))); var openInterests = result.Select(slice => slice.Get(typeof(OpenInterest)) as DataDictionary<OpenInterest>).Where(dataDictionary => dataDictionary.Count > 0).ToList(); Assert.AreEqual(0, openInterests.Count); } private QCAlgorithm GetAlgorithm(IDataCacheProvider cacheProvider, DateTime dateTime) { var algorithm = new QCAlgorithm(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.HistoryProvider = new SubscriptionDataReaderHistoryProvider(); algorithm.SetDateTime(dateTime.ConvertToUtc(algorithm.TimeZone)); algorithm.HistoryProvider.Initialize(new HistoryProviderInitializeParameters( null, null, _dataProvider, cacheProvider, _mapFileProvider, _factorFileProvider, null, false, new DataPermissionManager())); return algorithm; } private class TestHistoryProvider : HistoryProviderBase { public override int DataPointCount { get; } public List<HistoryRequest> HistryRequests { get; } = new List<HistoryRequest>(); public List<Slice> Slices { get; set; } = new List<Slice>(); public override void Initialize(HistoryProviderInitializeParameters parameters) { throw new NotImplementedException(); } public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone) { foreach (var request in requests) { HistryRequests.Add(request); } var startTime = requests.Min(x => x.StartTimeUtc.ConvertFromUtc(x.DataTimeZone)); var endTime = requests.Max(x => x.EndTimeUtc.ConvertFromUtc(x.DataTimeZone)); return Slices.Where(x => x.Time >= startTime && x.Time <= endTime).ToList(); } } } }
namespace android.content.pm { [global::MonoJavaBridge.JavaClass()] public partial class ApplicationInfo : android.content.pm.PackageItemInfo, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static ApplicationInfo() { InitJNI(); } protected ApplicationInfo(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public new partial class DisplayNameComparator : java.lang.Object, java.util.Comparator { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static DisplayNameComparator() { InitJNI(); } protected DisplayNameComparator(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _compare1853; public virtual int compare(android.content.pm.ApplicationInfo arg0, android.content.pm.ApplicationInfo arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.DisplayNameComparator._compare1853, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass, global::android.content.pm.ApplicationInfo.DisplayNameComparator._compare1853, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _compare1854; public virtual int compare(java.lang.Object arg0, java.lang.Object arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.DisplayNameComparator._compare1854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass, global::android.content.pm.ApplicationInfo.DisplayNameComparator._compare1854, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _DisplayNameComparator1855; public DisplayNameComparator(android.content.pm.PackageManager arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass, global::android.content.pm.ApplicationInfo.DisplayNameComparator._DisplayNameComparator1855, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ApplicationInfo$DisplayNameComparator")); global::android.content.pm.ApplicationInfo.DisplayNameComparator._compare1853 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass, "compare", "(Landroid/content/pm/ApplicationInfo;Landroid/content/pm/ApplicationInfo;)I"); global::android.content.pm.ApplicationInfo.DisplayNameComparator._compare1854 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass, "compare", "(Ljava/lang/Object;Ljava/lang/Object;)I"); global::android.content.pm.ApplicationInfo.DisplayNameComparator._DisplayNameComparator1855 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.DisplayNameComparator.staticClass, "<init>", "(Landroid/content/pm/PackageManager;)V"); } } internal static global::MonoJavaBridge.MethodId _toString1856; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo._toString1856)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._toString1856)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _dump1857; public virtual void dump(android.util.Printer arg0, java.lang.String arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo._dump1857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._dump1857, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _writeToParcel1858; public override void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo._writeToParcel1858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._writeToParcel1858, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents1859; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo._describeContents1859); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._describeContents1859); } internal static global::MonoJavaBridge.MethodId _loadDescription1860; public virtual global::java.lang.CharSequence loadDescription(android.content.pm.PackageManager arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo._loadDescription1860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._loadDescription1860, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _ApplicationInfo1861; public ApplicationInfo() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._ApplicationInfo1861); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _ApplicationInfo1862; public ApplicationInfo(android.content.pm.ApplicationInfo arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.pm.ApplicationInfo.staticClass, global::android.content.pm.ApplicationInfo._ApplicationInfo1862, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _taskAffinity1863; public global::java.lang.String taskAffinity { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _permission1864; public global::java.lang.String permission { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _processName1865; public global::java.lang.String processName { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _className1866; public global::java.lang.String className { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _descriptionRes1867; public int descriptionRes { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _theme1868; public int theme { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _manageSpaceActivityName1869; public global::java.lang.String manageSpaceActivityName { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _backupAgentName1870; public global::java.lang.String backupAgentName { get { return default(global::java.lang.String); } set { } } public static int FLAG_SYSTEM { get { return 1; } } public static int FLAG_DEBUGGABLE { get { return 2; } } public static int FLAG_HAS_CODE { get { return 4; } } public static int FLAG_PERSISTENT { get { return 8; } } public static int FLAG_FACTORY_TEST { get { return 16; } } public static int FLAG_ALLOW_TASK_REPARENTING { get { return 32; } } public static int FLAG_ALLOW_CLEAR_USER_DATA { get { return 64; } } public static int FLAG_UPDATED_SYSTEM_APP { get { return 128; } } public static int FLAG_TEST_ONLY { get { return 256; } } public static int FLAG_SUPPORTS_SMALL_SCREENS { get { return 512; } } public static int FLAG_SUPPORTS_NORMAL_SCREENS { get { return 1024; } } public static int FLAG_SUPPORTS_LARGE_SCREENS { get { return 2048; } } public static int FLAG_RESIZEABLE_FOR_SCREENS { get { return 4096; } } public static int FLAG_SUPPORTS_SCREEN_DENSITIES { get { return 8192; } } public static int FLAG_VM_SAFE_MODE { get { return 16384; } } public static int FLAG_ALLOW_BACKUP { get { return 32768; } } public static int FLAG_KILL_AFTER_RESTORE { get { return 65536; } } public static int FLAG_RESTORE_ANY_VERSION { get { return 131072; } } public static int FLAG_EXTERNAL_STORAGE { get { return 262144; } } internal static global::MonoJavaBridge.FieldId _flags1871; public int flags { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _sourceDir1872; public global::java.lang.String sourceDir { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _publicSourceDir1873; public global::java.lang.String publicSourceDir { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _sharedLibraryFiles1874; public global::java.lang.String[] sharedLibraryFiles { get { return default(global::java.lang.String[]); } set { } } internal static global::MonoJavaBridge.FieldId _dataDir1875; public global::java.lang.String dataDir { get { return default(global::java.lang.String); } set { } } internal static global::MonoJavaBridge.FieldId _uid1876; public int uid { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _targetSdkVersion1877; public int targetSdkVersion { get { return default(int); } set { } } internal static global::MonoJavaBridge.FieldId _enabled1878; public bool enabled { get { return default(bool); } set { } } internal static global::MonoJavaBridge.FieldId _CREATOR1879; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.pm.ApplicationInfo.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/pm/ApplicationInfo")); global::android.content.pm.ApplicationInfo._toString1856 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "toString", "()Ljava/lang/String;"); global::android.content.pm.ApplicationInfo._dump1857 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "dump", "(Landroid/util/Printer;Ljava/lang/String;)V"); global::android.content.pm.ApplicationInfo._writeToParcel1858 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.content.pm.ApplicationInfo._describeContents1859 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "describeContents", "()I"); global::android.content.pm.ApplicationInfo._loadDescription1860 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "loadDescription", "(Landroid/content/pm/PackageManager;)Ljava/lang/CharSequence;"); global::android.content.pm.ApplicationInfo._ApplicationInfo1861 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "<init>", "()V"); global::android.content.pm.ApplicationInfo._ApplicationInfo1862 = @__env.GetMethodIDNoThrow(global::android.content.pm.ApplicationInfo.staticClass, "<init>", "(Landroid/content/pm/ApplicationInfo;)V"); } } }
// Copyright (C) 2014 dot42 // // Original filename: String.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.Globalization; using System.Text; using Dot42; using Dot42.Internal; using Java.Lang; using Java.Util; namespace System { partial class String { public const string Empty = ""; /// <summary> /// Creates a string with the specified character repeated 'count' times. /// </summary> public String(char c, int count) : this(Constuct(c, count)) { } private static char[] Constuct(char c, int count) { var result = new char[count]; Arrays.Fill(result, c); return result; } /// <summary> /// Gets the number of characters in the string /// </summary> int Java.Lang.ICharSequence.GetLength() { return Length; } /// <summary> /// Compare strings /// </summary> [Inline] public static int Compare(string strA, string strB) { return Compare(strA, strB, false); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, string strB, bool ignoreCase) { if (ReferenceEquals(strA, null) && ReferenceEquals(strB, null)) return 0; if (ReferenceEquals(strA, null)) return 1; if (ReferenceEquals(strB, null)) return -1; if (ignoreCase) return strA.CompareToIgnoreCase(strB); return strA.CompareTo(strB); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, string strB, StringComparison comparisonType) { var ignoreCase = (comparisonType == StringComparison.InvariantCultureIgnoreCase) || (comparisonType == StringComparison.CurrentCultureIgnoreCase) || (comparisonType == StringComparison.OrdinalIgnoreCase); return Compare(strA, strB, ignoreCase); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo cultureInfo) { var a = strA.JavaSubstring(indexA, indexA + length); var b = strB.JavaSubstring(indexB, indexB + length); if (ignoreCase) return a.CompareToIgnoreCase(b); else return a.CompareTo(b); } /// <summary> /// Compare strings /// </summary> [Inline] public static int CompareOrdinal(string strA, string strB) { return Compare(strA, strB, StringComparison.Ordinal); } /// <summary> /// Does this string contain the given sub string? /// </summary> [Inline] public bool Contains(string value) { return Contains((ICharSequence) value); } /// <summary> /// Copy a specified numbers of characters from this string to the given array. /// </summary> public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException("destination"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (sourceIndex + count > Length) throw new ArgumentOutOfRangeException("count"); if (destinationIndex + count > destination.Length) throw new ArgumentOutOfRangeException("count"); while (count > 0) { destination[destinationIndex++] = this[sourceIndex++]; count--; } } /// <summary> /// Replaces format items in the given string with a string representation of the given argument. /// </summary> [Inline] public static string Format(string format, object arg0) { if (format == null) throw new ArgumentNullException("format"); return Format(null, format, new[] { arg0 }); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> [Inline] public static string Format(string format, object arg0, object arg1) { if (format == null) throw new ArgumentNullException("format"); return Format(null, format, new[] { arg0, arg1 }); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> [Inline] public static string Format(string format, object arg0, object arg1, object arg2) { if (format == null) throw new ArgumentNullException("format"); return Format(null, format, new[] { arg0, arg1, arg2 }); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> [Inline] public static string Format(string format, params object[] args) { return Format(null, format, args); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> [Inline] public static string Format(IFormatProvider provider, string format, params object[] args) { var helper = new FormatHelper(null, provider, format, args); return helper.Format().ToString(); } /// <summary> /// Gets the index of the first use of the given character in this string. /// </summary> /// <returns>The index of the first use of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOf(char ch) { return IndexOf((int) ch); } /// <summary> /// Gets the index of the first use of the given character in this string. /// The search starts at the given index. /// </summary> /// <returns>The index of the first use of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOf(char ch, int startIndex) { return IndexOf((int)ch, startIndex); } /// <summary> /// Gets the index of the first use of any of the given characters in this string. /// </summary> /// <returns>The index of the first use of any of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOfAny(char[] array) { return IndexOfAny(array, 0, GetLength()); } /// <summary> /// Gets the index of the first use of any of the given characters in this string. /// </summary> /// <returns>The index of the first use of any of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOfAny(char[] array, int startIndex) { return IndexOfAny(array, startIndex, GetLength() - startIndex); } /// <summary> /// Gets the index of the first use of any of the given characters in this string. /// </summary> /// <returns>The index of the first use of any of the given character or -1 if the given character is not used.</returns> public int IndexOfAny(char[] array, int startIndex, int count) { if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if (count < 0) throw new ArgumentOutOfRangeException("count"); var length = GetLength(); if (startIndex + count > length) throw new ArgumentOutOfRangeException(); var arrayLen = array.Length; var endIndex = startIndex + count; for (var i = startIndex; i < endIndex; i++) { var ch = CharAt(i); for (var j = 0; j < arrayLen; j++) { if (array[j] == ch) return i; } } return -1; } /// <summary> /// Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position and examines a specified number of character positions. /// </summary> public int IndexOf(string value, int startIndex, int count) { if ((count < 0) || (count > (Length - startIndex))) throw new ArgumentOutOfRangeException("count"); if ((startIndex < 0) || (startIndex > Length)) throw new ArgumentOutOfRangeException("startIndex"); var subString = JavaSubstring(startIndex, startIndex + count); var index = subString.IndexOf(value); return (index < 0) ? index : index + startIndex; } /// <summary> /// Returns a new string that right-aligns the characters in this string by padding them with spaces on the left, for a specified total length. /// </summary> [Inline] public string PadLeft(int totalWidth) { return PadLeft(totalWidth, ' '); } /// <summary> /// Returns a new string that right-aligns the characters in this string by padding them given character on the left, for a specified total length. /// </summary> public string PadLeft(int totalWidth, char paddingChar) { var length = Length; if (totalWidth <= length) return this; var builder = new StringBuilder(this); var padLength = totalWidth - length; builder.Insert(0, new RepeatingCharSequence(paddingChar, padLength)); return builder.ToString(); } /// <summary> /// Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length. /// </summary> [Inline] public string PadRight(int totalWidth) { return PadRight(totalWidth, ' '); } /// <summary> /// Returns a new string that left-aligns the characters in this string by padding them given character on the right, for a specified total length. /// </summary> public string PadRight(int totalWidth, char paddingChar) { var length = Length; if (totalWidth <= length) return this; var builder = new StringBuilder(this); var padLength = totalWidth - length; builder.Append(new RepeatingCharSequence(paddingChar, padLength)); return builder.ToString(); } /// <summary> /// Return a new instance which is this string with all characters from the given index on removed. /// </summary> [Inline] public string Remove(int startIndex) { if ((startIndex < 0) || (startIndex >= Length)) throw new ArgumentOutOfRangeException("startIndex"); return JavaSubstring(0, startIndex); } /// <summary> /// Return a new instance which is this string with count characters from the given index on removed. /// </summary> public string Remove(int startIndex, int count) { var len = Length; if ((startIndex < 0) || (startIndex >= len)) throw new ArgumentOutOfRangeException("startIndex"); if ((count < 0) || (startIndex + count >= len)) throw new ArgumentOutOfRangeException("count"); if (count == 0) return this; if (startIndex == 0) return JavaSubstring(count, (len - count + 1)); var sb = new StringBuilder(); sb.Append(this, 0, startIndex); sb.Append(this, startIndex + count, len - (startIndex + count)); return sb.ToString(); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> [Inline] public string[] Split(params char[] separator) { return Split(separator, int.MaxValue, StringSplitOptions.None); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> [Inline] public string[] Split(char[] separator, int count) { return Split(separator, count, StringSplitOptions.None); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> [Inline] public string[] Split(char[] separator, StringSplitOptions options) { return Split(separator, int.MaxValue, options); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> public string[] Split(char[] separator, int count, StringSplitOptions options) { if (count < 0) throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero."); if ((options != StringSplitOptions.None) && (options != StringSplitOptions.RemoveEmptyEntries)) throw new ArgumentException("Illegal enum value: " + options + "."); var removeEmptyEntries = (options & StringSplitOptions.RemoveEmptyEntries) != 0; var length = Length; if ((length == 0) && removeEmptyEntries) return new string[0]; if (count <= 1) { return count == 0 ? new string[0] : new[] { this }; } var list = new ArrayList<string>(); var start = 0; var index = 0; while (index < length) { if (Contains(separator, CharAt(index))) { // Split here if ((!removeEmptyEntries) || (start != index)) { list.Add(JavaSubstring(start, index)); } index++; start = index; if (list.Count + 1 >= count) break; } else { index++; } } // Add last part (if needed) if (start <= index) { if ((!removeEmptyEntries) || (start != index)) { list.Add(JavaSubstring(start, index)); } } return list.ToArray<string>(new string[list.Count]); } /// <summary> /// Does the given array contain the given character? /// </summary> private static bool Contains(char[] array, char value) { var length = array.Length; for (var i = 0; i < length; i++) if (array[i] == value) return true; return false; } /// <summary> /// Return a substring of this instance. /// </summary> [Dot42.DexImport("substring", "(I)Ljava/lang/String;")] public string Substring(int start) { return default(string); } /// <summary> /// Return a substring of this instance. /// </summary> [Inline] public string Substring(int startIndex, int length) { if (length < 0) throw new ArgumentOutOfRangeException("length"); return JavaSubstring(startIndex, startIndex + length); } /// <summary> /// Is the given string null or zero length. /// </summary> [Inline] public static bool IsNullOrEmpty(string value) { return (value == null) || (value.Length == 0); } /// <summary> /// Is the given string null or consists only of whitespace characters. /// </summary> [Inline] public static bool IsNullOrWhiteSpace(string value) { return (value == null) || (value.Trim().Length == 0); } /// <summary> /// Create a concatenation of all strings in the array with the given separator between each array element. /// </summary> public static string Join(string separator, params string[] array) { if (array.Length == 0) return ""; var sb = new StringBuffer(); var first = true; foreach (var element in array) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Create a concatenation of all strings in the array with the given separator between each array element. /// </summary> public static string Join(string separator, params object[] array) { if ((array.Length == 0) || (array[0] == null)) return ""; var sb = new StringBuffer(); var first = true; foreach (var element in array) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Create a concatenation of all strings in the array with the given separator between each array element. /// </summary> public static string Join(string separator, IEnumerable<string> strings) { var sb = new StringBuffer(); var first = true; foreach (var element in strings) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Create a concatenation of all objects in the enumerable with the given separator between each element. /// </summary> public static string Join<T>(string separator, IEnumerable<T> objects) { var sb = new StringBuffer(); var first = true; foreach (var element in objects) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Gets a string representation of the given value. /// </summary> public static string Concat(object value) { return (value == null) ? string.Empty : value.ToString(); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(object v1, object v2) { v1 = v1 ?? string.Empty; v2 = v2 ?? string.Empty; return Concat(v1.ToString(), v2.ToString()); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(object v1, object v2, object v3) { v1 = v1 ?? string.Empty; v2 = v2 ?? string.Empty; v3 = v3 ?? string.Empty; return Concat(v1.ToString(), v2.ToString(), v3.ToString()); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(object v1, object v2, object v3, object v4) { v1 = v1 ?? string.Empty; v2 = v2 ?? string.Empty; v3 = v3 ?? string.Empty; v4 = v4 ?? string.Empty; return Concat(v1.ToString(), v2.ToString(), v3.ToString(), v4.ToString()); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(params object[] args) { if (args == null) throw new ArgumentNullException("args"); var sb = new Java.Lang.StringBuffer(); for (var i = 0; i < args.Length; i++) { var arg = args[i]; if (arg != null) sb.Append(arg); } return sb.ToString(); } /// <summary> /// Concatenate v1 and v2. /// </summary> public static string Concat(string v1, string v2) { if (string.IsNullOrEmpty(v1)) { if (string.IsNullOrEmpty(v2)) return string.Empty; return v2; } if (string.IsNullOrEmpty(v2)) return v1; return v1.Concat(v2); } /// <summary> /// Concatenate v1, v2 and v3. /// </summary> public static string Concat(string v1, string v2, string v3) { v1 = v1 ?? string.Empty; v2 = v2 ?? string.Empty; v3 = v3 ?? string.Empty; return v1.Concat(v2).Concat(v3); } /// <summary> /// Concatenate v1, v2, v3 and v4. /// </summary> public static string Concat(string v1, string v2, string v3, string v4) { v1 = v1 ?? string.Empty; v2 = v2 ?? string.Empty; v3 = v3 ?? string.Empty; v4 = v4 ?? string.Empty; return v1.Concat(v2).Concat(v3).Concat(v4); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(params string[] args) { if (args == null) throw new ArgumentNullException("args"); var sb = new Java.Lang.StringBuffer(); for (var i = 0; i < args.Length; i++) { var arg = args[i]; if (arg != null) sb.Append(arg); } return sb.ToString(); } /// <summary> /// Is this string equal to the given string? /// </summary> [Inline] public bool Equals(string other) { return Equals((object) other); } /// <summary> /// Is string a equal to string b? /// </summary> [Inline] public static bool Equals(string a, string b) { if (a == null) return b == null; return a.Equals(b); } /// <summary> /// Return a new string in which all occurrences of the given old value have been replaced with the given new value. /// </summary> [Inline] public string Replace(string oldValue, string newValue) { return Replace((ICharSequence) oldValue, (ICharSequence) newValue); } [Inline] public string ToUpper(CultureInfo culture) { return ToUpper(culture.Locale); } [Inline] public string ToUpperInvariant() { return ToUpper(CultureInfo.InvariantCulture); } [Inline] public string ToLower(CultureInfo culture) { return ToLower(culture.Locale); } [Inline] public string ToLowerInvariant() { return ToLower(CultureInfo.InvariantCulture); } /// <summary> /// Removes all leading and trailing occurrences of a set of characters specified in an array from the current object. /// </summary> public string Trim(params char[] trimChars) { if (Length == 0) return Empty; int start = 0; if (trimChars != null && trimChars.Length != 0) start = FindNotInTable(0, Length, 1, trimChars); int end = 0; if (trimChars != null && trimChars.Length != 0) end = FindNotInTable(Length - 1, -1, -1, trimChars); end++; if (start == 0 && end == Length) return this; return JavaSubstring(start, end); } /// <summary> /// Removes all leading occurrences of a set of characters specified in an array from the current object. /// </summary> public string TrimStart(params char[] trimChars) { if (Length == 0) return Empty; int start = 0; if (trimChars != null && trimChars.Length != 0) start = FindNotInTable(0, Length, 1, trimChars); if (start == 0) return this; return JavaSubstring(start, Length); } /// <summary> /// Removes all trailing occurrences of a set of characters specified in an array from the current object. /// </summary> public String TrimEnd(params char[] trimChars) { if (Length == 0) return Empty; int end = 0; if (trimChars != null && trimChars.Length != 0) end = FindNotInTable(Length - 1, -1, -1, trimChars); end++; if (end == Length) return this; return JavaSubstring(0, end); } private int FindNotInTable(int pos, int target, int change, char[] table) { while (pos != target) { char c = this[pos]; int x = 0; while (x < table.Length) { if (c == table[x]) break; x++; } if (x == table.Length) return pos; pos += change; } return pos; } /// <summary> /// Is string a equal to string b? /// </summary> public static bool operator ==(string a, string b) { return Equals(a, b); } /// <summary> /// Is string a not equal to string b? /// </summary> public static bool operator !=(string a, string b) { return !Equals(a, b); } } }
namespace android.telephony.gsm { [global::MonoJavaBridge.JavaClass()] public partial class SmsMessage : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected SmsMessage(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public sealed partial class MessageClass : java.lang.Enum { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal MessageClass(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static global::android.telephony.gsm.SmsMessage.MessageClass[] values() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage.MessageClass._m0.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage.MessageClass._m0 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "values", "()[Landroid/telephony/gsm/SmsMessage/MessageClass;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.telephony.gsm.SmsMessage.MessageClass>(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.MessageClass.staticClass, global::android.telephony.gsm.SmsMessage.MessageClass._m0)) as android.telephony.gsm.SmsMessage.MessageClass[]; } private static global::MonoJavaBridge.MethodId _m1; public static global::android.telephony.gsm.SmsMessage.MessageClass valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage.MessageClass._m1.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage.MessageClass._m1 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/telephony/gsm/SmsMessage$MessageClass;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.gsm.SmsMessage.MessageClass>(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.MessageClass.staticClass, global::android.telephony.gsm.SmsMessage.MessageClass._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.telephony.gsm.SmsMessage.MessageClass; } internal static global::MonoJavaBridge.FieldId _CLASS_05168; public static global::android.telephony.gsm.SmsMessage.MessageClass CLASS_0 { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.gsm.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, _CLASS_05168)) as android.telephony.gsm.SmsMessage.MessageClass; } } internal static global::MonoJavaBridge.FieldId _CLASS_15169; public static global::android.telephony.gsm.SmsMessage.MessageClass CLASS_1 { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.gsm.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, _CLASS_15169)) as android.telephony.gsm.SmsMessage.MessageClass; } } internal static global::MonoJavaBridge.FieldId _CLASS_25170; public static global::android.telephony.gsm.SmsMessage.MessageClass CLASS_2 { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.gsm.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, _CLASS_25170)) as android.telephony.gsm.SmsMessage.MessageClass; } } internal static global::MonoJavaBridge.FieldId _CLASS_35171; public static global::android.telephony.gsm.SmsMessage.MessageClass CLASS_3 { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.gsm.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, _CLASS_35171)) as android.telephony.gsm.SmsMessage.MessageClass; } } internal static global::MonoJavaBridge.FieldId _UNKNOWN5172; public static global::android.telephony.gsm.SmsMessage.MessageClass UNKNOWN { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.telephony.gsm.SmsMessage.MessageClass>(@__env.GetStaticObjectField(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, _UNKNOWN5172)) as android.telephony.gsm.SmsMessage.MessageClass; } } static MessageClass() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.telephony.gsm.SmsMessage.MessageClass.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/gsm/SmsMessage$MessageClass")); global::android.telephony.gsm.SmsMessage.MessageClass._CLASS_05168 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "CLASS_0", "Landroid/telephony/gsm/SmsMessage$MessageClass;"); global::android.telephony.gsm.SmsMessage.MessageClass._CLASS_15169 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "CLASS_1", "Landroid/telephony/gsm/SmsMessage$MessageClass;"); global::android.telephony.gsm.SmsMessage.MessageClass._CLASS_25170 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "CLASS_2", "Landroid/telephony/gsm/SmsMessage$MessageClass;"); global::android.telephony.gsm.SmsMessage.MessageClass._CLASS_35171 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "CLASS_3", "Landroid/telephony/gsm/SmsMessage$MessageClass;"); global::android.telephony.gsm.SmsMessage.MessageClass._UNKNOWN5172 = @__env.GetStaticFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.MessageClass.staticClass, "UNKNOWN", "Landroid/telephony/gsm/SmsMessage$MessageClass;"); } } [global::MonoJavaBridge.JavaClass()] public partial class SubmitPdu : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected SubmitPdu(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.SubmitPdu.staticClass, "toString", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage.SubmitPdu._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public SubmitPdu() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage.SubmitPdu._m1.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage.SubmitPdu._m1 = @__env.GetMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.SubmitPdu.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.gsm.SmsMessage.SubmitPdu.staticClass, global::android.telephony.gsm.SmsMessage.SubmitPdu._m1); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _encodedScAddress5173; public byte[] encodedScAddress { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.GetObjectField(this.JvmHandle, _encodedScAddress5173)) as byte[]; } set { } } internal static global::MonoJavaBridge.FieldId _encodedMessage5174; public byte[] encodedMessage { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.GetObjectField(this.JvmHandle, _encodedMessage5174)) as byte[]; } set { } } static SubmitPdu() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.telephony.gsm.SmsMessage.SubmitPdu.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/gsm/SmsMessage$SubmitPdu")); global::android.telephony.gsm.SmsMessage.SubmitPdu._encodedScAddress5173 = @__env.GetFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.SubmitPdu.staticClass, "encodedScAddress", "[B"); global::android.telephony.gsm.SmsMessage.SubmitPdu._encodedMessage5174 = @__env.GetFieldIDNoThrow(global::android.telephony.gsm.SmsMessage.SubmitPdu.staticClass, "encodedMessage", "[B"); } } public new byte[] UserData { get { return getUserData(); } } private static global::MonoJavaBridge.MethodId _m0; public virtual byte[] getUserData() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getUserData", "()[B", ref global::android.telephony.gsm.SmsMessage._m0) as byte[]; } public new int Status { get { return getStatus(); } } private static global::MonoJavaBridge.MethodId _m1; public virtual int getStatus() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "getStatus", "()I", ref global::android.telephony.gsm.SmsMessage._m1); } private static global::MonoJavaBridge.MethodId _m2; public static global::android.telephony.gsm.SmsMessage createFromPdu(byte[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m2.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m2 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "createFromPdu", "([B)Landroid/telephony/gsm/SmsMessage;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.telephony.gsm.SmsMessage; } private static global::MonoJavaBridge.MethodId _m3; public static int getTPLayerLengthForPDU(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m3.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m3 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "getTPLayerLengthForPDU", "(Ljava/lang/String;)I"); return @__env.CallStaticIntMethod(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public static int[] calculateLength(java.lang.CharSequence arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m4.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m4 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "calculateLength", "(Ljava/lang/CharSequence;Z)[I"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as int[]; } public static int[] calculateLength(string arg0, bool arg1) { return calculateLength((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1); } private static global::MonoJavaBridge.MethodId _m5; public static int[] calculateLength(java.lang.String arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m5.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m5 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "calculateLength", "(Ljava/lang/String;Z)[I"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as int[]; } private static global::MonoJavaBridge.MethodId _m6; public static global::android.telephony.gsm.SmsMessage.SubmitPdu getSubmitPdu(java.lang.String arg0, java.lang.String arg1, short arg2, byte[] arg3, bool arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m6.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m6 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;S[BZ)Landroid/telephony/gsm/SmsMessage$SubmitPdu;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.telephony.gsm.SmsMessage.SubmitPdu; } private static global::MonoJavaBridge.MethodId _m7; public static global::android.telephony.gsm.SmsMessage.SubmitPdu getSubmitPdu(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2, bool arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m7.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m7 = @__env.GetStaticMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "getSubmitPdu", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)Landroid/telephony/gsm/SmsMessage$SubmitPdu;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.telephony.gsm.SmsMessage.SubmitPdu; } public new global::java.lang.String ServiceCenterAddress { get { return getServiceCenterAddress(); } } private static global::MonoJavaBridge.MethodId _m8; public virtual global::java.lang.String getServiceCenterAddress() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getServiceCenterAddress", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m8) as java.lang.String; } public new global::java.lang.String OriginatingAddress { get { return getOriginatingAddress(); } } private static global::MonoJavaBridge.MethodId _m9; public virtual global::java.lang.String getOriginatingAddress() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getOriginatingAddress", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m9) as java.lang.String; } public new global::java.lang.String DisplayOriginatingAddress { get { return getDisplayOriginatingAddress(); } } private static global::MonoJavaBridge.MethodId _m10; public virtual global::java.lang.String getDisplayOriginatingAddress() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getDisplayOriginatingAddress", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m10) as java.lang.String; } public new global::java.lang.String MessageBody { get { return getMessageBody(); } } private static global::MonoJavaBridge.MethodId _m11; public virtual global::java.lang.String getMessageBody() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getMessageBody", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m11) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m12; public virtual global::android.telephony.gsm.SmsMessage.MessageClass getMessageClass() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.telephony.gsm.SmsMessage.MessageClass>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getMessageClass", "()Landroid/telephony/gsm/SmsMessage$MessageClass;", ref global::android.telephony.gsm.SmsMessage._m12) as android.telephony.gsm.SmsMessage.MessageClass; } public new global::java.lang.String DisplayMessageBody { get { return getDisplayMessageBody(); } } private static global::MonoJavaBridge.MethodId _m13; public virtual global::java.lang.String getDisplayMessageBody() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getDisplayMessageBody", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m13) as java.lang.String; } public new global::java.lang.String PseudoSubject { get { return getPseudoSubject(); } } private static global::MonoJavaBridge.MethodId _m14; public virtual global::java.lang.String getPseudoSubject() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getPseudoSubject", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m14) as java.lang.String; } public new long TimestampMillis { get { return getTimestampMillis(); } } private static global::MonoJavaBridge.MethodId _m15; public virtual long getTimestampMillis() { return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "getTimestampMillis", "()J", ref global::android.telephony.gsm.SmsMessage._m15); } private static global::MonoJavaBridge.MethodId _m16; public virtual bool isEmail() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isEmail", "()Z", ref global::android.telephony.gsm.SmsMessage._m16); } public new global::java.lang.String EmailBody { get { return getEmailBody(); } } private static global::MonoJavaBridge.MethodId _m17; public virtual global::java.lang.String getEmailBody() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getEmailBody", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m17) as java.lang.String; } public new global::java.lang.String EmailFrom { get { return getEmailFrom(); } } private static global::MonoJavaBridge.MethodId _m18; public virtual global::java.lang.String getEmailFrom() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getEmailFrom", "()Ljava/lang/String;", ref global::android.telephony.gsm.SmsMessage._m18) as java.lang.String; } public new int ProtocolIdentifier { get { return getProtocolIdentifier(); } } private static global::MonoJavaBridge.MethodId _m19; public virtual int getProtocolIdentifier() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "getProtocolIdentifier", "()I", ref global::android.telephony.gsm.SmsMessage._m19); } private static global::MonoJavaBridge.MethodId _m20; public virtual bool isReplace() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isReplace", "()Z", ref global::android.telephony.gsm.SmsMessage._m20); } private static global::MonoJavaBridge.MethodId _m21; public virtual bool isCphsMwiMessage() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isCphsMwiMessage", "()Z", ref global::android.telephony.gsm.SmsMessage._m21); } private static global::MonoJavaBridge.MethodId _m22; public virtual bool isMWIClearMessage() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isMWIClearMessage", "()Z", ref global::android.telephony.gsm.SmsMessage._m22); } private static global::MonoJavaBridge.MethodId _m23; public virtual bool isMWISetMessage() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isMWISetMessage", "()Z", ref global::android.telephony.gsm.SmsMessage._m23); } private static global::MonoJavaBridge.MethodId _m24; public virtual bool isMwiDontStore() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isMwiDontStore", "()Z", ref global::android.telephony.gsm.SmsMessage._m24); } public new byte[] Pdu { get { return getPdu(); } } private static global::MonoJavaBridge.MethodId _m25; public virtual byte[] getPdu() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.telephony.gsm.SmsMessage.staticClass, "getPdu", "()[B", ref global::android.telephony.gsm.SmsMessage._m25) as byte[]; } public new int StatusOnSim { get { return getStatusOnSim(); } } private static global::MonoJavaBridge.MethodId _m26; public virtual int getStatusOnSim() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "getStatusOnSim", "()I", ref global::android.telephony.gsm.SmsMessage._m26); } public new int IndexOnSim { get { return getIndexOnSim(); } } private static global::MonoJavaBridge.MethodId _m27; public virtual int getIndexOnSim() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "getIndexOnSim", "()I", ref global::android.telephony.gsm.SmsMessage._m27); } private static global::MonoJavaBridge.MethodId _m28; public virtual bool isStatusReportMessage() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isStatusReportMessage", "()Z", ref global::android.telephony.gsm.SmsMessage._m28); } private static global::MonoJavaBridge.MethodId _m29; public virtual bool isReplyPathPresent() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.telephony.gsm.SmsMessage.staticClass, "isReplyPathPresent", "()Z", ref global::android.telephony.gsm.SmsMessage._m29); } private static global::MonoJavaBridge.MethodId _m30; public SmsMessage() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.telephony.gsm.SmsMessage._m30.native == global::System.IntPtr.Zero) global::android.telephony.gsm.SmsMessage._m30 = @__env.GetMethodIDNoThrow(global::android.telephony.gsm.SmsMessage.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.telephony.gsm.SmsMessage.staticClass, global::android.telephony.gsm.SmsMessage._m30); Init(@__env, handle); } public static int ENCODING_UNKNOWN { get { return 0; } } public static int ENCODING_7BIT { get { return 1; } } public static int ENCODING_8BIT { get { return 2; } } public static int ENCODING_16BIT { get { return 3; } } public static int MAX_USER_DATA_BYTES { get { return 140; } } public static int MAX_USER_DATA_SEPTETS { get { return 160; } } public static int MAX_USER_DATA_SEPTETS_WITH_HEADER { get { return 153; } } static SmsMessage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.telephony.gsm.SmsMessage.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/telephony/gsm/SmsMessage")); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using IfacesEnumsStructsClasses; namespace DemoApp { /// <summary> /// To demonstrate how to receive events from /// an HTML dialog's document and window objects launched /// using showModelessDialog() and showModalDialog() methods! /// /// Sample call: /// 1) Load (dragdrop) ModalModelessDialogs.htm onto frmMain. /// 2) In an event handler call: /// <code> /// m_HtmlDlgHandler.StartHandling(); /// m_HtmlDlgHandler.Show(); /// </code> /// 3) launch a modal or modaless dialog by using one of the buttons /// in the ModalModelessDialogs.htm page. /// </summary> public partial class frmHTMLDialogHandler : Form, IHTMLEventCallBack { #region Variables private CSEXWBDLMANLib.csDLManClass m_csexwbCOMLib = new CSEXWBDLMANLib.csDLManClass(); private WindowsHookUtil.HookInfo m_CBT = new WindowsHookUtil.HookInfo(CSEXWBDLMANLib.WINDOWSHOOK_TYPES.WHT_CBT); private const string m_HTMLDlgClassName = "Internet Explorer_TridentDlgFrame"; private string m_strTemp = string.Empty; private int m_NCode = 0; private WindowEnumerator winenum = new WindowEnumerator(); private IHTMLDocument2 m_pDoc2 = null; private IHTMLWindow2 m_pWin2 = null; private System.Collections.ArrayList m_Ctls = new System.Collections.ArrayList(); private int m_Count = 0; private int m_Counter = 0; private Timer m_timer = new Timer(); private IntPtr m_Dialog = IntPtr.Zero; private IntPtr m_IE = IntPtr.Zero; private bool m_IsEventsConnected = false; private csExWB.cHTMLElementEvents m_elemEvents = new csExWB.cHTMLElementEvents(); private csExWB.cHTMLWindowEvents m_winEvents = new csExWB.cHTMLWindowEvents(); #endregion #region Form events public frmHTMLDialogHandler() { InitializeComponent(); //Initialize event handlers for document and window int[] dispids = { (int)HTMLEventDispIds.ID_ONKEYUP, (int)HTMLEventDispIds.ID_ONCLICK }; m_elemEvents.InitHTMLEvents(this, dispids, Iid_Clsids.DIID_HTMLElementEvents2); int[] dispids1 = { (int)HTMLEventDispIds.ID_ONUNLOAD }; m_winEvents.InitHTMLEvents(this, dispids1, Iid_Clsids.DIID_HTMLWindowEvents2); m_timer.Enabled = false; m_timer.Interval = 150; m_timer.Tick += new EventHandler(m_timer_Tick); this.FormClosing += new FormClosingEventHandler(frmHTMLDialogHandler_FormClosing); } void frmHTMLDialogHandler_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { m_CBT.IsHooked = false; m_csexwbCOMLib.SetupWindowsHook( CSEXWBDLMANLib.WINDOWSHOOK_TYPES.WHT_CBT, (int)this.Handle.ToInt32(), m_CBT.IsHooked, ref m_CBT.UniqueMsgID); m_Dialog = IntPtr.Zero; m_IsEventsConnected = false; if (m_elemEvents.m_IsCOnnected) m_elemEvents.DisconnectHtmlEvents(); if (m_winEvents.m_IsCOnnected) m_winEvents.DisconnectHtmlEvents(); this.Hide(); } } protected override void WndProc(ref Message m) { if (m.Msg == m_CBT.UniqueMsgID) { m_csexwbCOMLib.HookProcNCode(CSEXWBDLMANLib.WINDOWSHOOK_TYPES.WHT_CBT, ref m_NCode); if (m_NCode == WindowsHookUtil.HCBT_CREATEWND) { m_strTemp = WinApis.GetWindowClass(m.WParam); //Marshal.PtrToStringAnsi(m_CREATESTRUCT.lpszClass); if (!string.IsNullOrEmpty(m_strTemp)) { if ((m_strTemp.Equals(m_HTMLDlgClassName, StringComparison.CurrentCultureIgnoreCase)) && (m_Dialog == IntPtr.Zero)) { m_Dialog = m.WParam; //got it } } } else if (m_NCode == WindowsHookUtil.HCBT_ACTIVATE) { //Already have this window? if ((m_Dialog != IntPtr.Zero) && (m_IsEventsConnected == false) && (m_Dialog == m.WParam)) { //m.WParam contains handle to the new window m_IsEventsConnected = true; m_timer.Start(); } } } else base.WndProc(ref m); } #endregion void m_timer_Tick(object sender, EventArgs e) { m_timer.Stop(); this.richTextBox1.Clear(); //Enum child windows winenum.enumerate(m_Dialog); //Get the control names m_Ctls = winenum.GetControlsClassNames(); m_Count = m_Ctls.Count; this.richTextBox1.AppendText("HTMLDialog total child windows count =" + m_Count.ToString() + "\r\n"); for (m_Counter = 0; m_Counter < m_Count; m_Counter++) { this.richTextBox1.AppendText(m_Ctls[m_Counter].ToString() + "\r\n"); //Find IE_Server if ((m_Ctls[m_Counter] != null) && (m_Ctls[m_Counter].ToString().Equals("Internet Explorer_Server", StringComparison.CurrentCultureIgnoreCase)) ) { //subscribe to documentelement events //so we can handle key + unload events m_IE = (IntPtr)Int32.Parse(winenum.GetControlsHwnds()[m_Counter].ToString()); this.richTextBox1.AppendText("Internet Explorer_Server HWND =" + m_IE.ToString() + "\r\n"); if (m_IE != IntPtr.Zero) { m_pDoc2 = winenum.GetIEHTMLDocument2FromWindowHandle(m_IE); IHTMLDocument3 doc3 = m_pDoc2 as IHTMLDocument3; if (doc3 != null) { if(m_elemEvents.ConnectToHtmlEvents(doc3.documentElement)) this.richTextBox1.AppendText("Subscribed to Document events = OK\r\n"); else this.richTextBox1.AppendText("Subscribed to Document events = FAILED\r\n"); } if (m_pDoc2 != null) { m_pWin2 = m_pDoc2.parentWindow as IHTMLWindow2; if (m_pWin2 != null) { if (m_winEvents.ConnectToHtmlEvents(m_pWin2)) this.richTextBox1.AppendText("Subscribed to Window events = OK\r\n"); else this.richTextBox1.AppendText("Subscribed to Window events = FAILED\r\n"); } } } break; } } winenum.clear(); } public void StartHandling() { m_CBT.IsHooked = true; m_csexwbCOMLib.SetupWindowsHook( CSEXWBDLMANLib.WINDOWSHOOK_TYPES.WHT_CBT, (int)this.Handle.ToInt32(), m_CBT.IsHooked, ref m_CBT.UniqueMsgID); } #region IHTMLEventCallBack Members bool IHTMLEventCallBack.HandleHTMLEvent(HTMLEventType EventType, HTMLEventDispIds EventDispId, IHTMLEventObj pEvtObj) { bool bret = true; //always allow bubbling of events try { if ((EventType == HTMLEventType.HTMLWindowEvent) && (EventDispId == HTMLEventDispIds.ID_ONUNLOAD)) { m_elemEvents.DisconnectHtmlEvents(); m_winEvents.DisconnectHtmlEvents(); this.richTextBox1.AppendText("\r\nWindow Closed!"); } else if (EventType == HTMLEventType.HTMLElementEvent) { if ((EventDispId == HTMLEventDispIds.ID_ONCLICK) || (EventDispId == HTMLEventDispIds.ID_ONKEYUP)) { if ((pEvtObj != null) && (pEvtObj.SrcElement != null)) this.richTextBox1.AppendText("\r\nHTML_Document_Event==>tagName =" + pEvtObj.SrcElement.tagName); } } } catch (Exception ee) { this.richTextBox1.AppendText("frmHTMLDialogHandler_HandleHTMLEvent\r\n" + ee.ToString()); } return bret; } #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; #if CCINamespace namespace Microsoft.Cci{ #else namespace System.Compiler{ #endif public enum OpCode{ Nop = 0x00, Break = 0x01, Ldarg_0 = 0x02, Ldarg_1 = 0x03, Ldarg_2 = 0x04, Ldarg_3 = 0x05, Ldloc_0 = 0x06, Ldloc_1 = 0x07, Ldloc_2 = 0x08, Ldloc_3 = 0x09, Stloc_0 = 0x0a, Stloc_1 = 0x0b, Stloc_2 = 0x0c, Stloc_3 = 0x0d, Ldarg_S = 0x0e, Ldarga_S = 0x0f, Starg_S = 0x10, Ldloc_S = 0x11, Ldloca_S = 0x12, Stloc_S = 0x13, Ldnull = 0x14, Ldc_I4_M1 = 0x15, Ldc_I4_0 = 0x16, Ldc_I4_1 = 0x17, Ldc_I4_2 = 0x18, Ldc_I4_3 = 0x19, Ldc_I4_4 = 0x1a, Ldc_I4_5 = 0x1b, Ldc_I4_6 = 0x1c, Ldc_I4_7 = 0x1d, Ldc_I4_8 = 0x1e, Ldc_I4_S = 0x1f, Ldc_I4 = 0x20, Ldc_I8 = 0x21, Ldc_R4 = 0x22, Ldc_R8 = 0x23, Dup = 0x25, Pop = 0x26, Jmp = 0x27, Call = 0x28, Calli = 0x29, Ret = 0x2a, Br_S = 0x2b, Brfalse_S = 0x2c, Brtrue_S = 0x2d, Beq_S = 0x2e, Bge_S = 0x2f, Bgt_S = 0x30, Ble_S = 0x31, Blt_S = 0x32, Bne_Un_S = 0x33, Bge_Un_S = 0x34, Bgt_Un_S = 0x35, Ble_Un_S = 0x36, Blt_Un_S = 0x37, Br = 0x38, Brfalse = 0x39, Brtrue = 0x3a, Beq = 0x3b, Bge = 0x3c, Bgt = 0x3d, Ble = 0x3e, Blt = 0x3f, Bne_Un = 0x40, Bge_Un = 0x41, Bgt_Un = 0x42, Ble_Un = 0x43, Blt_Un = 0x44, @Switch = 0x45, Ldind_I1 = 0x46, Ldind_U1 = 0x47, Ldind_I2 = 0x48, Ldind_U2 = 0x49, Ldind_I4 = 0x4a, Ldind_U4 = 0x4b, Ldind_I8 = 0x4c, Ldind_I = 0x4d, Ldind_R4 = 0x4e, Ldind_R8 = 0x4f, Ldind_Ref = 0x50, Stind_Ref = 0x51, Stind_I1 = 0x52, Stind_I2 = 0x53, Stind_I4 = 0x54, Stind_I8 = 0x55, Stind_R4 = 0x56, Stind_R8 = 0x57, Add = 0x58, Sub = 0x59, Mul = 0x5a, Div = 0x5b, Div_Un = 0x5c, Rem = 0x5d, Rem_Un = 0x5e, And = 0x5f, Or = 0x60, Xor = 0x61, Shl = 0x62, Shr = 0x63, Shr_Un = 0x64, Neg = 0x65, Not = 0x66, Conv_I1 = 0x67, Conv_I2 = 0x68, Conv_I4 = 0x69, Conv_I8 = 0x6a, Conv_R4 = 0x6b, Conv_R8 = 0x6c, Conv_U4 = 0x6d, Conv_U8 = 0x6e, Callvirt = 0x6f, Cpobj = 0x70, Ldobj = 0x71, Ldstr = 0x72, Newobj = 0x73, Castclass = 0x74, Isinst = 0x75, Conv_R_Un = 0x76, Unbox = 0x79, Throw = 0x7a, Ldfld = 0x7b, Ldflda = 0x7c, Stfld = 0x7d, Ldsfld = 0x7e, Ldsflda = 0x7f, Stsfld = 0x80, Stobj = 0x81, Conv_Ovf_I1_Un = 0x82, Conv_Ovf_I2_Un = 0x83, Conv_Ovf_I4_Un = 0x84, Conv_Ovf_I8_Un = 0x85, Conv_Ovf_U1_Un = 0x86, Conv_Ovf_U2_Un = 0x87, Conv_Ovf_U4_Un = 0x88, Conv_Ovf_U8_Un = 0x89, Conv_Ovf_I_Un = 0x8a, Conv_Ovf_U_Un = 0x8b, Box = 0x8c, Newarr = 0x8d, Ldlen = 0x8e, Ldelema = 0x8f, Ldelem_I1 = 0x90, Ldelem_U1 = 0x91, Ldelem_I2 = 0x92, Ldelem_U2 = 0x93, Ldelem_I4 = 0x94, Ldelem_U4 = 0x95, Ldelem_I8 = 0x96, Ldelem_I = 0x97, Ldelem_R4 = 0x98, Ldelem_R8 = 0x99, Ldelem_Ref = 0x9a, Stelem_I = 0x9b, Stelem_I1 = 0x9c, Stelem_I2 = 0x9d, Stelem_I4 = 0x9e, Stelem_I8 = 0x9f, Stelem_R4 = 0xa0, Stelem_R8 = 0xa1, Stelem_Ref = 0xa2, Ldelem = 0xa3, Stelem = 0xa4, Unbox_Any = 0xa5, Conv_Ovf_I1 = 0xb3, Conv_Ovf_U1 = 0xb4, Conv_Ovf_I2 = 0xb5, Conv_Ovf_U2 = 0xb6, Conv_Ovf_I4 = 0xb7, Conv_Ovf_U4 = 0xb8, Conv_Ovf_I8 = 0xb9, Conv_Ovf_U8 = 0xba, Refanyval = 0xc2, Ckfinite = 0xc3, Mkrefany = 0xc6, Ldtoken = 0xd0, Conv_U2 = 0xd1, Conv_U1 = 0xd2, Conv_I = 0xd3, Conv_Ovf_I = 0xd4, Conv_Ovf_U = 0xd5, Add_Ovf = 0xd6, Add_Ovf_Un = 0xd7, Mul_Ovf = 0xd8, Mul_Ovf_Un = 0xd9, Sub_Ovf = 0xda, Sub_Ovf_Un = 0xdb, Endfinally = 0xdc, Leave = 0xdd, Leave_S = 0xde, Stind_I = 0xdf, Conv_U = 0xe0, Prefix7 = 0xf8, Prefix6 = 0xf9, Prefix5 = 0xfa, Prefix4 = 0xfb, Prefix3 = 0xfc, Prefix2 = 0xfd, Prefix1 = 0xfe, PrefixRef = 0xff, Arglist = 0xfe00, Ceq = 0xfe01, Cgt = 0xfe02, Cgt_Un = 0xfe03, Clt = 0xfe04, Clt_Un = 0xfe05, Ldftn = 0xfe06, Ldvirtftn = 0xfe07, Ldarg = 0xfe09, Ldarga = 0xfe0a, Starg = 0xfe0b, Ldloc = 0xfe0c, Ldloca = 0xfe0d, Stloc = 0xfe0e, Localloc = 0xfe0f, Endfilter = 0xfe11, Unaligned_ = 0xfe12, Volatile_ = 0xfe13, Tail_ = 0xfe14, Initobj = 0xfe15, Constrained_ = 0xfe16, Cpblk = 0xfe17, Initblk = 0xfe18, Rethrow = 0xfe1a, Sizeof = 0xfe1c, Refanytype = 0xfe1d, Readonly_ = 0xfe1e, // fake opcodes #if WHIDBEY [CLSCompliant(false)] #endif _Locals = 0xfef7, #if WHIDBEY [CLSCompliant(false)] #endif _Try = 0xfef8, #if WHIDBEY [CLSCompliant(false)] #endif _EndTry = 0xfef9, #if WHIDBEY [CLSCompliant(false)] #endif _Filter = 0xfefa, #if WHIDBEY [CLSCompliant(false)] #endif _EndFilter = 0xfefb, #if WHIDBEY [CLSCompliant(false)] #endif _Catch = 0xfefc, #if WHIDBEY [CLSCompliant(false)] #endif _Finally = 0xfefd, #if WHIDBEY [CLSCompliant(false)] #endif _Fault = 0xfefe, #if WHIDBEY [CLSCompliant(false)] #endif _EndHandler = 0xfeff } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal { public partial class IPAddressesAddIPAddress { /// <summary> /// messageBox control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.SimpleMessageBox messageBox; /// <summary> /// validatorsSummary control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ValidationSummary validatorsSummary; /// <summary> /// consistent Addresses control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.CustomValidator consistentAddresses; /// <summary> /// locPool control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locPool; /// <summary> /// ddlPools control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlPools; /// <summary> /// locServer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locServer; /// <summary> /// ddlServer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlServer; /// <summary> /// lblExternalIP control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize lblExternalIP; /// <summary> /// startIP control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EditIPAddressControl startIP; /// <summary> /// locTo control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locTo; /// <summary> /// endIP control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EditIPAddressControl endIP; /// <summary> /// InternalAddressRow control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow InternalAddressRow; /// <summary> /// lblInternalIP control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize lblInternalIP; /// <summary> /// internalIP control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EditIPAddressControl internalIP; /// <summary> /// SubnetRow control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow SubnetRow; /// <summary> /// locSubnetMask control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locSubnetMask; /// <summary> /// subnetMask control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EditIPAddressControl subnetMask; /// <summary> /// GatewayRow control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow GatewayRow; /// <summary> /// locDefaultGateway control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize locDefaultGateway; /// <summary> /// defaultGateway control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.UserControls.EditIPAddressControl defaultGateway; /// <summary> /// lblComments control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Localize lblComments; /// <summary> /// txtComments control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtComments; /// <summary> /// btnAdd control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnAdd; /// <summary> /// btnCancel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnCancel; } }
// ====================================== // Author: Ebenezer Monney // Email: info@ebenmonney.com // Copyright (c) 2017 www.ebenmonney.com // ====================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.SpaServices.Webpack; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json.Serialization; using DAL; using DAL.Models; using System.Net; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using FluentValidation.AspNetCore; using AutoMapper; using Newtonsoft.Json; using DAL.Core; using DAL.Core.Interfaces; using Microsoft.AspNetCore.Authorization; using medicme.ViewModels; using medicme.Helpers; using medicme.Policies; using AppPermissions = DAL.Core.ApplicationPermissions; namespace medicme { public class Startup { public IConfigurationRoot Configuration { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => { options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"], b => b.MigrationsAssembly("medicme")); options.UseOpenIddict(); }); // add identity services.AddIdentity<ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Configure Identity options and password complexity here services.Configure<IdentityOptions>(options => { // User settings options.User.RequireUniqueEmail = true; // //// Password settings // //options.Password.RequireDigit = true; // //options.Password.RequiredLength = 8; // //options.Password.RequireNonAlphanumeric = false; // //options.Password.RequireUppercase = true; // //options.Password.RequireLowercase = false; // //// Lockout settings // //options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30); // //options.Lockout.MaxFailedAccessAttempts = 10; }); // add OpenIddict services.AddOpenIddict() .AddEntityFrameworkCoreStores<ApplicationDbContext>() .AddMvcBinders() .DisableHttpsRequirement() .EnableTokenEndpoint("/connect/token") .AllowPasswordFlow() .AllowRefreshTokenFlow() //.UseJsonWebTokens() //Use JWT if preferred .AddSigningKey(new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration["STSKey"]))); // Enable cors if required //services.AddCors(); // Add framework services. services.AddMvc(); //Todo: ***Using DataAnnotations for validation until Swashbuckle supports FluentValidation*** //services.AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>()); //.AddJsonOptions(opts => //{ // opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //}); services.AddSwaggerGen(o => { o.AddSecurityDefinition("BearerAuth", new Swashbuckle.Swagger.Model.ApiKeyScheme { Name = "Authorization", Description = "Login with your bearer authentication token. e.g. Bearer <auth-token>", In = "header", Type = "apiKey" }); }); services.AddAuthorization(options => { options.AddPolicy(AuthPolicies.ViewUserByUserIdPolicy, policy => policy.Requirements.Add(new ViewUserByIdRequirement())); options.AddPolicy(AuthPolicies.ViewUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewUsers)); options.AddPolicy(AuthPolicies.ManageUserByUserIdPolicy, policy => policy.Requirements.Add(new ManageUserByIdRequirement())); options.AddPolicy(AuthPolicies.ManageUsersPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageUsers)); options.AddPolicy(AuthPolicies.ViewRoleByRoleNamePolicy, policy => policy.Requirements.Add(new ViewRoleByNameRequirement())); options.AddPolicy(AuthPolicies.ViewRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ViewRoles)); options.AddPolicy(AuthPolicies.AssignRolesPolicy, policy => policy.Requirements.Add(new AssignRolesRequirement())); options.AddPolicy(AuthPolicies.ManageRolesPolicy, policy => policy.RequireClaim(CustomClaimTypes.Permission, AppPermissions.ManageRoles)); }); Mapper.Initialize(cfg => { cfg.AddProfile<AutoMapperProfile>(); }); // Repositories services.AddScoped<IUnitOfWork, UnitOfWork>(); services.AddScoped<IAccountManager, AccountManager>(); // Auth Policies services.AddSingleton<IAuthorizationHandler, ViewUserByIdHandler>(); services.AddSingleton<IAuthorizationHandler, ManageUserByIdHandler>(); services.AddSingleton<IAuthorizationHandler, ViewRoleByNameHandler>(); services.AddSingleton<IAuthorizationHandler, AssignRolesHandler>(); // DB Creation and Seeding services.AddTransient<IDatabaseInitializer, DatabaseInitializer>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IDatabaseInitializer databaseInitializer, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(LogLevel.Warning); loggerFactory.AddFile(Configuration.GetSection("Logging")); Utilities.ConfigureLogger(loggerFactory); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true }); } else { app.UseExceptionHandler("/Home/Error"); } // Configure Cors if enabled //app.UseCors(builder => builder // .AllowAnyOrigin() // .AllowAnyHeader() // .AllowAnyMethod()); app.UseStaticFiles(); app.UseOAuthValidation(); app.UseOpenIddict(); // Configure jwt bearer authentication if enabled //app.UseJwtBearerAuthentication(new JwtBearerOptions //{ // AutomaticAuthenticate = true, // AutomaticChallenge = true, // RequireHttpsMetadata = false, // Audience = "http://localhost:58292/", // Authority = "http://localhost:58292/", // //TokenValidationParameters = new TokenValidationParameters // //{ // // ValidateIssuer = true, // // ValidIssuer = "http://localhost:58292/", // // ValidateAudience = true, // // ValidAudience = "http://localhost:58292/", // // ValidateLifetime = true, // //} //}); app.UseExceptionHandler(builder => { builder.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = MediaTypeNames.ApplicationJson; var error = context.Features.Get<IExceptionHandlerFeature>(); if (error != null) { string errorMsg = JsonConvert.SerializeObject(new { error = error.Error.Message }); await context.Response.WriteAsync(errorMsg).ConfigureAwait(false); } }); }); app.UseSwagger(); app.UseSwaggerUi(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); try { databaseInitializer.Seed().Wait(); } catch (Exception ex) { Utilities.CreateLogger<Startup>().LogCritical(LoggingEvents.INIT_DATABASE, ex, LoggingEvents.INIT_DATABASE.Name); throw; } } } }
// <copyright file="Permutation.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2010 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> namespace MathNet.Numerics { using System; using Properties; /// <summary> /// Class to represent a permutation for a subset of the natural numbers. /// </summary> [Serializable] public class Permutation { #region fields /// <summary> /// Entry _indices[i] represents the location to which i is permuted to. /// </summary> private readonly int[] _indices; #endregion fields #region Constructor /// <summary> /// Initializes a new instance of the Permutation class. /// </summary> /// <param name="indices">An array which represents where each integer is permuted too: indices[i] represents that integer i /// is permuted to location indices[i].</param> public Permutation(int[] indices) { if (!CheckForProperPermutation(indices)) { throw new ArgumentException(Resources.PermutationAsIntArrayInvalid, "indices"); } _indices = (int[])indices.Clone(); } #endregion /// <summary> /// Gets the number of elements this permutation is over. /// </summary> public int Dimension { get { return _indices.Length; } } /// <summary> /// Computes where <paramref name="idx"/> permutes too. /// </summary> /// <param name="idx">The index to permute from.</param> /// <returns>The index which is permuted to.</returns> public int this[int idx] { get { return _indices[idx]; } } /// <summary> /// Computes the inverse of the permutation. /// </summary> /// <returns>The inverse of the permutation.</returns> public Permutation Inverse() { var invIdx = new int[Dimension]; for (int i = 0; i < invIdx.Length; i++) { invIdx[_indices[i]] = i; } return new Permutation(invIdx); } /// <summary> /// Construct an array from a sequence of inversions. /// </summary> /// <example> /// From wikipedia: the permutation 12043 has the inversions (0,2), (1,2) and (3,4). This would be /// encoded using the array [22244]. /// </example> /// <param name="inv">The set of inversions to construct the permutation from.</param> /// <returns>A permutation generated from a sequence of inversions.</returns> public static Permutation FromInversions(int[] inv) { var idx = new int[inv.Length]; for (int i = 0; i < inv.Length; i++) { idx[i] = i; } for (int i = inv.Length - 1; i >= 0; i--) { if (idx[i] != inv[i]) { int t = idx[i]; idx[i] = idx[inv[i]]; idx[inv[i]] = t; } } return new Permutation(idx); } /// <summary> /// Construct a sequence of inversions from the permutation. /// </summary> /// <example> /// From wikipedia: the permutation 12043 has the inversions (0,2), (1,2) and (3,4). This would be /// encoded using the array [22244]. /// </example> /// <returns>A sequence of inversions.</returns> public int[] ToInversions() { var idx = (int[])_indices.Clone(); for (int i = 0; i < idx.Length; i++) { if (idx[i] != i) { #if !PORTABLE int q = Array.FindIndex(idx, i + 1, x => x == i); #else int q = -1; for(int j = i+1; j < Dimension; j++) { if(idx[j] == i) { q = j; break; } } #endif var t = idx[i]; idx[i] = q; idx[q] = t; } } return idx; } /// <summary> /// Checks whether the <paramref name="indices"/> array represents a proper permutation. /// </summary> /// <param name="indices">An array which represents where each integer is permuted too: indices[i] represents that integer i /// is permuted to location indices[i].</param> /// <returns>True if <paramref name="indices"/> represents a proper permutation, <c>false</c> otherwise.</returns> static bool CheckForProperPermutation(int[] indices) { var idxCheck = new bool[indices.Length]; for (int i = 0; i < indices.Length; i++) { if (indices[i] >= indices.Length || indices[i] < 0) { return false; } idxCheck[indices[i]] = true; } for (int i = 0; i < indices.Length; i++) { if (idxCheck[i] == false) { return false; } } return true; } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using Orleans; using Orleans.Runtime; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; namespace DefaultCluster.Tests.General { public class EchoTaskGrainTests : HostedTestClusterEnsureDefaultStarted { private readonly TimeSpan timeout = Debugger.IsAttached ? TimeSpan.FromMinutes(10) : TimeSpan.FromSeconds(10); const string expectedEcho = "Hello from EchoGrain"; const string expectedEchoError = "Error from EchoGrain"; private IEchoTaskGrain grain; public static readonly TimeSpan Epsilon = TimeSpan.FromSeconds(1); public EchoTaskGrainTests(DefaultClusterFixture fixture) : base(fixture) { if (HostedCluster.SecondarySilos.Count == 0) { HostedCluster.StartAdditionalSilo(); HostedCluster.WaitForLivenessToStabilizeAsync().Wait(); } } [Fact, TestCategory("BVT"), TestCategory("Echo")] public void EchoGrain_GetGrain() { grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_Echo() { Stopwatch clock = new Stopwatch(); clock.Start(); grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); this.Logger.Info("CreateGrain took " + clock.Elapsed); clock.Restart(); string received = await grain.EchoAsync(expectedEcho); this.Logger.Info("EchoGrain.Echo took " + clock.Elapsed); Assert.Equal(expectedEcho, received); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_EchoError() { grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); Task<string> promise = grain.EchoErrorAsync(expectedEchoError); await promise.ContinueWith(t => { if (!t.IsFaulted) Assert.True(false); // EchoError should not have completed successfully Exception exc = t.Exception; while (exc is AggregateException) exc = exc.InnerException; string received = exc.Message; Assert.Equal(expectedEchoError, received); }).WithTimeout(timeout); } [Fact, TestCategory("SlowBVT"), TestCategory("Echo"), TestCategory("Timeout")] public async Task EchoGrain_Timeout_Wait() { grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); TimeSpan delay30 = TimeSpan.FromSeconds(30); // grain call timeout (set in config) TimeSpan delay45 = TimeSpan.FromSeconds(45); TimeSpan delay60 = TimeSpan.FromSeconds(60); Stopwatch sw = new Stopwatch(); sw.Start(); Task<int> promise = grain.BlockingCallTimeoutAsync(delay60); await promise.ContinueWith( t => { if (!t.IsFaulted) Assert.True(false); // BlockingCallTimeout should not have completed successfully Exception exc = t.Exception; while (exc is AggregateException) exc = exc.InnerException; Assert.IsAssignableFrom<TimeoutException>(exc); }).WithTimeout(delay45); sw.Stop(); Assert.True(TimeIsLonger(sw.Elapsed, delay30), $"Elapsed time out of range: {sw.Elapsed}"); Assert.True(TimeIsShorter(sw.Elapsed, delay60), $"Elapsed time out of range: {sw.Elapsed}"); } [Fact, TestCategory("SlowBVT"), TestCategory("Echo")] public async Task EchoGrain_Timeout_Await() { grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); TimeSpan delay30 = TimeSpan.FromSeconds(30); TimeSpan delay60 = TimeSpan.FromSeconds(60); Stopwatch sw = new Stopwatch(); sw.Start(); try { int res = await grain.BlockingCallTimeoutAsync(delay60); Assert.True(false); // BlockingCallTimeout should not have completed successfully } catch (Exception exc) { while (exc is AggregateException) exc = exc.InnerException; Assert.IsAssignableFrom<TimeoutException>(exc); } sw.Stop(); Assert.True(TimeIsLonger(sw.Elapsed, delay30), $"Elapsed time out of range: {sw.Elapsed}"); Assert.True(TimeIsShorter(sw.Elapsed, delay60), $"Elapsed time out of range: {sw.Elapsed}"); } [Fact, TestCategory("SlowBVT"), TestCategory("Echo"), TestCategory("Timeout")] public async Task EchoGrain_Timeout_Result() { grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); TimeSpan delay30 = TimeSpan.FromSeconds(30); TimeSpan delay60 = TimeSpan.FromSeconds(60); Stopwatch sw = new Stopwatch(); sw.Start(); try { int res = await grain.BlockingCallTimeoutAsync(delay60); Assert.True(false, "BlockingCallTimeout should not have completed successfully, but returned " + res); } catch (Exception exc) { while (exc is AggregateException) exc = exc.InnerException; Assert.IsAssignableFrom<TimeoutException>(exc); } sw.Stop(); Assert.True(TimeIsLonger(sw.Elapsed, delay30), $"Elapsed time out of range: {sw.Elapsed}"); Assert.True(TimeIsShorter(sw.Elapsed, delay60), $"Elapsed time out of range: {sw.Elapsed}"); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_LastEcho() { Stopwatch clock = new Stopwatch(); await EchoGrain_Echo(); clock.Start(); string received = await grain.GetLastEchoAsync(); this.Logger.Info("EchoGrain.LastEcho took " + clock.Elapsed); Assert.Equal(expectedEcho, received); // LastEcho-Echo await EchoGrain_EchoError(); clock.Restart(); received = await grain.GetLastEchoAsync(); this.Logger.Info("EchoGrain.LastEcho-Error took " + clock.Elapsed); Assert.Equal(expectedEchoError, received); // LastEcho-Error } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_Ping() { Stopwatch clock = new Stopwatch(); string what = "CreateGrain"; clock.Start(); grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); this.Logger.Info("{0} took {1}", what, clock.Elapsed); what = "EchoGrain.Ping"; clock.Restart(); await grain.PingAsync().WithTimeout(timeout); this.Logger.Info("{0} took {1}", what, clock.Elapsed); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_PingSilo_Local() { Stopwatch clock = new Stopwatch(); string what = "CreateGrain"; clock.Start(); grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); this.Logger.Info("{0} took {1}", what, clock.Elapsed); what = "EchoGrain.PingLocalSilo"; clock.Restart(); await grain.PingLocalSiloAsync().WithTimeout(timeout); this.Logger.Info("{0} took {1}", what, clock.Elapsed); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_PingSilo_Remote() { Stopwatch clock = new Stopwatch(); string what = "CreateGrain"; clock.Start(); grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); this.Logger.Info("{0} took {1}", what, clock.Elapsed); SiloAddress silo1 = HostedCluster.Primary.SiloAddress; SiloAddress silo2 = HostedCluster.SecondarySilos[0].SiloAddress; what = "EchoGrain.PingRemoteSilo[1]"; clock.Restart(); await grain.PingRemoteSiloAsync(silo1).WithTimeout(timeout); this.Logger.Info("{0} took {1}", what, clock.Elapsed); what = "EchoGrain.PingRemoteSilo[2]"; clock.Restart(); await grain.PingRemoteSiloAsync(silo2).WithTimeout(timeout); this.Logger.Info("{0} took {1}", what, clock.Elapsed); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_PingSilo_OtherSilo() { Stopwatch clock = new Stopwatch(); string what = "CreateGrain"; clock.Start(); grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); this.Logger.Info("{0} took {1}", what, clock.Elapsed); what = "EchoGrain.PingOtherSilo"; clock.Restart(); await grain.PingOtherSiloAsync().WithTimeout(timeout); this.Logger.Info("{0} took {1}", what, clock.Elapsed); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_PingSilo_OtherSilo_Membership() { Stopwatch clock = new Stopwatch(); string what = "CreateGrain"; clock.Start(); grain = this.GrainFactory.GetGrain<IEchoTaskGrain>(Guid.NewGuid()); this.Logger.Info("{0} took {1}", what, clock.Elapsed); what = "EchoGrain.PingOtherSiloMembership"; clock.Restart(); await grain.PingClusterMemberAsync().WithTimeout(timeout); this.Logger.Info("{0} took {1}", what, clock.Elapsed); } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoTaskGrain_Await() { IBlockingEchoTaskGrain g = this.GrainFactory.GetGrain<IBlockingEchoTaskGrain>(GetRandomGrainId()); string received = await g.Echo(expectedEcho); Assert.Equal(expectedEcho, received); // Echo received = await g.CallMethodAV_Await(expectedEcho); Assert.Equal(expectedEcho, received); // CallMethodAV_Await received = await g.CallMethodTask_Await(expectedEcho); Assert.Equal(expectedEcho, received); // CallMethodTask_Await } [Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Echo")] public async Task EchoTaskGrain_Await_Reentrant() { IReentrantBlockingEchoTaskGrain g = this.GrainFactory.GetGrain<IReentrantBlockingEchoTaskGrain>(GetRandomGrainId()); string received = await g.Echo(expectedEcho); Assert.Equal(expectedEcho, received); // Echo received = await g.CallMethodAV_Await(expectedEcho); Assert.Equal(expectedEcho, received); // CallMethodAV_Await received = await g.CallMethodTask_Await(expectedEcho); Assert.Equal(expectedEcho, received); // CallMethodTask_Await } [Fact, TestCategory("BVT"), TestCategory("Echo")] public async Task EchoGrain_EchoNullable() { Stopwatch clock = new Stopwatch(); clock.Start(); var grain = this.GrainFactory.GetGrain<IEchoGrain>(Guid.NewGuid()); this.Logger.Info("CreateGrain took " + clock.Elapsed); clock.Restart(); var now = DateTime.Now; var received = await grain.EchoNullable(now); this.Logger.Info("EchoGrain.EchoNullable took " + clock.Elapsed); Assert.Equal(now, received); clock.Restart(); received = await grain.EchoNullable(null); this.Logger.Info("EchoGrain.EchoNullable took " + clock.Elapsed); Assert.Null(received); } // ---------- Utility methods ---------- private bool TimeIsLonger(TimeSpan time, TimeSpan limit) { this.Logger.Info("Compare TimeIsLonger: Actual={0} Limit={1} Epsilon={2}", time, limit, Epsilon); return time >= (limit - Epsilon); } private bool TimeIsShorter(TimeSpan time, TimeSpan limit) { this.Logger.Info("Compare TimeIsShorter: Actual={0} Limit={1} Epsilon={2}", time, limit, Epsilon); return time <= (limit + Epsilon); } } }
using GameTimer; using InputHelper; using Microsoft.Xna.Framework; using System; using System.Threading.Tasks; namespace MenuBuddy { /// <summary> /// A widget is a screen item that can be displayed /// </summary> public abstract class Widget : IWidget, IDisposable { #region Fields private HorizontalAlignment _horizontal; private VerticalAlignment _vertical; private bool _drawWhenInactive = true; protected Rectangle _rect; private Point _position; private float _scale; public event EventHandler<HighlightEventArgs> OnHighlight; /// <summary> /// whether or not this dude is highlighted /// </summary> private bool _highlight = false; #endregion //Fields #region Properties public string Name { get; set; } = "Widget"; public GameClock HighlightClock { get; protected set; } public virtual bool IsHighlighted { get { return _highlight; } set { var prev = _highlight; _highlight = value; if (!prev && _highlight) { HighlightClock.Start(); } } } /// <summary> /// The area of this item /// </summary> public virtual Rectangle Rect { get { return _rect; } } /// <summary> /// set the position of the item /// </summary> public virtual Point Position { get { return _position; } set { if (_position != value) { _position = value; CalculateRect(); } } } public virtual HorizontalAlignment Horizontal { get { return _horizontal; } set { if (_horizontal != value) { _horizontal = value; CalculateRect(); } } } public virtual VerticalAlignment Vertical { get { return _vertical; } set { if (_vertical != value) { _vertical = value; CalculateRect(); } } } public virtual bool DrawWhenInactive { get { return _drawWhenInactive; } set { _drawWhenInactive = value; } } /// <summary> /// Where to layer the item. /// low numbers go in the back, higher numbers in the front /// </summary> public float Layer { get; set; } public virtual float Scale { get { return _scale; } set { if (_scale != value) { _scale = value; CalculateRect(); } } } public bool HasBackground { get; set; } public bool HasOutline { get; set; } public virtual ITransitionObject TransitionObject { get; set; } public bool Highlightable { get; set; } protected Background Background { get; set; } private bool _prevTapHeld; public bool WasTapped { get; private set; } public bool IsTapHeld { get; private set; } public bool IsTappable { get; set; } protected IInputHelper InputHelper { get; set; } public bool IsHidden { get; set; } = false; #endregion //Properties #region Initialization /// <summary> /// constructor! /// </summary> protected Widget() { Highlightable = true; _horizontal = HorizontalAlignment.Left; _vertical = VerticalAlignment.Top; _scale = 1.0f; HighlightClock = new GameClock(); TransitionObject = new WipeTransitionObject(StyleSheet.DefaultTransition); Background = new Background(); IsTappable = false; _prevTapHeld = false; } protected Widget(Widget inst) { _horizontal = inst.Horizontal; _vertical = inst.Vertical; _scale = inst.Scale; _drawWhenInactive = inst.DrawWhenInactive; _rect = new Rectangle(inst.Rect.Location, inst.Rect.Size); _position = new Point(inst.Position.X, inst.Position.Y); Layer = inst.Layer; HighlightClock = new GameClock(inst.HighlightClock); OnHighlight = inst.OnHighlight; HasBackground = inst.HasBackground; HasOutline = inst.HasOutline; TransitionObject = inst.TransitionObject; Background = inst.Background; IsTappable = inst.IsTappable; } /// <summary> /// Get a deep copy of this item /// </summary> /// <returns></returns> public abstract IScreenItem DeepCopy(); #endregion //Initialization #region Methods /// <summary> /// Available load content method for child classes. /// </summary> /// <param name="screen"></param> public virtual async Task LoadContent(IScreen screen) { await Background.LoadContent(screen); InputHelper = screen.ScreenManager.Game.Services.GetService<IInputHelper>(); } public virtual void UnloadContent() { TransitionObject = null; OnHighlight = null; } /// <summary> /// Recalculate the rect of this widget /// </summary> protected abstract void CalculateRect(); public virtual void Update(IScreen screen, GameClock gameTime) { HighlightClock.Update(gameTime); if (IsTappable) { IsTapHeld = InputHelper.Highlights.Exists(x => Rect.Contains(x.Position)); WasTapped = !_prevTapHeld && IsTapHeld; _prevTapHeld = IsTapHeld; } } /// <summary> /// Check if we should draw this widget. /// Widgets can be hidden is the screen is inactive /// </summary> /// <param name="screen"></param> /// <returns></returns> protected bool ShouldDraw(IScreen screen) { //check if we don't want to draw this widget when inactive return (!IsHidden && (DrawWhenInactive || screen.IsActive)); } public virtual void DrawBackground(IScreen screen, GameClock gameTime) { if (!ShouldDraw(screen)) { return; } //darw the background rectangle if in touch mode if (screen.IsActive) { Background.Draw(this, screen); } } public abstract void Draw(IScreen screen, GameClock gameTime); /// <summary> /// Get teh position to draw this widget /// </summary> /// <returns></returns> protected virtual Point DrawPosition(IScreen screen) { //take the transition position into account return TransitionObject.Position(screen, Rect); } public virtual bool CheckHighlight(HighlightEventArgs highlight) { if (Highlightable) { //get the previous value var prev = IsHighlighted; //Check if this dude should be highlighted var currentHighlight = Rect.Contains(highlight.Position); if (!prev && currentHighlight) { //This is a new highlight IsHighlighted = true; //Do we need to run the highlight event? if (null != OnHighlight) { OnHighlight(this, highlight); } } else if (prev && !currentHighlight) { //Check if this thing is still highlighted IsHighlighted = highlight.InputHelper.Highlights.Exists(x => Rect.Contains(x.Position)); } } return IsHighlighted; } public virtual void Dispose() { UnloadContent(); } public override string ToString() { return Name; } #endregion //Methods } }
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using Parse; using Parse.Common.Internal; using Parse.Core.Internal; using Parse.Push.Internal; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Parse { /// <summary> /// Represents this app installed on this device. Use this class to track information you want /// to sample from (i.e. if you update a field on app launch, you can issue a query to see /// the number of devices which were active in the last N hours). /// </summary> [ParseClassName("_Installation")] public partial class ParseInstallation : ParseObject { private static readonly HashSet<string> readOnlyKeys = new HashSet<string> { "deviceType", "deviceUris", "installationId", "timeZone", "localeIdentifier", "parseVersion", "appName", "appIdentifier", "appVersion", "pushType" }; internal static IParseCurrentInstallationController CurrentInstallationController { get { return ParsePushPlugins.Instance.CurrentInstallationController; } } internal static IDeviceInfoController DeviceInfoController { get { return ParsePushPlugins.Instance.DeviceInfoController; } } /// <summary> /// Constructs a new ParseInstallation. Generally, you should not need to construct /// ParseInstallations yourself. Instead use <see cref="CurrentInstallation"/>. /// </summary> public ParseInstallation() : base() { } /// <summary> /// Gets the ParseInstallation representing this app on this device. /// </summary> public static ParseInstallation CurrentInstallation { get { var task = CurrentInstallationController.GetAsync(CancellationToken.None); // TODO (hallucinogen): this will absolutely break on Unity, but how should we resolve this? task.Wait(); return task.Result; } } internal static void ClearInMemoryInstallation() { CurrentInstallationController.ClearFromMemory(); } /// <summary> /// Constructs a <see cref="ParseQuery{ParseInstallation}"/> for ParseInstallations. /// </summary> /// <remarks> /// Only the following types of queries are allowed for installations: /// /// <code> /// query.GetAsync(objectId) /// query.WhereEqualTo(key, value) /// query.WhereMatchesKeyInQuery&lt;TOther&gt;(key, keyInQuery, otherQuery) /// </code> /// /// You can add additional query conditions, but one of the above must appear as a top-level <c>AND</c> /// clause in the query. /// </remarks> public static ParseQuery<ParseInstallation> Query { get { return new ParseQuery<ParseInstallation>(); } } /// <summary> /// A GUID that uniquely names this app installed on this device. /// </summary> [ParseFieldName("installationId")] public Guid InstallationId { get { string installationIdString = GetProperty<string>("InstallationId"); Guid? installationId = null; try { installationId = new Guid(installationIdString); } catch (Exception) { // Do nothing. } return installationId.Value; } internal set { Guid installationId = value; SetProperty<string>(installationId.ToString(), "InstallationId"); } } /// <summary> /// The runtime target of this installation object. /// </summary> [ParseFieldName("deviceType")] public string DeviceType { get { return GetProperty<string>("DeviceType"); } internal set { SetProperty<string>(value, "DeviceType"); } } /// <summary> /// The user-friendly display name of this application. /// </summary> [ParseFieldName("appName")] public string AppName { get { return GetProperty<string>("AppName"); } internal set { SetProperty<string>(value, "AppName"); } } /// <summary> /// A version string consisting of Major.Minor.Build.Revision. /// </summary> [ParseFieldName("appVersion")] public string AppVersion { get { return GetProperty<string>("AppVersion"); } internal set { SetProperty<string>(value, "AppVersion"); } } /// <summary> /// The system-dependent unique identifier of this installation. This identifier should be /// sufficient to distinctly name an app on stores which may allow multiple apps with the /// same display name. /// </summary> [ParseFieldName("appIdentifier")] public string AppIdentifier { get { return GetProperty<string>("AppIdentifier"); } internal set { SetProperty<string>(value, "AppIdentifier"); } } /// <summary> /// The time zone in which this device resides. This string is in the tz database format /// Parse uses for local-time pushes. Due to platform restrictions, the mapping is less /// granular on Windows than it may be on other systems. E.g. The zones /// America/Vancouver America/Dawson America/Whitehorse, America/Tijuana, PST8PDT, and /// America/Los_Angeles are all reported as America/Los_Angeles. /// </summary> [ParseFieldName("timeZone")] public string TimeZone { get { return GetProperty<string>("TimeZone"); } private set { SetProperty<string>(value, "TimeZone"); } } /// <summary> /// The users locale. This field gets automatically populated by the SDK. /// Can be null (Parse Push uses default language in this case). /// </summary> [ParseFieldName("localeIdentifier")] public string LocaleIdentifier { get { return GetProperty<string>("LocaleIdentifier"); } private set { SetProperty<string>(value, "LocaleIdentifier"); } } /// <summary> /// Gets the locale identifier in the format: [language code]-[COUNTRY CODE]. /// </summary> /// <returns>The locale identifier in the format: [language code]-[COUNTRY CODE].</returns> private string GetLocaleIdentifier() { String languageCode = null; String countryCode = null; if (CultureInfo.CurrentCulture != null) { languageCode = CultureInfo.CurrentCulture.TwoLetterISOLanguageName; } if (RegionInfo.CurrentRegion != null) { countryCode = RegionInfo.CurrentRegion.TwoLetterISORegionName; } if (string.IsNullOrEmpty(countryCode)) { return languageCode; } else { return string.Format("{0}-{1}", languageCode, countryCode); } } /// <summary> /// The version of the Parse SDK used to build this application. /// </summary> [ParseFieldName("parseVersion")] public Version ParseVersion { get { var versionString = GetProperty<string>("ParseVersion"); Version version = null; try { version = new Version(versionString); } catch (Exception) { // Do nothing. } return version; } private set { Version version = value; SetProperty<string>(version.ToString(), "ParseVersion"); } } /// <summary> /// A sequence of arbitrary strings which are used to identify this installation for push notifications. /// By convention, the empty string is known as the "Broadcast" channel. /// </summary> [ParseFieldName("channels")] public IList<string> Channels { get { return GetProperty<IList<string>>("Channels"); } set { SetProperty(value, "Channels"); } } protected override bool IsKeyMutable(string key) { return !readOnlyKeys.Contains(key); } protected override Task SaveAsync(Task toAwait, CancellationToken cancellationToken) { Task platformHookTask = null; if (CurrentInstallationController.IsCurrent(this)) { var configuration = ParseClient.CurrentConfiguration; // 'this' is required in order for the extension method to be used. this.SetIfDifferent("deviceType", DeviceInfoController.DeviceType); this.SetIfDifferent("timeZone", DeviceInfoController.DeviceTimeZone); this.SetIfDifferent("localeIdentifier", GetLocaleIdentifier()); this.SetIfDifferent("parseVersion", GetParseVersion().ToString()); this.SetIfDifferent("appVersion", configuration.VersionInfo.BuildVersion ?? DeviceInfoController.AppBuildVersion); this.SetIfDifferent("appIdentifier", DeviceInfoController.AppIdentifier); this.SetIfDifferent("appName", DeviceInfoController.AppName); platformHookTask = DeviceInfoController.ExecuteParseInstallationSaveHookAsync(this); } return platformHookTask.Safe().OnSuccess(_ => { return base.SaveAsync(toAwait, cancellationToken); }).Unwrap().OnSuccess(_ => { if (CurrentInstallationController.IsCurrent(this)) { return Task.FromResult(0); } return CurrentInstallationController.SetAsync(this, cancellationToken); }).Unwrap(); } private Version GetParseVersion() { return new AssemblyName(typeof(ParseInstallation).GetTypeInfo().Assembly.FullName).Version; } /// <summary> /// This mapping of Windows names to a standard everyone else uses is maintained /// by the Unicode consortium, which makes this officially the first helpful /// interaction between Unicode and Microsoft. /// Unfortunately this is a little lossy in that we only store the first mapping in each zone because /// Microsoft does not give us more granular location information. /// Built from http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/zone_tzid.html /// </summary> internal static readonly Dictionary<string, string> TimeZoneNameMap = new Dictionary<string, string>() { {"Dateline Standard Time", "Etc/GMT+12"}, {"UTC-11", "Etc/GMT+11"}, {"Hawaiian Standard Time", "Pacific/Honolulu"}, {"Alaskan Standard Time", "America/Anchorage"}, {"Pacific Standard Time (Mexico)", "America/Santa_Isabel"}, {"Pacific Standard Time", "America/Los_Angeles"}, {"US Mountain Standard Time", "America/Phoenix"}, {"Mountain Standard Time (Mexico)", "America/Chihuahua"}, {"Mountain Standard Time", "America/Denver"}, {"Central America Standard Time", "America/Guatemala"}, {"Central Standard Time", "America/Chicago"}, {"Central Standard Time (Mexico)", "America/Mexico_City"}, {"Canada Central Standard Time", "America/Regina"}, {"SA Pacific Standard Time", "America/Bogota"}, {"Eastern Standard Time", "America/New_York"}, {"US Eastern Standard Time", "America/Indianapolis"}, {"Venezuela Standard Time", "America/Caracas"}, {"Paraguay Standard Time", "America/Asuncion"}, {"Atlantic Standard Time", "America/Halifax"}, {"Central Brazilian Standard Time", "America/Cuiaba"}, {"SA Western Standard Time", "America/La_Paz"}, {"Pacific SA Standard Time", "America/Santiago"}, {"Newfoundland Standard Time", "America/St_Johns"}, {"E. South America Standard Time", "America/Sao_Paulo"}, {"Argentina Standard Time", "America/Buenos_Aires"}, {"SA Eastern Standard Time", "America/Cayenne"}, {"Greenland Standard Time", "America/Godthab"}, {"Montevideo Standard Time", "America/Montevideo"}, {"Bahia Standard Time", "America/Bahia"}, {"UTC-02", "Etc/GMT+2"}, {"Azores Standard Time", "Atlantic/Azores"}, {"Cape Verde Standard Time", "Atlantic/Cape_Verde"}, {"Morocco Standard Time", "Africa/Casablanca"}, {"UTC", "Etc/GMT"}, {"GMT Standard Time", "Europe/London"}, {"Greenwich Standard Time", "Atlantic/Reykjavik"}, {"W. Europe Standard Time", "Europe/Berlin"}, {"Central Europe Standard Time", "Europe/Budapest"}, {"Romance Standard Time", "Europe/Paris"}, {"Central European Standard Time", "Europe/Warsaw"}, {"W. Central Africa Standard Time", "Africa/Lagos"}, {"Namibia Standard Time", "Africa/Windhoek"}, {"GTB Standard Time", "Europe/Bucharest"}, {"Middle East Standard Time", "Asia/Beirut"}, {"Egypt Standard Time", "Africa/Cairo"}, {"Syria Standard Time", "Asia/Damascus"}, {"E. Europe Standard Time", "Asia/Nicosia"}, {"South Africa Standard Time", "Africa/Johannesburg"}, {"FLE Standard Time", "Europe/Kiev"}, {"Turkey Standard Time", "Europe/Istanbul"}, {"Israel Standard Time", "Asia/Jerusalem"}, {"Jordan Standard Time", "Asia/Amman"}, {"Arabic Standard Time", "Asia/Baghdad"}, {"Kaliningrad Standard Time", "Europe/Kaliningrad"}, {"Arab Standard Time", "Asia/Riyadh"}, {"E. Africa Standard Time", "Africa/Nairobi"}, {"Iran Standard Time", "Asia/Tehran"}, {"Arabian Standard Time", "Asia/Dubai"}, {"Azerbaijan Standard Time", "Asia/Baku"}, {"Russian Standard Time", "Europe/Moscow"}, {"Mauritius Standard Time", "Indian/Mauritius"}, {"Georgian Standard Time", "Asia/Tbilisi"}, {"Caucasus Standard Time", "Asia/Yerevan"}, {"Afghanistan Standard Time", "Asia/Kabul"}, {"Pakistan Standard Time", "Asia/Karachi"}, {"West Asia Standard Time", "Asia/Tashkent"}, {"India Standard Time", "Asia/Calcutta"}, {"Sri Lanka Standard Time", "Asia/Colombo"}, {"Nepal Standard Time", "Asia/Katmandu"}, {"Central Asia Standard Time", "Asia/Almaty"}, {"Bangladesh Standard Time", "Asia/Dhaka"}, {"Ekaterinburg Standard Time", "Asia/Yekaterinburg"}, {"Myanmar Standard Time", "Asia/Rangoon"}, {"SE Asia Standard Time", "Asia/Bangkok"}, {"N. Central Asia Standard Time", "Asia/Novosibirsk"}, {"China Standard Time", "Asia/Shanghai"}, {"North Asia Standard Time", "Asia/Krasnoyarsk"}, {"Singapore Standard Time", "Asia/Singapore"}, {"W. Australia Standard Time", "Australia/Perth"}, {"Taipei Standard Time", "Asia/Taipei"}, {"Ulaanbaatar Standard Time", "Asia/Ulaanbaatar"}, {"North Asia East Standard Time", "Asia/Irkutsk"}, {"Tokyo Standard Time", "Asia/Tokyo"}, {"Korea Standard Time", "Asia/Seoul"}, {"Cen. Australia Standard Time", "Australia/Adelaide"}, {"AUS Central Standard Time", "Australia/Darwin"}, {"E. Australia Standard Time", "Australia/Brisbane"}, {"AUS Eastern Standard Time", "Australia/Sydney"}, {"West Pacific Standard Time", "Pacific/Port_Moresby"}, {"Tasmania Standard Time", "Australia/Hobart"}, {"Yakutsk Standard Time", "Asia/Yakutsk"}, {"Central Pacific Standard Time", "Pacific/Guadalcanal"}, {"Vladivostok Standard Time", "Asia/Vladivostok"}, {"New Zealand Standard Time", "Pacific/Auckland"}, {"UTC+12", "Etc/GMT-12"}, {"Fiji Standard Time", "Pacific/Fiji"}, {"Magadan Standard Time", "Asia/Magadan"}, {"Tonga Standard Time", "Pacific/Tongatapu"}, {"Samoa Standard Time", "Pacific/Apia"} }; /// <summary> /// This is a mapping of odd TimeZone offsets to their respective IANA codes across the world. /// This list was compiled from painstakingly pouring over the information available at /// https://en.wikipedia.org/wiki/List_of_tz_database_time_zones. /// </summary> internal static readonly Dictionary<TimeSpan, String> TimeZoneOffsetMap = new Dictionary<TimeSpan, string>() { { new TimeSpan(12, 45, 0), "Pacific/Chatham" }, { new TimeSpan(10, 30, 0), "Australia/Lord_Howe" }, { new TimeSpan(9, 30, 0), "Australia/Adelaide" }, { new TimeSpan(8, 45, 0), "Australia/Eucla" }, { new TimeSpan(8, 30, 0), "Asia/Pyongyang" }, // Parse in North Korea confirmed. { new TimeSpan(6, 30, 0), "Asia/Rangoon" }, { new TimeSpan(5, 45, 0), "Asia/Kathmandu" }, { new TimeSpan(5, 30, 0), "Asia/Colombo" }, { new TimeSpan(4, 30, 0), "Asia/Kabul" }, { new TimeSpan(3, 30, 0), "Asia/Tehran" }, { new TimeSpan(-3, 30, 0), "America/St_Johns" }, { new TimeSpan(-4, 30, 0), "America/Caracas" }, { new TimeSpan(-9, 30, 0), "Pacific/Marquesas" }, }; } }
using System; using ModestTree; #if !ZEN_NOT_UNITY3D using UnityEngine; #endif namespace Zenject { public class Binder { readonly Type _contractType; readonly DiContainer _container; readonly string _bindIdentifier; readonly SingletonProviderMap _singletonMap; public Binder( DiContainer container, Type contractType, string bindIdentifier, SingletonProviderMap singletonMap) { _container = container; _contractType = contractType; _bindIdentifier = bindIdentifier; _singletonMap = singletonMap; } public Type ContractType { get { return _contractType; } } public BindingConditionSetter ToTransient() { #if !ZEN_NOT_UNITY3D if (_contractType.DerivesFrom(typeof(Component))) { throw new ZenjectBindException( "Should not use ToTransient for Monobehaviours (when binding type '{0}'), you probably want either ToLookup or ToTransientFromPrefab" .Fmt(_contractType.Name())); } #endif return ToProvider(new TransientProvider(_container, _contractType)); } public BindingConditionSetter ToTransient(Type concreteType) { #if !ZEN_NOT_UNITY3D if (concreteType.DerivesFrom(typeof(Component))) { throw new ZenjectBindException( "Should not use ToTransient for Monobehaviours (when binding type '{0}'), you probably want either ToLookup or ToTransientFromPrefab" .Fmt(concreteType.Name())); } #endif return ToProvider(new TransientProvider(_container, concreteType)); } public BindingConditionSetter ToSingle() { return ToSingle((string)null); } public BindingConditionSetter ToSingle(string concreteIdentifier) { #if !ZEN_NOT_UNITY3D if (_contractType.DerivesFrom(typeof(Component))) { throw new ZenjectBindException( "Should not use ToSingle for Monobehaviours (when binding type '{0}'), you probably want either ToLookup or ToSinglePrefab or ToSingleGameObject" .Fmt(_contractType.Name())); } #endif return ToProvider(_singletonMap.CreateProviderFromType(concreteIdentifier, _contractType)); } public BindingConditionSetter ToSingle(Type concreteType) { return ToSingle(null, concreteType); } public BindingConditionSetter ToSingle(string concreteIdentifier, Type concreteType) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } return ToProvider(_singletonMap.CreateProviderFromType(concreteIdentifier, concreteType)); } public BindingConditionSetter ToSingle(Type concreteType, string concreteIdentifier) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } #if !ZEN_NOT_UNITY3D if (concreteType.DerivesFrom(typeof(Component))) { throw new ZenjectBindException( "Should not use ToSingle for Monobehaviours (when binding type '{0}' to '{1}'), you probably want either ToLookup or ToSinglePrefab or ToSinglePrefabResource or ToSingleGameObject" .Fmt(_contractType.Name(), concreteType.Name())); } #endif return ToProvider(_singletonMap.CreateProviderFromType(concreteIdentifier, concreteType)); } public virtual BindingConditionSetter ToProvider(ProviderBase provider) { _container.RegisterProvider( provider, new BindingId(_contractType, _bindIdentifier)); if (_contractType.IsValueType) { var nullableType = typeof(Nullable<>).MakeGenericType(_contractType); // Also bind to nullable primitives // this is useful so that we can have optional primitive dependencies _container.RegisterProvider( provider, new BindingId(nullableType, _bindIdentifier)); } return new BindingConditionSetter(provider); } #if !ZEN_NOT_UNITY3D // Note that concreteType here could be an interface as well public BindingConditionSetter ToSinglePrefab( Type concreteType, string concreteIdentifier, GameObject prefab) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } if (ZenUtil.IsNull(prefab)) { throw new ZenjectBindException( "Received null prefab while binding type '{0}'".Fmt(concreteType.Name())); } var prefabSingletonMap = _container.Resolve<PrefabSingletonProviderMap>(); return ToProvider( prefabSingletonMap.CreateProvider(concreteIdentifier, concreteType, prefab, null)); } public BindingConditionSetter ToTransientPrefab(Type concreteType, GameObject prefab) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } // We have to cast to object otherwise we get SecurityExceptions when this function is run outside of unity if (ZenUtil.IsNull(prefab)) { throw new ZenjectBindException("Received null prefab while binding type '{0}'".Fmt(concreteType.Name())); } return ToProvider(new GameObjectTransientProviderFromPrefab(concreteType, _container, prefab)); } public BindingConditionSetter ToSingleGameObject() { return ToSingleGameObject(_contractType.Name()); } // Creates a new game object and adds the given type as a new component on it // NOTE! The string given here is just a name and not a singleton identifier public BindingConditionSetter ToSingleGameObject(string name) { if (!_contractType.IsSubclassOf(typeof(Component))) { throw new ZenjectBindException("Expected UnityEngine.Component derived type when binding type '{0}'".Fmt(_contractType.Name())); } return ToProvider(new GameObjectSingletonProvider(_contractType, _container, name)); } // Creates a new game object and adds the given type as a new component on it // NOTE! The string given here is just a name and not a singleton identifier public BindingConditionSetter ToSingleGameObject(Type concreteType, string name) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } return ToProvider(new GameObjectSingletonProvider(concreteType, _container, name)); } public BindingConditionSetter ToTransientPrefabResource(string resourcePath) { return ToTransientPrefabResource(_contractType, resourcePath); } public BindingConditionSetter ToTransientPrefabResource(Type concreteType, string resourcePath) { Assert.IsNotNull(resourcePath); return ToProvider(new GameObjectTransientProviderFromPrefabResource(concreteType, _container, resourcePath)); } public BindingConditionSetter ToSinglePrefabResource(Type concreteType, string concreteIdentifier, string resourcePath) { Assert.That(concreteType.DerivesFromOrEqual(_contractType)); Assert.IsNotNull(resourcePath); var prefabSingletonMap = _container.Resolve<PrefabSingletonProviderMap>(); return ToProvider( prefabSingletonMap.CreateProvider(concreteIdentifier, concreteType, null, resourcePath)); } public BindingConditionSetter ToSinglePrefabResource(string resourcePath) { return ToSinglePrefabResource(null, resourcePath); } public BindingConditionSetter ToSinglePrefabResource(string identifier, string resourcePath) { return ToSinglePrefabResource(_contractType, identifier, resourcePath); } public BindingConditionSetter ToTransientPrefab(GameObject prefab) { return ToTransientPrefab(_contractType, prefab); } public BindingConditionSetter ToSinglePrefab(GameObject prefab) { return ToSinglePrefab(null, prefab); } public BindingConditionSetter ToSinglePrefab(string identifier, GameObject prefab) { return ToSinglePrefab(_contractType, identifier, prefab); } #endif protected BindingConditionSetter ToSingleMethodBase<TConcrete>(string concreteIdentifier, Func<InjectContext, TConcrete> method) { return ToProvider(_singletonMap.CreateProviderFromMethod(concreteIdentifier, method)); } protected BindingConditionSetter ToMethodBase<T>(Func<InjectContext, T> method) { if (!typeof(T).DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(typeof(T), _contractType.Name())); } return ToProvider(new MethodProvider<T>(method)); } protected BindingConditionSetter ToLookupBase<TConcrete>(string identifier) { return ToMethodBase<TConcrete>((ctx) => ctx.Container.Resolve<TConcrete>( new InjectContext( ctx.Container, typeof(TConcrete), identifier, false, ctx.ObjectType, ctx.ObjectInstance, ctx.MemberName, ctx, null, ctx.FallBackValue))); } protected BindingConditionSetter ToGetterBase<TObj, TResult>(string identifier, Func<TObj, TResult> method) { return ToMethodBase((ctx) => method(ctx.Container.Resolve<TObj>( new InjectContext( ctx.Container, typeof(TObj), identifier, false, ctx.ObjectType, ctx.ObjectInstance, ctx.MemberName, ctx, null, ctx.FallBackValue)))); } public BindingConditionSetter ToInstance(Type concreteType, object instance) { if (ZenUtil.IsNull(instance) && !_container.AllowNullBindings) { string message; if (_contractType == concreteType) { message = "Received null instance during Bind command with type '{0}'".Fmt(_contractType.Name()); } else { message = "Received null instance during Bind command when binding type '{0}' to '{1}'".Fmt(_contractType.Name(), concreteType.Name()); } throw new ZenjectBindException(message); } if (!ZenUtil.IsNull(instance) && !instance.GetType().DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } return ToProvider(new InstanceProvider(concreteType, instance)); } protected BindingConditionSetter ToSingleInstance(Type concreteType, string concreteIdentifier, object instance) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } if (ZenUtil.IsNull(instance) && !_container.AllowNullBindings) { string message; if (_contractType == concreteType) { message = "Received null singleton instance during Bind command with type '{0}'".Fmt(_contractType.Name()); } else { message = "Received null singleton instance during Bind command when binding type '{0}' to '{1}'".Fmt(_contractType.Name(), concreteType.Name()); } throw new ZenjectBindException(message); } return ToProvider(_singletonMap.CreateProviderFromInstance(concreteIdentifier, concreteType, instance)); } #if !ZEN_NOT_UNITY3D protected BindingConditionSetter ToSingleMonoBehaviourBase<TConcrete>(GameObject gameObject) { return ToProvider(new MonoBehaviourSingletonProvider(typeof(TConcrete), _container, gameObject)); } public BindingConditionSetter ToResource(string resourcePath) { return ToResource(_contractType, resourcePath); } public BindingConditionSetter ToResource(Type concreteType, string resourcePath) { if (!concreteType.DerivesFromOrEqual(_contractType)) { throw new ZenjectBindException( "Invalid type given during bind command. Expected type '{0}' to derive from type '{1}'".Fmt(concreteType.Name(), _contractType.Name())); } return ToProvider(new ResourceProvider(concreteType, resourcePath)); } #endif } }
using System; using System.Collections.Generic; using ModestTree; namespace Zenject { // Zero params public class MethodProviderWithContainer<TValue> : IProvider { readonly Func<DiContainer, TValue> _method; public MethodProviderWithContainer(Func<DiContainer, TValue> method) { _method = method; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(InjectContext context, List<TypeValuePair> args) { Assert.IsEmpty(args); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); if (context.Container.IsValidating) { // Don't do anything when validating, we can't make any assumptions on the given method yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { _method(context.Container) }; } } } // One params public class MethodProviderWithContainer<TParam1, TValue> : IProvider { readonly Func<DiContainer, TParam1, TValue> _method; public MethodProviderWithContainer(Func<DiContainer, TParam1, TValue> method) { _method = method; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 1); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual(typeof(TParam1))); if (context.Container.IsValidating) { // Don't do anything when validating, we can't make any assumptions on the given method yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { _method( context.Container, (TParam1)args[0].Value) }; } } } // Two params public class MethodProviderWithContainer<TParam1, TParam2, TValue> : IProvider { readonly Func<DiContainer, TParam1, TParam2, TValue> _method; public MethodProviderWithContainer(Func<DiContainer, TParam1, TParam2, TValue> method) { _method = method; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 2); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual(typeof(TParam1))); Assert.That(args[1].Type.DerivesFromOrEqual(typeof(TParam2))); if (context.Container.IsValidating) { // Don't do anything when validating, we can't make any assumptions on the given method yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { _method( context.Container, (TParam1)args[0].Value, (TParam2)args[1].Value) }; } } } // Three params public class MethodProviderWithContainer<TParam1, TParam2, TParam3, TValue> : IProvider { readonly Func<DiContainer, TParam1, TParam2, TParam3, TValue> _method; public MethodProviderWithContainer(Func<DiContainer, TParam1, TParam2, TParam3, TValue> method) { _method = method; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 3); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual(typeof(TParam1))); Assert.That(args[1].Type.DerivesFromOrEqual(typeof(TParam2))); Assert.That(args[2].Type.DerivesFromOrEqual(typeof(TParam3))); if (context.Container.IsValidating) { // Don't do anything when validating, we can't make any assumptions on the given method yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { _method( context.Container, (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value) }; } } } // Four params public class MethodProviderWithContainer<TParam1, TParam2, TParam3, TParam4, TValue> : IProvider { readonly ModestTree.Util.Func<DiContainer, TParam1, TParam2, TParam3, TParam4, TValue> _method; public MethodProviderWithContainer(ModestTree.Util.Func<DiContainer, TParam1, TParam2, TParam3, TParam4, TValue> method) { _method = method; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 4); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual(typeof(TParam1))); Assert.That(args[1].Type.DerivesFromOrEqual(typeof(TParam2))); Assert.That(args[2].Type.DerivesFromOrEqual(typeof(TParam3))); Assert.That(args[3].Type.DerivesFromOrEqual(typeof(TParam4))); if (context.Container.IsValidating) { // Don't do anything when validating, we can't make any assumptions on the given method yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { _method( context.Container, (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value) }; } } } // Five params public class MethodProviderWithContainer<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : IProvider { readonly ModestTree.Util.Func<DiContainer, TParam1, TParam2, TParam3, TParam4, TParam5, TValue> _method; public MethodProviderWithContainer(ModestTree.Util.Func<DiContainer, TParam1, TParam2, TParam3, TParam4, TParam5, TValue> method) { _method = method; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public IEnumerator<List<object>> GetAllInstancesWithInjectSplit(InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 5); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.That(args[0].Type.DerivesFromOrEqual(typeof(TParam1))); Assert.That(args[1].Type.DerivesFromOrEqual(typeof(TParam2))); Assert.That(args[2].Type.DerivesFromOrEqual(typeof(TParam3))); Assert.That(args[3].Type.DerivesFromOrEqual(typeof(TParam4))); Assert.That(args[4].Type.DerivesFromOrEqual(typeof(TParam5))); if (context.Container.IsValidating) { // Don't do anything when validating, we can't make any assumptions on the given method yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { _method( context.Container, (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value, (TParam5)args[4].Value) }; } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.ComponentModel; using System.Management.Automation.Runspaces; namespace System.Management.Automation { /// <summary> /// Serves as the arguments for events triggered by exceptions in the SetValue method of <see cref="PSObjectPropertyDescriptor"/> /// </summary> /// <remarks> /// The sender of this event is an object of type <see cref="PSObjectPropertyDescriptor"/>. /// It is permitted to subclass <see cref="SettingValueExceptionEventArgs"/> /// but there is no established scenario for doing this, nor has it been tested. /// </remarks> public class SettingValueExceptionEventArgs : EventArgs { /// <summary> /// Gets and sets a <see cref="System.Boolean"/> indicating if the SetValue method of <see cref="PSObjectPropertyDescriptor"/> /// should throw the exception associated with this event. /// </summary> /// <remarks> /// The default value is true, indicating that the Exception associated with this event will be thrown. /// </remarks> public bool ShouldThrow { get; set; } /// <summary> /// Gets the exception that triggered the associated event. /// </summary> public Exception Exception { get; } /// <summary> /// Initializes a new instance of <see cref="SettingValueExceptionEventArgs"/> setting the value of of the exception that triggered the associated event. /// </summary> /// <param name="exception">Exception that triggered the associated event</param> internal SettingValueExceptionEventArgs(Exception exception) { Exception = exception; ShouldThrow = true; } } /// <summary> /// Serves as the arguments for events triggered by exceptions in the GetValue /// method of <see cref="PSObjectPropertyDescriptor"/> /// </summary> /// <remarks> /// The sender of this event is an object of type <see cref="PSObjectPropertyDescriptor"/>. /// It is permitted to subclass <see cref="GettingValueExceptionEventArgs"/> /// but there is no established scenario for doing this, nor has it been tested. /// </remarks> public class GettingValueExceptionEventArgs : EventArgs { /// <summary> /// Gets and sets a <see cref="System.Boolean"/> indicating if the GetValue method of <see cref="PSObjectPropertyDescriptor"/> /// should throw the exception associated with this event. /// </summary> public bool ShouldThrow { get; set; } /// <summary> /// Gets the Exception that triggered the associated event. /// </summary> public Exception Exception { get; } /// <summary> /// Initializes a new instance of <see cref="GettingValueExceptionEventArgs"/> setting the value of of the exception that triggered the associated event. /// </summary> /// <param name="exception">Exception that triggered the associated event</param> internal GettingValueExceptionEventArgs(Exception exception) { Exception = exception; ValueReplacement = null; ShouldThrow = true; } /// <summary> /// Gets and sets the value that will serve as a replacement to the return of the GetValue /// method of <see cref="PSObjectPropertyDescriptor"/>. If this property is not set /// to a value other than null then the exception associated with this event is thrown. /// </summary> public object ValueReplacement { get; set; } } /// <summary> /// Serves as the property information generated by the GetProperties method of <see cref="PSObjectTypeDescriptor"/>. /// </summary> /// <remarks> /// It is permitted to subclass <see cref="SettingValueExceptionEventArgs"/> /// but there is no established scenario for doing this, nor has it been tested. /// </remarks> public class PSObjectPropertyDescriptor : PropertyDescriptor { internal event EventHandler<SettingValueExceptionEventArgs> SettingValueException; internal event EventHandler<GettingValueExceptionEventArgs> GettingValueException; internal PSObjectPropertyDescriptor(string propertyName, Type propertyType, bool isReadOnly, AttributeCollection propertyAttributes) : base(propertyName, Utils.EmptyArray<Attribute>()) { IsReadOnly = isReadOnly; Attributes = propertyAttributes; PropertyType = propertyType; } /// <summary> /// Gets the collection of attributes for this member. /// </summary> public override AttributeCollection Attributes { get; } /// <summary> /// Gets a value indicating whether this property is read-only. /// </summary> public override bool IsReadOnly { get; } /// <summary> /// This method has no effect for <see cref="PSObjectPropertyDescriptor"/>. /// CanResetValue returns false. /// </summary> /// <param name="component">This parameter is ignored for <see cref="PSObjectPropertyDescriptor"/></param> public override void ResetValue(object component) { } /// <summary> /// Returns false to indicate that ResetValue has no effect. /// </summary> /// <param name="component">The component to test for reset capability. </param> /// <returns>false</returns> public override bool CanResetValue(object component) { return false; } /// <summary> /// Returns true to indicate that the value of this property needs to be persisted. /// </summary> /// <param name="component">The component with the property to be examined for persistence.</param> /// <returns>true</returns> public override bool ShouldSerializeValue(object component) { return true; } /// <summary> /// Gets the type of the component this property is bound to. /// </summary> /// <remarks>This property returns the <see cref="PSObject"/> type.</remarks> public override Type ComponentType { get { return typeof(PSObject); } } /// <summary> /// Gets the type of the property value. /// </summary> public override Type PropertyType { get; } /// <summary> /// Gets the current value of the property on a component. /// </summary> /// <param name="component">The component with the property for which to retrieve the value. </param> /// <returns>The value of a property for a given component.</returns> /// <exception cref="ExtendedTypeSystemException"> /// If the property has not been found in the component or an exception has /// been thrown when getting the value of the property. /// This Exception will only be thrown if there is no event handler for the GettingValueException /// event of the <see cref="PSObjectTypeDescriptor"/> that created this <see cref="PSObjectPropertyDescriptor"/>. /// If there is an event handler, it can prevent this exception from being thrown, by changing /// the ShouldThrow property of <see cref="GettingValueExceptionEventArgs"/> from its default /// value of true to false. /// </exception> /// <exception cref="PSArgumentNullException">If <paramref name="component"/> is null.</exception> /// <exception cref="PSArgumentException">if <paramref name="component"/> is not /// an <see cref="PSObject"/> or an <see cref="PSObjectTypeDescriptor"/>.</exception> public override object GetValue(object component) { if (component == null) { throw PSTraceSource.NewArgumentNullException("component"); } PSObject mshObj = GetComponentPSObject(component); PSPropertyInfo property; try { property = mshObj.Properties[this.Name] as PSPropertyInfo; if (property == null) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to get its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorGetValue", null, ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name); bool shouldThrow; object returnValue = DealWithGetValueException(e, out shouldThrow); if (shouldThrow) { throw e; } return returnValue; } return property.Value; } catch (ExtendedTypeSystemException e) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception getting the value of the property \"{0}\": \"{1}\".", this.Name, e.Message); bool shouldThrow; object returnValue = DealWithGetValueException(e, out shouldThrow); if (shouldThrow) { throw; } return returnValue; } } private static PSObject GetComponentPSObject(object component) { // If you use the PSObjectTypeDescriptor directly as your object, it will be the component // if you use a provider, the PSObject will be the component. PSObject mshObj = component as PSObject; if (mshObj == null) { PSObjectTypeDescriptor descriptor = component as PSObjectTypeDescriptor; if (descriptor == null) { throw PSTraceSource.NewArgumentException("component", ExtendedTypeSystem.InvalidComponent, "component", typeof(PSObject).Name, typeof(PSObjectTypeDescriptor).Name); } mshObj = descriptor.Instance; } return mshObj; } private object DealWithGetValueException(ExtendedTypeSystemException e, out bool shouldThrow) { GettingValueExceptionEventArgs eventArgs = new GettingValueExceptionEventArgs(e); if (GettingValueException != null) { GettingValueException.SafeInvoke(this, eventArgs); PSObjectTypeDescriptor.typeDescriptor.WriteLine( "GettingValueException event has been triggered resulting in ValueReplacement:\"{0}\".", eventArgs.ValueReplacement); } shouldThrow = eventArgs.ShouldThrow; return eventArgs.ValueReplacement; } /// <summary> /// Sets the value of the component to a different value. /// </summary> /// <param name="component">The component with the property value that is to be set. </param> /// <param name="value">The new value.</param> /// <exception cref="ExtendedTypeSystemException"> /// If the property has not been found in the component or an exception has /// been thrown when setting the value of the property. /// This Exception will only be thrown if there is no event handler for the SettingValueException /// event of the <see cref="PSObjectTypeDescriptor"/> that created this <see cref="PSObjectPropertyDescriptor"/>. /// If there is an event handler, it can prevent this exception from being thrown, by changing /// the ShouldThrow property of <see cref="SettingValueExceptionEventArgs"/> /// from its default value of true to false. /// </exception> /// <exception cref="PSArgumentNullException">If <paramref name="component"/> is null.</exception> /// <exception cref="PSArgumentException">if <paramref name="component"/> is not an /// <see cref="PSObject"/> or an <see cref="PSObjectTypeDescriptor"/>. /// </exception> public override void SetValue(object component, object value) { if (component == null) { throw PSTraceSource.NewArgumentNullException("component"); } PSObject mshObj = GetComponentPSObject(component); try { PSPropertyInfo property = mshObj.Properties[this.Name] as PSPropertyInfo; if (property == null) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Could not find property \"{0}\" to set its value.", this.Name); ExtendedTypeSystemException e = new ExtendedTypeSystemException("PropertyNotFoundInPropertyDescriptorSetValue", null, ExtendedTypeSystem.PropertyNotFoundInTypeDescriptor, this.Name); bool shouldThrow; DealWithSetValueException(e, out shouldThrow); if (shouldThrow) { throw e; } return; } property.Value = value; } catch (ExtendedTypeSystemException e) { PSObjectTypeDescriptor.typeDescriptor.WriteLine("Exception setting the value of the property \"{0}\": \"{1}\".", this.Name, e.Message); bool shouldThrow; DealWithSetValueException(e, out shouldThrow); if (shouldThrow) { throw; } } OnValueChanged(component, EventArgs.Empty); } private void DealWithSetValueException(ExtendedTypeSystemException e, out bool shouldThrow) { SettingValueExceptionEventArgs eventArgs = new SettingValueExceptionEventArgs(e); if (SettingValueException != null) { SettingValueException.SafeInvoke(this, eventArgs); PSObjectTypeDescriptor.typeDescriptor.WriteLine( "SettingValueException event has been triggered resulting in ShouldThrow:\"{0}\".", eventArgs.ShouldThrow); } shouldThrow = eventArgs.ShouldThrow; return; } } /// <summary> /// Provides information about the properties for an object of the type <see cref="PSObject"/>. /// </summary> public class PSObjectTypeDescriptor : CustomTypeDescriptor { internal static PSTraceSource typeDescriptor = PSTraceSource.GetTracer("TypeDescriptor", "Traces the behavior of PSObjectTypeDescriptor, PSObjectTypeDescriptionProvider and PSObjectPropertyDescriptor.", false); /// <summary> /// Occurs when there was an exception setting the value of a property. /// </summary> /// <remarks> /// The ShouldThrow property of the <see cref="SettingValueExceptionEventArgs"/> allows /// subscribers to prevent the exception from being thrown. /// </remarks> public event EventHandler<SettingValueExceptionEventArgs> SettingValueException; /// <summary> /// Occurs when there was an exception getting the value of a property. /// </summary> /// <remarks> /// The ShouldThrow property of the <see cref="GettingValueExceptionEventArgs"/> allows /// subscribers to prevent the exception from being thrown. /// </remarks> public event EventHandler<GettingValueExceptionEventArgs> GettingValueException; /// <summary> /// Initializes a new instance of the <see cref="PSObjectTypeDescriptor"/> that provides /// property information about <paramref name="instance"/>. /// </summary> /// <param name="instance">The <see cref="PSObject"/> this class retrieves property information from.</param> public PSObjectTypeDescriptor(PSObject instance) { Instance = instance; } /// <summary> /// Gets the <see cref="PSObject"/> this class retrieves property information from. /// </summary> public PSObject Instance { get; } private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attributes, ref PropertyDescriptorCollection returnValue) { using (typeDescriptor.TraceScope("Checking property \"{0}\".", propertyInfo.Name)) { // WriteOnly properties are not returned in TypeDescriptor.GetProperties, so we do the same. if (!propertyInfo.IsGettable) { typeDescriptor.WriteLine("Property \"{0}\" is write-only so it has been skipped.", propertyInfo.Name); return; } AttributeCollection propertyAttributes = null; Type propertyType = typeof(object); if (attributes != null && attributes.Length != 0) { PSProperty property = propertyInfo as PSProperty; if (property != null) { DotNetAdapter.PropertyCacheEntry propertyEntry = property.adapterData as DotNetAdapter.PropertyCacheEntry; if (propertyEntry == null) { typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it is an adapted property (not a .NET property).", property.Name); } else if (property.isDeserialized) { // At the moment we are not serializing attributes, so we can skip // the attribute check if the property is deserialized. typeDescriptor.WriteLine("Skipping attribute check for property \"{0}\" because it has been deserialized.", property.Name); } else { propertyType = propertyEntry.propertyType; propertyAttributes = propertyEntry.Attributes; foreach (Attribute attribute in attributes) { if (!propertyAttributes.Contains(attribute)) { typeDescriptor.WriteLine("Property \"{0}\" does not contain attribute \"{1}\" so it has been skipped.", property.Name, attribute); return; } } } } } if (propertyAttributes == null) { propertyAttributes = new AttributeCollection(); } typeDescriptor.WriteLine("Adding property \"{0}\".", propertyInfo.Name); PSObjectPropertyDescriptor propertyDescriptor = new PSObjectPropertyDescriptor(propertyInfo.Name, propertyType, !propertyInfo.IsSettable, propertyAttributes); propertyDescriptor.SettingValueException += this.SettingValueException; propertyDescriptor.GettingValueException += this.GettingValueException; returnValue.Add(propertyDescriptor); } } /// <summary> /// Returns a collection of property descriptors for the <see cref="PSObject"/> represented by this type descriptor. /// </summary> /// <returns>A PropertyDescriptorCollection containing the property descriptions for the <see cref="PSObject"/> represented by this type descriptor.</returns> public override PropertyDescriptorCollection GetProperties() { return GetProperties(null); } /// <summary> /// Returns a filtered collection of property descriptors for the <see cref="PSObject"/> represented by this type descriptor. /// </summary> /// <param name="attributes">An array of attributes to use as a filter. This can be a null reference (Nothing in Visual Basic).</param> /// <returns>A PropertyDescriptorCollection containing the property descriptions for the <see cref="PSObject"/> represented by this type descriptor.</returns> public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { using (typeDescriptor.TraceScope("Getting properties.")) { PropertyDescriptorCollection returnValue = new PropertyDescriptorCollection(null); if (Instance == null) { return returnValue; } foreach (PSPropertyInfo property in Instance.Properties) { CheckAndAddProperty(property, attributes, ref returnValue); } return returnValue; } } /// <summary> /// Determines whether the Instance property of <paramref name="obj"/> is equal to the current Instance. /// </summary> /// <param name="obj">The Object to compare with the current Object.</param> /// <returns>true if the Instance property of <paramref name="obj"/> is equal to the current Instance; otherwise, false.</returns> public override bool Equals(object obj) { PSObjectTypeDescriptor other = obj as PSObjectTypeDescriptor; if (other == null) { return false; } if (this.Instance == null || other.Instance == null) { return ReferenceEquals(this, other); } return other.Instance.Equals(this.Instance); } /// <summary> /// Provides a value for hashing algorithms. /// </summary> /// <returns>A hash code for the current object</returns> public override int GetHashCode() { if (this.Instance == null) { return base.GetHashCode(); } return this.Instance.GetHashCode(); } /// <summary> /// Returns the default property for this object. /// </summary> /// <returns>An <see cref="PSObjectPropertyDescriptor"/> that represents the default property for this object, or a null reference (Nothing in Visual Basic) if this object does not have properties</returns> public override PropertyDescriptor GetDefaultProperty() { if (this.Instance == null) { return null; } string defaultProperty = null; PSMemberSet standardMembers = this.Instance.PSStandardMembers; if (standardMembers != null) { PSNoteProperty note = standardMembers.Properties[TypeTable.DefaultDisplayProperty] as PSNoteProperty; if (note != null) { defaultProperty = note.Value as string; } } if (defaultProperty == null) { object[] defaultPropertyAttributes = this.Instance.BaseObject.GetType().GetCustomAttributes(typeof(DefaultPropertyAttribute), true); if (defaultPropertyAttributes.Length == 1) { DefaultPropertyAttribute defaultPropertyAttribute = defaultPropertyAttributes[0] as DefaultPropertyAttribute; if (defaultPropertyAttribute != null) { defaultProperty = defaultPropertyAttribute.Name; } } } PropertyDescriptorCollection properties = this.GetProperties(); if (defaultProperty != null) { // There is a defaultProperty, but let's check if it is actually one of the properties we are // returning in GetProperties foreach (PropertyDescriptor descriptor in properties) { if (String.Equals(descriptor.Name, defaultProperty, StringComparison.OrdinalIgnoreCase)) { return descriptor; } } } return null; } /// <summary> /// Returns a type converter for this object. /// </summary> /// <returns>A <see cref="TypeConverter"/> that is the converter for this object, or a null reference (Nothing in Visual Basic) if there is no <see cref="TypeConverter"/> for this object.</returns> public override TypeConverter GetConverter() { if (this.Instance == null) { // If we return null, some controls will have an exception saying that this // GetConverter returned an illegal value return new TypeConverter(); } object baseObject = this.Instance.BaseObject; TypeConverter retValue = LanguagePrimitives.GetConverter(baseObject.GetType(), null) as TypeConverter ?? TypeDescriptor.GetConverter(baseObject); return retValue; } /// <summary> /// Returns the object that this value is a member of. /// </summary> /// <param name="pd">A <see cref="PropertyDescriptor"/> that represents the property whose owner is to be found.</param> /// <returns>An object that represents the owner of the specified property.</returns> public override object GetPropertyOwner(PropertyDescriptor pd) { return this.Instance; } #region Overrides Forwarded To BaseObject #region ReadMe // This region contains methods implemented like: // TypeDescriptor.OverrideName(this.Instance.BaseObject) // They serve the purpose of exposing Attributes and other information from the BaseObject // of an PSObject, since the PSObject itself does not have the concept of class (or member) // attributes. // The calls are not recursive because the BaseObject was implemented so it is never // another PSObject. ImmediateBaseObject or PSObject.Base could cause the call to be // recursive in the case of an object like "new PSObject(new PSObject())". // Even if we used ImmediateBaseObject, the recursion would be finite since we would // keep getting an ImmediatebaseObject until it ceased to be an PSObject. #endregion ReadMe /// <summary> /// Returns the default event for this object. /// </summary> /// <returns>An <see cref="EventDescriptor"/> that represents the default event for this object, or a null reference (Nothing in Visual Basic) if this object does not have events.</returns> public override EventDescriptor GetDefaultEvent() { if (this.Instance == null) { return null; } return TypeDescriptor.GetDefaultEvent(this.Instance.BaseObject); } /// <summary> /// Returns the events for this instance of a component. /// </summary> /// <returns>An <see cref="EventDescriptorCollection"/> that represents the events for this component instance.</returns> public override EventDescriptorCollection GetEvents() { if (this.Instance == null) { return new EventDescriptorCollection(null); } return TypeDescriptor.GetEvents(this.Instance.BaseObject); } /// <summary> /// Returns the events for this instance of a component using the attribute array as a filter. /// </summary> /// <param name="attributes">An array of type <see cref="Attribute"/> that is used as a filter. </param> /// <returns>An <see cref="EventDescriptorCollection"/> that represents the events for this component instance that match the given set of attributes.</returns> public override EventDescriptorCollection GetEvents(Attribute[] attributes) { if (this.Instance == null) { return null; } return TypeDescriptor.GetEvents(this.Instance.BaseObject, attributes); } /// <summary> /// Returns a collection of type <see cref="Attribute"/> for this object. /// </summary> /// <returns>An <see cref="AttributeCollection"/> with the attributes for this object.</returns> public override AttributeCollection GetAttributes() { if (this.Instance == null) { return new AttributeCollection(); } return TypeDescriptor.GetAttributes(this.Instance.BaseObject); } /// <summary> /// Returns the class name of this object. /// </summary> /// <returns>The class name of the object, or a null reference (Nothing in Visual Basic) if the class does not have a name.</returns> public override string GetClassName() { if (this.Instance == null) { return null; } return TypeDescriptor.GetClassName(this.Instance.BaseObject); } /// <summary> /// Returns the name of this object. /// </summary> /// <returns>The name of the object, or a null reference (Nothing in Visual Basic) if object does not have a name.</returns> public override string GetComponentName() { if (this.Instance == null) { return null; } return TypeDescriptor.GetComponentName(this.Instance.BaseObject); } /// <summary> /// Returns an editor of the specified type for this object. /// </summary> /// <param name="editorBaseType">A <see cref="Type"/> that represents the editor for this object.</param> /// <returns>An object of the specified type that is the editor for this object, or a null reference (Nothing in Visual Basic) if the editor cannot be found.</returns> public override object GetEditor(Type editorBaseType) { if (this.Instance == null) { return null; } return TypeDescriptor.GetEditor(this.Instance.BaseObject, editorBaseType); } #endregion Forwarded To BaseObject } /// <summary> /// Retrieves a <see cref="PSObjectTypeDescriptor"/> to provides information about the properties for an object of the type <see cref="PSObject"/>. /// </summary> public class PSObjectTypeDescriptionProvider : TypeDescriptionProvider { /// <summary> /// Occurs when there was an exception setting the value of a property. /// </summary> /// <remarks> /// The ShouldThrow property of the <see cref="SettingValueExceptionEventArgs"/> allows /// subscribers to prevent the exception from being thrown. /// </remarks> public event EventHandler<SettingValueExceptionEventArgs> SettingValueException; /// <summary> /// Occurs when there was an exception getting the value of a property. /// </summary> /// <remarks> /// The ShouldThrow property of the <see cref="GettingValueExceptionEventArgs"/> allows /// subscribers to prevent the exception from being thrown. /// </remarks> public event EventHandler<GettingValueExceptionEventArgs> GettingValueException; /// <summary> /// Initializes a new instance of <see cref="PSObjectTypeDescriptionProvider"/> /// </summary> public PSObjectTypeDescriptionProvider() { } /// <summary> /// Retrieves a <see cref="PSObjectTypeDescriptor"/> to provide information about the properties for an object of the type <see cref="PSObject"/>. /// </summary> /// <param name="objectType">The type of object for which to retrieve the type descriptor. If this parameter is not noll and is not the <see cref="PSObject"/>, the return of this method will be null.</param> /// <param name="instance">An instance of the type. If instance is null or has a type other than <see cref="PSObject"/>, this method returns null.</param> /// <returns>An <see cref="ICustomTypeDescriptor"/> that can provide property information for the /// type <see cref="PSObject"/>, or null if <paramref name="objectType"/> is not null, /// but has a type other than <see cref="PSObject"/>.</returns> public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { PSObject mshObj = instance as PSObject; #region ReadMe // Instance can be null, in a couple of circumstances: // 1) In one of the many calls to this method caused by setting the SelectedObject // property of a PropertyGrid. // 2) If, by mistake, an object[] or Collection<PSObject> is used instead of an ArrayList // to set the DataSource property of a DataGrid or DatagridView. // // It would be nice to throw an exception for the case 2) instructing the user to use // an ArrayList, but since we have case 1) and maybe others we haven't found we return // an PSObjectTypeDescriptor(null). PSObjectTypeDescriptor's GetProperties // checks for null instance and returns an empty property collection. // All other overrides also check for null and return some default result. // Case 1), which is using a PropertyGrid seems to be unaffected by these results returned // by PSObjectTypeDescriptor overrides when the Instance is null, so we must conclude // that the TypeDescriptor returned by that call where instance is null is not used // for anything meaningful. That null instance PSObjectTypeDescriptor is only one // of the many PSObjectTypeDescriptor's returned by this method in a PropertyGrid use. // Some of the other calls to this method are passing a valid instance and the objects // returned by these calls seem to be the ones used for meaningful calls in the PropertyGrid. // // It might sound strange that we are not verifying the type of objectType or of instance // to be PSObject, but in this PropertyGrid use that passes a null instance (case 1), if // we return null we have an exception flagging the return as invalid. Since we cannot // return null and MSDN has a note saying that we should return null instead of throwing // exceptions, the safest behavior seems to be creating this PSObjectTypeDescriptor with // null instance. #endregion ReadMe PSObjectTypeDescriptor typeDescriptor = new PSObjectTypeDescriptor(mshObj); typeDescriptor.SettingValueException += this.SettingValueException; typeDescriptor.GettingValueException += this.GettingValueException; return typeDescriptor; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions; using Microsoft.WindowsAzure.Commands.ServiceManagement.Model; using Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Commands.Sync.Download; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using Security.Cryptography; using Security.Cryptography.X509Certificates; namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Test.FunctionalTests { internal class Utilities { #region Constants public static string windowsAzurePowershellPath = Path.Combine(Environment.CurrentDirectory, "ServiceManagement\\Azure"); public const string windowsAzurePowershellServiceModule = "Azure.psd1"; public const string windowsAzurePowershellModuleServiceManagementPlatformImageRepository = "PIR.psd1"; public const string windowsAzurePowershellModuleServiceManagementPreview = "AzurePreview.psd1"; public const string AzurePowershellCommandsModule = "Microsoft.WindowsAzure.Commands.dll"; public const string AzurePowershellServiceManagementModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.dll"; public const string AzurePowershellStorageModule = "Microsoft.WindowsAzure.Commands.Storage.dll"; public const string AzurePowershellModuleServiceManagementPirModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.PlatformImageRepository.dll"; public const string AzurePowershellModuleServiceManagementPreviewModule = "Microsoft.WindowsAzure.Commands.ServiceManagement.Preview.dll"; // AzureAffinityGroup public const string NewAzureAffinityGroupCmdletName = "New-AzureAffinityGroup"; public const string GetAzureAffinityGroupCmdletName = "Get-AzureAffinityGroup"; public const string SetAzureAffinityGroupCmdletName = "Set-AzureAffinityGroup"; public const string RemoveAzureAffinityGroupCmdletName = "Remove-AzureAffinityGroup"; // AzureAvailablitySet public const string SetAzureAvailabilitySetCmdletName = "Set-AzureAvailabilitySet"; public const string RemoveAzureAvailabilitySetCmdletName = "Remove-AzureAvailabilitySet"; // AzureCertificate & AzureCertificateSetting public const string AddAzureCertificateCmdletName = "Add-AzureCertificate"; public const string GetAzureCertificateCmdletName = "Get-AzureCertificate"; public const string RemoveAzureCertificateCmdletName = "Remove-AzureCertificate"; public const string NewAzureCertificateSettingCmdletName = "New-AzureCertificateSetting"; // AzureDataDisk public const string AddAzureDataDiskCmdletName = "Add-AzureDataDisk"; public const string GetAzureDataDiskCmdletName = "Get-AzureDataDisk"; public const string SetAzureDataDiskCmdletName = "Set-AzureDataDisk"; public const string RemoveAzureDataDiskCmdletName = "Remove-AzureDataDisk"; // AzureDeployment public const string NewAzureDeploymentCmdletName = "New-AzureDeployment"; public const string GetAzureDeploymentCmdletName = "Get-AzureDeployment"; public const string SetAzureDeploymentCmdletName = "Set-AzureDeployment"; public const string RemoveAzureDeploymentCmdletName = "Remove-AzureDeployment"; public const string MoveAzureDeploymentCmdletName = "Move-AzureDeployment"; public const string GetAzureDeploymentEventCmdletName = "Get-AzureDeploymentEvent"; // AzureDisk public const string AddAzureDiskCmdletName = "Add-AzureDisk"; public const string GetAzureDiskCmdletName = "Get-AzureDisk"; public const string UpdateAzureDiskCmdletName = "Update-AzureDisk"; public const string RemoveAzureDiskCmdletName = "Remove-AzureDisk"; // AzureDns public const string NewAzureDnsCmdletName = "New-AzureDns"; public const string GetAzureDnsCmdletName = "Get-AzureDns"; public const string SetAzureDnsCmdletName = "Set-AzureDns"; public const string AddAzureDnsCmdletName = "Add-AzureDns"; public const string RemoveAzureDnsCmdletName = "Remove-AzureDns"; // AzureEndpoint public const string AddAzureEndpointCmdletName = "Add-AzureEndpoint"; public const string GetAzureEndpointCmdletName = "Get-AzureEndpoint"; public const string SetAzureEndpointCmdletName = "Set-AzureEndpoint"; public const string RemoveAzureEndpointCmdletName = "Remove-AzureEndpoint"; // AzureLocation public const string GetAzureLocationCmdletName = "Get-AzureLocation"; // AzureOSDisk & AzureOSVersion public const string GetAzureOSDiskCmdletName = "Get-AzureOSDisk"; public const string SetAzureOSDiskCmdletName = "Set-AzureOSDisk"; public const string GetAzureOSVersionCmdletName = "Get-AzureOSVersion"; // AzureProvisioningConfig public const string AddAzureProvisioningConfigCmdletName = "Add-AzureProvisioningConfig"; // AzurePublishSettingsFile public const string ImportAzurePublishSettingsFileCmdletName = "Import-AzurePublishSettingsFile"; public const string GetAzurePublishSettingsFileCmdletName = "Get-AzurePublishSettingsFile"; public const string AddAzureEnvironmentCmdletName = "Add-AzureEnvironment"; // AzureQuickVM public const string NewAzureQuickVMCmdletName = "New-AzureQuickVM"; //Get-AzureWinRMUri public const string GetAzureWinRMUriCmdletName = "Get-AzureWinRMUri"; // AzurePlatformVMImage public const string SetAzurePlatformVMImageCmdletName = "Set-AzurePlatformVMImage"; public const string GetAzurePlatformVMImageCmdletName = "Get-AzurePlatformVMImage"; public const string RemoveAzurePlatformVMImageCmdletName = "Remove-AzurePlatformVMImage"; public const string NewAzurePlatformComputeImageConfigCmdletName = "New-AzurePlatformComputeImageConfig"; public const string NewAzurePlatformMarketplaceImageConfigCmdletName = "New-AzurePlatformMarketplaceImageConfig"; // AzureRemoteDesktopFile public const string GetAzureRemoteDesktopFileCmdletName = "Get-AzureRemoteDesktopFile"; // AzureReservedIP public const string NewAzureReservedIPCmdletName = "New-AzureReservedIP"; public const string GetAzureReservedIPCmdletName = "Get-AzureReservedIP"; public const string RemoveAzureReservedIPCmdletName = "Remove-AzureReservedIP"; public const string SetAzureReservedIPAssociationCmdletName = "Set-AzureReservedIPAssociation"; public const string RemoveAzureReservedIPAssociationCmdletName = "Remove-AzureReservedIPAssociation"; public const string AddAzureVirtualIPCmdletName = "Add-AzureVirtualIP"; public const string RemoveAzureVirtualIPCmdletName = "Remove-AzureVirtualIP"; // AzureRole & AzureRoleInstnace public const string GetAzureRoleCmdletName = "Get-AzureRole"; public const string SetAzureRoleCmdletName = "Set-AzureRole"; public const string GetAzureRoleInstanceCmdletName = "Get-AzureRoleInstance"; // AzureRoleSize public const string GetAzureRoleSizeCmdletName = "Get-AzureRoleSize"; // AzureService public const string NewAzureServiceCmdletName = "New-AzureService"; public const string GetAzureServiceCmdletName = "Get-AzureService"; public const string SetAzureServiceCmdletName = "Set-AzureService"; public const string RemoveAzureServiceCmdletName = "Remove-AzureService"; // AzureServiceAvailableExtension public const string GetAzureServiceAvailableExtensionCmdletName = "Get-AzureServiceAvailableExtension"; // AzureServiceExtension public const string NewAzureServiceExtensionConfigCmdletName = "New-AzureServiceExtensionConfig"; public const string SetAzureServiceExtensionCmdletName = "Set-AzureServiceExtension"; public const string GetAzureServiceExtensionCmdletName = "Get-AzureServiceExtension"; public const string RemoveAzureServiceExtensionCmdletName = "Remove-AzureServiceExtension"; // AzureServiceRemoteDesktopExtension public const string NewAzureServiceRemoteDesktopExtensionConfigCmdletName = "New-AzureServiceRemoteDesktopExtensionConfig"; public const string SetAzureServiceRemoteDesktopExtensionCmdletName = "Set-AzureServiceRemoteDesktopExtension"; public const string GetAzureServiceRemoteDesktopExtensionCmdletName = "Get-AzureServiceRemoteDesktopExtension"; public const string RemoveAzureServiceRemoteDesktopExtensionCmdletName = "Remove-AzureServiceRemoteDesktopExtension"; // AzureServiceDiagnosticExtension public const string NewAzureServiceDiagnosticsExtensionConfigCmdletName = "New-AzureServiceDiagnosticsExtensionConfig"; public const string SetAzureServiceDiagnosticsExtensionCmdletName = "Set-AzureServiceDiagnosticsExtension"; public const string GetAzureServiceDiagnosticsExtensionCmdletName = "Get-AzureServiceDiagnosticsExtension"; public const string RemoveAzureServiceDiagnosticsExtensionCmdletName = "Remove-AzureServiceDiagnosticsExtension"; // AzureSSHKey public const string NewAzureSSHKeyCmdletName = "New-AzureSSHKey"; // AzureStorageAccount public const string NewAzureStorageAccountCmdletName = "New-AzureStorageAccount"; public const string GetAzureStorageAccountCmdletName = "Get-AzureStorageAccount"; public const string SetAzureStorageAccountCmdletName = "Set-AzureStorageAccount"; public static string RemoveAzureStorageAccountCmdletName = "Remove-AzureStorageAccount"; //AzureDomainJoinExtension public const string NewAzureServiceDomainJoinExtensionConfig = "New-AzureServiceADDomainExtensionConfig"; public const string SetAzureServiceDomainJoinExtension = "Set-AzureServiceADDomainExtension"; public const string RemoveAzureServiceDomainJoinExtension = "Remove-AzureServiceADDomainExtension"; public const string GetAzureServiceDomainJoinExtension = "Get-AzureServiceADDomainExtension"; // AzureStorageKey public static string NewAzureStorageKeyCmdletName = "New-AzureStorageKey"; public static string GetAzureStorageKeyCmdletName = "Get-AzureStorageKey"; // AzureSubnet public static string GetAzureSubnetCmdletName = "Get-AzureSubnet"; public static string SetAzureSubnetCmdletName = "Set-AzureSubnet"; // AzureSubscription public const string GetAzureSubscriptionCmdletName = "Get-AzureSubscription"; public const string SetAzureSubscriptionCmdletName = "Set-AzureSubscription"; public const string SelectAzureSubscriptionCmdletName = "Select-AzureSubscription"; public const string RemoveAzureSubscriptionCmdletName = "Remove-AzureSubscription"; // AzureEnvironment public const string GetAzureEnvironmentCmdletName = "Get-AzureEnvironment"; public const string SetAzureEnvironmentCmdletName = "Set-AzureEnvironment"; // AzureVhd public static string AddAzureVhdCmdletName = "Add-AzureVhd"; public static string SaveAzureVhdCmdletName = "Save-AzureVhd"; // AzureVM public const string NewAzureVMCmdletName = "New-AzureVM"; public const string GetAzureVMCmdletName = "Get-AzureVM"; public const string UpdateAzureVMCmdletName = "Update-AzureVM"; public const string RemoveAzureVMCmdletName = "Remove-AzureVM"; public const string ExportAzureVMCmdletName = "Export-AzureVM"; public const string ImportAzureVMCmdletName = "Import-AzureVM"; public const string StartAzureVMCmdletName = "Start-AzureVM"; public const string StopAzureVMCmdletName = "Stop-AzureVM"; public const string RestartAzureVMCmdletName = "Restart-AzureVM"; // AzureVMConfig public const string NewAzureVMConfigCmdletName = "New-AzureVMConfig"; // AzureVMImage public const string AddAzureVMImageCmdletName = "Add-AzureVMImage"; public const string GetAzureVMImageCmdletName = "Get-AzureVMImage"; public const string RemoveAzureVMImageCmdletName = "Remove-AzureVMImage"; public const string SaveAzureVMImageCmdletName = "Save-AzureVMImage"; public const string UpdateAzureVMImageCmdletName = "Update-AzureVMImage"; // AzureVMSize public const string SetAzureVMSizeCmdletName = "Set-AzureVMSize"; // AzureVNetConfig & AzureVNetConnection public const string GetAzureVNetConfigCmdletName = "Get-AzureVNetConfig"; public const string SetAzureVNetConfigCmdletName = "Set-AzureVNetConfig"; public const string RemoveAzureVNetConfigCmdletName = "Remove-AzureVNetConfig"; public const string GetAzureVNetConnectionCmdletName = "Get-AzureVNetConnection"; // AzureVnetGateway & AzureVnetGatewayKey public const string NewAzureVNetGatewayCmdletName = "New-AzureVNetGateway"; public const string GetAzureVNetGatewayCmdletName = "Get-AzureVNetGateway"; public const string SetAzureVNetGatewayCmdletName = "Set-AzureVNetGateway"; public const string RemoveAzureVNetGatewayCmdletName = "Remove-AzureVNetGateway"; public const string GetAzureVNetGatewayKeyCmdletName = "Get-AzureVNetGatewayKey"; // AzureVNetSite public const string GetAzureVNetSiteCmdletName = "Get-AzureVNetSite"; // AzureWalkUpgradeDomain public const string SetAzureWalkUpgradeDomainCmdletName = "Set-AzureWalkUpgradeDomain"; public const string GetModuleCmdletName = "Get-Module"; public const string TestAzureNameCmdletName = "Test-AzureName"; public const string CopyAzureStorageBlobCmdletName = "Copy-AzureStorageBlob"; public static string SetAzureAclConfigCmdletName = "Set-AzureAclConfig"; public static string NewAzureAclConfigCmdletName = "New-AzureAclConfig"; public static string GetAzureAclConfigCmdletName = "Get-AzureAclConfig"; public static string SetAzureLoadBalancedEndpointCmdletName = "Set-AzureLoadBalancedEndpoint"; public const string ResetAzureRoleInstanceCmdletName = "ReSet-AzureRoleInstance"; //Static CA cmdlets public const string TestAzureStaticVNetIPCmdletName = "Test-AzureStaticVNetIP"; public const string SetAzureStaticVNetIPCmdletName = "Set-AzureStaticVNetIP"; public const string GetAzureStaticVNetIPCmdletName = "Get-AzureStaticVNetIP"; public const string RemoveAzureStaticVNetIPCmdletName = "Remove-AzureStaticVNetIP"; public const string GetAzureVMBGInfoExtensionCmdletName = "Get-AzureVMBGInfoExtension"; public const string SetAzureVMBGInfoExtensionCmdletName = "Set-AzureVMBGInfoExtension"; public const string RemoveAzureVMBGInfoExtensionCmdletName = "Remove-AzureVMBGInfoExtension"; // Generic Azure VM Extension cmdlets public const string GetAzureVMExtensionCmdletName = "Get-AzureVMExtension"; public const string SetAzureVMExtensionCmdletName = "Set-AzureVMExtension"; public const string RemoveAzureVMExtensionCmdletName = "Remove-AzureVMExtension"; public const string GetAzureVMAvailableExtensionCmdletName = "Get-AzureVMAvailableExtension"; public const string GetAzureVMExtensionConfigTemplateCmdletName = "Get-AzureVMExtensionConfigTemplate"; // VM Access Extesnion public const string GetAzureVMAccessExtensionCmdletName = "Get-AzureVMAccessExtension"; public const string SetAzureVMAccessExtensionCmdletName = "Set-AzureVMAccessExtension"; public const string RemoveAzureVMAccessExtensionCmdletName = "Remove-AzureVMAccessExtension"; // Custom script extension public const string SetAzureVMCustomScriptExtensionCmdletName = "Set-AzureVMCustomScriptExtension"; public const string GetAzureVMCustomScriptExtensionCmdletName = "Get-AzureVMCustomScriptExtension"; public const string RemoveAzureVMCustomScriptExtensionCmdletName = "Remove-AzureVMCustomScriptExtension"; public const string PaaSDiagnosticsExtensionName = "PaaSDiagnostics"; // VM Image Disk public const string GetAzureVMImageDiskConfigSetCmdletName = "Get-AzureVMImageDiskConfigSet"; public const string SetAzureVMImageDataDiskConfigCmdletName = "Set-AzureVMImageDataDiskConfig"; public const string SetAzureVMImageOSDiskConfigCmdletName = "Set-AzureVMImageOSDiskConfig"; public const string NewAzureVMImageDiskConfigSetCmdletName = "New-AzureVMImageDiskConfigSet"; //ILB public const string NewAzureInternalLoadBalancerConfigCmdletName = "New-AzureInternalLoadBalancerConfig"; public const string AddAzureInternalLoadBalancerCmdletName = "Add-AzureInternalLoadBalancer"; public const string GetAzureInternalLoadBalancerCmdletName = "Get-AzureInternalLoadBalancer"; public const string SetAzureInternalLoadBalancerCmdletName = "Set-AzureInternalLoadBalancer"; public const string RemoveAzureInternalLoadBalancerCmdletName = "Remove-AzureInternalLoadBalancer"; public const string SetAzurePublicIPCmdletName = "Set-AzurePublicIP"; public const string GetAzurePublicIPCmdletName = "Get-AzurePublicIP"; // NetworkInterface config public const string AddAzureNetworkInterfaceConfig = "Add-AzureNetworkInterfaceConfig"; public const string SetAzureNetworkInterfaceConfig = "Set-AzureNetworkInterfaceConfig"; public const string RemoveAzureNetworkInterfaceConfig = "Remove-AzureNetworkInterfaceConfig"; public const string GetAzureNetworkInterfaceConfig = "Get-AzureNetworkInterfaceConfig"; // SqlServer extension public const string SetAzureVMSqlServerExtensionCmdletName = "Set-AzureVMSqlServerExtension"; public const string GetAzureVMSqlServerExtensionCmdletName = "Get-AzureVMSqlServerExtension"; public const string RemoveAzureVMSqlServerExtensionCmdletName = "Remove-AzureVMSqlServerExtension"; #endregion private static ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); public static string GetUniqueShortName(string prefix = "", int length = 6, string suffix = "", bool includeDate = false) { string dateSuffix = ""; if (includeDate) { dateSuffix = string.Format("-{0}{1}", DateTime.Now.Year, DateTime.Now.DayOfYear); } return string.Format("{0}{1}{2}{3}", prefix, Guid.NewGuid().ToString("N").Substring(0, length), suffix, dateSuffix); } public static int MatchKeywords(string input, string[] keywords, bool exactMatch = true) { //returns -1 for no match, 0 for exact match, and a positive number for how many keywords are matched. int result = 0; if (string.IsNullOrEmpty(input) || keywords.Length == 0) return -1; foreach (string keyword in keywords) { //For whole word match, modify pattern to be "\b{0}\b" if (!string.IsNullOrEmpty(keyword) && Regex.IsMatch(input, string.Format(@"{0}", Regex.Escape(keyword)), RegexOptions.IgnoreCase)) { result++; } } if (result == keywords.Length) { return 0; } else if (result == 0) { return -1; } else { if (exactMatch) { return -1; } else { return result; } } } public static bool GetAzureVMAndWaitForReady(string serviceName, string vmName,int waitTime, int maxWaitTime ) { Console.WriteLine("Waiting for the vm {0} to reach \"ReadyRole\" "); DateTime startTime = DateTime.Now; DateTime MaxEndTime = startTime.AddMilliseconds(maxWaitTime); while (true) { Console.WriteLine("Getting vm '{0}' details:",vmName); var vmRoleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Console.WriteLine("Current status of the VM is {0} ", vmRoleContext.InstanceStatus); if (vmRoleContext.InstanceStatus == "ReadyRole") { Console.WriteLine("Instance status reached expected ReadyRole state. Exiting wait."); return true; } else { if (DateTime.Compare(DateTime.Now, MaxEndTime) > 0) { Console.WriteLine("Maximum wait time reached and instance status didnt reach \"ReadyRole\" state. Exiting wait. "); return false; } else { Console.WriteLine("Waiting for {0} seconds for the {1} status to be ReadyRole", waitTime / 1000, vmName); Thread.Sleep(waitTime); } } } } public static bool PrintAndCompareDeployment (DeploymentInfoContext deployment, string serviceName, string deploymentName, string deploymentLabel, string slot, string status, int instanceCount) { Console.WriteLine("ServiceName:{0}, DeploymentID: {1}, Uri: {2}", deployment.ServiceName, deployment.DeploymentId, deployment.Url.AbsoluteUri); Console.WriteLine("Name - {0}, Label - {1}, Slot - {2}, Status - {3}", deployment.DeploymentName, deployment.Label, deployment.Slot, deployment.Status); Console.WriteLine("RoleInstance: {0}", deployment.RoleInstanceList.Count); foreach (var instance in deployment.RoleInstanceList) { Console.WriteLine("InstanceName - {0}, InstanceStatus - {1}", instance.InstanceName, instance.InstanceStatus); } Assert.AreEqual(deployment.ServiceName, serviceName); Assert.AreEqual(deployment.DeploymentName, deploymentName); Assert.AreEqual(deployment.Label, deploymentLabel); Assert.AreEqual(deployment.Slot, slot); if (status != null) { Assert.AreEqual(deployment.Status, status); } Assert.AreEqual(deployment.RoleInstanceList.Count, instanceCount); Assert.IsNotNull(deployment.LastModifiedTime); Assert.IsNotNull(deployment.CreatedTime); return true; } // CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name' public static bool CheckRemove<Arg, Ret>(Func<Arg, Ret> fn, Arg name) { try { fn(name); Console.WriteLine("{0} still exists!", name); return false; } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("{0} does not exist.", name); return true; } else { Console.WriteLine("Error: {0}", e.ToString()); return false; } } } public static PersistentVM CreateVMObjectWithDataDiskSubnetAndAvailibilitySet(string vmName, OS os, string username, string password, string subnet) { string disk1 = "Disk1"; int diskSize = 30; string availabilitySetName = Utilities.GetUniqueShortName("AvailSet"); string img = string.Empty; bool isWindowsOs = false; if (os == OS.Windows) { img = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Windows" }, false); isWindowsOs = true; } else { img = vmPowershellCmdlets.GetAzureVMImageName(new[] { "Linux" }, false); isWindowsOs = false; } PersistentVM vm = Utilities.CreateIaaSVMObject(vmName, InstanceSize.Small, img, isWindowsOs, username, password); AddAzureDataDiskConfig azureDataDiskConfigInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize, disk1, 0, HostCaching.ReadWrite.ToString()); azureDataDiskConfigInfo1.Vm = vm; vm = vmPowershellCmdlets.SetAzureSubnet(vm, new string[] { subnet }); vm = vmPowershellCmdlets.SetAzureAvailabilitySet(availabilitySetName, vm); return vm; } // CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name' public static bool CheckRemove<Arg1, Arg2, Ret>(Func<Arg1, Arg2, Ret> fn, Arg1 name1, Arg2 name2) { try { fn(name1, name2); Console.WriteLine("{0}, {1} still exist!", name1, name2); return false; } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("{0}, {1} is successfully removed", name1, name2); return true; } else { Console.WriteLine("Error: {0}", e.ToString()); return false; } } } // CheckRemove checks if 'fn(name)' exists. 'fn(name)' is usually 'Get-AzureXXXXX name' public static bool CheckRemove<Arg1, Arg2, Arg3, Ret>(Func<Arg1, Arg2, Arg3, Ret> fn, Arg1 name1, Arg2 name2, Arg3 name3) { try { fn(name1, name2, name3); Console.WriteLine("{0}, {1}, {2} still exist!", name1, name2, name3); return false; } catch (Exception e) { if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("{0}, {1}, {2} is successfully removed", name1, name2, name3); return true; } else { Console.WriteLine("Error: {0}", e.ToString()); return false; } } } public static BlobHandle GetBlobHandle(string blob, string key) { BlobUri blobPath; Assert.IsTrue(BlobUri.TryParseUri(new Uri(blob), out blobPath)); return new BlobHandle(blobPath, key); } /// <summary> /// Retry the given action until success or timed out. /// </summary> /// <param name="act">the action</param> /// <param name="errorMessage">retry for this error message</param> /// <param name="maxTry">the max number of retries</param> /// <param name="intervalSeconds">the interval between retries</param> public static void RetryActionUntilSuccess(Action act, string errorMessage, int maxTry, int intervalSeconds) { int i = 0; while (i < maxTry) { try { act(); return; } catch (Exception e) { if (e.ToString().Contains(errorMessage) || (e.InnerException != null && e.InnerException.ToString().Contains(errorMessage))) { i++; if (i == maxTry) { Console.WriteLine("Max number of retry is reached: {0}", errorMessage); throw; } Console.WriteLine("{0} error occurs! retrying ...", errorMessage); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } Thread.Sleep(TimeSpan.FromSeconds(intervalSeconds)); continue; } else { Console.WriteLine(e); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } throw; } } } } /// <summary> /// Retry the given action until success or timed out. /// </summary> /// <param name="act">the action</param> /// <param name="errorMessages">retry for this error messages</param> /// <param name="maxTry">the max number of retries</param> /// <param name="intervalSeconds">the interval between retries</param> public static void RetryActionUntilSuccess(Action act, string[] errorMessages, int maxTry, int intervalSeconds) { int i = 0; while (i < maxTry) { try { act(); return; } catch (Exception e) { bool found = false; foreach (var errorMessage in errorMessages) { if (e.ToString().Contains(errorMessage) || (e.InnerException != null && e.InnerException.ToString().Contains(errorMessage))) { found = true; i++; if (i == maxTry) { Console.WriteLine("Max number of retry is reached: {0}", errorMessage); throw; } Console.WriteLine("{0} error occurs! retrying ...", errorMessage); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } Thread.Sleep(TimeSpan.FromSeconds(intervalSeconds)); break; } } if (!found) { Console.WriteLine(e); if (e.InnerException != null) { Console.WriteLine(e.InnerException); } throw; } } } } /// <summary> /// This method verifies if a given error occurs during the action. Otherwise, it throws. /// </summary> /// <param name="act">Action item</param> /// <param name="errorMessage">Required error message</param> public static void VerifyFailure(Action act, string errorMessage) { try { act(); Assert.Fail("Should have failed, but it succeeded!!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } if (e.ToString().Contains(errorMessage)) { Console.WriteLine("This failure is expected: {0}", e.InnerException); } else { Console.WriteLine(e); throw; } } } /// <summary> /// /// </summary> /// <param name="act"></param> /// <param name="errorMessage"></param> public static void TryAndIgnore(Action act, string errorMessage) { try { act(); } catch (Exception e) { if (e.ToString().Contains(errorMessage)) { Console.WriteLine("Ignoring exception: {0}", e.InnerException); } else { Console.WriteLine(e); throw; } } } public static X509Certificate2 InstallCert(string certFile, StoreLocation location = StoreLocation.CurrentUser, StoreName name = StoreName.My) { var cert = new X509Certificate2(certFile); var certStore = new X509Store(name, location); certStore.Open(OpenFlags.ReadWrite); certStore.Add(cert); certStore.Close(); Console.WriteLine("Cert, {0}, is installed.", cert.Thumbprint); return cert; } public static void UninstallCert(X509Certificate2 cert, StoreLocation location, StoreName name) { try { X509Store certStore = new X509Store(name, location); certStore.Open(OpenFlags.ReadWrite); certStore.Remove(cert); certStore.Close(); Console.WriteLine("Cert, {0}, is uninstalled.", cert.Thumbprint); } catch (Exception e) { Console.WriteLine("Error during uninstalling the cert: {0}", e.ToString()); throw; } } public static X509Certificate2 CreateCertificate(string password, string issuer = "CN=Microsoft Azure Powershell Test", string friendlyName = "PSTest") { var keyCreationParameters = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowExport, KeyCreationOptions = CngKeyCreationOptions.None, KeyUsage = CngKeyUsages.AllUsages, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider }; keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None)); CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters); var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer)) { TakeOwnershipOfKey = true }; X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams); key = null; cert.FriendlyName = friendlyName; byte[] bytes = cert.Export(X509ContentType.Pfx, password); X509Certificate2 returnCert = new X509Certificate2(); returnCert.Import(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return returnCert; } public static SecureString convertToSecureString(string str) { SecureString secureStr = new SecureString(); foreach (char c in str) { secureStr.AppendChar(c); } return secureStr; } public static string FindSubstring(string givenStr, char givenChar, int i) { if (i > 0) { return FindSubstring(givenStr.Substring(givenStr.IndexOf(givenChar) + 1), givenChar, i - 1); } else { return givenStr; } } public static bool CompareDateTime(DateTime expectedDate, string givenDate) { DateTime resultExpDate = DateTime.Parse(givenDate); bool result = (resultExpDate.Day == expectedDate.Day); result &= (resultExpDate.Month == expectedDate.Month); result &= (resultExpDate.Year == expectedDate.Year); return result; } public static string GetInnerXml(string xmlString, string tag) { string removedHeader = "<" + Utilities.FindSubstring(xmlString, '<', 2); byte[] encodedString = Encoding.UTF8.GetBytes(xmlString); MemoryStream stream = new MemoryStream(encodedString); stream.Flush(); stream.Position = 0; XmlDocument xml = new XmlDocument(); xml.Load(stream); return xml.GetElementsByTagName(tag)[0].InnerXml; } public static void CompareWadCfg(string wadcfg, XmlDocument daconfig) { if (string.IsNullOrWhiteSpace(wadcfg)) { Assert.IsNull(wadcfg); } else { string innerXml = daconfig.InnerXml; StringAssert.Contains(Utilities.FindSubstring(innerXml, '<', 2), Utilities.FindSubstring(wadcfg, '<', 2)); } } static public string GenerateSasUri(string blobStorageEndpointFormat, string storageAccount, string storageAccountKey, string blobContainer, string vhdName, int hours = 10, bool read = true, bool write = true, bool delete = true, bool list = true) { string destinationSasUri = string.Format(@blobStorageEndpointFormat, storageAccount) + string.Format("/{0}/{1}", blobContainer, vhdName); var destinationBlob = new CloudPageBlob(new Uri(destinationSasUri), new StorageCredentials(storageAccount, storageAccountKey)); SharedAccessBlobPermissions permission = 0; permission |= (read) ? SharedAccessBlobPermissions.Read : 0; permission |= (write) ? SharedAccessBlobPermissions.Write : 0; permission |= (delete) ? SharedAccessBlobPermissions.Delete : 0; permission |= (list) ? SharedAccessBlobPermissions.List : 0; var policy = new SharedAccessBlobPolicy() { Permissions = permission, SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(hours) }; string destinationBlobToken = destinationBlob.GetSharedAccessSignature(policy); return (destinationSasUri + destinationBlobToken); } static public void RecordTimeTaken(ref DateTime prev) { var period = DateTime.Now - prev; Console.WriteLine("{0} minutes {1} seconds and {2} ms passed...", period.Minutes.ToString(), period.Seconds.ToString(), period.Milliseconds.ToString()); prev = DateTime.Now; } public static void PrintContext<T>(T obj) { PrintTypeContents(typeof(T), obj); } public static void PrintContextAndItsBase<T>(T obj) { Type type = typeof(T); PrintTypeContents(type, obj); PrintTypeContents(type.BaseType, obj); } private static void PrintTypeContents<T>(Type type, T obj) { foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null)); } else if (typeName.Contains("Boolean")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null).ToString()); } else { Console.WriteLine("This type is not printed: {0}", typeName); } } } public static void PrintCompleteContext<T>(T obj) { Type type = typeof(T); foreach (PropertyInfo property in type.GetProperties()) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null)); } else if (typeName.Contains("Boolean")) { Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null).ToString()); } else { Console.WriteLine("This type is not printed: {0}", typeName); } } } public static bool validateHttpUri(string uri) { Uri uriResult; return Uri.TryCreate(uri, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp; } public static PersistentVM CreateIaaSVMObject(string vmName,InstanceSize size,string imageName,bool isWindows = true,string username = null,string password = null,bool disableGuestAgent = false) { //Create an IaaS VM var azureVMConfigInfo = new AzureVMConfigInfo(vmName, size.ToString(), imageName); AzureProvisioningConfigInfo azureProvisioningConfig = null; if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(username)) { azureProvisioningConfig = new AzureProvisioningConfigInfo(isWindows ? OS.Windows:OS.Linux, username, password,disableGuestAgent); } var persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); return vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); } public static void PrintHeader(string title) { if (title.Length > 100) { Console.WriteLine(string.Format("{0}{1}{0}", "> > >", title)); } else { int headerLineLength = 100; Console.WriteLine(); Console.WriteLine(string.Format("{0}{1}{0}", new String('>', (headerLineLength - title.Length) / 2), title)); } } public static void PrintFooter(string title) { if (title.Length > 100) { Console.WriteLine(string.Format("{0}{1}{0}", "< < <", title)); } else { int headerLineLength = 100; string completed = ": Completed"; Console.WriteLine(string.Format("{0}{1}{0}", new String('<', (headerLineLength - (title.Length + completed.Length)) / 2), title + completed)); } } public static void PrintSeperationLineStart(string title,char seperator) { int headerLineLength = 100; string completed = ": Completed"; Console.WriteLine(string.Format("{0}{1}{0}", new String(seperator, (headerLineLength - (title.Length + completed.Length)) / 2), title + completed)); } public static void PrintSeperationLineEnd(string title,string successMessage, char seperator) { int headerLineLength = 100; Console.WriteLine(string.Format("{0}{1}{0}", new String(seperator, (headerLineLength - (title.Length + successMessage.Length)) / 2), title + successMessage)); } public static string ConvertToJsonArray(string[] values) { List<string> files = new List<string>(); foreach (string s in values) { files.Add(string.Format("'{0}'", s)); } return string.Join(",", files); } public static string GetSASUri(string blobUrlRoot,string storageAccoutnName,string primaryKey, string container, string filename, TimeSpan persmissionDuration,SharedAccessBlobPermissions permissionType) { // Set the destination string httpsBlobUrlRoot = string.Format("https:{0}", blobUrlRoot.Substring(blobUrlRoot.IndexOf('/'))); string vhdDestUri = httpsBlobUrlRoot + string.Format("{0}/{1}", container, filename); var destinationBlob = new CloudPageBlob(new Uri(vhdDestUri), new StorageCredentials(storageAccoutnName, primaryKey)); var policy2 = new SharedAccessBlobPolicy() { Permissions = permissionType, SharedAccessExpiryTime = DateTime.UtcNow.Add(persmissionDuration) }; var destinationBlobToken2 = destinationBlob.GetSharedAccessSignature(policy2); vhdDestUri += destinationBlobToken2; return vhdDestUri; } public static PersistentVM GetAzureVM(string vmName, string serviceName) { var vmroleContext = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); return vmroleContext.VM; } public static void LogAssert(Action method,string actionTitle) { Console.Write(actionTitle); method(); Console.WriteLine(": verified"); } public static void ExecuteAndLog(Action method,string actionTitle) { PrintHeader(actionTitle); method(); PrintFooter(actionTitle); } public static VirtualMachineExtensionImageContext GetAzureVMExtenionInfo(string extensionName) { List<VirtualMachineExtensionImageContext> extensionInfo = new List<VirtualMachineExtensionImageContext>(); extensionInfo.AddRange(vmPowershellCmdlets.GetAzureVMAvailableExtension()); return extensionInfo.Find(c => c.ExtensionName.Equals(extensionName)); } } }
using Microsoft.Xna.Framework; // concrete implementations of all tweenable types namespace Nez.Tweens { public class IntTween : Tween<int> { public static IntTween Create() { return TweenManager.CacheIntTweens ? Pool<IntTween>.Obtain() : new IntTween(); } public IntTween() { } public IntTween(ITweenTarget<int> target, int to, float duration) { Initialize(target, to, duration); } public override ITween<int> SetIsRelative() { _isRelative = true; _toValue += _fromValue; return this; } protected override void UpdateValue() { _target.SetTweenedValue((int) Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheIntTweens) Pool<IntTween>.Free(this); } } public class FloatTween : Tween<float> { public static FloatTween Create() { return TweenManager.CacheFloatTweens ? Pool<FloatTween>.Obtain() : new FloatTween(); } public FloatTween() { } public FloatTween(ITweenTarget<float> target, float to, float duration) { Initialize(target, to, duration); } public override ITween<float> SetIsRelative() { _isRelative = true; _toValue += _fromValue; return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheFloatTweens) Pool<FloatTween>.Free(this); } } public class Vector2Tween : Tween<Vector2> { public static Vector2Tween Create() { return TweenManager.CacheVector2Tweens ? Pool<Vector2Tween>.Obtain() : new Vector2Tween(); } public Vector2Tween() { } public Vector2Tween(ITweenTarget<Vector2> target, Vector2 to, float duration) { Initialize(target, to, duration); } public override ITween<Vector2> SetIsRelative() { _isRelative = true; _toValue += _fromValue; return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheVector2Tweens) Pool<Vector2Tween>.Free(this); } } public class Vector3Tween : Tween<Vector3> { public static Vector3Tween Create() { return TweenManager.CacheVector3Tweens ? Pool<Vector3Tween>.Obtain() : new Vector3Tween(); } public Vector3Tween() { } public Vector3Tween(ITweenTarget<Vector3> target, Vector3 to, float duration) { Initialize(target, to, duration); } public override ITween<Vector3> SetIsRelative() { _isRelative = true; _toValue += _fromValue; return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheVector3Tweens) Pool<Vector3Tween>.Free(this); } } public class Vector4Tween : Tween<Vector4> { public static Vector4Tween Create() { return TweenManager.CacheVector4Tweens ? Pool<Vector4Tween>.Obtain() : new Vector4Tween(); } public Vector4Tween() { } public Vector4Tween(ITweenTarget<Vector4> target, Vector4 to, float duration) { Initialize(target, to, duration); } public override ITween<Vector4> SetIsRelative() { _isRelative = true; _toValue += _fromValue; return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheVector4Tweens) Pool<Vector4Tween>.Free(this); } } public class QuaternionTween : Tween<Quaternion> { public static QuaternionTween Create() { return TweenManager.CacheQuaternionTweens ? Pool<QuaternionTween>.Obtain() : new QuaternionTween(); } public QuaternionTween() { } public QuaternionTween(ITweenTarget<Quaternion> target, Quaternion to, float duration) { Initialize(target, to, duration); } public override ITween<Quaternion> SetIsRelative() { _isRelative = true; _toValue *= _fromValue; return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheQuaternionTweens) Pool<QuaternionTween>.Free(this); } } public class ColorTween : Tween<Color> { public static ColorTween Create() { return TweenManager.CacheColorTweens ? Pool<ColorTween>.Obtain() : new ColorTween(); } public ColorTween() { } public ColorTween(ITweenTarget<Color> target, Color to, float duration) { Initialize(target, to, duration); } public override ITween<Color> SetIsRelative() { _isRelative = true; _toValue.R += _fromValue.R; _toValue.G += _fromValue.G; _toValue.B += _fromValue.B; _toValue.A += _fromValue.A; return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheColorTweens) Pool<ColorTween>.Free(this); } } public class RectangleTween : Tween<Rectangle> { public static RectangleTween Create() { return TweenManager.CacheRectTweens ? Pool<RectangleTween>.Obtain() : new RectangleTween(); } public RectangleTween() { } public RectangleTween(ITweenTarget<Rectangle> target, Rectangle to, float duration) { Initialize(target, to, duration); } public override ITween<Rectangle> SetIsRelative() { _isRelative = true; _toValue = new Rectangle ( _toValue.X + _fromValue.X, _toValue.Y + _fromValue.Y, _toValue.Width + _fromValue.Width, _toValue.Height + _fromValue.Height ); return this; } protected override void UpdateValue() { _target.SetTweenedValue(Lerps.Ease(_easeType, _fromValue, _toValue, _elapsedTime, _duration)); } public override void RecycleSelf() { base.RecycleSelf(); if (_shouldRecycleTween && TweenManager.CacheRectTweens) Pool<RectangleTween>.Free(this); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; namespace StructureMap { internal static class ReflectionHelper { public static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expression) { var memberExpression = getMemberExpression(expression); return (PropertyInfo) memberExpression.Member; } public static PropertyInfo GetProperty<TModel, T>(Expression<Func<TModel, T>> expression) { var memberExpression = getMemberExpression(expression); return (PropertyInfo) memberExpression.Member; } public static MemberInfo GetMember<T>(Expression<Func<T, object>> expression) { var memberExpression = getMemberExpression(expression); return memberExpression.Member; } public static MemberInfo GetMember<TModel, T>(Expression<Func<TModel, T>> expression) { var memberExpression = getMemberExpression(expression); return memberExpression.Member; } private static MemberExpression getMemberExpression<TModel, T>(Expression<Func<TModel, T>> expression) { MemberExpression memberExpression = null; if (expression.Body.NodeType == ExpressionType.Convert) { var body = (UnaryExpression) expression.Body; memberExpression = body.Operand as MemberExpression; } else if (expression.Body.NodeType == ExpressionType.MemberAccess) { memberExpression = expression.Body as MemberExpression; } if (memberExpression == null) throw new ArgumentException("Not a member access", "member"); return memberExpression; } public static MethodInfo GetMethod<T>(Expression<Func<T, object>> expression) { var methodCall = expression.Body is UnaryExpression ? (MethodCallExpression) ((UnaryExpression) expression.Body).Operand : (MethodCallExpression) expression.Body; return methodCall.Method; } public static MethodInfo GetMethod<T, U>(Expression<Func<T, U>> expression) { var methodCall = (MethodCallExpression) expression.Body; return methodCall.Method; } public static MethodInfo GetMethod<T, U, V>(Expression<Func<T, U, V>> expression) { var methodCall = (MethodCallExpression) expression.Body; return methodCall.Method; } } /// <summary> /// Provides virtual methods that can be used by subclasses to parse an expression tree. /// </summary> /// <remarks> /// This class actually already exists in the System.Core assembly...as an internal class. /// I can only speculate as to why it is internal, but it is obviously much too dangerous /// for anyone outside of Microsoft to be using... /// </remarks> [DebuggerStepThrough, DebuggerNonUserCode] public abstract class ExpressionVisitorBase { public virtual Expression Visit(Expression exp) { if (exp == null) return exp; switch (exp.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: return VisitUnary((UnaryExpression) exp); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: return VisitBinary((BinaryExpression) exp); case ExpressionType.TypeIs: return VisitTypeIs((TypeBinaryExpression) exp); case ExpressionType.Conditional: return VisitConditional((ConditionalExpression) exp); case ExpressionType.Constant: return VisitConstant((ConstantExpression) exp); case ExpressionType.Parameter: return VisitParameter((ParameterExpression) exp); case ExpressionType.MemberAccess: return VisitMemberAccess((MemberExpression) exp); case ExpressionType.Call: return VisitMethodCall((MethodCallExpression) exp); case ExpressionType.Lambda: return VisitLambda((LambdaExpression) exp); case ExpressionType.New: return VisitNew((NewExpression) exp); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return VisitNewArray((NewArrayExpression) exp); case ExpressionType.Invoke: return VisitInvocation((InvocationExpression) exp); case ExpressionType.MemberInit: return VisitMemberInit((MemberInitExpression) exp); case ExpressionType.ListInit: return VisitListInit((ListInitExpression) exp); default: throw new NotSupportedException(String.Format("Unhandled expression type: '{0}'", exp.NodeType)); } } protected virtual MemberBinding VisitBinding(MemberBinding binding) { switch (binding.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment) binding); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding) binding); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding) binding); default: throw new NotSupportedException(string.Format("Unhandled binding type '{0}'", binding.BindingType)); } } protected virtual ElementInit VisitElementInitializer(ElementInit initializer) { var arguments = VisitList(initializer.Arguments); if (arguments != initializer.Arguments) { return Expression.ElementInit(initializer.AddMethod, arguments); } return initializer; } protected virtual Expression VisitUnary(UnaryExpression u) { var operand = Visit(u.Operand); if (operand != u.Operand) { return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method); } return u; } protected virtual Expression VisitBinary(BinaryExpression b) { var left = Visit(b.Left); var right = Visit(b.Right); var conversion = Visit(b.Conversion); if (left != b.Left || right != b.Right || conversion != b.Conversion) { if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null) return Expression.Coalesce(left, right, conversion as LambdaExpression); else return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method); } return b; } protected virtual Expression VisitTypeIs(TypeBinaryExpression b) { var expr = Visit(b.Expression); if (expr != b.Expression) { return Expression.TypeIs(expr, b.TypeOperand); } return b; } protected virtual Expression VisitConstant(ConstantExpression c) { return c; } protected virtual Expression VisitConditional(ConditionalExpression c) { var test = Visit(c.Test); var ifTrue = Visit(c.IfTrue); var ifFalse = Visit(c.IfFalse); if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse) { return Expression.Condition(test, ifTrue, ifFalse); } return c; } protected virtual Expression VisitParameter(ParameterExpression p) { return p; } protected virtual Expression VisitMemberAccess(MemberExpression m) { var exp = Visit(m.Expression); if (exp != m.Expression) { return Expression.MakeMemberAccess(exp, m.Member); } return m; } protected virtual Expression VisitMethodCall(MethodCallExpression m) { var obj = Visit(m.Object); IEnumerable<Expression> args = VisitList(m.Arguments); if (obj != m.Object || args != m.Arguments) { return Expression.Call(obj, m.Method, args); } return m; } protected virtual ReadOnlyCollection<Expression> VisitList(ReadOnlyCollection<Expression> original) { List<Expression> list = null; for (int i = 0, n = original.Count; i < n; i++) { var p = Visit(original[i]); if (list != null) { list.Add(p); } else if (p != original[i]) { list = new List<Expression>(n); for (var j = 0; j < i; j++) { list.Add(original[j]); } list.Add(p); } } if (list != null) return new ReadOnlyCollection<Expression>(list); return original; } protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment) { var e = Visit(assignment.Expression); if (e != assignment.Expression) { return Expression.Bind(assignment.Member, e); } return assignment; } protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) { var bindings = VisitBindingList(binding.Bindings); if (bindings != binding.Bindings) { return Expression.MemberBind(binding.Member, bindings); } return binding; } protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding) { var initializers = VisitElementInitializerList(binding.Initializers); if (initializers != binding.Initializers) { return Expression.ListBind(binding.Member, initializers); } return binding; } protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original) { List<MemberBinding> list = null; for (int i = 0, n = original.Count; i < n; i++) { var b = VisitBinding(original[i]); if (list != null) { list.Add(b); } else if (b != original[i]) { list = new List<MemberBinding>(n); for (var j = 0; j < i; j++) { list.Add(original[j]); } list.Add(b); } } if (list != null) return list; return original; } protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original) { List<ElementInit> list = null; for (int i = 0, n = original.Count; i < n; i++) { var init = VisitElementInitializer(original[i]); if (list != null) { list.Add(init); } else if (init != original[i]) { list = new List<ElementInit>(n); for (var j = 0; j < i; j++) { list.Add(original[j]); } list.Add(init); } } if (list != null) return list; return original; } protected virtual Expression VisitLambda(LambdaExpression lambda) { var body = Visit(lambda.Body); if (body != lambda.Body) { return Expression.Lambda(lambda.Type, body, lambda.Parameters); } return lambda; } protected virtual NewExpression VisitNew(NewExpression nex) { IEnumerable<Expression> args = VisitList(nex.Arguments); if (args != nex.Arguments) { if (nex.Members != null) return Expression.New(nex.Constructor, args, nex.Members); else return Expression.New(nex.Constructor, args); } return nex; } protected virtual Expression VisitMemberInit(MemberInitExpression init) { var n = VisitNew(init.NewExpression); var bindings = VisitBindingList(init.Bindings); if (n != init.NewExpression || bindings != init.Bindings) { return Expression.MemberInit(n, bindings); } return init; } protected virtual Expression VisitListInit(ListInitExpression init) { var n = VisitNew(init.NewExpression); var initializers = VisitElementInitializerList(init.Initializers); if (n != init.NewExpression || initializers != init.Initializers) { return Expression.ListInit(n, initializers); } return init; } protected virtual Expression VisitNewArray(NewArrayExpression na) { IEnumerable<Expression> exprs = VisitList(na.Expressions); if (exprs != na.Expressions) { if (na.NodeType == ExpressionType.NewArrayInit) { return Expression.NewArrayInit(na.Type.GetElementType(), exprs); } else { return Expression.NewArrayBounds(na.Type.GetElementType(), exprs); } } return na; } protected virtual Expression VisitInvocation(InvocationExpression iv) { IEnumerable<Expression> args = VisitList(iv.Arguments); var expr = Visit(iv.Expression); if (args != iv.Arguments || expr != iv.Expression) { return Expression.Invoke(expr, args); } return iv; } } internal class ConstructorFinderVisitor : ExpressionVisitorBase { private ConstructorInfo _constructor; public ConstructorInfo Constructor { get { return _constructor; } } protected override NewExpression VisitNew(NewExpression nex) { _constructor = nex.Constructor; return base.VisitNew(nex); } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using UnityEngine; using UnityEditor.ShaderGraph; namespace UnityEditor.Graphing.UnitTests { [TestFixture] public class BaseMaterialGraphTests { [OneTimeSetUp] public void RunBeforeAnyTests() { Debug.unityLogger.logHandler = new ConsoleLogHandler(); } [Test] public void TestCanCreateBaseMaterialGraph() { var graph = new GraphData(); Assert.AreEqual(0, graph.edges.Count()); Assert.AreEqual(0, graph.GetNodes<AbstractMaterialNode>().Count()); } [Test] public void TestCanAddNodeToBaseMaterialGraph() { var graph = new GraphData(); var node = new TestNode(); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.AreEqual("Test Node", graph.GetNodes<AbstractMaterialNode>().FirstOrDefault().name); Assert.AreEqual(graph, node.owner); } [Test] public void TestCanRemoveNodeFromBaseMaterialGraph() { var graph = new GraphData(); var node = new TestNode(); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); graph.RemoveNode(graph.GetNodes<AbstractMaterialNode>().FirstOrDefault()); Assert.AreEqual(0, graph.GetNodes<AbstractMaterialNode>().Count()); } [Test] public void TestCanModifyNodeDrawState() { var node = new TestNode(); node.name = "Test Node"; var drawState = node.drawState; var newPos = new Rect(10, 10, 0, 0); drawState.position = newPos; drawState.expanded = false; node.drawState = drawState; Assert.AreEqual(drawState, node.drawState); Assert.AreEqual(newPos, node.drawState.position); Assert.IsFalse(node.drawState.expanded); } class SetErrorNode : TestNode { public void SetError() { hasError = true; } public void ClearError() { hasError = false; } } [Test] public void TestChildClassCanModifyErrorState() { var node = new SetErrorNode(); node.SetError(); Assert.IsTrue(node.hasError); node.ClearError(); Assert.IsFalse(node.hasError); } [Test] public void TestNodeGUIDCanBeRewritten() { var node = new TestNode(); var guid = node.guid; var newGuid = node.RewriteGuid(); Assert.AreNotEqual(guid, newGuid); } class TestableNode : TestNode { public const int Input0 = 0; public const int Input1 = 1; public const int Input2 = 2; public const int Output0 = 3; public const int Output1 = 4; public const int Output2 = 5; public TestableNode() { AddSlot(new TestSlot(Input0, "Input", SlotType.Input)); AddSlot(new TestSlot(Input1, "Input", SlotType.Input)); AddSlot(new TestSlot(Input2, "Input", SlotType.Input)); AddSlot(new TestSlot(Output0, "Output", SlotType.Output)); AddSlot(new TestSlot(Output1, "Output", SlotType.Output)); AddSlot(new TestSlot(Output2, "Output", SlotType.Output)); } } [Test] public void TestRemoveNodeFromBaseMaterialGraphCleansEdges() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); var edge = graph.edges.FirstOrDefault(); Assert.AreEqual(createdEdge, edge); graph.RemoveNode(outputNode); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.AreEqual(0, graph.edges.Count()); Assert.AreEqual(inputNode, graph.GetNodes<AbstractMaterialNode>().FirstOrDefault()); } private class NoDeleteNode : TestNode { public override bool canDeleteNode { get { return false; } } } [Test] public void TestCanNotRemoveNoDeleteNodeFromBaseMaterialGraph() { var graph = new GraphData(); var node = new NoDeleteNode(); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.Catch<InvalidOperationException>(() => graph.RemoveNode(node)); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); } private class OnEnableNode : TestNode, IOnAssetEnabled { public bool called = false; public void OnEnable() { called = true; } } [Test] public void TestSerializedGraphDelegatesOnEnableCalls() { var graph = new GraphData(); var node = new OnEnableNode(); node.name = "Test Node"; graph.AddNode(node); Assert.IsFalse(node.called); graph.OnEnable(); Assert.IsTrue(node.called); } [Test] public void TestCanFindNodeInBaseMaterialGraph() { var graph = new GraphData(); var node = new TestNode(); graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.IsNotNull(graph.GetNodeFromGuid(node.guid)); Assert.IsNull(graph.GetNodeFromGuid(Guid.NewGuid())); } [Test] public void TestCanAddSlotToTestNode() { var graph = new GraphData(); var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output)); node.AddSlot(new TestSlot(1, "input", SlotType.Input)); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault(); Assert.AreEqual(1, found.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetInputSlots<ISlot>().FirstOrDefault().id); Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count()); Assert.AreEqual(0, found.GetOutputSlots<ISlot>().FirstOrDefault().id); Assert.AreEqual(2, found.GetSlots<ISlot>().Count()); } [Test] public void TestCanNotAddNullSlotToTestNode() { var node = new TestNode(); Assert.Throws<ArgumentException>(() => node.AddSlot(null)); } [Test] public void TestCanRemoveSlotFromTestNode() { var graph = new GraphData(); var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output)); node.AddSlot(new TestSlot(1, "input", SlotType.Input)); graph.AddNode(node); Assert.AreEqual(2, node.GetSlots<ISlot>().Count()); Assert.AreEqual(1, node.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, node.GetOutputSlots<ISlot>().Count()); node.RemoveSlot(1); Assert.AreEqual(1, node.GetSlots<ISlot>().Count()); Assert.AreEqual(0, node.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, node.GetOutputSlots<ISlot>().Count()); } [Test] public void TestCanRemoveSlotsWithNonMathingNameFromTestNode() { var graph = new GraphData(); var node = new TestableNode(); graph.AddNode(node); Assert.AreEqual(6, node.GetSlots<ISlot>().Count()); Assert.AreEqual(3, node.GetInputSlots<ISlot>().Count()); Assert.AreEqual(3, node.GetOutputSlots<ISlot>().Count()); node.RemoveSlotsNameNotMatching(new[] {TestableNode.Input1}); Assert.AreEqual(1, node.GetSlots<ISlot>().Count()); Assert.AreEqual(1, node.GetInputSlots<ISlot>().Count()); Assert.AreEqual(0, node.GetOutputSlots<ISlot>().Count()); Assert.IsNull(node.FindInputSlot<ISlot>(TestableNode.Input0)); Assert.IsNotNull(node.FindInputSlot<ISlot>(TestableNode.Input1)); Assert.IsNull(node.FindInputSlot<ISlot>(TestableNode.Input2)); } [Test] public void TestCanNotAddDuplicateSlotToTestNode() { var graph = new GraphData(); var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output)); node.AddSlot(new TestSlot(0, "output", SlotType.Output)); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault(); Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetSlots<ISlot>().Count()); } [Test] public void TestCanUpdateDisplaynameByReaddingSlotToTestNode() { var graph = new GraphData(); var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output)); node.AddSlot(new TestSlot(0, "output_updated", SlotType.Output)); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault(); Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetSlots<ISlot>().Count()); var slot = found.GetOutputSlots<ISlot>().FirstOrDefault(); Assert.AreEqual("output_updated(4)", slot.displayName); } [Test] public void TestCanUpdateSlotPriority() { var graph = new GraphData(); var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output, 0)); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault(); Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetSlots<ISlot>().Count()); var slot = found.GetOutputSlots<ISlot>().FirstOrDefault(); Assert.AreEqual(0, slot.priority); slot.priority = 2; Assert.AreEqual(2, slot.priority); } [Test] public void TestCanUpdateSlotPriorityByReaddingSlotToTestNode() { var graph = new GraphData(); var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output, 0)); node.AddSlot(new TestSlot(0, "output", SlotType.Output, 5)); node.name = "Test Node"; graph.AddNode(node); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); var found = graph.GetNodes<AbstractMaterialNode>().FirstOrDefault(); Assert.AreEqual(0, found.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetOutputSlots<ISlot>().Count()); Assert.AreEqual(1, found.GetSlots<ISlot>().Count()); var slot = found.GetOutputSlots<ISlot>().FirstOrDefault(); Assert.AreEqual(5, slot.priority); } [Test] public void TestCanUpdateSlotDisplayName() { var node = new TestNode(); node.AddSlot(new TestSlot(0, "output", SlotType.Output)); node.name = "Test Node"; Assert.AreEqual(0, node.GetInputSlots<ISlot>().Count()); Assert.AreEqual(1, node.GetOutputSlots<ISlot>().Count()); Assert.AreEqual(1, node.GetSlots<ISlot>().Count()); var slot = node.GetOutputSlots<ISlot>().FirstOrDefault(); Assert.IsNotNull(slot); Assert.AreEqual("output(4)", slot.displayName); slot.displayName = "test"; Assert.AreEqual("test(4)", slot.displayName); } [Test] public void TestCanFindSlotOnTestNode() { var node = new TestableNode(); Assert.AreEqual(6, node.GetSlots<ISlot>().Count()); Assert.IsNotNull(node.FindInputSlot<ISlot>(TestableNode.Input0)); Assert.IsNull(node.FindInputSlot<ISlot>(TestableNode.Output0)); Assert.IsNotNull(node.FindOutputSlot<ISlot>(TestableNode.Output0)); Assert.IsNull(node.FindOutputSlot<ISlot>(TestableNode.Input0)); Assert.IsNotNull(node.FindSlot<ISlot>(TestableNode.Input0)); Assert.IsNotNull(node.FindSlot<ISlot>(TestableNode.Output0)); Assert.IsNull(node.FindSlot<ISlot>(555)); } [Test] public void TestCanFindSlotReferenceOnTestNode() { var node = new TestableNode(); Assert.AreEqual(6, node.GetSlots<ISlot>().Count()); Assert.IsNotNull(node.GetSlotReference(TestableNode.Input0)); Assert.IsNotNull(node.GetSlotReference(TestableNode.Output0)); Assert.Throws<ArgumentException>(() => node.GetSlotReference(555)); } [Test] public void TestCanConnectAndTraverseTwoNodesOnBaseMaterialGraph() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); var edge = graph.edges.FirstOrDefault(); Assert.AreEqual(createdEdge, edge); var foundOutputNode = graph.GetNodeFromGuid(edge.outputSlot.nodeGuid); var foundOutputSlot = foundOutputNode.FindOutputSlot<ISlot>(edge.outputSlot.slotId); Assert.AreEqual(outputNode, foundOutputNode); Assert.IsNotNull(foundOutputSlot); var foundInputNode = graph.GetNodeFromGuid(edge.inputSlot.nodeGuid); var foundInputSlot = foundInputNode.FindInputSlot<ISlot>(edge.inputSlot.slotId); Assert.AreEqual(inputNode, foundInputNode); Assert.IsNotNull(foundInputSlot); } [Test] public void TestCanConnectAndTraverseThreeNodesOnBaseMaterialGraph() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var middleNode = new TestableNode(); graph.AddNode(middleNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(3, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), middleNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); graph.Connect(middleNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(2, graph.edges.Count()); var edgesOnMiddleNode = NodeUtils.GetAllEdges(middleNode); Assert.AreEqual(2, edgesOnMiddleNode.Count()); List<AbstractMaterialNode> result = new List<AbstractMaterialNode>(); NodeUtils.DepthFirstCollectNodesFromNode(result, inputNode); Assert.AreEqual(3, result.Count); result.Clear(); NodeUtils.DepthFirstCollectNodesFromNode(result, inputNode, NodeUtils.IncludeSelf.Exclude); Assert.AreEqual(2, result.Count); result.Clear(); NodeUtils.DepthFirstCollectNodesFromNode(result, null); Assert.AreEqual(0, result.Count); } [Test] public void TestExceptionIfBadNodeConfigurationWorks() { var node = new TestableNode(); Assert.DoesNotThrow( () => NodeUtils.SlotConfigurationExceptionIfBadConfiguration( node, new[] {TestableNode.Input0, TestableNode.Input1, TestableNode.Input2}, new[] {TestableNode.Output0, TestableNode.Output1, TestableNode.Output2, }) ); Assert.Throws<SlotConfigurationException>( () => NodeUtils.SlotConfigurationExceptionIfBadConfiguration( node, new[] {666, TestableNode.Input1, TestableNode.Input2}, new[] {TestableNode.Output0, TestableNode.Output1, TestableNode.Output2, }) ); Assert.Throws<SlotConfigurationException>( () => NodeUtils.SlotConfigurationExceptionIfBadConfiguration( node, new[] {TestableNode.Input0, TestableNode.Input1, TestableNode.Input2}, new[] {666, TestableNode.Output1, TestableNode.Output2, }) ); Assert.DoesNotThrow( () => NodeUtils.SlotConfigurationExceptionIfBadConfiguration( node, new[] {TestableNode.Input0}, new[] {TestableNode.Output0}) ); } [Test] public void TestConectionToSameInputReplacesOldInput() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); var edge = graph.edges.FirstOrDefault(); Assert.AreEqual(createdEdge, edge); var createdEdge2 = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); var edge2 = graph.edges.FirstOrDefault(); Assert.AreEqual(createdEdge2, edge2); } [Test] public void TestRemovingSlotRemovesConnectedEdges() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); outputNode.RemoveSlot(TestableNode.Output0); Assert.AreEqual(0, graph.edges.Count()); } [Test] public void TestCanNotConnectToNullSlot() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); var createdEdge2 = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), new SlotReference(Guid.NewGuid(), 666)); Assert.AreEqual(0, graph.edges.Count()); Assert.IsNull(createdEdge2); } [Test] public void TestCanNotConnectTwoOuputSlotsOnBaseMaterialGraph() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var outputNode2 = new TestableNode(); graph.AddNode(outputNode2); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); var createdEdge = graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), outputNode2.GetSlotReference(TestableNode.Output0)); Assert.IsNull(createdEdge); Assert.AreEqual(0, graph.edges.Count()); } [Test] public void TestCanNotConnectTwoInputSlotsOnBaseMaterialGraph() { var graph = new GraphData(); var inputNode = new TestableNode(); graph.AddNode(inputNode); var inputNode2 = new TestableNode(); graph.AddNode(inputNode2); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); var createdEdge = graph.Connect(inputNode.GetSlotReference(TestableNode.Input0), inputNode2.GetSlotReference(TestableNode.Input0)); Assert.IsNull(createdEdge); Assert.AreEqual(0, graph.edges.Count()); } [Test] public void TestRemovingNodeRemovesConectedEdgesOnBaseMaterialGraph() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); graph.RemoveNode(graph.GetNodes<AbstractMaterialNode>().FirstOrDefault()); Assert.AreEqual(1, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.AreEqual(0, graph.edges.Count()); } [Test] public void TestRemovingEdgeOnBaseMaterialGraph() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); graph.RemoveEdge(graph.edges.FirstOrDefault()); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.AreEqual(0, graph.edges.Count()); } [Test] public void TestRemovingElementsFromBaseMaterialGraph() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); graph.RemoveElements(graph.GetNodes<AbstractMaterialNode>(), graph.edges, Enumerable.Empty<GroupData>()); Assert.AreEqual(0, graph.GetNodes<AbstractMaterialNode>().Count()); Assert.AreEqual(0, graph.edges.Count()); } [Test] public void TestCanGetEdgesOnBaseMaterialGraphFromSlotReference() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); Assert.AreEqual(1, graph.GetEdges(inputNode.GetSlotReference(TestableNode.Input0)).Count()); Assert.AreEqual(1, graph.GetEdges(outputNode.GetSlotReference(TestableNode.Output0)).Count()); Assert.Throws<ArgumentException>(() => outputNode.GetSlotReference(666)); } [Test] public void TestGetInputsWithNoConnection() { var graph = new GraphData(); var outputNode = new TestableNode(); graph.AddNode(outputNode); var inputNode = new TestableNode(); graph.AddNode(inputNode); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(outputNode.GetSlotReference(TestableNode.Output0), inputNode.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); var slots = inputNode.GetInputsWithNoConnection(); Assert.AreEqual(2, slots.Count()); CollectionAssert.AreEqual(new[] { TestableNode.Input1, TestableNode.Input2 }, slots.Select(x => x.id)); } [Test] public void TestCyclicConnectionsAreNotAllowedOnGraph() { var graph = new GraphData(); var nodeA = new TestableNode(); graph.AddNode(nodeA); var nodeB = new TestableNode(); graph.AddNode(nodeB); Assert.AreEqual(2, graph.GetNodes<AbstractMaterialNode>().Count()); graph.Connect(nodeA.GetSlotReference(TestableNode.Output0), nodeB.GetSlotReference(TestableNode.Input0)); Assert.AreEqual(1, graph.edges.Count()); var edge = graph.Connect(nodeB.GetSlotReference(TestableNode.Output0), nodeA.GetSlotReference(TestableNode.Input0)); Assert.IsNull(edge); Assert.AreEqual(1, graph.edges.Count()); } } }
using System; using System.Threading.Tasks; using System.Web; using System.Net; using System.Text; using System.IO; using System.Threading; using System.Collections.Generic; using System.Security.Cryptography; using System.ComponentModel; using SteamBot.SteamGroups; using SteamKit2; using SteamTrade; using SteamKit2.Internal; using SteamTrade.TradeOffer; namespace SteamBot { public class Bot { public string BotControlClass; // If the bot is logged in fully or not. This is only set // when it is. public bool IsLoggedIn = false; // The bot's display name. Changing this does not mean that // the bot's name will change. public string DisplayName { get; private set; } // The response to all chat messages sent to it. public string ChatResponse; // A list of SteamIDs that this bot recognizes as admins. public ulong[] Admins; public SteamFriends SteamFriends; public SteamClient SteamClient; public SteamTrading SteamTrade; public SteamUser SteamUser; public SteamGameCoordinator SteamGameCoordinator; public SteamNotifications SteamNotifications; // The current trade; if the bot is not in a trade, this is // null. public Trade CurrentTrade; public bool IsDebugMode = false; // The log for the bot. This logs with the bot's display name. public Log log; public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id); public UserHandlerCreator CreateHandler; Dictionary<ulong, UserHandler> userHandlers = new Dictionary<ulong, UserHandler>(); private List<SteamID> friends; public IEnumerable<SteamID> FriendsList { get { CreateFriendsListIfNecessary(); return friends; } } // The maximum amount of time the bot will trade for. public int MaximumTradeTime { get; private set; } // The maximum amount of time the bot will wait in between // trade actions. public int MaximiumActionGap { get; private set; } //The current game that the bot is playing, for posterity. public int CurrentGame = 0; // The Steam Web API key. public string apiKey; // The prefix put in the front of the bot's display name. string DisplayNamePrefix; // Log level to use for this bot Log.LogLevel LogLevel; // The number, in milliseconds, between polls for the trade. int TradePollingInterval; public string MyUserNonce; public string MyUniqueId; string sessionId; string token; string tokensecure; bool CookiesAreInvalid = true; bool isprocess; public bool IsRunning = false; public string AuthCode { get; set; } SteamUser.LogOnDetails logOnDetails; TradeManager tradeManager; private TradeOfferManager tradeOfferManager; private Task<Inventory> myInventoryTask; public Inventory MyInventory { get { myInventoryTask.Wait(); return myInventoryTask.Result; } } private BackgroundWorker backgroundWorker; public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false) { logOnDetails = new SteamUser.LogOnDetails { Username = config.Username, Password = config.Password }; DisplayName = config.DisplayName; ChatResponse = config.ChatResponse; MaximumTradeTime = config.MaximumTradeTime; MaximiumActionGap = config.MaximumActionGap; DisplayNamePrefix = config.DisplayNamePrefix; TradePollingInterval = config.TradePollingInterval <= 100 ? 800 : config.TradePollingInterval; Admins = config.Admins; this.apiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey; this.isprocess = process; try { LogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true); } catch (ArgumentException) { Console.WriteLine("Invalid LogLevel provided in configuration. Defaulting to 'INFO'"); LogLevel = Log.LogLevel.Info; } log = new Log(config.LogFile, this.DisplayName, LogLevel); CreateHandler = handlerCreator; BotControlClass = config.BotControlClass; // Hacking around https ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate; log.Debug("Initializing Steam Bot..."); SteamClient = new SteamClient(); SteamClient.AddHandler(new SteamNotifications()); SteamTrade = SteamClient.GetHandler<SteamTrading>(); SteamUser = SteamClient.GetHandler<SteamUser>(); SteamFriends = SteamClient.GetHandler<SteamFriends>(); SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>(); SteamNotifications = SteamClient.GetHandler<SteamNotifications>(); backgroundWorker = new BackgroundWorker { WorkerSupportsCancellation = true }; backgroundWorker.DoWork += BackgroundWorkerOnDoWork; backgroundWorker.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted; backgroundWorker.RunWorkerAsync(); } private void CreateFriendsListIfNecessary() { if (friends != null) return; friends = new List<SteamID>(); for (int i = 0; i < SteamFriends.GetFriendCount(); i++) { friends.Add(SteamFriends.GetFriendByIndex(i)); } } /// <summary> /// Occurs when the bot needs the SteamGuard authentication code. /// </summary> /// <remarks> /// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/> /// </remarks> public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired; /// <summary> /// Starts the callback thread and connects to Steam via SteamKit2. /// </summary> /// <remarks> /// THIS NEVER RETURNS. /// </remarks> /// <returns><c>true</c>. See remarks</returns> public bool StartBot() { IsRunning = true; log.Info("Connecting..."); if (!backgroundWorker.IsBusy) // background worker is not running backgroundWorker.RunWorkerAsync(); SteamClient.Connect(); log.Success("Done Loading Bot!"); return true; // never get here } /// <summary> /// Disconnect from the Steam network and stop the callback /// thread. /// </summary> public void StopBot() { IsRunning = false; log.Debug("Trying to shut down bot thread."); SteamClient.Disconnect(); backgroundWorker.CancelAsync(); } /// <summary> /// Creates a new trade with the given partner. /// </summary> /// <returns> /// <c>true</c>, if trade was opened, /// <c>false</c> if there is another trade that must be closed first. /// </returns> public bool OpenTrade(SteamID other) { if (CurrentTrade != null || CheckCookies() == false) return false; SteamTrade.Trade(other); return true; } /// <summary> /// Closes the current active trade. /// </summary> public void CloseTrade() { if (CurrentTrade == null) return; UnsubscribeTrade(GetUserHandler(CurrentTrade.OtherSID), CurrentTrade); tradeManager.StopTrade(); CurrentTrade = null; } void OnTradeTimeout(object sender, EventArgs args) { // ignore event params and just null out the trade. GetUserHandler(CurrentTrade.OtherSID).OnTradeTimeout(); } /// <summary> /// Create a new trade offer with the specified partner /// </summary> /// <param name="other">SteamId of the partner</param> /// <returns></returns> public TradeOffer NewTradeOffer(SteamID other) { return tradeOfferManager.NewOffer(other); } /// <summary> /// Try to get a specific trade offer using the offerid /// </summary> /// <param name="offerId"></param> /// <param name="tradeOffer"></param> /// <returns></returns> public bool TryGetTradeOffer(string offerId, out TradeOffer tradeOffer) { return tradeOfferManager.GetOffer(offerId, out tradeOffer); } public void HandleBotCommand(string command) { try { GetUserHandler(SteamClient.SteamID).OnBotCommand(command); } catch (ObjectDisposedException e) { // Writing to console because odds are the error was caused by a disposed log. Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); if (!this.IsRunning) { Console.WriteLine("The Bot is no longer running and could not write to the log. Try Starting this bot first."); } } catch (Exception e) { Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e)); } } bool HandleTradeSessionStart(SteamID other) { if (CurrentTrade != null) return false; try { tradeManager.InitializeTrade(SteamUser.SteamID, other); CurrentTrade = tradeManager.CreateTrade(SteamUser.SteamID, other); CurrentTrade.OnClose += CloseTrade; SubscribeTrade(CurrentTrade, GetUserHandler(other)); tradeManager.StartTradeThread(CurrentTrade); return true; } catch (SteamTrade.Exceptions.InventoryFetchException ie) { // we shouldn't get here because the inv checks are also // done in the TradeProposedCallback handler. string response = String.Empty; if (ie.FailingSteamId.ConvertToUInt64() == other.ConvertToUInt64()) { response = "Trade failed. Could not correctly fetch your backpack. Either the inventory is inaccessible or your backpack is private."; } else { response = "Trade failed. Could not correctly fetch my backpack."; } SteamFriends.SendChatMessage(other, EChatEntryType.ChatMsg, response); log.Info("Bot sent other: " + response); CurrentTrade = null; return false; } } public void SetGamePlaying(int id) { var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed); if (id != 0) gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed { game_id = new GameID(id), }); SteamClient.Send(gamePlaying); CurrentGame = id; } void HandleSteamMessage(ICallbackMsg msg) { log.Debug(msg.ToString()); #region Login msg.Handle<SteamClient.ConnectedCallback>(callback => { log.Debug("Connection Callback: " + callback.Result); if (callback.Result == EResult.OK) { UserLogOn(); } else { log.Error("Failed to connect to Steam Community, trying again..."); SteamClient.Connect(); } }); msg.Handle<SteamUser.LoggedOnCallback>(callback => { log.Debug("Logged On Callback: " + callback.Result); if (callback.Result == EResult.OK) { MyUserNonce = callback.WebAPIUserNonce; } else { log.Error("Login Error: " + callback.Result); } if (callback.Result == EResult.AccountLogonDenied) { log.Interface("This account is SteamGuard enabled. Enter the code via the `auth' command."); // try to get the steamguard auth code from the event callback var eva = new SteamGuardRequiredEventArgs(); FireOnSteamGuardRequired(eva); if (!String.IsNullOrEmpty(eva.SteamGuard)) logOnDetails.AuthCode = eva.SteamGuard; else logOnDetails.AuthCode = Console.ReadLine(); } if (callback.Result == EResult.InvalidLoginAuthCode) { log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command."); logOnDetails.AuthCode = Console.ReadLine(); } }); msg.Handle<SteamUser.LoginKeyCallback>(callback => { MyUniqueId = callback.UniqueID.ToString(); UserWebLogOn(); if (Trade.CurrentSchema == null) { log.Info("Downloading Schema..."); Trade.CurrentSchema = Schema.FetchSchema(apiKey); log.Success("Schema Downloaded!"); } SteamFriends.SetPersonaName(DisplayNamePrefix + DisplayName); SteamFriends.SetPersonaState(EPersonaState.Online); log.Success("Steam Bot Logged In Completely!"); IsLoggedIn = true; GetUserHandler(SteamClient.SteamID).OnLoginCompleted(); }); msg.Handle<SteamUser.WebAPIUserNonceCallback>(webCallback => { log.Debug("Received new WebAPIUserNonce."); if (webCallback.Result == EResult.OK) { MyUserNonce = webCallback.Nonce; UserWebLogOn(); } else { log.Error("WebAPIUserNonce Error: " + webCallback.Result); } }); msg.Handle<SteamUser.UpdateMachineAuthCallback>( authCallback => OnUpdateMachineAuthCallback(authCallback) ); #endregion #region Friends msg.Handle<SteamFriends.FriendsListCallback>(callback => { foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList) { switch (friend.SteamID.AccountType) { case EAccountType.Clan: if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnGroupAdd()) { AcceptGroupInvite(friend.SteamID); } else { DeclineGroupInvite(friend.SteamID); } } break; default: CreateFriendsListIfNecessary(); if (friend.Relationship == EFriendRelationship.None) { friends.Remove(friend.SteamID); GetUserHandler(friend.SteamID).OnFriendRemove(); RemoveUserHandler(friend.SteamID); } else if (friend.Relationship == EFriendRelationship.RequestRecipient) { if (GetUserHandler(friend.SteamID).OnFriendAdd()) { if(!friends.Contains(friend.SteamID)) { friends.Add(friend.SteamID); } else { log.Error("Friend was added who was already in friends list: " + friend.SteamID); } SteamFriends.AddFriend(friend.SteamID); } else { SteamFriends.RemoveFriend(friend.SteamID); RemoveUserHandler(friend.SteamID); } } break; } } }); msg.Handle<SteamFriends.FriendMsgCallback>(callback => { EChatEntryType type = callback.EntryType; if (callback.EntryType == EChatEntryType.ChatMsg) { log.Info(String.Format("Chat Message from {0}: {1}", SteamFriends.GetFriendPersonaName(callback.Sender), callback.Message )); GetUserHandler(callback.Sender).OnMessage(callback.Message, type); } }); #endregion #region Group Chat msg.Handle<SteamFriends.ChatMsgCallback>(callback => { GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message); }); #endregion #region Trading msg.Handle<SteamTrading.SessionStartCallback>(callback => { bool started = HandleTradeSessionStart(callback.OtherClient); if (!started) log.Error("Could not start the trade session."); else log.Debug("SteamTrading.SessionStartCallback handled successfully. Trade Opened."); }); msg.Handle<SteamTrading.TradeProposedCallback>(callback => { if (CheckCookies() == false) { SteamTrade.RespondToTrade(callback.TradeID, false); return; } try { tradeManager.InitializeTrade(SteamUser.SteamID, callback.OtherClient); } catch (WebException we) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade error: " + we.Message); SteamTrade.RespondToTrade(callback.TradeID, false); return; } catch (Exception) { SteamFriends.SendChatMessage(callback.OtherClient, EChatEntryType.ChatMsg, "Trade declined. Could not correctly fetch your backpack."); SteamTrade.RespondToTrade(callback.TradeID, false); return; } //if (tradeManager.OtherInventory.IsPrivate) //{ // SteamFriends.SendChatMessage(callback.OtherClient, // EChatEntryType.ChatMsg, // "Trade declined. Your backpack cannot be private."); // SteamTrade.RespondToTrade (callback.TradeID, false); // return; //} if (CurrentTrade == null && GetUserHandler(callback.OtherClient).OnTradeRequest()) SteamTrade.RespondToTrade(callback.TradeID, true); else SteamTrade.RespondToTrade(callback.TradeID, false); }); msg.Handle<SteamTrading.TradeResultCallback>(callback => { if (callback.Response == EEconTradeResponse.Accepted) { log.Debug("Trade Status: " + callback.Response); log.Info("Trade Accepted!"); GetUserHandler(callback.OtherClient).OnTradeRequestReply(true, callback.Response.ToString()); } else { log.Warn("Trade failed: " + callback.Response); CloseTrade(); GetUserHandler(callback.OtherClient).OnTradeRequestReply(false, callback.Response.ToString()); } }); #endregion #region Disconnect msg.Handle<SteamUser.LoggedOffCallback>(callback => { IsLoggedIn = false; log.Warn("Logged Off: " + callback.Result); }); msg.Handle<SteamClient.DisconnectedCallback>(callback => { IsLoggedIn = false; CloseTrade(); log.Warn("Disconnected from Steam Network!"); SteamClient.Connect(); }); #endregion #region Notifications msg.Handle<SteamBot.SteamNotifications.NotificationCallback>(callback => { //currently only appears to be of trade offer if (callback.Notifications.Count != 0) { foreach (var notification in callback.Notifications) { log.Info(notification.UserNotificationType + " notification"); } } // Get offers only if cookies are valid if (CheckCookies()) tradeOfferManager.GetOffers(); }); msg.Handle<SteamBot.SteamNotifications.CommentNotificationCallback>(callback => { //various types of comment notifications on profile/activity feed etc //log.Info("received CommentNotificationCallback"); //log.Info("New Commments " + callback.CommentNotifications.CountNewComments); //log.Info("New Commments Owners " + callback.CommentNotifications.CountNewCommentsOwner); //log.Info("New Commments Subscriptions" + callback.CommentNotifications.CountNewCommentsSubscriptions); }); #endregion } void UserLogOn() { // get sentry file which has the machine hw info saved // from when a steam guard code was entered Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username))); if (fi.Exists && fi.Length > 0) logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName)); else logOnDetails.SentryFileHash = null; SteamUser.LogOn(logOnDetails); } void UserWebLogOn() { while (true) { bool authd = SteamWeb.Authenticate(MyUniqueId, SteamClient, out sessionId, out token, out tokensecure, MyUserNonce); if (authd) { log.Success("User Authenticated!"); tradeManager = new TradeManager(apiKey, sessionId, token); tradeManager.SetTradeTimeLimits(MaximumTradeTime, MaximiumActionGap, TradePollingInterval); tradeManager.OnTimeout += OnTradeTimeout; tradeOfferManager = new TradeOfferManager(apiKey, sessionId, token, tokensecure); SubscribeTradeOffer(tradeOfferManager); CookiesAreInvalid = false; // Success, check trade offers which we have received while we were offline tradeOfferManager.GetOffers(); break; } else { log.Warn("Authentication failed, retrying in 2s..."); Thread.Sleep(2000); } } } /// <summary> /// Checks if sessionId and token cookies are still valid. /// Sets cookie flag if they are invalid. /// </summary> /// <returns>true if cookies are valid; otherwise false</returns> bool CheckCookies() { // We still haven't re-authenticated if (CookiesAreInvalid) return false; // Construct cookie container CookieContainer cookies = new CookieContainer(); cookies.Add(new Cookie("sessionid", sessionId, String.Empty, "steamcommunity.com")); cookies.Add(new Cookie("steamLogin", token, String.Empty, "steamcommunity.com")); try { if (!SteamWeb.VerifyCookies(cookies)) { // Cookies are no longer valid log.Warn("Cookies are invalid. Need to re-authenticate."); CookiesAreInvalid = true; SteamUser.RequestWebAPIUserNonce(); return false; } else { return true; } } catch { // Even if exception is caught, we should still continue. log.Warn("Cookie check failed. http://steamcommunity.com is possibly down."); return true; } } UserHandler GetUserHandler(SteamID sid) { if (!userHandlers.ContainsKey(sid)) { userHandlers[sid.ConvertToUInt64()] = CreateHandler(this, sid); } return userHandlers[sid.ConvertToUInt64()]; } void RemoveUserHandler(SteamID sid) { if (userHandlers.ContainsKey(sid)) { userHandlers.Remove(sid); } } static byte[] SHAHash(byte[] input) { SHA1Managed sha = new SHA1Managed(); byte[] output = sha.ComputeHash(input); sha.Clear(); return output; } void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth) { byte[] hash = SHAHash(machineAuth.Data); Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles")); File.WriteAllBytes(System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data); var authResponse = new SteamUser.MachineAuthDetails { BytesWritten = machineAuth.BytesToWrite, FileName = machineAuth.FileName, FileSize = machineAuth.BytesToWrite, Offset = machineAuth.Offset, SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs LastError = 0, // result from win32 GetLastError Result = EResult.OK, // if everything went okay, otherwise ~who knows~ JobID = machineAuth.JobID, // so we respond to the correct server job }; // send off our response SteamUser.SendMachineAuthResponse(authResponse); } /// <summary> /// Gets the bot's inventory and stores it in MyInventory. /// </summary> /// <example> This sample shows how to find items in the bot's inventory from a user handler. /// <code> /// Bot.GetInventory(); // Get the inventory first /// foreach (var item in Bot.MyInventory.Items) /// { /// if (item.Defindex == 5021) /// { /// // Bot has a key in its inventory /// } /// } /// </code> /// </example> public void GetInventory() { myInventoryTask = Task.Factory.StartNew(() => Inventory.FetchInventory(SteamUser.SteamID, apiKey)); } public void TradeOfferRouter(TradeOffer offer) { if (offer.OfferState == TradeOfferState.TradeOfferStateActive) { GetUserHandler(offer.PartnerSteamId).OnNewTradeOffer(offer); } } public void SubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnNewTradeOffer += TradeOfferRouter; } //todo: should unsubscribe eventually... public void UnsubscribeTradeOffer(TradeOfferManager tradeOfferManager) { tradeOfferManager.OnNewTradeOffer -= TradeOfferRouter; } /// <summary> /// Subscribes all listeners of this to the trade. /// </summary> public void SubscribeTrade(Trade trade, UserHandler handler) { trade.OnSuccess += handler.OnTradeSuccess; trade.OnClose += handler.OnTradeClose; trade.OnError += handler.OnTradeError; trade.OnStatusError += handler.OnStatusError; //trade.OnTimeout += OnTradeTimeout; trade.OnAfterInit += handler.OnTradeInit; trade.OnUserAddItem += handler.OnTradeAddItem; trade.OnUserRemoveItem += handler.OnTradeRemoveItem; trade.OnMessage += handler.OnTradeMessage; trade.OnUserSetReady += handler.OnTradeReadyHandler; trade.OnUserAccept += handler.OnTradeAcceptHandler; } /// <summary> /// Unsubscribes all listeners of this from the current trade. /// </summary> public void UnsubscribeTrade(UserHandler handler, Trade trade) { trade.OnSuccess -= handler.OnTradeSuccess; trade.OnClose -= handler.OnTradeClose; trade.OnError -= handler.OnTradeError; trade.OnStatusError -= handler.OnStatusError; //Trade.OnTimeout -= OnTradeTimeout; trade.OnAfterInit -= handler.OnTradeInit; trade.OnUserAddItem -= handler.OnTradeAddItem; trade.OnUserRemoveItem -= handler.OnTradeRemoveItem; trade.OnMessage -= handler.OnTradeMessage; trade.OnUserSetReady -= handler.OnTradeReadyHandler; trade.OnUserAccept -= handler.OnTradeAcceptHandler; } #region Background Worker Methods private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) { if (runWorkerCompletedEventArgs.Error != null) { Exception ex = runWorkerCompletedEventArgs.Error; var s = string.Format("Unhandled exceptions in bot {0} callback thread: {1} {2}", DisplayName, Environment.NewLine, ex); log.Error(s); log.Info("This bot died. Stopping it.."); //backgroundWorker.RunWorkerAsync(); //Thread.Sleep(10000); StopBot(); //StartBot(); } log.Dispose(); } private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs) { ICallbackMsg msg; while (!backgroundWorker.CancellationPending) { try { msg = SteamClient.WaitForCallback(true); HandleSteamMessage(msg); } catch (WebException e) { log.Error("URI: " + (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown") + " >> " + e.ToString()); System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds. } catch (Exception e) { log.Error(e.ToString()); log.Warn("Restarting bot..."); } } } #endregion Background Worker Methods private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e) { // Set to null in case this is another attempt this.AuthCode = null; EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired; if (handler != null) handler(this, e); else { while (true) { if (this.AuthCode != null) { e.SteamGuard = this.AuthCode; break; } Thread.Sleep(5); } } } #region Group Methods /// <summary> /// Accepts the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to accept the invite from.</param> private void AcceptGroupInvite(SteamID group) { var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); AcceptInvite.Body.GroupID = group.ConvertToUInt64(); AcceptInvite.Body.AcceptInvite = true; this.SteamClient.Send(AcceptInvite); } /// <summary> /// Declines the invite to a Steam Group /// </summary> /// <param name="group">SteamID of the group to decline the invite from.</param> private void DeclineGroupInvite(SteamID group) { var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite); DeclineInvite.Body.GroupID = group.ConvertToUInt64(); DeclineInvite.Body.AcceptInvite = false; this.SteamClient.Send(DeclineInvite); } /// <summary> /// Invites a use to the specified Steam Group /// </summary> /// <param name="user">SteamID of the user to invite.</param> /// <param name="groupId">SteamID of the group to invite the user to.</param> public void InviteUserToGroup(SteamID user, SteamID groupId) { var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan); InviteUser.Body.GroupID = groupId.ConvertToUInt64(); InviteUser.Body.Invitee = user.ConvertToUInt64(); InviteUser.Body.UnknownInfo = true; this.SteamClient.Send(InviteUser); } #endregion } }
using System; using Microsoft.AspNetCore.Mvc; using jamiewest.ChartJs.Charts; using jamiewest.ChartJs.Data; using jamiewest.ChartJs; using jamiewest.ChartJs.Options.Scales; using ChartJs.Mvc.Samples.Utilities; using Microsoft.Extensions.Options; namespace ChartJs.Mvc.Samples.Controllers { [Produces("application/json")] public class ChartsController : Controller { Random _randomNumber = new Random(); [HttpGet] [Route("api/chart/line/basic")] public string LineChartExample() { LineChart chart = new LineChart(); chart.Data.Labels = new string[] { "January", "February", "March", "April", "May", "June", "July" }; chart.Data.Datasets.Add(new LineDataset() { Label = "My First dataset", Fill = false, BackgroundColor = new string[] { ChartColors.Red }, BorderColor = new string[] { ChartColors.Red }, Data = new int[] { RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor() } }); chart.Data.Datasets.Add(new LineDataset() { Label = "My Second dataset", Fill = false, BackgroundColor = new string[] { ChartColors.Blue }, BorderColor = new string[] { ChartColors.Blue }, Data = new int[] { RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor() }, }); chart.Options.Responsive = true; chart.Options.Title.Display = true; //chart.Options.Title.Text = "Chart.js Line Chart"; chart.Options.Tooltip.Mode = "index"; chart.Options.Tooltip.Intersect = true; chart.Options.Hover.Mode = "nearest"; chart.Options.Hover.intersect = true; var xAxesCommonOption = new CommonOptions(); xAxesCommonOption.Display = true; xAxesCommonOption.ScaleLabel.Display = true; xAxesCommonOption.ScaleLabel.LabelString = "Month"; chart.Options.Scales.xAxes.Add(xAxesCommonOption); var yAxesCommonOption = new CommonOptions(); yAxesCommonOption.Display = true; yAxesCommonOption.ScaleLabel.Display = true; yAxesCommonOption.ScaleLabel.LabelString = "Value"; chart.Options.Scales.yAxes.Add(yAxesCommonOption); return chart.ToString(); } [HttpGet] [Route("api/chart/bar/basic")] public string BarChartExample() { BarChart chart = new BarChart(); chart.Data.Labels = new string[] { "January", "February", "March", "April", "May", "June", "July" }; chart.Data.Datasets.Add(new BarDataset() { Label = "My First dataset", BackgroundColor = new string[] { "rgba(255, 99, 132, .5)" }, BorderColor = new string[] { ChartColors.Red }, BorderWidth = new int[] { 1 }, Data = new int[] { RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor() } }); chart.Data.Datasets.Add(new BarDataset() { Label = "My Second dataset", BackgroundColor = new string[] { "rgba(54, 162, 235, .5)" }, BorderColor = new string[] { ChartColors.Blue }, BorderWidth = new int[] { 1 }, Data = new int[] { RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor(), RandomScalingFactor() }, }); chart.Options.Responsive = true; chart.Options.Title.Display = true; chart.Options.Title.Text = "Chart.js Line Chart"; chart.Options.Tooltip.Mode = "index"; chart.Options.Tooltip.Intersect = true; chart.Options.Hover.Mode = "nearest"; chart.Options.Hover.intersect = true; var xAxesCommonOption = new CommonOptions(); xAxesCommonOption.Display = true; xAxesCommonOption.ScaleLabel.Display = true; xAxesCommonOption.ScaleLabel.LabelString = "Month"; chart.Options.Scales.xAxes.Add(xAxesCommonOption); var yAxesCommonOption = new CommonOptions(); yAxesCommonOption.Display = true; yAxesCommonOption.ScaleLabel.Display = true; yAxesCommonOption.ScaleLabel.LabelString = "Value"; chart.Options.Scales.yAxes.Add(yAxesCommonOption); return chart.ToString(); } [HttpGet] [Route("api/chart/pie/basic")] public string PieChartExample() { PieChart chart = new PieChart(); chart.Data.Labels = new string[] { "Red", "Orange", "Yellow", "Green", "Blue" }; chart.Data.Datasets.Add(new PieDataset() { Label = "Dataset 1", Data = new int[] { 10, 20, 30, 30, 20 }, BackgroundColor = new string[] { ChartColors.Red, ChartColors.Orange, ChartColors.Yellow, ChartColors.Green, ChartColors.Blue } }); return chart.ToString(); } private int RandomScalingFactor(int min = -100, int max = 100) { return _randomNumber.Next(-100, 100); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableArrayTest : SimpleElementImmutablesTestBase { private static readonly ImmutableArray<int> s_emptyDefault; private static readonly ImmutableArray<int> s_empty = ImmutableArray.Create<int>(); private static readonly ImmutableArray<int> s_oneElement = ImmutableArray.Create(1); private static readonly ImmutableArray<int> s_manyElements = ImmutableArray.Create(1, 2, 3); private static readonly ImmutableArray<GenericParameterHelper> s_oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1)); private static readonly ImmutableArray<string> s_twoElementRefTypeWithNull = ImmutableArray.Create("1", null); [Fact] public void CreateEmpty() { Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray<int>.Empty); } [Fact] public void CreateFromEnumerable() { Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange((IEnumerable<int>)null)); IEnumerable<int> source = new[] { 1, 2, 3 }; var array = ImmutableArray.CreateRange(source); Assert.Equal(3, array.Length); } [Fact] public void CreateFromEmptyEnumerableReturnsSingleton() { IEnumerable<int> emptySource1 = new int[0]; var immutable = ImmutableArray.CreateRange(emptySource1); // This equality check returns true if the underlying arrays are the same instance. Assert.Equal(s_empty, immutable); } [Fact] public void CreateRangeFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, i => i + 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, i => i + 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, i => i)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, (Func<int, int>)null)); } [Fact] public void CreateRangeFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, (i, j) => i + j, 0.5); Assert.Equal(new[] { 4.5, 5.5, 6.5, 7.5 }, copy1); var copy2 = ImmutableArray.CreateRange(array, (i, j) => i + j, 1); Assert.Equal(new[] { 5, 6, 7, 8 }, copy2); var copy3 = ImmutableArray.CreateRange(array, (int i, object j) => i, null); Assert.Equal(new[] { 4, 5, 6, 7 }, copy3); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, (Func<int, int, int>)null, 0)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelector() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, i => i + 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, i => i); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, i => i * 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, i => i + 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, i => i); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, i => i); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, i => i); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, i => i); Assert.Equal(new int[] { }, copy8); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(s_empty, 0, 0, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, (Func<int, int>)null)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 0, 5, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 4, 1, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 3, 2, i => i)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 1, -1, i => i)); } [Fact] public void CreateRangeSliceFromImmutableArrayWithSelectorAndArgument() { var array = ImmutableArray.Create(4, 5, 6, 7); var copy1 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0.5); Assert.Equal(new double[] { }, copy1); var copy2 = ImmutableArray.CreateRange(array, 0, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy2); var copy3 = ImmutableArray.CreateRange(array, 0, 1, (i, j) => i * j, 2); Assert.Equal(new int[] { 8 }, copy3); var copy4 = ImmutableArray.CreateRange(array, 0, 2, (i, j) => i + j, 1); Assert.Equal(new int[] { 5, 6 }, copy4); var copy5 = ImmutableArray.CreateRange(array, 0, 4, (i, j) => i + j, 0); Assert.Equal(new int[] { 4, 5, 6, 7 }, copy5); var copy6 = ImmutableArray.CreateRange(array, 3, 1, (i, j) => i + j, 0); Assert.Equal(new int[] { 7 }, copy6); var copy7 = ImmutableArray.CreateRange(array, 3, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy7); var copy8 = ImmutableArray.CreateRange(array, 4, 0, (i, j) => i + j, 0); Assert.Equal(new int[] { }, copy8); var copy9 = ImmutableArray.CreateRange(array, 0, 1, (int i, object j) => i, null); Assert.Equal(new int[] { 4 }, copy9); Assert.Equal(new int[] { }, ImmutableArray.CreateRange(s_empty, 0, 0, (i, j) => i + j, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(array, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange(s_empty, 0, 0, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(s_empty, -1, 1, (Func<int, int, int>)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, -1, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 0, 5, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 4, 1, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 3, 2, (i, j) => i + j, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.CreateRange(array, 1, -1, (i, j) => i + j, 0)); } [Fact] public void CreateFromSliceOfImmutableArray() { var array = ImmutableArray.Create(4, 5, 6, 7); Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Equal(new int[] { }, ImmutableArray.Create(s_empty, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(s_empty, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfImmutableArrayOptimizations() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 0, array.Length); Assert.Equal(array, slice); // array instance actually shared between the two } [Fact] public void CreateFromSliceOfImmutableArrayEmptyReturnsSingleton() { var array = ImmutableArray.Create(4, 5, 6, 7); var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(s_empty, slice); } [Fact] public void CreateFromSliceOfArray() { var array = new int[] { 4, 5, 6, 7 }; Assert.Equal(new[] { 4, 5 }, ImmutableArray.Create(array, 0, 2)); Assert.Equal(new[] { 5, 6 }, ImmutableArray.Create(array, 1, 2)); Assert.Equal(new[] { 6, 7 }, ImmutableArray.Create(array, 2, 2)); Assert.Equal(new[] { 7 }, ImmutableArray.Create(array, 3, 1)); Assert.Equal(new int[0], ImmutableArray.Create(array, 4, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 0, array.Length + 1)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, 1, array.Length)); Assert.Throws<ArgumentOutOfRangeException>(() => ImmutableArray.Create(array, array.Length + 1, 0)); } [Fact] public void CreateFromSliceOfArrayEmptyReturnsSingleton() { var array = new int[] { 4, 5, 6, 7 }; var slice = ImmutableArray.Create(array, 1, 0); Assert.Equal(s_empty, slice); slice = ImmutableArray.Create(array, array.Length, 0); Assert.Equal(s_empty, slice); } [Fact] public void CreateFromArray() { var source = new[] { 1, 2, 3 }; var immutable = ImmutableArray.Create(source); Assert.Equal(source, immutable); } [Fact] public void CreateFromNullArray() { int[] nullArray = null; ImmutableArray<int> immutable = ImmutableArray.Create(nullArray); Assert.False(immutable.IsDefault); Assert.Equal(0, immutable.Length); } [Fact] public void Covariance() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.False(baseImmutable.IsDefault); Assert.Equal(derivedImmutable, baseImmutable); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.False(derivedImmutable2.IsDefault); Assert.Equal(derivedImmutable, derivedImmutable2); // Try a cast that would fail. Assert.True(baseImmutable.As<Encoder>().IsDefault); } [Fact] public void DowncastOfDefaultStructs() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = derivedImmutable.As<object>(); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } /// <summary> /// Verifies that using an ordinary Create factory method is smart enough to reuse /// an underlying array when possible. /// </summary> [Fact] public void CovarianceImplicit() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray.CreateRange<object>(derivedImmutable); Assert.Equal(derivedImmutable, baseImmutable); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.Equal(derivedImmutable, derivedImmutable2); } [Fact] public void CastUpReference() { ImmutableArray<string> derivedImmutable = ImmutableArray.Create("a", "b", "c"); ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable); Assert.Equal(derivedImmutable, baseImmutable); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. Assert.Equal(derivedImmutable, baseImmutable.As<string>()); Assert.Equal(derivedImmutable, baseImmutable.CastArray<string>()); } [Fact] public void CastUpReferenceDefaultValue() { ImmutableArray<string> derivedImmutable = default(ImmutableArray<string>); ImmutableArray<object> baseImmutable = ImmutableArray<object>.CastUp(derivedImmutable); Assert.True(baseImmutable.IsDefault); Assert.True(derivedImmutable.IsDefault); // Make sure we can reverse that, as a means to verify the underlying array is the same instance. ImmutableArray<string> derivedImmutable2 = baseImmutable.As<string>(); Assert.True(derivedImmutable2.IsDefault); Assert.True(derivedImmutable == derivedImmutable2); } [Fact] public void CastUpRefToInterface() { var stringArray = ImmutableArray.Create("a", "b"); var enumArray = ImmutableArray<IEnumerable>.CastUp(stringArray); Assert.Equal(2, enumArray.Length); Assert.Equal(stringArray, enumArray.CastArray<string>()); Assert.Equal(stringArray, enumArray.As<string>()); } [Fact] public void CastUpInterfaceToInterface() { var genericEnumArray = ImmutableArray.Create<IEnumerable<int>>(new List<int>(), new List<int>()); var legacyEnumArray = ImmutableArray<IEnumerable>.CastUp(genericEnumArray); Assert.Equal(2, legacyEnumArray.Length); Assert.Equal(genericEnumArray, legacyEnumArray.As<IEnumerable<int>>()); Assert.Equal(genericEnumArray, legacyEnumArray.CastArray<IEnumerable<int>>()); } [Fact] public void CastUpArrayToSystemArray() { var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 }); var sysArray = ImmutableArray<Array>.CastUp(arrayArray); Assert.Equal(2, sysArray.Length); Assert.Equal(arrayArray, sysArray.As<int[]>()); Assert.Equal(arrayArray, sysArray.CastArray<int[]>()); } [Fact] public void CastUpArrayToObject() { var arrayArray = ImmutableArray.Create(new int[] { 1, 2 }, new int[] { 3, 4 }); var objArray = ImmutableArray<object>.CastUp(arrayArray); Assert.Equal(2, objArray.Length); Assert.Equal(arrayArray, objArray.As<int[]>()); Assert.Equal(arrayArray, objArray.CastArray<int[]>()); } [Fact] public void CastUpDelegateToSystemDelegate() { var delArray = ImmutableArray.Create<Action>(() => { }, () => { }); var sysDelArray = ImmutableArray<Delegate>.CastUp(delArray); Assert.Equal(2, sysDelArray.Length); Assert.Equal(delArray, sysDelArray.As<Action>()); Assert.Equal(delArray, sysDelArray.CastArray<Action>()); } [Fact] public void CastArrayUnrelatedInterface() { var strArray = ImmutableArray.Create<string>("cat", "dog"); var compArray = ImmutableArray<IComparable>.CastUp(strArray); var enumArray = compArray.CastArray<IEnumerable>(); Assert.Equal(2, enumArray.Length); Assert.Equal(strArray, enumArray.As<string>()); Assert.Equal(strArray, enumArray.CastArray<string>()); } [Fact] public void CastArrayBadInterface() { var formattableArray = ImmutableArray.Create<IFormattable>(1, 2); Assert.Throws(typeof(InvalidCastException), () => formattableArray.CastArray<IComparable>()); } [Fact] public void CastArrayBadRef() { var objArray = ImmutableArray.Create<object>("cat", "dog"); Assert.Throws(typeof(InvalidCastException), () => objArray.CastArray<string>()); } [Fact] public void ToImmutableArray() { IEnumerable<int> source = new[] { 1, 2, 3 }; ImmutableArray<int> immutable = source.ToImmutableArray(); Assert.Equal(source, immutable); ImmutableArray<int> immutable2 = immutable.ToImmutableArray(); Assert.Equal(immutable, immutable2); // this will compare array reference equality. } [Fact] public void Count() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Length); Assert.Throws<InvalidOperationException>(() => ((ICollection)s_emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((ICollection<int>)s_emptyDefault).Count); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyCollection<int>)s_emptyDefault).Count); Assert.Equal(0, s_empty.Length); Assert.Equal(0, ((ICollection)s_empty).Count); Assert.Equal(0, ((ICollection<int>)s_empty).Count); Assert.Equal(0, ((IReadOnlyCollection<int>)s_empty).Count); Assert.Equal(1, s_oneElement.Length); Assert.Equal(1, ((ICollection)s_oneElement).Count); Assert.Equal(1, ((ICollection<int>)s_oneElement).Count); Assert.Equal(1, ((IReadOnlyCollection<int>)s_oneElement).Count); } [Fact] public void IsEmpty() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.IsEmpty); Assert.True(s_empty.IsEmpty); Assert.False(s_oneElement.IsEmpty); } [Fact] public void IndexOfDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.IndexOf(5, 0, 0)); } [Fact] public void LastIndexOfDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.LastIndexOf(5, 0, 0)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableArray.CreateRange(seq), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Contains() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Contains(0)); Assert.False(s_empty.Contains(0)); Assert.True(s_oneElement.Contains(1)); Assert.False(s_oneElement.Contains(2)); Assert.True(s_manyElements.Contains(3)); Assert.False(s_oneElementRefType.Contains(null)); Assert.True(s_twoElementRefTypeWithNull.Contains(null)); } [Fact] public void ContainsEqualityComparer() { var array = ImmutableArray.Create("a", "B"); Assert.False(array.Contains("A", StringComparer.Ordinal)); Assert.True(array.Contains("A", StringComparer.OrdinalIgnoreCase)); Assert.False(array.Contains("b", StringComparer.Ordinal)); Assert.True(array.Contains("b", StringComparer.OrdinalIgnoreCase)); } [Fact] public void Enumerator() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.GetEnumerator()); ImmutableArray<int>.Enumerator enumerator = default(ImmutableArray<int>.Enumerator); Assert.Throws<NullReferenceException>(() => enumerator.Current); Assert.Throws<NullReferenceException>(() => enumerator.MoveNext()); enumerator = s_empty.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = s_manyElements.GetEnumerator(); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<IndexOutOfRangeException>(() => enumerator.Current); } [Fact] public void ObjectEnumerator() { Assert.Throws<InvalidOperationException>(() => ((IEnumerable<int>)s_emptyDefault).GetEnumerator()); IEnumerator<int> enumerator = ((IEnumerable<int>)s_empty).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator = ((IEnumerable<int>)s_manyElements).GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public void EnumeratorWithNullValues() { var enumerationResult = System.Linq.Enumerable.ToArray(s_twoElementRefTypeWithNull); Assert.Equal("1", enumerationResult[0]); Assert.Null(enumerationResult[1]); } [Fact] public void EqualityCheckComparesInternalArrayByReference() { var immutable1 = ImmutableArray.Create(1); var immutable2 = ImmutableArray.Create(1); Assert.NotEqual(immutable1, immutable2); Assert.True(immutable1.Equals(immutable1)); Assert.True(immutable1.Equals((object)immutable1)); } [Fact] public void EqualsObjectNull() { Assert.False(s_empty.Equals((object)null)); } [Fact] public void OperatorsAndEquality() { Assert.True(s_empty.Equals(s_empty)); var emptySame = s_empty; Assert.True(s_empty == emptySame); Assert.False(s_empty != emptySame); // empty and default should not be seen as equal Assert.False(s_empty.Equals(s_emptyDefault)); Assert.False(s_empty == s_emptyDefault); Assert.True(s_empty != s_emptyDefault); Assert.False(s_emptyDefault == s_empty); Assert.True(s_emptyDefault != s_empty); Assert.False(s_empty.Equals(s_oneElement)); Assert.False(s_empty == s_oneElement); Assert.True(s_empty != s_oneElement); Assert.False(s_oneElement == s_empty); Assert.True(s_oneElement != s_empty); } [Fact] public void NullableOperators() { ImmutableArray<int>? nullArray = null; ImmutableArray<int>? nonNullDefault = s_emptyDefault; ImmutableArray<int>? nonNullEmpty = s_empty; Assert.True(nullArray == nonNullDefault); Assert.False(nullArray != nonNullDefault); Assert.True(nonNullDefault == nullArray); Assert.False(nonNullDefault != nullArray); Assert.False(nullArray == nonNullEmpty); Assert.True(nullArray != nonNullEmpty); Assert.False(nonNullEmpty == nullArray); Assert.True(nonNullEmpty != nullArray); } [Fact] public void GetHashCodeTest() { Assert.Equal(0, s_emptyDefault.GetHashCode()); Assert.NotEqual(0, s_empty.GetHashCode()); Assert.NotEqual(0, s_oneElement.GetHashCode()); } [Fact] public void Add() { var source = new[] { 1, 2 }; var array1 = ImmutableArray.Create(source); var array2 = array1.Add(3); Assert.Equal(source, array1); Assert.Equal(new[] { 1, 2, 3 }, array2); Assert.Equal(new[] { 1 }, s_empty.Add(1)); } [Fact] public void AddRange() { var nothingToEmpty = s_empty.AddRange(Enumerable.Empty<int>()); Assert.False(nothingToEmpty.IsDefault); Assert.True(nothingToEmpty.IsEmpty); Assert.Equal(new[] { 1, 2 }, s_empty.AddRange(Enumerable.Range(1, 2))); Assert.Equal(new[] { 1, 2 }, s_empty.AddRange(new[] { 1, 2 })); Assert.Equal(new[] { 1, 2, 3, 4 }, s_manyElements.AddRange(new[] { 4 })); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, s_manyElements.AddRange(new[] { 4, 5 })); } [Fact] public void AddRangeDefaultEnumerable() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(Enumerable.Range(1, 2))); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(new[] { 1, 2 })); } [Fact] public void AddRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(s_empty)); Assert.Throws<NullReferenceException>(() => s_empty.AddRange(s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(s_oneElement)); Assert.Throws<NullReferenceException>(() => s_oneElement.AddRange(s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.AddRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.AddRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.AddRange(emptyDefaultBoxed)); } [Fact] public void AddRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.AddRange(s_empty)); Assert.Equal(s_oneElement, s_empty.AddRange(s_oneElement)); // struct overload Assert.Equal(s_oneElement, s_empty.AddRange((IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.AddRange(s_empty)); } [Fact] public void Insert() { var array1 = ImmutableArray.Create<char>(); Assert.Throws<ArgumentOutOfRangeException>(() => array1.Insert(-1, 'a')); Assert.Throws<ArgumentOutOfRangeException>(() => array1.Insert(1, 'a')); var insertFirst = array1.Insert(0, 'c'); Assert.Equal(new[] { 'c' }, insertFirst); var insertLeft = insertFirst.Insert(0, 'a'); Assert.Equal(new[] { 'a', 'c' }, insertLeft); var insertRight = insertFirst.Insert(1, 'e'); Assert.Equal(new[] { 'c', 'e' }, insertRight); var insertBetween = insertLeft.Insert(1, 'b'); Assert.Equal(new[] { 'a', 'b', 'c' }, insertBetween); } [Fact] public void InsertDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(0, 10)); } [Fact] public void InsertRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.InsertRange(0, s_empty)); Assert.Equal(s_oneElement, s_empty.InsertRange(0, s_oneElement)); // struct overload Assert.Equal(s_oneElement, s_empty.InsertRange(0, (IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.InsertRange(0, s_empty)); } [Fact] public void InsertRangeEmpty() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(-1, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.Insert(1, 10)); Assert.Equal(new int[0], s_empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(s_empty, s_empty.InsertRange(0, Enumerable.Empty<int>())); Assert.Equal(new[] { 1 }, s_empty.InsertRange(0, new[] { 1 })); Assert.Equal(new[] { 2, 3, 4 }, s_empty.InsertRange(0, new[] { 2, 3, 4 })); Assert.Equal(new[] { 2, 3, 4 }, s_empty.InsertRange(0, Enumerable.Range(2, 3))); Assert.Equal(s_manyElements, s_manyElements.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.InsertRange(1, s_oneElement)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.InsertRange(-1, s_oneElement)); } [Fact] public void InsertRangeDefault() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(-1, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, Enumerable.Empty<int>())); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, new[] { 1 })); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, new[] { 2, 3, 4 })); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, Enumerable.Range(2, 3))); } /// <summary> /// Validates that a fixed bug in the inappropriate adding of the /// Empty singleton enumerator to the reusable instances bag does not regress. /// </summary> [Fact] public void EmptyEnumeratorReuseRegressionTest() { IEnumerable<int> oneElementBoxed = s_oneElement; IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyDefaultBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed)); Assert.Equal(oneElementBoxed, oneElementBoxed); } [Fact] public void InsertRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, s_empty)); Assert.Throws<NullReferenceException>(() => s_empty.InsertRange(0, s_emptyDefault)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, s_oneElement)); Assert.Throws<NullReferenceException>(() => s_oneElement.InsertRange(0, s_emptyDefault)); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.InsertRange(0, emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.InsertRange(0, oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.InsertRange(0, emptyDefaultBoxed)); } [Fact] public void InsertRangeLeft() { Assert.Equal(new[] { 7, 1, 2, 3 }, s_manyElements.InsertRange(0, new[] { 7 })); Assert.Equal(new[] { 7, 8, 1, 2, 3 }, s_manyElements.InsertRange(0, new[] { 7, 8 })); } [Fact] public void InsertRangeMid() { Assert.Equal(new[] { 1, 7, 2, 3 }, s_manyElements.InsertRange(1, new[] { 7 })); Assert.Equal(new[] { 1, 7, 8, 2, 3 }, s_manyElements.InsertRange(1, new[] { 7, 8 })); } [Fact] public void InsertRangeRight() { Assert.Equal(new[] { 1, 2, 3, 7 }, s_manyElements.InsertRange(3, new[] { 7 })); Assert.Equal(new[] { 1, 2, 3, 7, 8 }, s_manyElements.InsertRange(3, new[] { 7, 8 })); } [Fact] public void RemoveAt() { Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveAt(0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveAt(1)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveAt(-1)); Assert.Equal(new int[0], s_oneElement.RemoveAt(0)); Assert.Equal(new[] { 2, 3 }, s_manyElements.RemoveAt(0)); Assert.Equal(new[] { 1, 3 }, s_manyElements.RemoveAt(1)); Assert.Equal(new[] { 1, 2 }, s_manyElements.RemoveAt(2)); } [Fact] public void Remove() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.Remove(5)); Assert.False(s_empty.Remove(5).IsDefault); Assert.True(s_oneElement.Remove(1).IsEmpty); Assert.Equal(new[] { 2, 3 }, s_manyElements.Remove(1)); Assert.Equal(new[] { 1, 3 }, s_manyElements.Remove(2)); Assert.Equal(new[] { 1, 2 }, s_manyElements.Remove(3)); } [Fact] public void RemoveRange() { Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveRange(0, 0)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveRange(1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.RemoveRange(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveRange(0, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.RemoveRange(0, -1)); var fourElements = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(new int[0], s_oneElement.RemoveRange(0, 1)); Assert.Equal(s_oneElement.ToArray(), s_oneElement.RemoveRange(0, 0)); Assert.Equal(new[] { 3, 4 }, fourElements.RemoveRange(0, 2)); Assert.Equal(new[] { 1, 4 }, fourElements.RemoveRange(1, 2)); Assert.Equal(new[] { 1, 2 }, fourElements.RemoveRange(2, 2)); } [Fact] public void RemoveRangeDefaultStruct() { Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(s_empty)); Assert.Throws<ArgumentNullException>(() => Assert.Equal(s_empty, s_empty.RemoveRange(s_emptyDefault))); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(s_oneElement)); Assert.Throws<ArgumentNullException>(() => Assert.Equal(s_oneElement, s_oneElement.RemoveRange(s_emptyDefault))); IEnumerable<int> emptyBoxed = s_empty; IEnumerable<int> emptyDefaultBoxed = s_emptyDefault; IEnumerable<int> oneElementBoxed = s_oneElement; Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(emptyBoxed)); Assert.Throws<InvalidOperationException>(() => s_empty.RemoveRange(emptyDefaultBoxed)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(oneElementBoxed)); Assert.Throws<InvalidOperationException>(() => s_oneElement.RemoveRange(emptyDefaultBoxed)); } [Fact] public void RemoveRangeNoOpIdentity() { Assert.Equal(s_empty, s_empty.RemoveRange(s_empty)); Assert.Equal(s_empty, s_empty.RemoveRange(s_oneElement)); // struct overload Assert.Equal(s_empty, s_empty.RemoveRange((IEnumerable<int>)s_oneElement)); // enumerable overload Assert.Equal(s_oneElement, s_oneElement.RemoveRange(s_empty)); } [Fact] public void RemoveAll() { Assert.Throws<ArgumentNullException>(() => s_oneElement.RemoveAll(null)); var array = ImmutableArray.CreateRange(Enumerable.Range(1, 10)); var removedEvens = array.RemoveAll(n => n % 2 == 0); var removedOdds = array.RemoveAll(n => n % 2 == 1); var removedAll = array.RemoveAll(n => true); var removedNone = array.RemoveAll(n => false); Assert.Equal(new[] { 1, 3, 5, 7, 9 }, removedEvens); Assert.Equal(new[] { 2, 4, 6, 8, 10 }, removedOdds); Assert.True(removedAll.IsEmpty); Assert.Equal(Enumerable.Range(1, 10), removedNone); Assert.False(s_empty.RemoveAll(n => false).IsDefault); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveAll(n => false)); } [Fact] public void RemoveRangeEnumerableTest() { var list = ImmutableArray.Create(1, 2, 3); Assert.Throws<ArgumentNullException>(() => list.RemoveRange(null)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.RemoveRange(new int[0]).IsDefault); Assert.False(s_empty.RemoveRange(new int[0]).IsDefault); ImmutableArray<int> removed2 = list.RemoveRange(new[] { 2 }); Assert.Equal(2, removed2.Length); Assert.Equal(new[] { 1, 3 }, removed2); ImmutableArray<int> removed13 = list.RemoveRange(new[] { 1, 3, 5 }); Assert.Equal(1, removed13.Length); Assert.Equal(new[] { 2 }, removed13); Assert.Equal(new[] { 1, 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 2, 4, 5, 7, 10 })); Assert.Equal(new[] { 3, 6, 8, 9 }, ImmutableArray.CreateRange(Enumerable.Range(1, 10)).RemoveRange(new[] { 1, 2, 4, 5, 7, 10 })); Assert.Equal(list, list.RemoveRange(new[] { 5 })); Assert.Equal(ImmutableArray.Create<int>(), ImmutableArray.Create<int>().RemoveRange(new[] { 1 })); var listWithDuplicates = ImmutableArray.Create(1, 2, 2, 3); Assert.Equal(new[] { 1, 2, 3 }, listWithDuplicates.RemoveRange(new[] { 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2 })); Assert.Equal(new[] { 1, 3 }, listWithDuplicates.RemoveRange(new[] { 2, 2, 2 })); } [Fact] public void Replace() { Assert.Equal(new[] { 5 }, s_oneElement.Replace(1, 5)); Assert.Equal(new[] { 6, 2, 3 }, s_manyElements.Replace(1, 6)); Assert.Equal(new[] { 1, 6, 3 }, s_manyElements.Replace(2, 6)); Assert.Equal(new[] { 1, 2, 6 }, s_manyElements.Replace(3, 6)); Assert.Equal(new[] { 1, 2, 3, 4 }, ImmutableArray.Create(1, 3, 3, 4).Replace(3, 2)); } [Fact] public void ReplaceMissingThrowsTest() { Assert.Throws<ArgumentException>(() => s_empty.Replace(5, 3)); } [Fact] public void SetItem() { Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.SetItem(0, 10)); Assert.Throws<NullReferenceException>(() => s_emptyDefault.SetItem(0, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => s_oneElement.SetItem(1, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => s_empty.SetItem(-1, 10)); Assert.Equal(new[] { 12345 }, s_oneElement.SetItem(0, 12345)); Assert.Equal(new[] { 12345, 2, 3 }, s_manyElements.SetItem(0, 12345)); Assert.Equal(new[] { 1, 12345, 3 }, s_manyElements.SetItem(1, 12345)); Assert.Equal(new[] { 1, 2, 12345 }, s_manyElements.SetItem(2, 12345)); } [Fact] public void CopyToArray() { { var target = new int[s_manyElements.Length]; s_manyElements.CopyTo(target); Assert.Equal(target, s_manyElements); } { var target = new int[0]; Assert.Throws<NullReferenceException>(() => s_emptyDefault.CopyTo(target)); } } [Fact] public void CopyToIntArrayIntInt() { var source = ImmutableArray.Create(1, 2, 3); var target = new int[4]; source.CopyTo(1, target, 3, 1); Assert.Equal(new[] { 0, 0, 0, 2 }, target); } [Fact] public void Concat() { var array1 = ImmutableArray.Create(1, 2, 3); var array2 = ImmutableArray.Create(4, 5, 6); var concat = array1.Concat(array2); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, concat); } /// <summary> /// Verifies reuse of the original array when concatenated to an empty array. /// </summary> [Fact] public void ConcatEdgeCases() { // empty arrays Assert.Equal(s_manyElements, s_manyElements.Concat(s_empty)); Assert.Equal(s_manyElements, s_empty.Concat(s_manyElements)); // default arrays s_manyElements.Concat(s_emptyDefault); Assert.Throws<InvalidOperationException>(() => s_manyElements.Concat(s_emptyDefault).Count()); Assert.Throws<InvalidOperationException>(() => s_emptyDefault.Concat(s_manyElements).Count()); } [Fact] public void IsDefault() { Assert.True(s_emptyDefault.IsDefault); Assert.False(s_empty.IsDefault); Assert.False(s_oneElement.IsDefault); } [Fact] public void IsDefaultOrEmpty() { Assert.True(s_empty.IsDefaultOrEmpty); Assert.True(s_emptyDefault.IsDefaultOrEmpty); Assert.False(s_oneElement.IsDefaultOrEmpty); } [Fact] public void IndexGetter() { Assert.Equal(1, s_oneElement[0]); Assert.Equal(1, ((IList)s_oneElement)[0]); Assert.Equal(1, ((IList<int>)s_oneElement)[0]); Assert.Equal(1, ((IReadOnlyList<int>)s_oneElement)[0]); Assert.Throws<IndexOutOfRangeException>(() => s_oneElement[1]); Assert.Throws<IndexOutOfRangeException>(() => s_oneElement[-1]); Assert.Throws<NullReferenceException>(() => s_emptyDefault[0]); Assert.Throws<InvalidOperationException>(() => ((IList)s_emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IList<int>)s_emptyDefault)[0]); Assert.Throws<InvalidOperationException>(() => ((IReadOnlyList<int>)s_emptyDefault)[0]); } [Fact] public void ExplicitMethods() { IList<int> c = s_oneElement; Assert.Throws<NotSupportedException>(() => c.Add(3)); Assert.Throws<NotSupportedException>(() => c.Clear()); Assert.Throws<NotSupportedException>(() => c.Remove(3)); Assert.True(c.IsReadOnly); Assert.Throws<NotSupportedException>(() => c.Insert(0, 2)); Assert.Throws<NotSupportedException>(() => c.RemoveAt(0)); Assert.Equal(s_oneElement[0], c[0]); Assert.Throws<NotSupportedException>(() => c[0] = 8); var enumerator = c.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(s_oneElement[0], enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void Sort() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort()); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array uneffected. } [Fact] public void SortNullComparer() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Equal(new[] { 1, 2, 3, 4 }, array.Sort(null)); Assert.Equal(new[] { 2, 4, 1, 3 }, array); // original array uneffected. } [Fact] public void SortRange() { var array = ImmutableArray.Create(2, 4, 1, 3); Assert.Throws<ArgumentOutOfRangeException>(() => array.Sort(-1, 2, Comparer<int>.Default)); Assert.Throws<ArgumentOutOfRangeException>(() => array.Sort(1, 4, Comparer<int>.Default)); Assert.Equal(new int[] { 2, 4, 1, 3 }, array.Sort(array.Length, 0, Comparer<int>.Default)); Assert.Equal(new[] { 2, 1, 4, 3 }, array.Sort(1, 2, Comparer<int>.Default)); } [Fact] public void SortComparer() { var array = ImmutableArray.Create("c", "B", "a"); Assert.Equal(new[] { "a", "B", "c" }, array.Sort(StringComparer.OrdinalIgnoreCase)); Assert.Equal(new[] { "B", "a", "c" }, array.Sort(StringComparer.Ordinal)); } [Fact] public void SortPreservesArrayWhenAlreadySorted() { var sortedArray = ImmutableArray.Create(1, 2, 3, 4); Assert.Equal(sortedArray, sortedArray.Sort()); var mostlySorted = ImmutableArray.Create(1, 2, 3, 4, 6, 5, 7, 8, 9, 10); Assert.Equal(mostlySorted, mostlySorted.Sort(0, 5, Comparer<int>.Default)); Assert.Equal(mostlySorted, mostlySorted.Sort(5, 5, Comparer<int>.Default)); Assert.Equal(Enumerable.Range(1, 10), mostlySorted.Sort(4, 2, Comparer<int>.Default)); } [Fact] public void ToBuilder() { Assert.Equal(0, s_empty.ToBuilder().Count); Assert.Throws<NullReferenceException>(() => s_emptyDefault.ToBuilder().Count); var builder = s_oneElement.ToBuilder(); Assert.Equal(s_oneElement.ToArray(), builder); builder = s_manyElements.ToBuilder(); Assert.Equal(s_manyElements.ToArray(), builder); // Make sure that changing the builder doesn't change the original immutable array. int expected = s_manyElements[0]; builder[0] = expected + 1; Assert.Equal(expected, s_manyElements[0]); Assert.Equal(expected + 1, builder[0]); } [Fact] public void StructuralEquatableEqualsDefault() { IStructuralEquatable eq = s_emptyDefault; Assert.True(eq.Equals(s_emptyDefault, EqualityComparer<int>.Default)); Assert.False(eq.Equals(s_empty, EqualityComparer<int>.Default)); Assert.False(eq.Equals(s_oneElement, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEquals() { IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var otherArray = new object[] { 1, 2, 3 }; var otherImmArray = ImmutableArray.Create(otherArray); var unequalArray = new int[] { 1, 2, 4 }; var unequalImmArray = ImmutableArray.Create(unequalArray); var unrelatedArray = new string[3]; var unrelatedImmArray = ImmutableArray.Create(unrelatedArray); var otherList = new List<int> { 1, 2, 3 }; Assert.Equal(array.Equals(otherArray, EqualityComparer<int>.Default), immArray.Equals(otherImmArray, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(otherList, EqualityComparer<int>.Default), immArray.Equals(otherList, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unrelatedArray, EverythingEqual<object>.Default), immArray.Equals(unrelatedImmArray, EverythingEqual<object>.Default)); Assert.Equal(array.Equals(new object(), EqualityComparer<int>.Default), immArray.Equals(new object(), EqualityComparer<int>.Default)); Assert.Equal(array.Equals(null, EqualityComparer<int>.Default), immArray.Equals(null, EqualityComparer<int>.Default)); Assert.Equal(array.Equals(unequalArray, EqualityComparer<int>.Default), immArray.Equals(unequalImmArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableEqualsArrayInterop() { IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); var unequalArray = new int[] { 1, 2, 4 }; Assert.True(immArray.Equals(array, EqualityComparer<int>.Default)); Assert.False(immArray.Equals(unequalArray, EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCodeDefault() { IStructuralEquatable defaultImmArray = s_emptyDefault; Assert.Equal(0, defaultImmArray.GetHashCode(EqualityComparer<int>.Default)); } [Fact] public void StructuralEquatableGetHashCode() { IStructuralEquatable emptyArray = new int[0]; IStructuralEquatable emptyImmArray = s_empty; IStructuralEquatable array = new int[3] { 1, 2, 3 }; IStructuralEquatable immArray = ImmutableArray.Create(1, 2, 3); Assert.Equal(emptyArray.GetHashCode(EqualityComparer<int>.Default), emptyImmArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EqualityComparer<int>.Default), immArray.GetHashCode(EqualityComparer<int>.Default)); Assert.Equal(array.GetHashCode(EverythingEqual<int>.Default), immArray.GetHashCode(EverythingEqual<int>.Default)); } [Fact] public void StructuralComparableDefault() { IStructuralComparable def = s_emptyDefault; IStructuralComparable mt = s_empty; // default to default is fine, and should be seen as equal. Assert.Equal(0, def.CompareTo(s_emptyDefault, Comparer<int>.Default)); // default to empty and vice versa should throw, on the basis that // arrays compared that are of different lengths throw. Empty vs. default aren't really compatible. Assert.Throws<ArgumentException>(() => def.CompareTo(s_empty, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => mt.CompareTo(s_emptyDefault, Comparer<int>.Default)); } [Fact] public void StructuralComparable() { IStructuralComparable array = new int[3] { 1, 2, 3 }; IStructuralComparable equalArray = new int[3] { 1, 2, 3 }; IStructuralComparable immArray = ImmutableArray.Create((int[])array); IStructuralComparable equalImmArray = ImmutableArray.Create((int[])equalArray); IStructuralComparable longerArray = new int[] { 1, 2, 3, 4 }; IStructuralComparable longerImmArray = ImmutableArray.Create((int[])longerArray); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalImmArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => array.CompareTo(longerArray, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => immArray.CompareTo(longerImmArray, Comparer<int>.Default)); var list = new List<int> { 1, 2, 3 }; Assert.Throws<ArgumentException>(() => array.CompareTo(list, Comparer<int>.Default)); Assert.Throws<ArgumentException>(() => immArray.CompareTo(list, Comparer<int>.Default)); } [Fact] public void StructuralComparableArrayInterop() { IStructuralComparable array = new int[3] { 1, 2, 3 }; IStructuralComparable equalArray = new int[3] { 1, 2, 3 }; IStructuralComparable immArray = ImmutableArray.Create((int[])array); IStructuralComparable equalImmArray = ImmutableArray.Create((int[])equalArray); Assert.Equal(array.CompareTo(equalArray, Comparer<int>.Default), immArray.CompareTo(equalArray, Comparer<int>.Default)); } [Fact] public void BinarySearch() { Assert.Throws<ArgumentNullException>(() => Assert.Equal(Array.BinarySearch(new int[0], 5), ImmutableArray.BinarySearch(default(ImmutableArray<int>), 5))); Assert.Equal(Array.BinarySearch(new int[0], 5), ImmutableArray.BinarySearch(ImmutableArray.Create<int>(), 5)); Assert.Equal(Array.BinarySearch(new int[] { 3 }, 5), ImmutableArray.BinarySearch(ImmutableArray.Create(3), 5)); Assert.Equal(Array.BinarySearch(new int[] { 5 }, 5), ImmutableArray.BinarySearch(ImmutableArray.Create(5), 5)); } [Fact] public void OfType() { Assert.Equal(0, s_emptyDefault.OfType<int>().Count()); Assert.Equal(0, s_empty.OfType<int>().Count()); Assert.Equal(1, s_oneElement.OfType<int>().Count()); Assert.Equal(1, s_twoElementRefTypeWithNull.OfType<string>().Count()); } [Fact] public void Add_ThreadSafety() { // Note the point of this thread-safety test is *not* to test the thread-safety of the test itself. // This test has a known issue where the two threads will stomp on each others updates, but that's not the point. // The point is that ImmutableArray`1.Add should *never* throw. But if it reads its own T[] field more than once, // it *can* throw because the field can be replaced with an array of another length. // In fact, much worse can happen where we corrupt data if we are for example copying data out of the array // in (for example) a CopyTo method and we read from the field more than once. // Also noteworthy: this method only tests the thread-safety of the Add method. // While it proves the general point, any method that reads 'this' more than once is vulnerable. var array = ImmutableArray.Create<int>(); Action mutator = () => { for (int i = 0; i < 100; i++) { ImmutableInterlocked.InterlockedExchange(ref array, array.Add(1)); } }; Task.WaitAll(Task.Run(mutator), Task.Run(mutator)); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableArray.Create(contents); } /// <summary> /// A structure that takes exactly 3 bytes of memory. /// </summary> private struct ThreeByteStruct : IEquatable<ThreeByteStruct> { public ThreeByteStruct(byte first, byte second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public byte Field1; public byte Field2; public byte Field3; public bool Equals(ThreeByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is ThreeByteStruct) { return this.Equals((ThreeByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that takes exactly 9 bytes of memory. /// </summary> private struct NineByteStruct : IEquatable<NineByteStruct> { public NineByteStruct(int first, int second, int third, int fourth, int fifth, int sixth, int seventh, int eighth, int ninth) { this.Field1 = (byte)first; this.Field2 = (byte)second; this.Field3 = (byte)third; this.Field4 = (byte)fourth; this.Field5 = (byte)fifth; this.Field6 = (byte)sixth; this.Field7 = (byte)seventh; this.Field8 = (byte)eighth; this.Field9 = (byte)ninth; } public byte Field1; public byte Field2; public byte Field3; public byte Field4; public byte Field5; public byte Field6; public byte Field7; public byte Field8; public byte Field9; public bool Equals(NineByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3 && this.Field4 == other.Field4 && this.Field5 == other.Field5 && this.Field6 == other.Field6 && this.Field7 == other.Field7 && this.Field8 == other.Field8 && this.Field9 == other.Field9; } public override bool Equals(object obj) { if (obj is NineByteStruct) { return this.Equals((NineByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } /// <summary> /// A structure that requires 9 bytes of memory but occupies 12 because of memory alignment. /// </summary> private struct TwelveByteStruct : IEquatable<TwelveByteStruct> { public TwelveByteStruct(int first, int second, byte third) { this.Field1 = first; this.Field2 = second; this.Field3 = third; } public int Field1; public int Field2; public byte Field3; public bool Equals(TwelveByteStruct other) { return this.Field1 == other.Field1 && this.Field2 == other.Field2 && this.Field3 == other.Field3; } public override bool Equals(object obj) { if (obj is TwelveByteStruct) { return this.Equals((TwelveByteStruct)obj); } return false; } public override int GetHashCode() { return this.Field1; } } private struct StructWithReferenceTypeField { public string foo; public StructWithReferenceTypeField(string foo) { this.foo = foo; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlServerCe; using System.IO; using DowUtils; namespace Factotum { public partial class AppMain : Form { // Allow 3 seconds to connect to webservice const int BlacklistCheckTimeout = 3000; public AppMain() { InitializeComponent(); } private void customerToolStripMenuItem_Click(object sender, EventArgs e) { CustomerConfigView ccv = new CustomerConfigView(); ccv.MdiParent = this; ccv.Show(); } private void AppMain_FormClosing(object sender, FormClosingEventArgs e) { Globals.cnn.Close(); Globals.DatabaseChanged -= new EventHandler(Globals_DatabaseChanged); Globals.CurrentOutageChanged -= new EventHandler(Globals_CurrentOutageChanged); backupCurrentDB(); } private void AppMain_Load(object sender, EventArgs e) { UserSettings.Load(); AppDomain.CurrentDomain.SetData("DataDirectory", Globals.AppDataFolder); Globals.SetDefaultFactotumDataFolder(); Globals.SetDefaultImageFolder(); Globals.SetDefaultMeterDataFolder(); Globals.InitConnection(); // Get the Database Version and type (IsMasterDB). // We need to know what kind of database Factotum.sdf is in case the user double-clicks // and we need to back up. Globals.ReadDatabaseInfo(); // It's startup of a fresh install if (Globals.IsNewDB) { // No need to back up first. Globals.ConvertCurrentDbToMaster(); } if (!Globals.IsNewDB) { // This needs to be set to do the caption right Globals.SetCurrentOutageID(); } // If the user has specified a database by clicking on a database file, // Let them backup and open it. bool isOpenedWithFile = false; string[] args = Environment.GetCommandLineArgs(); if (args.Length == 2) { DialogResult resp = MessageBox.Show( "Would you like to open this data file: \n" + args[1], "Factotum: Open Data File?", MessageBoxButtons.YesNo); if (resp == DialogResult.Yes) { // Open the selected file. Prompt the user to backup first, unless // its a new (empty) database. isOpenedWithFile = handleFileOpenRequest(args[1], !Globals.IsNewDB); } } // If the current database was changed by the previous block, // The OpenDatabaseFile method will take care of getting and acting on the // new database info. // Wire up these handlers for keeping the caption and menus refreshed if the user // opens a different database later. Globals.DatabaseChanged += new EventHandler(Globals_DatabaseChanged); Globals.CurrentOutageChanged += new EventHandler(Globals_CurrentOutageChanged); // Handle menus and form caption handleMenuEnabling(); UpdateFormCaption(); } private void UpdateFormCaption() { this.Text = "Factotum " + Globals.VersionString; string database = Globals.IsMasterDB ? " - Master Data File - " : " - Outage Data File - "; string outage; if (Globals.CurrentOutageID != null) outage = "Current Outage: " + new EOutage(Globals.CurrentOutageID).OutageName; else outage = "No Current Outage"; this.Text += database + " (" + outage + ")"; } void Globals_CurrentOutageChanged(object sender, EventArgs e) { handleMenuEnabling(); UpdateFormCaption(); } void Globals_DatabaseChanged(object sender, EventArgs e) { handleMenuEnabling(); UpdateFormCaption(); } public void handleMenuEnabling() { bool masterDB = Globals.IsMasterDB; bool newDB = Globals.IsNewDB; //bool inactiveDB = !Globals.ActivationOK; bool outageOK = Globals.CurrentOutageID != null; this.componentReportToolStripMenuItem.Visible = !masterDB; this.importComponentReportDefinitionToolStripMenuItem.Visible = !masterDB; this.importOutageConfigurationDataToolStripMenuItem.Visible = masterDB; this.customerToolStripMenuItem.Visible = masterDB; this.toolKitsToolStripMenuItem.Visible = !masterDB; this.viewChangesFromOutageToolStripMenuItem.Visible = masterDB; this.convertToMasterDBToolStripMenuItem.Enabled = !masterDB && !newDB; this.importOutageConfigurationDataToolStripMenuItem.Enabled = !newDB; this.equipmentToolStripMenuItem.Enabled = !newDB; this.proceduresToolStripMenuItem.Enabled = !newDB; this.componentMaterialsToolStripMenuItem.Enabled = !newDB; this.componentsToolStripMenuItem.Enabled = !newDB; this.componentTypesToolStripMenuItem.Enabled = !newDB; this.importToolStripMenuItem.Enabled = !newDB; this.outageToolStripMenuItem.Enabled = !newDB; this.componentReportToolStripMenuItem.Enabled = !newDB; this.utilitiesToolStripMenuItem.Enabled = !newDB; this.siteConfigurationToolStripMenuItem.Enabled = !newDB; this.preferencesToolStripMenuItem.Enabled = !newDB; this.exportToolStripMenuItem.Enabled = !newDB; this.inspectorsToolStripMenuItem.Enabled = !newDB; this.ImportComponentsToolStripMenuItem.Enabled = outageOK; this.currentOutageToolStripMenuItem.Enabled = outageOK; } private void componentMaterialsToolStripMenuItem_Click(object sender, EventArgs e) { MaterialTypeView frm = new MaterialTypeView(); frm.MdiParent = this; frm.Show(); } private void componentTypesToolStripMenuItem_Click(object sender, EventArgs e) { ComponentTypeView frm = new ComponentTypeView(); frm.MdiParent = this; frm.Show(); } private void pipeScheduleLookupToolStripMenuItem_Click(object sender, EventArgs e) { PipeScheduleView frm = new PipeScheduleView(); frm.MdiParent = this; frm.Show(); } private void componentsToolStripMenuItem_Click(object sender, EventArgs e) { ComponentView frm = new ComponentView(); frm.MdiParent = this; frm.Show(); } // This menu option is disabled for a Master database if we don't have a CurrentOutageID private void componentReportToolStripMenuItem_Click(object sender, EventArgs e) { InspectedComponentView frm = new InspectedComponentView((Guid)Globals.CurrentOutageID); frm.MdiParent = this; frm.Show(); } private void meterModelsToolStripMenuItem_Click(object sender, EventArgs e) { MeterModelView frm = new MeterModelView(); frm.MdiParent = this; frm.Show(); } private void transducerModelsToolStripMenuItem_Click(object sender, EventArgs e) { DucerModelView frm = new DucerModelView(); frm.MdiParent = this; frm.Show(); } private void transducersToolStripMenuItem_Click(object sender, EventArgs e) { DucerView frm = new DucerView(); frm.MdiParent = this; frm.Show(); } private void metersToolStripMenuItem_Click(object sender, EventArgs e) { MeterView frm = new MeterView(); frm.MdiParent = this; frm.Show(); } private void thermomToolStripMenuItem_Click(object sender, EventArgs e) { ThermoView frm = new ThermoView(); frm.MdiParent = this; frm.Show(); } private void calibrationBlocksToolStripMenuItem_Click(object sender, EventArgs e) { CalBlockView frm = new CalBlockView(); frm.MdiParent = this; frm.Show(); } private void gridProceduresToolStripMenuItem_Click(object sender, EventArgs e) { GridProcedureView frm = new GridProcedureView(); frm.MdiParent = this; frm.Show(); } private void calibrationProceduresToolStripMenuItem_Click(object sender, EventArgs e) { CalibrationProcedureView frm = new CalibrationProcedureView(); frm.MdiParent = this; frm.Show(); } private void couplantTypesToolStripMenuItem_Click(object sender, EventArgs e) { CouplantTypeView frm = new CouplantTypeView(); frm.MdiParent = this; frm.Show(); } // This menu option is disabled for a master database if we don't have a CurrentOutageID. private void currentOutageToolStripMenuItem_Click(object sender, EventArgs e) { Guid? OutageID = Globals.CurrentOutageID; if (OutageID != null) { OutageEdit frm = new OutageEdit(OutageID); frm.MdiParent = this; frm.Show(); } } private void inspectorsToolStripMenuItem_Click(object sender, EventArgs e) { InspectorView frm = new InspectorView(); frm.MdiParent = this; frm.Show(); } private void toolKitsToolStripMenuItem_Click(object sender, EventArgs e) { KitView frm = new KitView(); frm.MdiParent = this; frm.Show(); } private void gridSizesToolStripMenuItem_Click(object sender, EventArgs e) { GridSizeView frm = new GridSizeView(); frm.MdiParent = this; frm.Show(); } private void radialLocationsToolStripMenuItem_Click(object sender, EventArgs e) { RadialLocationView frm = new RadialLocationView(); frm.MdiParent = this; frm.Show(); } // This menu option is disabled for a master database if we don't have a CurrentOutageID. private void ImportComponentsToolStripMenuItem_Click(object sender, EventArgs e) { Guid? OutageID = Globals.CurrentOutageID; EOutage curOutage = new EOutage(OutageID); ComponentImporter frm = new ComponentImporter((Guid)curOutage.OutageUntID); frm.MdiParent = this; frm.Show(); } // This menu option is hidden for a master database. Report definitions are Outage-Specific data. private void importComponentReportDefinitionToolStripMenuItem_Click(object sender, EventArgs e) { ReportDefinitionImporter frm = new ReportDefinitionImporter((Guid)Globals.CurrentOutageID); frm.MdiParent = this; frm.Show(); } private void testConfigurationToolStripMenuItem_Click(object sender, EventArgs e) { Preferences_Master frm = new Preferences_Master(); frm.MdiParent = this; frm.Show(); } private void specialCalibrationParametersToolStripMenuItem_Click(object sender, EventArgs e) { SpecialCalParamView frm = new SpecialCalParamView(); frm.MdiParent = this; frm.Show(); } private void exportToolStripMenuItem_Click(object sender, EventArgs e) { string filePath; BackupCurrentDatabase(true, out filePath); } private bool BackupCurrentDatabase(bool IsUserBackupRequired, out string filePath) { filePath = null; if (IsUserBackupRequired) { saveFileDialog1.InitialDirectory = Globals.FactotumDataFolder; saveFileDialog1.Filter = (Globals.IsMasterDB ? "Factotum Master Data Files *.mfac | *.mfac" : "Factotum Outage Data Files *.ofac | *.ofac"); saveFileDialog1.DefaultExt = (Globals.IsMasterDB ? ".mfac" : ".ofac"); saveFileDialog1.FileName = Globals.getUniqueBackupFileName(Globals.FactotumDataFolder); DialogResult rslt = saveFileDialog1.ShowDialog(); // Note: If the user selects a file that already exists, the Save Dialog // will handle warning the user if (rslt == DialogResult.OK) { // Overwrite flag is specified -- could anything go wrong?? filePath = saveFileDialog1.FileName; File.Copy(Globals.FactotumDatabaseFilePath, filePath, true); } return (rslt == DialogResult.OK); } else { filePath = Path.GetTempPath() + "Factotum.sdf"; File.Copy(Globals.FactotumDatabaseFilePath, filePath, true); return true; } } // To open a new file, we must first backup the current file, // then open the new file and test for validity. If it's invalid, we need to // explain the problem and reopen the original. private void openToolStripMenuItem_Click(object sender, EventArgs e) { string filePathToOpen = null; if (!SelectFileToOpen(out filePathToOpen)) return; // Unless it's a new db, ask the user for a backup location first handleFileOpenRequest(filePathToOpen, !Globals.IsNewDB); } private void handleFileOpenRequest(string filePathToOpen) { handleFileOpenRequest(filePathToOpen, true); } private bool handleFileOpenRequest(string filePathToOpen, bool IsUserBackupRequired) { string backupPath = null; string message; // We always back up before opening, because the open operation may fail. // But in certain situations, like a new install, we'd rather not bother the user to // backup before opening. As far as they're concerned there's nothing to back up. // So in this case, back up to a temp file. if (!BackupBeforeFileOpen(IsUserBackupRequired, out backupPath)) return false; if (!OpenDatabaseFile(filePathToOpen, out message)) { // We always need to restore the original database if the Open attempt fails. if (Globals.cnn.State != ConnectionState.Closed) Globals.cnn.Close(); File.Copy(backupPath, Globals.FactotumDatabaseFilePath, true); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); Globals.ReadDatabaseInfo(); MessageBox.Show(message + "\nFile Open Operation was Cancelled", "Factotum: Cancelled File Open"); return false; } return true; } private bool SelectFileToOpen(out string filePath) { filePath = null; openFileDialog1.InitialDirectory = Globals.FactotumDataFolder; openFileDialog1.Filter = "All Factotum Data Files *.mfac, *.ofac|*.mfac;*.ofac|Factotum Master Data Files *.mfac|*.mfac|Factotum Outage Data Files *.ofac|*.ofac"; openFileDialog1.Title = "Select a Data File to Open"; openFileDialog1.DefaultExt = ".ofac"; DialogResult rslt = openFileDialog1.ShowDialog(); filePath = openFileDialog1.FileName; return (rslt == DialogResult.OK); } private bool BackupBeforeFileOpen(bool IsUserBackupRequired, out string filePath) { filePath = null; if (IsUserBackupRequired) { MessageBox.Show("The current data file must be backed up first.", "Factotum: Backup Required"); } if (!BackupCurrentDatabase(IsUserBackupRequired, out filePath)) { MessageBox.Show("File Open operation was cancelled", "Factotum: User Cancelled"); return false; } return true; } // Copy the file from the given path to the application directory, then // connect to it. private bool OpenDatabaseFile(string filePathToOpen, out string message) { // Close all the windows first foreach (Form mdiChild in this.MdiChildren) { mdiChild.Close(); } message = null; if (Globals.cnn.State != ConnectionState.Closed) Globals.cnn.Close(); // Overwrite flag is specified -- could anything go wrong?? File.Copy(filePathToOpen, Globals.FactotumDatabaseFilePath, true); try { if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); } catch (Exception ex) { ExceptionLogger.LogException(ex); message = "Unable to open data file."; return false; } Globals.ReadDatabaseInfo(); if (!Globals.IsDatabaseOk(out message)) { return false; } return true; } private void importOutageConfigurationDataToolStripMenuItem_Click(object sender, EventArgs e) { List<ChangeFinder> configTables = new List<ChangeFinder>(); openFileDialog1.InitialDirectory = Globals.FactotumDataFolder; openFileDialog1.Filter = "Outage Data Files *.ofac | *.ofac"; openFileDialog1.Title = "Select an Outage Data File to Import"; DialogResult rslt = openFileDialog1.ShowDialog(); if (rslt == DialogResult.OK) { // Copy the selected file to a temporary location so we can do some cleanup. string tempFile = Path.GetTempFileName(); string tempDbPath = tempFile.Substring(0,tempFile.Length - 4) + ".ofac"; // Overwrite flag is specified File.Copy(openFileDialog1.FileName, tempDbPath, true); string outageConnectionString = Globals.ConnectionStringForPath(tempDbPath); SqlCeConnection cnnOutage = new SqlCeConnection(outageConnectionString); // Check the database version. If it's too old, the user needs to open it and save it if (cnnOutage.State != ConnectionState.Open) cnnOutage.Open(); SqlCeCommand cmd = cnnOutage.CreateCommand(); cmd.CommandText = @"Select DatabaseVersion, IsMasterDB from Globals"; SqlCeDataReader rdr = cmd.ExecuteReader(); int DatabaseVersion = 0; bool isMasterDB = false; if (rdr.Read()) { DatabaseVersion = (int)rdr["DatabaseVersion"]; isMasterDB = (bool)rdr["IsMasterDB"]; } rdr.Close(); if (isMasterDB) { MessageBox.Show("The selected file does not contain outage data.","Factotum"); return; } if (DatabaseVersion < UserSettings.sets.DbVersion) { MessageBox.Show("The selected Outage Data File is an older version. The following must be done:\nOpen this file and Back it up to a new Outage Data file, then Import that new Outage Data File instead.","Factotum"); return; } // delete tool kit assignments, set UsedInOutage flags // reset IsLclChange flags, and update the OutageImportedOn date for the outage. ChangeFinder.CleanUpOutageDatabase(cnnOutage); // Do the table comparisons for each configuration table // The order of that the tables are added to the list is important. Add parent tables // first. ChgCustomer customerChanges = new ChgCustomer(Globals.cnn, cnnOutage); customerChanges.CompareTables_std(); configTables.Add(customerChanges); ChgCalibrationProcedure calibrationProcedureChanges = new ChgCalibrationProcedure(Globals.cnn, cnnOutage); calibrationProcedureChanges.CompareTables_std(); configTables.Add(calibrationProcedureChanges); ChgSite siteChanges = new ChgSite(Globals.cnn, cnnOutage); siteChanges.CompareTables_std(); configTables.Add(siteChanges); ChgUnit unitChanges = new ChgUnit(Globals.cnn, cnnOutage); unitChanges.CompareTables_std(); configTables.Add(unitChanges); ChgMeterModel meterModelChanges = new ChgMeterModel(Globals.cnn, cnnOutage); meterModelChanges.CompareTables_std(); configTables.Add(meterModelChanges); ChgDucerModel ducerModelChanges = new ChgDucerModel(Globals.cnn, cnnOutage); ducerModelChanges.CompareTables_std(); configTables.Add(ducerModelChanges); ChgDucer ducerChanges = new ChgDucer(Globals.cnn, cnnOutage); ducerChanges.CompareTables_std(); configTables.Add(ducerChanges); ChgMeter meterChanges = new ChgMeter(Globals.cnn, cnnOutage); meterChanges.CompareTables_std(); configTables.Add(meterChanges); ChgInspector inspectorChanges = new ChgInspector(Globals.cnn, cnnOutage); inspectorChanges.CompareTables_std(); configTables.Add(inspectorChanges); ChgCalBlock calBlockChanges = new ChgCalBlock(Globals.cnn, cnnOutage); calBlockChanges.CompareTables_std(); configTables.Add(calBlockChanges); ChgThermo thermoChanges = new ChgThermo(Globals.cnn, cnnOutage); thermoChanges.CompareTables_std(); configTables.Add(thermoChanges); ChgSpecialCalParam specialCalParamChanges = new ChgSpecialCalParam(Globals.cnn, cnnOutage); specialCalParamChanges.CompareTables_std(); configTables.Add(specialCalParamChanges); ChgCouplantType couplantTypeChanges = new ChgCouplantType(Globals.cnn, cnnOutage); couplantTypeChanges.CompareTables_std(); configTables.Add(couplantTypeChanges); ChgGridProcedure gridProcedureChanges = new ChgGridProcedure(Globals.cnn, cnnOutage); gridProcedureChanges.CompareTables_std(); configTables.Add(gridProcedureChanges); ChgComponentMaterial componentMaterialChanges = new ChgComponentMaterial(Globals.cnn, cnnOutage); componentMaterialChanges.CompareTables_std(); configTables.Add(componentMaterialChanges); ChgComponentType componentTypeChanges = new ChgComponentType(Globals.cnn, cnnOutage); componentTypeChanges.CompareTables_std(); configTables.Add(componentTypeChanges); ChgSystem systemChanges = new ChgSystem(Globals.cnn, cnnOutage); systemChanges.CompareTables_std(); configTables.Add(systemChanges); ChgLine lineChanges = new ChgLine(Globals.cnn, cnnOutage); lineChanges.CompareTables_std(); configTables.Add(lineChanges); ChgPipeScheduleLookup pipeScheduleLookupChanges = new ChgPipeScheduleLookup(Globals.cnn, cnnOutage); pipeScheduleLookupChanges.CompareTables_std(); configTables.Add(pipeScheduleLookupChanges); ChgRadialLocation radialLocationChanges = new ChgRadialLocation(Globals.cnn, cnnOutage); radialLocationChanges.CompareTables_std(); configTables.Add(radialLocationChanges); ChgGridSize gridSizeChanges = new ChgGridSize(Globals.cnn, cnnOutage); gridSizeChanges.CompareTables_std(); configTables.Add(gridSizeChanges); ChgComponent componentChanges = new ChgComponent(Globals.cnn, cnnOutage); componentChanges.CompareTables_std(); configTables.Add(componentChanges); ChgOutage outageChanges = new ChgOutage(Globals.cnn, cnnOutage); outageChanges.CompareTables_std(); configTables.Add(outageChanges); // Map tables ChgMeterDucer meterDucerChanges = new ChgMeterDucer(Globals.cnn, cnnOutage); meterDucerChanges.CompareTables_map(); configTables.Add(meterDucerChanges); ChgOutageGridProcedure outageGridProcedureChanges = new ChgOutageGridProcedure(Globals.cnn, cnnOutage); outageGridProcedureChanges.CompareTables_map(); configTables.Add(outageGridProcedureChanges); ChgOutageInspector outageInspectorChanges = new ChgOutageInspector(Globals.cnn, cnnOutage); outageInspectorChanges.CompareTables_map(); configTables.Add(outageInspectorChanges); bool first = true; foreach (ChangeFinder tbl in configTables) { tbl.AppendInsertionInfo(first); tbl.AppendModificationInfo(first); tbl.AppendAssignmentChangeInfo(first); first = false; tbl.UpdateOriginalTable(); } MessageBox.Show("Outage Data File Imported OK", "Factotum: Import Outage"); } } private void convertToMasterDBToolStripMenuItem_Click(object sender, EventArgs e) { string backupPath; if (BackupCurrentDatabase(true, out backupPath)) { Globals.ConvertCurrentDbToMaster(); } } private void linesToolStripMenuItem_Click(object sender, EventArgs e) { LineView frm = new LineView(); frm.MdiParent = this; frm.Show(); } private void systemsToolStripMenuItem_Click(object sender, EventArgs e) { SystemView frm = new SystemView(); frm.MdiParent = this; frm.Show(); } private void generalToolStripMenuItem_Click(object sender, EventArgs e) { Preferences_General frm = new Preferences_General(); frm.MdiParent = this; frm.Show(); } private void viewChangesFromOutageToolStripMenuItem_Click(object sender, EventArgs e) { OutageChangesViewer frm = new OutageChangesViewer(); frm.MdiParent = this; frm.Show(); } private void generateANewActivationKeyToolStripMenuItem_Click(object sender, EventArgs e) { ActivationKeyGenerator frm = new ActivationKeyGenerator(false); frm.MdiParent = this; frm.Show(); } private void tmrBackup_Tick(object sender, EventArgs e) { backupCurrentDB(); } private void backupCurrentDB() { File.Copy(Globals.FactotumDatabaseFilePath, Globals.FactotumBackupFilePath, true); } private void restoreAutobackupToolStripMenuItem_Click(object sender, EventArgs e) { if (!File.Exists(Globals.FactotumBackupFilePath)) { MessageBox.Show("No backup file exists","Factotum"); return; } handleFileOpenRequest(Globals.FactotumBackupFilePath, !Globals.IsNewDB); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using DontPanic.API.Areas.HelpPage.ModelDescriptions; using DontPanic.API.Areas.HelpPage.Models; namespace DontPanic.API.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: RunClient.cs // // Description: RunClient represents opaque data storage associated with runs // consumed by TextFormatter. // // History: // 05/05/2003 : [....] - moving from Avalon branch. // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.TextFormatting; using MS.Internal; using MS.Internal.Text; using MS.Internal.Documents; using MS.Internal.PtsHost.UnsafeNativeMethods; namespace MS.Internal.PtsHost { /// <summary> /// Inline object run. /// </summary> internal sealed class InlineObjectRun : TextEmbeddedObject { /// <summary> /// Constructor. /// </summary> /// <param name="cch">Number of text position in the text array occupied by the inline object.</param> /// <param name="element">UIElement representing the inline object.</param> /// <param name="textProps">Text run properties for the inline object.</param> /// <param name="host">Paragraph - the host of the inline object.</param> internal InlineObjectRun(int cch, UIElement element, TextRunProperties textProps, TextParagraph host) { _cch = cch; _textProps = textProps; _host = host; _inlineUIContainer = (InlineUIContainer)LogicalTreeHelper.GetParent(element); } /// <summary> /// Get inline object's measurement metrics. /// </summary> /// <param name="remainingParagraphWidth">Remaining paragraph width.</param> /// <returns>Inline object metrics.</returns> public override TextEmbeddedObjectMetrics Format(double remainingParagraphWidth) { Size desiredSize = _host.MeasureChild(this); // Make sure that LS/PTS limitations are not exceeded for object's size. TextDpi.EnsureValidObjSize(ref desiredSize); double baseline = desiredSize.Height; double baselineOffsetValue = (double)UIElementIsland.Root.GetValue(TextBlock.BaselineOffsetProperty); if(!DoubleUtil.IsNaN(baselineOffsetValue)) { baseline = baselineOffsetValue; } return new TextEmbeddedObjectMetrics(desiredSize.Width, desiredSize.Height, baseline); } /// <summary> /// Get computed bounding box of the inline object. /// </summary> /// <param name="rightToLeft">Run is drawn from right to left.</param> /// <param name="sideways">Run is drawn with its side parallel to baseline.</param> /// <returns>Computed bounding box size of text object.</returns> public override Rect ComputeBoundingBox(bool rightToLeft, bool sideways) { // Initially assume that bounding box is the same as layout box. // NOTE: PTS requires bounding box during line formatting. This eventually triggers // TextFormatter to call this function. // But at that time computed size is not available yet. Use desired size instead. Size size = UIElementIsland.Root.DesiredSize; double baseline = !sideways ? size.Height : size.Width; double baselineOffsetValue = (double)UIElementIsland.Root.GetValue(TextBlock.BaselineOffsetProperty); if (!sideways && !DoubleUtil.IsNaN(baselineOffsetValue)) { baseline = (double) baselineOffsetValue; } return new Rect(0, -baseline, sideways ? size.Height : size.Width, sideways ? size.Width : size.Height); } /// <summary> /// Draw the inline object. /// </summary> /// <param name="drawingContext">Drawing context.</param> /// <param name="origin">Origin where the object is drawn.</param> /// <param name="rightToLeft">Run is drawn from right to left.</param> /// <param name="sideways">Run is drawn with its side parallel to baseline.</param> public override void Draw(DrawingContext drawingContext, Point origin, bool rightToLeft, bool sideways) { // Inline object has its own visual and it is attached to a visual // tree during arrange process. // Do nothing here. } /// <summary> /// Reference to character buffer. /// </summary> public override CharacterBufferReference CharacterBufferReference { get { return new CharacterBufferReference(String.Empty, 0); } } /// <summary> /// Length of the inline object run. /// </summary> public override int Length { get { return _cch; } } /// <summary> /// A set of properties shared by every characters in the run /// </summary> public override TextRunProperties Properties { get { return _textProps; } } /// <summary> /// Line break condition before the inline object. /// </summary> public override LineBreakCondition BreakBefore { get { return LineBreakCondition.BreakDesired; } } /// <summary> /// Line break condition after the inline object. /// </summary> public override LineBreakCondition BreakAfter { get { return LineBreakCondition.BreakDesired; } } /// <summary> /// Flag indicates whether inline object has fixed size regardless of where /// it is placed within a line. /// </summary> public override bool HasFixedSize { get { // Size of inline object is not dependent on position in the line. return true; } } /// <summary> /// UIElementIsland representing embedded Element Layout island within content world. /// </summary> internal UIElementIsland UIElementIsland { get { return _inlineUIContainer.UIElementIsland; } } /// <summary> /// Number of text position in the text array occupied by the inline object. /// </summary> private readonly int _cch; /// <summary> /// Text run properties for the inline object. /// </summary> private readonly TextRunProperties _textProps; /// <summary> /// Paragraph - the host of the inline object. /// </summary> private readonly TextParagraph _host; /// <summary> /// Inline UI Container associated with this run client /// </summary> private InlineUIContainer _inlineUIContainer; } /// <summary> /// Floating object run. /// </summary> internal sealed class FloatingRun : TextHidden { internal FloatingRun(int length, bool figure) : base(length) { _figure = figure; } internal bool Figure { get { return _figure; } } private readonly bool _figure; } /// <summary> /// Custom paragraph break run. /// </summary> internal sealed class ParagraphBreakRun : TextEndOfParagraph { internal ParagraphBreakRun(int length, PTS.FSFLRES breakReason) : base(length) { BreakReason = breakReason; } internal readonly PTS.FSFLRES BreakReason; } /// <summary> /// Custom line break run. /// </summary> internal sealed class LineBreakRun : TextEndOfLine { internal LineBreakRun(int length, PTS.FSFLRES breakReason) : base(length) { BreakReason = breakReason; } internal readonly PTS.FSFLRES BreakReason; } }
using System.Runtime.InteropServices; using IL2CPU.API.Attribs; namespace Cosmos.Core { public class INTs { #region Enums // TODO: Protect IRQs like memory and ports are // TODO: Make IRQs so they are not hookable, and instead release high priority threads like FreeBSD (When we get threading) public enum EFlagsEnum : uint { Carry = 1, Parity = 1 << 2, AuxilliaryCarry = 1 << 4, Zero = 1 << 6, Sign = 1 << 7, Trap = 1 << 8, InterruptEnable = 1 << 9, Direction = 1 << 10, Overflow = 1 << 11, NestedTag = 1 << 14, Resume = 1 << 16, Virtual8086Mode = 1 << 17, AlignmentCheck = 1 << 18, VirtualInterrupt = 1 << 19, VirtualInterruptPending = 1 << 20, ID = 1 << 21 } [StructLayout(LayoutKind.Explicit, Size = 0x68)] public struct TSS { [FieldOffset(0)] public ushort Link; [FieldOffset(4)] public uint ESP0; [FieldOffset(8)] public ushort SS0; [FieldOffset(12)] public uint ESP1; [FieldOffset(16)] public ushort SS1; [FieldOffset(20)] public uint ESP2; [FieldOffset(24)] public ushort SS2; [FieldOffset(28)] public uint CR3; [FieldOffset(32)] public uint EIP; [FieldOffset(36)] public EFlagsEnum EFlags; [FieldOffset(40)] public uint EAX; [FieldOffset(44)] public uint ECX; [FieldOffset(48)] public uint EDX; [FieldOffset(52)] public uint EBX; [FieldOffset(56)] public uint ESP; [FieldOffset(60)] public uint EBP; [FieldOffset(64)] public uint ESI; [FieldOffset(68)] public uint EDI; [FieldOffset(72)] public ushort ES; [FieldOffset(76)] public ushort CS; [FieldOffset(80)] public ushort SS; [FieldOffset(84)] public ushort DS; [FieldOffset(88)] public ushort FS; [FieldOffset(92)] public ushort GS; [FieldOffset(96)] public ushort LDTR; [FieldOffset(102)] public ushort IOPBOffset; } [StructLayout(LayoutKind.Explicit, Size = 512)] public struct MMXContext { } [StructLayout(LayoutKind.Explicit, Size = 80)] public struct IRQContext { [FieldOffset(0)] public unsafe MMXContext* MMXContext; [FieldOffset(4)] public uint EDI; [FieldOffset(8)] public uint ESI; [FieldOffset(12)] public uint EBP; [FieldOffset(16)] public uint ESP; [FieldOffset(20)] public uint EBX; [FieldOffset(24)] public uint EDX; [FieldOffset(28)] public uint ECX; [FieldOffset(32)] public uint EAX; [FieldOffset(36)] public uint Interrupt; [FieldOffset(40)] public uint Param; [FieldOffset(44)] public uint EIP; [FieldOffset(48)] public uint CS; [FieldOffset(52)] public EFlagsEnum EFlags; [FieldOffset(56)] public uint UserESP; } #endregion [AsmMarker(AsmMarker.Type.Int_LastKnownAddress)] private static uint mLastKnownAddress; private static IRQDelegate[] mIRQ_Handlers = new IRQDelegate[256]; // We used to use: //Interrupts.IRQ01 += HandleKeyboardInterrupt; // But at one point we had issues with multi cast delegates, so we changed to this single cast option. // [1:48:37 PM] Matthijs ter Woord: the issues were: "they didn't work, would crash kernel". not sure if we still have them.. public static void SetIntHandler(byte aIntNo, IRQDelegate aHandler) { mIRQ_Handlers[aIntNo] = aHandler; } public static void SetIrqHandler(byte aIrqNo, IRQDelegate aHandler) { SetIntHandler((byte)(0x20 + aIrqNo), aHandler); } private static void IRQ(uint irq, ref IRQContext aContext) { var xCallback = mIRQ_Handlers[irq]; if (xCallback != null) { xCallback(ref aContext); } } public static void HandleInterrupt_Default(ref IRQContext aContext) { if (aContext.Interrupt >= 0x20 && aContext.Interrupt <= 0x2F) { if (aContext.Interrupt >= 0x28) { Global.PIC.EoiSlave(); } else { Global.PIC.EoiMaster(); } } } public delegate void IRQDelegate(ref IRQContext aContext); public delegate void ExceptionInterruptDelegate(ref IRQContext aContext, ref bool aHandled); #region Default Interrupt Handlers //IRQ 0 - System timer. Reserved for the system. Cannot be changed by a user. public static void HandleInterrupt_20(ref IRQContext aContext) { IRQ(0x20, ref aContext); Global.PIC.EoiMaster(); } //public static IRQDelegate IRQ01; //IRQ 1 - Keyboard. Reserved for the system. Cannot be altered even if no keyboard is present or needed. public static void HandleInterrupt_21(ref IRQContext aContext) { IRQ(0x21, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_22(ref IRQContext aContext) { IRQ(0x22, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_23(ref IRQContext aContext) { IRQ(0x23, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_24(ref IRQContext aContext) { IRQ(0x24, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_25(ref IRQContext aContext) { IRQ(0x25, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_26(ref IRQContext aContext) { IRQ(0x26, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_27(ref IRQContext aContext) { IRQ(0x27, ref aContext); Global.PIC.EoiMaster(); } public static void HandleInterrupt_28(ref IRQContext aContext) { IRQ(0x28, ref aContext); Global.PIC.EoiSlave(); } //IRQ 09 - (Added for AMD PCNet network card) //public static IRQDelegate IRQ09; public static void HandleInterrupt_29(ref IRQContext aContext) { IRQ(0x29, ref aContext); Global.PIC.EoiSlave(); } //IRQ 10 - (Added for VIA Rhine network card) //public static IRQDelegate IRQ10; public static void HandleInterrupt_2A(ref IRQContext aContext) { IRQ(0x2A, ref aContext); Global.PIC.EoiSlave(); } //IRQ 11 - (Added for RTL8139 network card) //public static IRQDelegate IRQ11; public static void HandleInterrupt_2B(ref IRQContext aContext) { IRQ(0x2B, ref aContext); Global.PIC.EoiSlave(); } public static void HandleInterrupt_2C(ref IRQContext aContext) { IRQ(0x2C, ref aContext); Global.PIC.EoiSlave(); } public static void HandleInterrupt_2D(ref IRQContext aContext) { IRQ(0x2D, ref aContext); Global.PIC.EoiSlave(); } //IRQ 14 - Primary IDE. If no Primary IDE this can be changed public static void HandleInterrupt_2E(ref IRQContext aContext) { IRQ(0x2E, ref aContext); Global.PIC.EoiSlave(); } //IRQ 15 - Secondary IDE public static void HandleInterrupt_2F(ref IRQContext aContext) { IRQ(0x2F, ref aContext); Global.PIC.EoiSlave(); } public static event IRQDelegate Interrupt30; // Interrupt 0x30, enter VMM public static void HandleInterrupt_30(ref IRQContext aContext) { if (Interrupt30 != null) { Interrupt30(ref aContext); } } public static void HandleInterrupt_35(ref IRQContext aContext) { aContext.EAX *= 2; aContext.EBX *= 2; aContext.ECX *= 2; aContext.EDX *= 2; } public static void HandleInterrupt_40(ref IRQContext aContext) { IRQ(0x40, ref aContext); } public static void HandleInterrupt_41(ref IRQContext aContext) { IRQ(0x41, ref aContext); } public static void HandleInterrupt_42(ref IRQContext aContext) { IRQ(0x42, ref aContext); } public static void HandleInterrupt_43(ref IRQContext aContext) { IRQ(0x43, ref aContext); } public static void HandleInterrupt_44(ref IRQContext aContext) { IRQ(0x44, ref aContext); } public static void HandleInterrupt_45(ref IRQContext aContext) { IRQ(0x45, ref aContext); } public static void HandleInterrupt_46(ref IRQContext aContext) { IRQ(0x46, ref aContext); } public static void HandleInterrupt_47(ref IRQContext aContext) { IRQ(0x47, ref aContext); } public static void HandleInterrupt_48(ref IRQContext aContext) { IRQ(0x48, ref aContext); } public static void HandleInterrupt_49(ref IRQContext aContext) { IRQ(0x49, ref aContext); } #endregion #region CPU Exceptions public static IRQDelegate GeneralProtectionFault; public static void HandleInterrupt_00(ref IRQContext aContext) { HandleException(aContext.EIP, "Divide by zero", "EDivideByZero", ref aContext, aContext.EIP); } public static void HandleInterrupt_01(ref IRQContext aContext) { HandleException(aContext.EIP, "Debug Exception", "Debug Exception", ref aContext); } public static void HandleInterrupt_02(ref IRQContext aContext) { HandleException(aContext.EIP, "Non Maskable Interrupt Exception", "Non Maskable Interrupt Exception", ref aContext); } public static void HandleInterrupt_03(ref IRQContext aContext) { HandleException(aContext.EIP, "Breakpoint Exception", "Breakpoint Exception", ref aContext); } public static void HandleInterrupt_04(ref IRQContext aContext) { HandleException(aContext.EIP, "Into Detected Overflow Exception", "Into Detected Overflow Exception", ref aContext); } public static void HandleInterrupt_05(ref IRQContext aContext) { HandleException(aContext.EIP, "Out of Bounds Exception", "Out of Bounds Exception", ref aContext); } public static void HandleInterrupt_06(ref IRQContext aContext) { // although mLastKnownAddress is a static, we need to get it here, any subsequent calls will change the value!!! var xLastKnownAddress = mLastKnownAddress; HandleException(aContext.EIP, "Invalid Opcode", "EInvalidOpcode", ref aContext, xLastKnownAddress); } public static void HandleInterrupt_07(ref IRQContext aContext) { HandleException(aContext.EIP, "No Coprocessor Exception", "No Coprocessor Exception", ref aContext); } public static void HandleInterrupt_08(ref IRQContext aContext) { HandleException(aContext.EIP, "Double Fault Exception", "Double Fault Exception", ref aContext); } public static void HandleInterrupt_09(ref IRQContext aContext) { HandleException(aContext.EIP, "Coprocessor Segment Overrun Exception", "Coprocessor Segment Overrun Exception", ref aContext); } public static void HandleInterrupt_0A(ref IRQContext aContext) { HandleException(aContext.EIP, "Bad TSS Exception", "Bad TSS Exception", ref aContext); } public static void HandleInterrupt_0B(ref IRQContext aContext) { HandleException(aContext.EIP, "Segment Not Present", "Segment Not Present", ref aContext); } public static void HandleInterrupt_0C(ref IRQContext aContext) { HandleException(aContext.EIP, "Stack Fault Exception", "Stack Fault Exception", ref aContext); } public static void HandleInterrupt_0D(ref IRQContext aContext) { if (GeneralProtectionFault != null) { GeneralProtectionFault(ref aContext); } else { HandleException(aContext.EIP, "General Protection Fault", "GPF", ref aContext); } } public static void HandleInterrupt_0E(ref IRQContext aContext) { HandleException(aContext.EIP, "Page Fault Exception", "Page Fault Exception", ref aContext); } public static void HandleInterrupt_0F(ref IRQContext aContext) { HandleException(aContext.EIP, "Unknown Interrupt Exception", "Unknown Interrupt Exception", ref aContext); } public static void HandleInterrupt_10(ref IRQContext aContext) { HandleException(aContext.EIP, "x87 Floating Point Exception", "Coprocessor Fault Exception", ref aContext); } public static void HandleInterrupt_11(ref IRQContext aContext) { HandleException(aContext.EIP, "Alignment Exception", "Alignment Exception", ref aContext); } public static void HandleInterrupt_12(ref IRQContext aContext) { HandleException(aContext.EIP, "Machine Check Exception", "Machine Check Exception", ref aContext); } public static void HandleInterrupt_13(ref IRQContext aContext) { HandleException(aContext.EIP, "SIMD Floating Point Exception", "SIMD Floating Point Exception", ref aContext); } #endregion private static void HandleException(uint aEIP, string aDescription, string aName, ref IRQContext ctx, uint lastKnownAddressValue = 0) { // At this point we are in a very unstable state. // Try not to use any Cosmos routines, just // report a crash dump. const string xHex = "0123456789ABCDEF"; uint xPtr = ctx.EIP; // we're printing exception info to the screen now: // 0/0: x // 1/0: exception number in hex unsafe { byte* xAddress = (byte*)0xB8000; PutErrorChar(0, 00, ' '); PutErrorChar(0, 01, '*'); PutErrorChar(0, 02, '*'); PutErrorChar(0, 03, '*'); PutErrorChar(0, 04, ' '); PutErrorChar(0, 05, 'C'); PutErrorChar(0, 06, 'P'); PutErrorChar(0, 07, 'U'); PutErrorChar(0, 08, ' '); PutErrorChar(0, 09, 'E'); PutErrorChar(0, 10, 'x'); PutErrorChar(0, 11, 'c'); PutErrorChar(0, 12, 'e'); PutErrorChar(0, 13, 'p'); PutErrorChar(0, 14, 't'); PutErrorChar(0, 15, 'i'); PutErrorChar(0, 16, 'o'); PutErrorChar(0, 17, 'n'); PutErrorChar(0, 18, ' '); PutErrorChar(0, 19, 'x'); PutErrorChar(0, 20, xHex[(int)((ctx.Interrupt >> 4) & 0xF)]); PutErrorChar(0, 21, xHex[(int)(ctx.Interrupt & 0xF)]); PutErrorChar(0, 22, ' '); PutErrorChar(0, 23, '*'); PutErrorChar(0, 24, '*'); PutErrorChar(0, 25, '*'); PutErrorChar(0, 26, ' '); if (lastKnownAddressValue != 0) { PutErrorString(1, 0, "Last known address: 0x"); PutErrorChar(1, 22, xHex[(int)((lastKnownAddressValue >> 28) & 0xF)]); PutErrorChar(1, 23, xHex[(int)((lastKnownAddressValue >> 24) & 0xF)]); PutErrorChar(1, 24, xHex[(int)((lastKnownAddressValue >> 20) & 0xF)]); PutErrorChar(1, 25, xHex[(int)((lastKnownAddressValue >> 16) & 0xF)]); PutErrorChar(1, 26, xHex[(int)((lastKnownAddressValue >> 12) & 0xF)]); PutErrorChar(1, 27, xHex[(int)((lastKnownAddressValue >> 8) & 0xF)]); PutErrorChar(1, 28, xHex[(int)((lastKnownAddressValue >> 4) & 0xF)]); PutErrorChar(1, 29, xHex[(int)(lastKnownAddressValue & 0xF)]); } } // lock up while (true) { } } private static void PutErrorChar(int line, int col, char c) { unsafe { byte* xAddress = (byte*)0xB8000; xAddress += ((line * 80) + col) * 2; xAddress[0] = (byte)c; xAddress[1] = 0x0C; } } private static void PutErrorString(int line, int startCol, string error) { for (int i = 0; i < error.Length; i++) { PutErrorChar(line, startCol + i, error[i]); } } // This is to trick IL2CPU to compile it in //TODO: Make a new attribute that IL2CPU sees when scanning to force inclusion so we dont have to do this. // We dont actually need to call this method public static void Dummy() { // Compiler magic bool xTest = false; if (xTest) { unsafe { var xCtx = new IRQContext(); HandleInterrupt_Default(ref xCtx); HandleInterrupt_00(ref xCtx); HandleInterrupt_01(ref xCtx); HandleInterrupt_02(ref xCtx); HandleInterrupt_03(ref xCtx); HandleInterrupt_04(ref xCtx); HandleInterrupt_05(ref xCtx); HandleInterrupt_06(ref xCtx); HandleInterrupt_07(ref xCtx); HandleInterrupt_08(ref xCtx); HandleInterrupt_09(ref xCtx); HandleInterrupt_0A(ref xCtx); HandleInterrupt_0B(ref xCtx); HandleInterrupt_0C(ref xCtx); HandleInterrupt_0D(ref xCtx); HandleInterrupt_0E(ref xCtx); HandleInterrupt_0F(ref xCtx); HandleInterrupt_10(ref xCtx); HandleInterrupt_11(ref xCtx); HandleInterrupt_12(ref xCtx); HandleInterrupt_13(ref xCtx); HandleInterrupt_20(ref xCtx); HandleInterrupt_21(ref xCtx); HandleInterrupt_22(ref xCtx); HandleInterrupt_23(ref xCtx); HandleInterrupt_24(ref xCtx); HandleInterrupt_25(ref xCtx); HandleInterrupt_26(ref xCtx); HandleInterrupt_27(ref xCtx); HandleInterrupt_28(ref xCtx); HandleInterrupt_29(ref xCtx); HandleInterrupt_2A(ref xCtx); HandleInterrupt_2B(ref xCtx); HandleInterrupt_2C(ref xCtx); HandleInterrupt_2D(ref xCtx); HandleInterrupt_2E(ref xCtx); HandleInterrupt_2F(ref xCtx); HandleInterrupt_30(ref xCtx); HandleInterrupt_35(ref xCtx); HandleInterrupt_40(ref xCtx); HandleInterrupt_41(ref xCtx); HandleInterrupt_42(ref xCtx); HandleInterrupt_43(ref xCtx); HandleInterrupt_44(ref xCtx); HandleInterrupt_45(ref xCtx); HandleInterrupt_46(ref xCtx); HandleInterrupt_47(ref xCtx); HandleInterrupt_48(ref xCtx); HandleInterrupt_49(ref xCtx); } } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Xml; using System.Globalization; using System.Drawing.Drawing2D; using System.Drawing.Printing; using System.IO; using UWin32; using System.Threading; using System.Text; using System.Diagnostics; namespace bg { class SBGE // Set of BGE { SortedList m_slbge; // the dataset GrapherParams m_cgp; ArrayList m_plptfi; RectangleF m_rcfDrawing; double m_dyPerBgUnit; double m_dxQuarter; bool m_fWgtAvg; int m_iFirstQuarter; float m_dxAdjust = 0; HScrollBar m_sbh; bool m_fColor = true; bool m_fNoCurves = false; object m_oTag; float m_dzaLineWidth = 1.0f; float m_dxOffset; float m_dyOffset; bool m_fMealLegend = false; DateTime m_dttmMeal; public void SetProps(GrapherParams cgp) { m_cgp = cgp; } public void SetMealLegend(DateTime dttmMeal) { m_dttmMeal = dttmMeal; m_fMealLegend = true; } public void SetNoCurves() { m_fNoCurves = true; } public void SetLineWidth(float dza) { m_dzaLineWidth = dza; } public RectangleF RectF { get { return m_rcfDrawing; } } public object Tag { get { return m_oTag; } set { m_oTag = value; } } public SBGE(GrapherParams cgp, Graphics gr, bool fWgtAvg) { m_cgp = cgp; m_fWgtAvg = fWgtAvg; Font font = new Font("Tahoma", 8); m_dxOffset = gr.MeasureString("0000", font).Width; m_dyOffset = gr.MeasureString("0\n0\n0\n0\n", font).Height; } public SBGE(GrapherParams cgp, float dxOffset, float dyOffset, bool fWgtAvg) { m_cgp = cgp; m_fWgtAvg = fWgtAvg; Font font = new Font("Tahoma", 8); m_dxOffset = dxOffset; m_dyOffset = dyOffset; } public void SetColor(bool fColor) { m_fColor = fColor; } public void SetDataSet(SortedList slbge, HScrollBar sbh) { m_sbh = sbh; m_slbge = slbge; } /* S E T F I R S T Q U A R T E R */ /*---------------------------------------------------------------------------- %%Function: SetFirstQuarter %%Qualified: bg.Grapher.SetFirstQuarter %%Contact: rlittle ----------------------------------------------------------------------------*/ public void SetFirstQuarter(int i) { m_iFirstQuarter = i; } /* G E T F I R S T Q U A R T E R */ /*---------------------------------------------------------------------------- %%Function: GetFirstQuarter %%Qualified: bg.Grapher.GetFirstQuarter %%Contact: rlittle ----------------------------------------------------------------------------*/ public int GetFirstQuarter() { return m_iFirstQuarter; } /* Y F R O M R E A D I N G */ /*---------------------------------------------------------------------------- %%Function: YFromReading %%Qualified: bg.Grapher.YFromReading %%Contact: rlittle ----------------------------------------------------------------------------*/ public float YFromReading(int nReading, double dyPerBgUnit) { if (nReading == 0) return -1.0F; return m_rcfDrawing.Top + m_rcfDrawing.Height - ((((float)nReading - (float)m_cgp.dBgLow) * (float)dyPerBgUnit)) - m_dyOffset; } /* X F R O M D A T E */ /*---------------------------------------------------------------------------- %%Function: XFromDate %%Qualified: bg.SBGE.XFromDate %%Contact: rlittle ----------------------------------------------------------------------------*/ public float XFromDate(DateTime dayFirst, DateTime dttm, double dxQuarter) { // calculate how many quarter hours long ticks = dttm.Ticks - dayFirst.Ticks; long lQuarters = ticks / (36000000000 / 4); return (float)((lQuarters * dxQuarter) + m_rcfDrawing.Left); // (m_dxOffset + m_dxLeftMargin)); } /* P T F F R O M B G E */ /*---------------------------------------------------------------------------- %%Function: PtfFromBge %%Qualified: bg.SBGE.PtfFromBge %%Contact: rlittle ----------------------------------------------------------------------------*/ PointF PtfFromBge(DateTime dayFirst, BGE bge, double dxQuarter, double dyBg) { float x = XFromDate(dayFirst, bge.Date, dxQuarter); float y = YFromReading(bge.Reading, dyBg); // now we've got the number of quarters. figure out the bge return new PointF(x,y); } /* P T F F R O M B G E A V G */ /*---------------------------------------------------------------------------- %%Function: PtfFromBgeAvg %%Qualified: bg.SBGE.PtfFromBgeAvg %%Contact: rlittle ----------------------------------------------------------------------------*/ PointF PtfFromBgeAvg(DateTime dayFirst, BGE bge, double dxQuarter, double dyBg) { float x = XFromDate(dayFirst, bge.Date, dxQuarter); float y = YFromReading(bge.WgtAvg, dyBg); // now we've got the number of quarters. figure out the bge return new PointF(x,y); } /* G E T F I R S T D A T E T I M E */ /*---------------------------------------------------------------------------- %%Function: GetFirstDateTime %%Qualified: bg.SBGE.GetFirstDateTime %%Contact: rlittle ----------------------------------------------------------------------------*/ public DateTime GetFirstDateTime() { PTFI ptfi = (PTFI)m_plptfi[0]; return new DateTime(ptfi.bge.Date.Year, ptfi.bge.Date.Month, ptfi.bge.Date.Day); } public DateTime GetLastDateTime() { DateTime dttmLast = ((PTFI)m_plptfi[m_plptfi.Count - 1]).bge.Date; return dttmLast; } /* C A L C G R A P H */ /*---------------------------------------------------------------------------- %%Function: CalcGraph %%Qualified: bg.SBGE.CalcGraph %%Contact: rlittle ----------------------------------------------------------------------------*/ public void CalcGraph(RectangleF rcf) { m_rcfDrawing = rcf; // graph the points in the dataset, m_cgp.nHalfDays at a time BGE bge = (BGE)m_slbge.GetByIndex(0); DateTime dayFirst = new DateTime(bge.Date.Year, bge.Date.Month, bge.Date.Day); // split apart the graphing range into intervals, by the quarter hour double cxQuarters = m_cgp.nHalfDays * 12 * 4; double dxQuarter = (rcf.Width - m_dxOffset / 2) / cxQuarters; double cyBg = m_cgp.dBgHigh - m_cgp.dBgLow; double dyBg = (rcf.Height - m_dyOffset) / cyBg; // build up a set of points to graph int iValue = 0; m_plptfi = new ArrayList(); float dxMax = 0; while (iValue < m_slbge.Values.Count) { bge = (BGE)m_slbge.GetByIndex(iValue); // set a point at bge PointF ptf; if (m_fWgtAvg) ptf = PtfFromBgeAvg(dayFirst, bge, dxQuarter, dyBg); else ptf = PtfFromBge(dayFirst, bge, dxQuarter, dyBg); if (ptf.X > dxMax) dxMax = ptf.X; PTFI ptfi; ptfi.ptf = ptf; ptfi.bge = bge; m_plptfi.Add(ptfi); iValue++; } if (m_sbh != null) { if (dxMax > dxQuarter * cxQuarters) { m_sbh.Minimum = 0; m_sbh.Maximum = (int)(((dxMax / dxQuarter)) - (m_cgp.nHalfDays * 12 * 4)); m_sbh.Visible = true; } else { m_sbh.Visible = false; } } m_dyPerBgUnit = dyBg; m_dxQuarter = dxQuarter; } public void PaintGraphGridlines(Graphics gr) { // ------------------------------ // FIRST: Draw the shaded ranges // ------------------------------ // how much should 0 based x-coordinates be adjusted? int dxAdjust = (int)(m_iFirstQuarter * m_dxQuarter); PTFI ptfi = (PTFI)m_plptfi[0]; DateTime dttmFirst = new DateTime(ptfi.bge.Date.Year, ptfi.bge.Date.Month, ptfi.bge.Date.Day); RectangleF rectfGraphBodyClip = new RectangleF(m_dxOffset + m_rcfDrawing.Left, m_rcfDrawing.Top, m_rcfDrawing.Width - m_dxOffset, m_rcfDrawing.Height - m_dyOffset); RectangleF rectfGraphFullClip = m_rcfDrawing; gr.SetClip(rectfGraphBodyClip); if (m_fNoCurves) ShadeRanges(gr); else ShadeCurvedRanges(gr, dxAdjust, dttmFirst); gr.ResetClip(); // ----------------------------------------- // SECOND: Draw the gridlines and the legend // ----------------------------------------- gr.SetClip(rectfGraphFullClip); SolidBrush brushBlue = new SolidBrush(Color.Blue); SolidBrush brushAvg = new SolidBrush(Color.Red); Pen penAvg = new Pen(Color.Red, (float)1); Pen penBlue = new Pen(Color.Blue, (float)1); Pen penGrid = new Pen(Color.DarkGray, (float)1); Pen penLightGrid = new Pen(Color.LightGray, (float)1); Pen penLight2Grid = new Pen(Color.LightBlue, (float)1); gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // now we've found the first index we're going to draw DateTime dttm = DateTime.Parse(dttmFirst.ToString("d")); // figure out the number of quarters in the first date we want // to display int nDayFirst = (m_iFirstQuarter) / (4 * 24) - 1; Font font = new Font("Tahoma", 8); // now we know (rounded up), what the first day will be // as a delta from the first day dttm = dttm.AddDays(nDayFirst); float dyOffsetRegion = m_dyOffset / 4; float yDateLegend = m_rcfDrawing.Bottom - m_dyOffset + dyOffsetRegion * 1.3F; // m_rcfDrawing.Height - m_dyBottomMargin - m_dyOffset + dyOffsetRegion * 1.3F; float xMacLastDrawn = 0.0F; float xMacNoonLastDrawn = 0.0F; Font fontSmall = new Font("Tahoma", 6); // figure out how many other gridlines we should draw // secondary gridlines must be at least wide enough to accommodate // the legend on every other gridline. float dxGrid2Legend = gr.MeasureString("23:59", fontSmall).Width; int nQuartersGrid2 = (int)(dxGrid2Legend / m_dxQuarter); // make sure its evenly divisble into 48 (12 * 4) if (nQuartersGrid2 > 48) nQuartersGrid2 = 48; while (48 % nQuartersGrid2 != 0) nQuartersGrid2++; for (int nDay = nDayFirst; nDay <= nDayFirst + m_cgp.nHalfDays / 2; nDay++) { dttm = dttm.AddDays(1); string s = dttm.ToString("MM/dd"); SizeF szf = gr.MeasureString(s, font); float x = XFromDate(dttmFirst, dttm, m_dxQuarter) - dxAdjust; if (x > m_rcfDrawing.Left + m_dxOffset) gr.DrawLine(penLightGrid, x, yDateLegend + dyOffsetRegion, x, 0); if (x + (float)m_dxQuarter * (4.0F * 12.0F) > m_rcfDrawing.Left + m_dxOffset) gr.DrawLine(penGrid, x + (float)m_dxQuarter * (4.0F * 12.0F), yDateLegend + dyOffsetRegion, x + (float)m_dxQuarter * (4.0F * 12.0F), 0); float dxNoon = gr.MeasureString("12:00", fontSmall).Width; if (xMacNoonLastDrawn < x + (float)m_dxQuarter * (4.0F * 12.0F) - dxNoon / 2.0F) { gr.DrawString("12:00", fontSmall, brushBlue, x + (float)m_dxQuarter * (4.0F * 12.0F) - dxNoon / 2.0F, yDateLegend + dyOffsetRegion / 1.5F); xMacNoonLastDrawn = x + (float)m_dxQuarter * (4.0F * 12.0F) + dxNoon / 2.0F; } x -= (szf.Width / 2.0F); if (xMacLastDrawn < x) { gr.DrawString(s, font, brushBlue, x, yDateLegend + dyOffsetRegion); xMacLastDrawn = x + gr.MeasureString(s, font).Width; } bool fText = false; for (int nGrid2 = 0; nGrid2 < 24 * 4; nGrid2 += nQuartersGrid2) { if (nGrid2 != 12 * 4) { x = XFromDate(dttmFirst, dttm.AddMinutes(nGrid2 * 15), m_dxQuarter) - dxAdjust; if (x > m_rcfDrawing.Left + m_dxOffset) { gr.DrawLine(penLight2Grid, x, yDateLegend + dyOffsetRegion, x, 0); if (fText) { int nHour = nGrid2 / 4; int nMinute = (nGrid2 % 4) * 15; string sText = nHour.ToString() + ":" + nMinute.ToString("0#"); float dxText = gr.MeasureString(sText, fontSmall).Width; x -= dxText / 2.0F; gr.DrawString(sText, fontSmall, brushBlue, x, yDateLegend + dyOffsetRegion / 4.0f); } } } fText = !fText; } } // put legend up int n; int dn = ((int)m_cgp.dBgHigh - (int)m_cgp.dBgLow) / m_cgp.nIntervals; gr.DrawLine(penBlue, m_dxOffset + (m_rcfDrawing.Left) - 1.0F, m_rcfDrawing.Top, m_dxOffset + (m_rcfDrawing.Left) - 1.0F, yDateLegend); gr.DrawLine(penBlue, m_dxOffset + (m_rcfDrawing.Left) - 1.0F, yDateLegend, m_rcfDrawing.Width + (m_rcfDrawing.Left) - 1.0F + m_dxOffset, yDateLegend); bool fLine = false; for (n = (int)m_cgp.dBgLow; n <= (int)m_cgp.dBgHigh; n += dn) { float x = m_rcfDrawing.Left /*m_dxLeftMargin*/ + 2.0F; float y = YFromReading(n, m_dyPerBgUnit); if (fLine) gr.DrawLine(penGrid, (m_dxOffset + m_rcfDrawing.Left) - 4.0F, y, (m_dxOffset + m_rcfDrawing.Left) + m_rcfDrawing.Width, y); fLine = !fLine; y -= (gr.MeasureString(n.ToString(), font).Height / 2.0F); x = (m_dxOffset + m_rcfDrawing.Left) - 4.0F - gr.MeasureString(n.ToString(), font).Width; gr.DrawString(n.ToString(), font, brushBlue, x, y); } gr.ResetClip(); m_dxAdjust = dxAdjust; } public void PaintGraph(Graphics gr) { int i, iLast; int dxAdjust = (int)(m_iFirstQuarter * m_dxQuarter); // how much should 0 based x-coordinates be adjusted? Pen penMeal = new Pen(Color.Green, m_dzaLineWidth); Pen penBlueThin = new Pen(Color.LightBlue, (float)0.5); Pen penBlue = new Pen(Color.Blue, (float)1); Pen penGrid = new Pen(Color.DarkGray, (float)1); Pen penLightGrid = new Pen(Color.LightGray, (float)1); SolidBrush brushBlue = new SolidBrush(Color.Blue); if (m_fWgtAvg) { brushBlue = new SolidBrush(Color.Red); penBlue = new Pen(Color.Red, (float)1); } double dxFirstQuarter = m_iFirstQuarter * m_dxQuarter + (m_dxOffset + m_rcfDrawing.Left/*m_dxLeftMargin*/); double dxLastQuarter = dxFirstQuarter + (m_cgp.nHalfDays * 12 * 4) * m_dxQuarter; RectangleF rectfGraphBodyClip = new RectangleF(m_dxOffset + m_rcfDrawing.Left, m_rcfDrawing.Top, // m_dyOffset + m_rcfDrawing.Width - m_dxOffset, m_rcfDrawing.Height - m_dyOffset); gr.SetClip(rectfGraphBodyClip); // ------------------------------ // THIRD: Graph the points // ------------------------------ PTFI ptfiLastMeal = new PTFI(); PTFI ptfi; ptfiLastMeal.bge = null; for (i = 0, iLast = m_plptfi.Count; i < iLast; i++) { PointF ptf; ptfi = ((PTFI)m_plptfi[i]); ptf = ptfi.ptf; // if its before our first point, skip it if (ptf.X < dxFirstQuarter) continue; if (ptf.Y == -1.0F && ptfi.bge.Reading == 0) { // lets get a real Y value for this by plotting a line on the curve if (i > 0) ptf.Y = ((PTFI)m_plptfi[i-1]).ptf.Y; else if (i < iLast) ptf.Y = ((PTFI)m_plptfi[i+1]).ptf.Y; else ptf.Y = 0; ptfi.ptf = ptf; m_plptfi[i] = ptfi; } if (ptfiLastMeal.bge != null && m_cgp.fShowMeals) { if (ptfiLastMeal.bge.Date.AddMinutes(90.0) <= ptfi.bge.Date && ptfiLastMeal.bge.Date.AddMinutes(150.0) >= ptfi.bge.Date) { float yAdjust; float xLast = ptfiLastMeal.ptf.X - dxAdjust; float yLast = ptfiLastMeal.ptf.Y; yAdjust = ptf.Y - yLast; if (yAdjust < 0.0F) yAdjust -= 15.0F; else yAdjust += 15.0F; // we have a match gr.DrawLine(penMeal, xLast + m_dzaLineWidth, yLast, xLast + m_dzaLineWidth, yLast + yAdjust); gr.DrawLine(penMeal, xLast + m_dzaLineWidth, yLast + yAdjust, ptf.X + m_dzaLineWidth - dxAdjust, yLast + yAdjust); gr.DrawLine(penMeal, ptf.X + m_dzaLineWidth - dxAdjust, yLast + yAdjust, ptf.X + m_dzaLineWidth - dxAdjust, ptf.Y + m_dzaLineWidth); ptfiLastMeal.bge = null; } else if (ptfiLastMeal.bge.Date.AddHours(150.0) < ptfi.bge.Date) ptfiLastMeal.bge = null; } if (ptfi.bge.Type != BGE.ReadingType.SpotTest) ptfiLastMeal = ptfi; if (ptf.X > dxLastQuarter) break; if (ptfi.bge.InterpReading) gr.DrawEllipse(penBlueThin, ptf.X - m_dzaLineWidth - dxAdjust, ptf.Y - m_dzaLineWidth, m_dzaLineWidth * 4.0f, m_dzaLineWidth * 4.0f); else gr.FillEllipse(brushBlue, ptf.X - m_dzaLineWidth - dxAdjust, ptf.Y - m_dzaLineWidth, m_dzaLineWidth * 4.0f, m_dzaLineWidth * 4.0f); if (i > 0) { PointF ptfLast = ((PTFI)m_plptfi[i - 1]).ptf; if (ptfLast.X >= dxFirstQuarter) gr.DrawLine(penBlue, ptfLast.X + 1 - dxAdjust, ptfLast.Y + 1, ptf.X + 1 - dxAdjust, ptf.Y + 1); } } // if we were doing the translucent range shading, we'd do it here. // ShadeRanges(pb, gr); gr.ResetClip(); m_dxAdjust = dxAdjust; } void AddCurvePoint(double dNext, double dCur, ref double dCum, ref ArrayList plptf, int dxAdjust, DateTime dttmFirst, ref DateTime dttm, double dHours, int nReading, int nPctSlop, int nPctAbove) { if (dNext - dCur - dCum < dHours) return; dCum += dHours; DateTime dttmForRender; dttmForRender = dttm.AddHours(dHours + (((double)dHours * (double)nPctSlop) / 100.0)); dttm = dttm.AddHours(dHours); float x = XFromDate(dttmFirst, dttmForRender, m_dxQuarter) - dxAdjust; PointF ptf = new PointF(x, YFromReading(nReading + (nReading * nPctAbove) / 100, m_dyPerBgUnit)); plptf.Add(ptf); } void ShadeRanges2(Graphics gr, int dxAdjust, DateTime dttmFirst, SolidBrush hBrushTrans, int nPctSlop, int nPctAbove) { // ok // shade the regions float yMin = YFromReading(80, m_dyPerBgUnit); float yMax = YFromReading(120, m_dyPerBgUnit); // ok, there are 7 days, starting at dttmFirst int iDay = 0; DateTime dttmCur; dttmCur = dttmFirst.AddMinutes(m_iFirstQuarter * 15.0); dttmCur = new DateTime(dttmCur.Year, dttmCur.Month, dttmCur.Day); ArrayList plptf = new ArrayList(); double []dMeals = { 8.0, 12.0, 18.0 }; double dHours = 0.0; int iplptfi = 0; while (iplptfi < m_plptfi.Count) { PTFI ptfi = (PTFI)m_plptfi[iplptfi]; if (ptfi.bge.Date >= dttmCur) break; iplptfi++; } AddCurvePoint(24.0, 0, ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0, 130, 0, nPctAbove); for (; iDay < m_cgp.nHalfDays / 2 + 2; iDay++) { // now, first analyze the day and determine when the meals are...otherwise, use the default meal times dMeals[0] = 8.0; dMeals[1] = 12.0; dMeals[2] = 18.0; // now, see if we can find meals in our day DateTime dttmNext = dttmCur.AddDays(1); while (iplptfi < m_plptfi.Count) { PTFI ptfi = (PTFI)m_plptfi[iplptfi]; if (ptfi.bge.Date >= dttmNext) break; if (ptfi.bge.Type == BGE.ReadingType.Dinner) dMeals[2] = ptfi.bge.Date.Hour; else if (ptfi.bge.Type == BGE.ReadingType.Breakfast) dMeals[0] = ptfi.bge.Date.Hour; else if (ptfi.bge.Type == BGE.ReadingType.Lunch) dMeals[1] = ptfi.bge.Date.Hour; iplptfi++; } dHours = 0; AddCurvePoint(dMeals[0], 0.0, ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, dMeals[0], 120, -nPctSlop, nPctAbove); // 0800 dHours = 0; AddCurvePoint(dMeals[1], dMeals[0], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0.5, 180, -nPctSlop, nPctAbove); // 0830 AddCurvePoint(dMeals[1], dMeals[0], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 1.0, 180, 0, nPctAbove); // 0930 AddCurvePoint(dMeals[1], dMeals[0], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0.5, 160, nPctSlop, nPctAbove); // 1000 AddCurvePoint(dMeals[1], dMeals[0], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 1.5, 120, nPctSlop, nPctAbove); // 1130 AddCurvePoint(dMeals[1], dMeals[0], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, dMeals[1] - dMeals[0] - dHours, 120, 0, nPctAbove); // 1200 dHours = 0; AddCurvePoint(dMeals[2], dMeals[1], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0.5, 180, -nPctSlop, nPctAbove); // 1230 AddCurvePoint(dMeals[2], dMeals[1], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 1.0, 180, 0, nPctAbove); // 1330 AddCurvePoint(dMeals[2], dMeals[1], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0.5, 160, nPctSlop, nPctAbove); // 1400 AddCurvePoint(dMeals[2], dMeals[1], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 1.5, 120, nPctSlop, nPctAbove); // 1530 AddCurvePoint(dMeals[2], dMeals[1], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, dMeals[2] - dMeals[1] - dHours, 120, 0, nPctAbove); // 1800 dHours = 0; AddCurvePoint(24.00, dMeals[2], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0.5, 180, -nPctSlop, nPctAbove); // 1830 AddCurvePoint(24.00, dMeals[2], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 1.0, 180, 0, nPctAbove); // 1930 AddCurvePoint(24.00, dMeals[2], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 0.5, 160, nPctSlop, nPctAbove); // 2000 AddCurvePoint(24.00, dMeals[2], ref dHours, ref plptf, dxAdjust, dttmFirst, ref dttmCur, 24.0 - dMeals[2] - dHours, 140, nPctSlop, nPctAbove); // 2400 // repeat for 7 days worth } // ok, now just fill a line back to the beginning while (iDay >= 0) { float x = XFromDate(dttmFirst, dttmCur, m_dxQuarter) - dxAdjust; float y = YFromReading(80 - (80 * nPctAbove) / 100, m_dyPerBgUnit); PointF ptf = new PointF(x, y); plptf.Add(ptf); dttmCur = dttmCur.AddDays(-1); iDay--; } PointF[] points; points = new PointF[plptf.Count]; int iptf = 0; foreach (PointF ptf in plptf) { points[iptf] = ptf; iptf++; } FillMode fm = FillMode.Winding; gr.FillClosedCurve(hBrushTrans, points, fm, 0.2F); } void ShadeCurvedRanges(Graphics gr, int dxAdjust, DateTime dttmFirst) { SolidBrush hBrushTrans; if (m_fColor) hBrushTrans = new SolidBrush(Color.FromArgb(255, 255, 255, 200/*167*/)); else hBrushTrans = new SolidBrush(Color.FromArgb(255, 215, 215, 215)); ShadeRanges2(gr, dxAdjust, dttmFirst, hBrushTrans, 10, 20); if (m_fColor) hBrushTrans = new SolidBrush(Color.FromArgb(255, 200/*174*/, 255, 200/*174*/)); else hBrushTrans = new SolidBrush(Color.FromArgb(255, 192, 192, 192)); ShadeRanges2(gr, dxAdjust, dttmFirst, hBrushTrans, 0, 0); } void ShadeRanges(Graphics gr) { // shade the regions float yMin = YFromReading(80, m_dyPerBgUnit); float yMax = YFromReading(120, m_dyPerBgUnit); SolidBrush hBrushTrans = new SolidBrush(Color.FromArgb(64, 0, 255, 0)); gr.FillRectangle(hBrushTrans, (m_dxOffset + m_rcfDrawing.Left/*m_dxLeftMargin*/), yMax, m_rcfDrawing.Width, Math.Abs(yMax - yMin)); yMin = YFromReading(120, m_dyPerBgUnit); yMax = YFromReading(140, m_dyPerBgUnit); hBrushTrans = new SolidBrush(Color.FromArgb(64, 255, 255, 0)); gr.FillRectangle(hBrushTrans, (m_dxOffset + m_rcfDrawing.Left/*m_dxLeftMargin*/), yMax, m_rcfDrawing.Width, Math.Abs(yMax - yMin)); yMin = YFromReading(60, m_dyPerBgUnit); yMax = YFromReading(80, m_dyPerBgUnit); gr.FillRectangle(hBrushTrans, (m_dxOffset + m_rcfDrawing.Left/*m_dxLeftMargin*/), yMax, m_rcfDrawing.Width, Math.Abs(yMax - yMin)); } /* F H I T T E S T */ /*---------------------------------------------------------------------------- %%Function: FHitTest %%Qualified: bg.SBGE.FHitTest %%Contact: rlittle ----------------------------------------------------------------------------*/ public bool FHitTest(Point ptClient, out object oHit, out RectangleF rectfHit) { rectfHit = new RectangleF();; PTFI ptfiHit; // figure out what we hit. // convert the pt into a raw point compatible with our array PointF ptfArray = new PointF(((float)ptClient.X) + m_dxAdjust, (float)ptClient.Y); ptfiHit = new PTFI(); bool fHit = false; // now we can go searching for a point this corresponds to foreach (PTFI ptfi in m_plptfi) { rectfHit = new RectangleF(ptfi.ptf.X - 4.0F, ptfi.ptf.Y - 4.0F, 8.0F, 8.0F); if (!rectfHit.Contains(ptfArray)) continue; fHit = true; ptfiHit = ptfi; break; } oHit = ptfiHit; return fHit; } } // ______ ______ _______ _____ _ _ _______ ______ // | ____ |_____/ |_____| |_____] |_____| |______ |_____/ // |_____| | \_ | | | | | |______ | \_ public class Grapher : GraphicBox { // _ _ ____ _ _ ___ ____ ____ _ _ ____ ____ _ ____ ___ _ ____ ____ // |\/| |___ |\/| |__] |___ |__/ | | |__| |__/ | |__| |__] | |___ [__ // | | |___ | | |__] |___ | \ \/ | | | \ | | | |__] |___ |___ ___] RectangleF m_rcfDrawing; GrapherParams m_cgp; SBGE m_sbge; SBGE m_sbgeAvg; /* G R A P H E R */ /*---------------------------------------------------------------------------- %%Function: Grapher %%Qualified: bg.Grapher.Grapher %%Contact: rlittle ----------------------------------------------------------------------------*/ public Grapher(RectangleF rcf, Graphics gr) // int nWidth, int nHeight { m_rcfDrawing = rcf; m_cgp.dBgLow = 30.0; m_cgp.dBgHigh = 220.0; m_cgp.nHalfDays = 14; m_cgp.nIntervals = 19; m_cgp.fShowMeals = false; m_sbge = new SBGE(m_cgp, gr, false); m_sbgeAvg = new SBGE(m_cgp, gr, true); } /* G E T D A Y S P E R P A G E */ /*---------------------------------------------------------------------------- %%Function: GetDaysPerPage %%Qualified: bg.Grapher.GetDaysPerPage %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public int GetDaysPerPage() { return m_cgp.nHalfDays / 2; } /* S E T D A Y S P E R P A G E */ /*---------------------------------------------------------------------------- %%Function: SetDaysPerPage %%Qualified: bg.Grapher.SetDaysPerPage %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void SetDaysPerPage(int nDaysPerPage) { m_cgp.nHalfDays = nDaysPerPage * 2; } /* S E T F I R S T F R O M S C R O L L */ /*---------------------------------------------------------------------------- %%Function: SetFirstFromScroll %%Qualified: bg.Grapher.SetFirstFromScroll %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void SetFirstFromScroll(int i) { m_sbge.SetFirstQuarter(i); m_sbgeAvg.SetFirstQuarter(i); } /* S E T C O L O R */ /*---------------------------------------------------------------------------- %%Function: SetColor %%Qualified: bg.Grapher.SetColor %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void SetColor(bool fColor) { m_sbge.SetColor(fColor); m_sbgeAvg.SetColor(fColor); } /* G E T F I R S T F O R S C R O L L */ /*---------------------------------------------------------------------------- %%Function: GetFirstForScroll %%Qualified: bg.Grapher.GetFirstForScroll %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public int GetFirstForScroll() { return m_sbge.GetFirstQuarter(); } /* G E T F I R S T D A T E T I M E */ /*---------------------------------------------------------------------------- %%Function: GetFirstDateTime %%Qualified: bg.Grapher.GetFirstDateTime %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public DateTime GetFirstDateTime() { DateTime dttmFirst = m_sbge.GetFirstDateTime(); DateTime dttm = DateTime.Parse(dttmFirst.ToString("d")); double nDayFirst = ((double)m_sbge.GetFirstQuarter() + 95.0) / (4.0 * 24.0) - 1.0; dttm = dttm.AddDays(nDayFirst); return dttm; } /* S E T F I R S T D A T E T I M E */ /*---------------------------------------------------------------------------- %%Function: SetFirstDateTime %%Qualified: bg.Grapher.SetFirstDateTime %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void SetFirstDateTime(DateTime dttm) { DateTime dttmFirst = m_sbge.GetFirstDateTime(); TimeSpan ts = dttm.Subtract(dttmFirst); m_sbge.SetFirstQuarter((int)(4.0 * ts.TotalHours) + 1); m_sbgeAvg.SetFirstQuarter((int)(4.0 * ts.TotalHours) + 1); } /* S E T D A T A P O I N T S */ /*---------------------------------------------------------------------------- %%Function: SetDataPoints %%Qualified: bg.Grapher.SetDataPoints %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void SetDataPoints(object oData, VScrollBar sbv, HScrollBar sbh) { m_sbge.SetDataSet((SortedList)oData, sbh); m_sbgeAvg.SetDataSet((SortedList)oData, sbh); } /* S E T P R O P S */ /*---------------------------------------------------------------------------- %%Function: SetProps %%Qualified: bg.Grapher.SetProps %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void SetProps(GrapherParams cgp) { m_cgp = cgp; m_sbge.SetProps(cgp); m_sbgeAvg.SetProps(cgp); } /* C A L C */ /*---------------------------------------------------------------------------- %%Function: Calc %%Qualified: bg.Grapher.Calc %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void Calc() { m_sbge.CalcGraph(m_rcfDrawing); m_sbgeAvg.CalcGraph(m_rcfDrawing); } // ___ ____ _ _ _ ___ _ _ _ ____ // |__] |__| | |\ | | | |\ | | __ // | | | | | \| | | | \| |__] /* D R A W B A N N E R */ /*---------------------------------------------------------------------------- %%Function: DrawBanner %%Qualified: bg.Grapher.DrawBanner %%Contact: rlittle ----------------------------------------------------------------------------*/ public void DrawBanner(Graphics gr, RectangleF rcf) { Font font = new Font("Tahoma", 12); // gr.DrawString("Graph", font, new SolidBrush(Color.Black), rcf); } /* P A I N T */ /*---------------------------------------------------------------------------- %%Function: Paint %%Qualified: bg.Grapher.Paint %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public void Paint(Graphics gr) { // there are several things that have to happen. // 1. Draw the shaded ranges // 2. Draw the grid lines // 3. Draw the actual points m_sbge.PaintGraphGridlines(gr); m_sbge.PaintGraph(gr); m_sbgeAvg.PaintGraph(gr); } /* F G E T L A S T D A T E T I M E O N P A G E */ /*---------------------------------------------------------------------------- %%Function: FGetLastDateTimeOnPage %%Qualified: bg.Grapher.FGetLastDateTimeOnPage %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public bool FGetLastDateTimeOnPage(out DateTime dttm) { DateTime dttmLast = m_sbge.GetLastDateTime(); dttm = GetFirstDateTime(); if (dttm.AddHours(m_cgp.nHalfDays * 12) > dttmLast) return false; dttm = dttm.AddHours(m_cgp.nHalfDays * 12); return true; } /* F H I T T E S T */ /*---------------------------------------------------------------------------- %%Function: FHitTest %%Qualified: bg.Grapher.FHitTest %%Contact: rlittle GraphicBox interface ----------------------------------------------------------------------------*/ public bool FHitTest(Point ptClient, out object oHit, out RectangleF rectfHit) { return m_sbge.FHitTest(ptClient, out oHit, out rectfHit); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Net; using JetBrains.Annotations; using Newtonsoft.Json.Linq; using NUnit.Framework; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Game.Graphics.Containers; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Rooms; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Screens.OnlinePlay.Playlists; using osu.Game.Screens.Ranking; using osu.Game.Tests.Beatmaps; using osu.Game.Tests.Resources; namespace osu.Game.Tests.Visual.Playlists { public class TestScenePlaylistsResultsScreen : ScreenTestScene { private const int scores_per_result = 10; private const int real_user_position = 200; private TestResultsScreen resultsScreen; private int lowestScoreId; // Score ID of the lowest score in the list. private int highestScoreId; // Score ID of the highest score in the list. private bool requestComplete; private int totalCount; private ScoreInfo userScore; [SetUp] public void Setup() => Schedule(() => { lowestScoreId = 1; highestScoreId = 1; requestComplete = false; totalCount = 0; userScore = TestResources.CreateTestScoreInfo(); userScore.TotalScore = 0; userScore.Statistics = new Dictionary<HitResult, int>(); bindHandler(); // beatmap is required to be an actual beatmap so the scores can get their scores correctly calculated for standardised scoring. // else the tests that rely on ordering will fall over. Beatmap.Value = CreateWorkingBeatmap(Ruleset.Value); }); [Test] public void TestShowWithUserScore() { AddStep("bind user score info handler", () => bindHandler(userScore: userScore)); createResults(() => userScore); AddAssert("user score selected", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineID == userScore.OnlineID).State == PanelState.Expanded); AddAssert($"score panel position is {real_user_position}", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineID == userScore.OnlineID).ScorePosition.Value == real_user_position); } [Test] public void TestShowNullUserScore() { createResults(); AddAssert("top score selected", () => this.ChildrenOfType<ScorePanel>().OrderByDescending(p => p.Score.TotalScore).First().State == PanelState.Expanded); } [Test] public void TestShowUserScoreWithDelay() { AddStep("bind user score info handler", () => bindHandler(true, userScore)); createResults(() => userScore); AddAssert("more than 1 panel displayed", () => this.ChildrenOfType<ScorePanel>().Count() > 1); AddAssert("user score selected", () => this.ChildrenOfType<ScorePanel>().Single(p => p.Score.OnlineID == userScore.OnlineID).State == PanelState.Expanded); } [Test] public void TestShowNullUserScoreWithDelay() { AddStep("bind delayed handler", () => bindHandler(true)); createResults(); AddAssert("top score selected", () => this.ChildrenOfType<ScorePanel>().OrderByDescending(p => p.Score.TotalScore).First().State == PanelState.Expanded); } [Test] public void TestFetchWhenScrolledToTheRight() { createResults(); AddStep("bind delayed handler", () => bindHandler(true)); for (int i = 0; i < 2; i++) { int beforePanelCount = 0; AddStep("get panel count", () => beforePanelCount = this.ChildrenOfType<ScorePanel>().Count()); AddStep("scroll to right", () => resultsScreen.ScorePanelList.ChildrenOfType<OsuScrollContainer>().Single().ScrollToEnd(false)); AddAssert("right loading spinner shown", () => resultsScreen.RightSpinner.State.Value == Visibility.Visible); waitForDisplay(); AddAssert($"count increased by {scores_per_result}", () => this.ChildrenOfType<ScorePanel>().Count() >= beforePanelCount + scores_per_result); AddAssert("right loading spinner hidden", () => resultsScreen.RightSpinner.State.Value == Visibility.Hidden); } } [Test] public void TestFetchWhenScrolledToTheLeft() { AddStep("bind user score info handler", () => bindHandler(userScore: userScore)); createResults(() => userScore); AddStep("bind delayed handler", () => bindHandler(true)); for (int i = 0; i < 2; i++) { int beforePanelCount = 0; AddStep("get panel count", () => beforePanelCount = this.ChildrenOfType<ScorePanel>().Count()); AddStep("scroll to left", () => resultsScreen.ScorePanelList.ChildrenOfType<OsuScrollContainer>().Single().ScrollToStart(false)); AddAssert("left loading spinner shown", () => resultsScreen.LeftSpinner.State.Value == Visibility.Visible); waitForDisplay(); AddAssert($"count increased by {scores_per_result}", () => this.ChildrenOfType<ScorePanel>().Count() >= beforePanelCount + scores_per_result); AddAssert("left loading spinner hidden", () => resultsScreen.LeftSpinner.State.Value == Visibility.Hidden); } } private void createResults(Func<ScoreInfo> getScore = null) { AddStep("load results", () => { LoadScreen(resultsScreen = new TestResultsScreen(getScore?.Invoke(), 1, new PlaylistItem(new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo) { RulesetID = new OsuRuleset().RulesetInfo.OnlineID })); }); AddUntilStep("wait for screen to load", () => resultsScreen.IsLoaded); waitForDisplay(); } private void waitForDisplay() { AddUntilStep("wait for scores loaded", () => requestComplete && resultsScreen.ScorePanelList.GetScorePanels().Count() == totalCount && resultsScreen.ScorePanelList.AllPanelsVisible); AddWaitStep("wait for display", 5); } private void bindHandler(bool delayed = false, ScoreInfo userScore = null, bool failRequests = false) => ((DummyAPIAccess)API).HandleRequest = request => { // pre-check for requests we should be handling (as they are scheduled below). switch (request) { case ShowPlaylistUserScoreRequest _: case IndexPlaylistScoresRequest _: break; default: return false; } requestComplete = false; double delay = delayed ? 3000 : 0; Scheduler.AddDelayed(() => { if (failRequests) { triggerFail(request); return; } switch (request) { case ShowPlaylistUserScoreRequest s: if (userScore == null) triggerFail(s); else triggerSuccess(s, createUserResponse(userScore)); break; case IndexPlaylistScoresRequest i: triggerSuccess(i, createIndexResponse(i)); break; } }, delay); return true; }; private void triggerSuccess<T>(APIRequest<T> req, T result) where T : class { requestComplete = true; req.TriggerSuccess(result); } private void triggerFail(APIRequest req) { requestComplete = true; req.TriggerFailure(new WebException("Failed.")); } private MultiplayerScore createUserResponse([NotNull] ScoreInfo userScore) { var multiplayerUserScore = new MultiplayerScore { ID = highestScoreId, Accuracy = userScore.Accuracy, Passed = userScore.Passed, Rank = userScore.Rank, Position = real_user_position, MaxCombo = userScore.MaxCombo, User = userScore.User, ScoresAround = new MultiplayerScoresAround { Higher = new MultiplayerScores(), Lower = new MultiplayerScores() } }; totalCount++; for (int i = 1; i <= scores_per_result; i++) { multiplayerUserScore.ScoresAround.Lower.Scores.Add(new MultiplayerScore { ID = --highestScoreId, Accuracy = userScore.Accuracy, Passed = true, Rank = userScore.Rank, MaxCombo = userScore.MaxCombo, User = new APIUser { Id = 2, Username = $"peppy{i}", CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }, }); multiplayerUserScore.ScoresAround.Higher.Scores.Add(new MultiplayerScore { ID = ++lowestScoreId, Accuracy = userScore.Accuracy, Passed = true, Rank = userScore.Rank, MaxCombo = userScore.MaxCombo, User = new APIUser { Id = 2, Username = $"peppy{i}", CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }, }); totalCount += 2; } addCursor(multiplayerUserScore.ScoresAround.Lower); addCursor(multiplayerUserScore.ScoresAround.Higher); return multiplayerUserScore; } private IndexedMultiplayerScores createIndexResponse(IndexPlaylistScoresRequest req) { var result = new IndexedMultiplayerScores(); string sort = req.IndexParams?.Properties["sort"].ToObject<string>() ?? "score_desc"; for (int i = 1; i <= scores_per_result; i++) { result.Scores.Add(new MultiplayerScore { ID = sort == "score_asc" ? --highestScoreId : ++lowestScoreId, Accuracy = 1, Passed = true, Rank = ScoreRank.X, MaxCombo = 1000, User = new APIUser { Id = 2, Username = $"peppy{i}", CoverUrl = "https://osu.ppy.sh/images/headers/profile-covers/c3.jpg", }, }); totalCount++; } addCursor(result); return result; } private void addCursor(MultiplayerScores scores) { scores.Cursor = new Cursor { Properties = new Dictionary<string, JToken> { { "total_score", JToken.FromObject(scores.Scores[^1].TotalScore) }, { "score_id", JToken.FromObject(scores.Scores[^1].ID) }, } }; scores.Params = new IndexScoresParams { Properties = new Dictionary<string, JToken> { { "sort", JToken.FromObject(scores.Scores[^1].ID > scores.Scores[^2].ID ? "score_asc" : "score_desc") } } }; } private class TestResultsScreen : PlaylistsResultsScreen { public new LoadingSpinner LeftSpinner => base.LeftSpinner; public new LoadingSpinner CentreSpinner => base.CentreSpinner; public new LoadingSpinner RightSpinner => base.RightSpinner; public new ScorePanelList ScorePanelList => base.ScorePanelList; public TestResultsScreen(ScoreInfo score, int roomId, PlaylistItem playlistItem, bool allowRetry = true) : base(score, roomId, playlistItem, allowRetry) { } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.DotNet.Cli.CommandLine; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Cli.CommandParsing { public static class CommandParserSupport { public static Command CreateNewCommandWithoutTemplateInfo(string commandName) => GetNewCommand(commandName, NewCommandVisibleArgs, NewCommandHiddenArgs, DebuggingCommandArgs); private static Command GetNewCommand(string commandName, params Option[][] args) { Option[] combinedArgs = ArrayExtensions.CombineArrays(args); return Create.Command(commandName, LocalizableStrings.CommandDescription, Accept.ZeroOrMoreArguments(), // this can't be ZeroOrOneArguments() because template args would cause errors combinedArgs); } // Final parser for when there is no template name provided. // Unmatched args are errors. public static Command CreateNewCommandForNoTemplateName(string commandName) { Option[] combinedArgs = ArrayExtensions.CombineArrays(NewCommandVisibleArgs, NewCommandHiddenArgs, DebuggingCommandArgs); return Create.Command(commandName, LocalizableStrings.CommandDescription, Accept.NoArguments(), true, combinedArgs); } private static Command GetNewCommandForTemplate(string commandName, string templateName, params Option[][] args) { Option[] combinedArgs = ArrayExtensions.CombineArrays(args); return Create.Command(commandName, LocalizableStrings.CommandDescription, Accept.ExactlyOneArgument().WithSuggestionsFrom(templateName), combinedArgs); } public static HashSet<string> ArgsForBuiltInCommands { get { if (_argsForBuiltInCommands == null) { Option[] allBuiltInArgs = ArrayExtensions.CombineArrays(NewCommandVisibleArgs, NewCommandHiddenArgs, NewCommandReservedArgs, DebuggingCommandArgs); _argsForBuiltInCommands = VariantsForOptions(allBuiltInArgs); } // return a copy so the original doesn't get modified. return new HashSet<string>(_argsForBuiltInCommands); } } private static HashSet<string> _argsForBuiltInCommands = null; // Creates a command setup with the args for "new", plus args for the input template parameters. public static Command CreateNewCommandWithArgsForTemplate(string commandName, string templateName, IReadOnlyList<ITemplateParameter> parameterDefinitions, IDictionary<string, string> longNameOverrides, IDictionary<string, string> shortNameOverrides, out IReadOnlyDictionary<string, IReadOnlyList<string>> templateParamMap) { IList<Option> paramOptionList = new List<Option>(); HashSet<string> initiallyTakenAliases = ArgsForBuiltInCommands; Dictionary<string, IReadOnlyList<string>> canonicalToVariantMap = new Dictionary<string, IReadOnlyList<string>>(); AliasAssignmentCoordinator assignmentCoordinator = new AliasAssignmentCoordinator(parameterDefinitions, longNameOverrides, shortNameOverrides, initiallyTakenAliases); if (assignmentCoordinator.InvalidParams.Count > 0) { string unusableDisplayList = string.Join(", ", assignmentCoordinator.InvalidParams); throw new Exception($"Template is malformed. The following parameter names are invalid: {unusableDisplayList}"); } foreach (ITemplateParameter parameter in parameterDefinitions.Where(x => x.Priority != TemplateParameterPriority.Implicit)) { Option option; IList<string> aliasesForParam = new List<string>(); if (assignmentCoordinator.LongNameAssignments.TryGetValue(parameter.Name, out string longVersion)) { aliasesForParam.Add(longVersion); } if (assignmentCoordinator.ShortNameAssignments.TryGetValue(parameter.Name, out string shortVersion)) { aliasesForParam.Add(shortVersion); } if (parameter is IAllowDefaultIfOptionWithoutValue parameterWithNoValueDefault && !string.IsNullOrEmpty(parameterWithNoValueDefault.DefaultIfOptionWithoutValue)) { // This switch can be provided with or without a value. // If the user doesn't specify a value, it gets the value of DefaultIfOptionWithoutValue option = Create.Option(string.Join("|", aliasesForParam), parameter.Documentation, Accept.ZeroOrOneArgument()); } else { // User must provide a value if this switch is specified. option = Create.Option(string.Join("|", aliasesForParam), parameter.Documentation, Accept.ExactlyOneArgument()); } paramOptionList.Add(option); // add the option canonicalToVariantMap.Add(parameter.Name, aliasesForParam.ToList()); // map the template canonical name to its aliases. } templateParamMap = canonicalToVariantMap; return GetNewCommandForTemplate(commandName, templateName, NewCommandVisibleArgs, NewCommandHiddenArgs, DebuggingCommandArgs, paramOptionList.ToArray()); } private static Option[] NewCommandVisibleArgs { get { return new[] { Create.Option("-h|--help", LocalizableStrings.DisplaysHelp, Accept.NoArguments()), Create.Option("-l|--list", LocalizableStrings.ListsTemplates, Accept.NoArguments()), Create.Option("-n|--name", LocalizableStrings.NameOfOutput, Accept.ExactlyOneArgument()), Create.Option("-o|--output", LocalizableStrings.OutputPath, Accept.ExactlyOneArgument()), Create.Option("-i|--install", LocalizableStrings.InstallHelp, Accept.OneOrMoreArguments()), Create.Option("-u|--uninstall", LocalizableStrings.UninstallHelp, Accept.ZeroOrMoreArguments()), Create.Option("--nuget-source", LocalizableStrings.NuGetSourceHelp, Accept.OneOrMoreArguments()), Create.Option("--type", LocalizableStrings.ShowsFilteredTemplates, Accept.ExactlyOneArgument()), Create.Option("--dry-run", LocalizableStrings.DryRunDescription, Accept.NoArguments()), Create.Option("--force", LocalizableStrings.ForcesTemplateCreation, Accept.NoArguments()), Create.Option("-lang|--language", LocalizableStrings.LanguageParameter, Accept.ExactlyOneArgument() .WithSuggestionsFrom("C#", "F#")), // don't give this a default, otherwise 'new -lang' is valid and assigns the default. User should have to explicitly give the value. }; } } private static Option[] NewCommandHiddenArgs { get { return new[] { //Create.Option("-a|--alias", LocalizableStrings.AliasHelp, Accept.ExactlyOneArgument()), //Create.Option("--show-alias", LocalizableStrings.ShowAliasesHelp, Accept.ZeroOrOneArgument()), // When these are un-hidden, be sure to set their help values like above. Create.Option("-a|--alias", string.Empty, Accept.ExactlyOneArgument()), Create.Option("--show-alias", string.Empty, Accept.ZeroOrOneArgument()), Create.Option("-x|--extra-args", string.Empty, Accept.OneOrMoreArguments()), Create.Option("--locale", string.Empty, Accept.ExactlyOneArgument()), Create.Option("--quiet", string.Empty, Accept.NoArguments()), Create.Option("-all|--show-all", string.Empty, Accept.NoArguments()), Create.Option("--allow-scripts", string.Empty, Accept.ZeroOrOneArgument()), Create.Option("--baseline", string.Empty, Accept.ExactlyOneArgument()), Create.Option("--update", string.Empty, Accept.NoArguments()), Create.Option("--update-no-prompt", string.Empty, Accept.NoArguments()), }; } } private static Option[] NewCommandReservedArgs { get { return new[] { Create.Option("--skip-update-check", string.Empty, Accept.NoArguments()), }; } } private static Option[] DebuggingCommandArgs { get { return new[] { Create.Option("--debug:attach", string.Empty, Accept.NoArguments()), Create.Option("--debug:rebuildcache", string.Empty, Accept.NoArguments()), Create.Option("--debug:ephemeral-hive", string.Empty, Accept.NoArguments()), Create.Option("--debug:reinit", string.Empty, Accept.NoArguments()), Create.Option("--debug:reset-config", string.Empty, Accept.NoArguments()), Create.Option("--debug:showconfig", string.Empty, Accept.NoArguments()), Create.Option("--debug:emit-timings", string.Empty, Accept.NoArguments()), Create.Option("--debug:emit-telemetry", string.Empty, Accept.NoArguments()), Create.Option("--debug:custom-hive", string.Empty, Accept.ExactlyOneArgument()), Create.Option("--debug:version", string.Empty, Accept.NoArguments()), Create.Option("--dev:install", string.Empty, Accept.NoArguments()), Create.Option("--trace:authoring", string.Empty, Accept.NoArguments()), Create.Option("--trace:install", string.Empty, Accept.NoArguments()), }; } } private static HashSet<string> VariantsForOptions(Option[] options) { HashSet<string> variants = new HashSet<string>(); if (options == null) { return variants; } for (int i = 0; i < options.Length; i++) { variants.UnionWith(options[i].RawAliases); } return variants; } } }
/* * 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 java = biz.ritter.javapi; namespace biz.ritter.javapi.lang{ /** * Creates operating system processes. * * @since 1.5 */ public sealed class ProcessBuilder { private java.util.List<String> commandJ; private java.io.File directoryJ; private java.util.Map<String, String> environmentJ; private bool redirectErrorStreamJ; /** * Constructs a new {@code ProcessBuilder} instance with the specified * operating system program and its arguments. * * @param command * the requested operating system program and its arguments. */ public ProcessBuilder(params String []commandJ): this(toList(commandJ)) { } /** * Constructs a new {@code ProcessBuilder} instance with the specified * operating system program and its arguments. Note that the list passed to * this constructor is not copied, so any subsequent updates to it are * reflected in this instance's state. * * @param command * the requested operating system program and its arguments. * @throws NullPointerException * if {@code command} is {@code null}. */ public ProcessBuilder(java.util.List<String> commandJ) :base(){ if (commandJ == null) { throw new NullPointerException(); } this.commandJ = commandJ; java.lang.SystemJ.getProperties(); this.environmentJ = // new org.apache.harmony.luni.platform.Environment.EnvironmentMap( java.lang.SystemJ.getenv(); } /** * Returns this process builder's current program and arguments. Note that * the returned list is not a copy and modifications to it will change the * state of this instance. * * @return this process builder's program and arguments. */ public java.util.List<String> command() { return commandJ; } /** * Changes the program and arguments of this process builder. * * @param command * the new operating system program and its arguments. * @return this process builder instance. */ public ProcessBuilder command(params String []commandJ) { return command(toList(commandJ)); } /** * Changes the program and arguments of this process builder. Note that the * list passed to this method is not copied, so any subsequent updates to it * are reflected in this instance's state. * * @param command * the new operating system program and its arguments. * @return this process builder instance. * @throws NullPointerException * if {@code command} is {@code null}. */ public ProcessBuilder command(java.util.List<String> commandJ) { if (commandJ == null) { throw new NullPointerException(); } this.commandJ = commandJ; return this; } /** * Returns the working directory of this process builder. If {@code null} is * returned, then the working directory of the Java process is used when a * process is started. * * @return the current working directory, may be {@code null}. */ public java.io.File directory() { return directoryJ; } /** * Changes the working directory of this process builder. If the specified * directory is {@code null}, then the working directory of the Java * process is used when a process is started. * * @param directory * the new working directory for this process builder. * @return this process builder instance. */ public ProcessBuilder directory(java.io.File directoryJ) { this.directoryJ = directoryJ; return this; } /** * Returns this process builder's current environment. When a process * builder instance is created, the environment is populated with a copy of * the environment, as returned by {@link System#getenv()}. Note that the * map returned by this method is not a copy and any changes made to it are * reflected in this instance's state. * * @return the map containing this process builder's environment variables. */ public java.util.Map<String, String> environment() { return environmentJ; } /** * Indicates whether the standard error should be redirected to standard * output. If redirected, the {@link Process#getErrorStream()} will always * return end of stream and standard error is written to * {@link Process#getInputStream()}. * * @return {@code true} if the standard error is redirected; {@code false} * otherwise. */ public bool redirectErrorStream() { return redirectErrorStreamJ; } /** * Changes the state of whether or not standard error is redirected to * standard output. * * @param redirectErrorStream * {@code true} to redirect standard error, {@code false} * otherwise. * @return this process builder instance. */ public ProcessBuilder redirectErrorStream(bool redirectErrorStreamJ) { this.redirectErrorStreamJ = redirectErrorStreamJ; return this; } /** * Starts a new process based on the current state of this process builder. * * @return the new {@code Process} instance. * @throws NullPointerException * if any of the elements of {@link #command()} is {@code null}. * @throws IndexOutOfBoundsException * if {@link #command()} is empty. * @throws SecurityException * if {@link SecurityManager#checkExec(String)} doesn't allow * process creation. * @throws IOException * if an I/O error happens. */ public Process start() {//throws IOException { if (commandJ.isEmpty()) { throw new IndexOutOfBoundsException(); } String[] cmdArray = new String[commandJ.size()]; for (int i = 0; i < cmdArray.Length; i++) { if ((cmdArray[i] = commandJ.get(i)) == null) { throw new NullPointerException(); } } String[] envArray = new String[environmentJ.size()]; int i2 = 0; /* foreach (Map.Entry<String, String> entry in environmentJ.entrySet()) { envArray[i2++] = entry.getKey() + "=" + entry.getValue(); //$NON-NLS-1$ } */ java.util.Iterator<String> it = environmentJ.keySet().iterator(); while (it.hasNext()) { String key = it.next(); String value = environmentJ.get(key); envArray[i2++] = key + "=" + value; } java.lang.Process process = Runtime.getRuntime().exec(cmdArray, envArray, directoryJ); // TODO implement support for redirectErrorStream return process; } private static java.util.List<String> toList(String[] strings) { java.util.ArrayList<String> arrayList = new java.util.ArrayList<String>(strings.Length); foreach (String str in strings) { arrayList.add(str); } return arrayList; } } }
using System; using System.Collections; using Drawing = System.Drawing; using Drawing2D = System.Drawing.Drawing2D; using WinForms = System.Windows.Forms; // 4/6/03 /// <summary> /// Summary description for ContactTreeNode. /// </summary> public class TreeNodeEx : ICloneable { private TreeNodeCollectionEx nodes; private string text = string.Empty, toolTipText = string.Empty; private bool isExpanded = true; private Drawing.Point location; private Drawing.Size size = new Drawing.Size(200, 50); private TreeViewEx treeView = null; private TreeNodeEx parent = null; private object tag; private WinForms.ContextMenu contextMenu = null; private bool visible = true; private int collapsedImageIndex = 0, expandedImageIndex = 0; public event EventHandler Selected; private Drawing.FontStyle fontStyle = Drawing.FontStyle.Regular; private Drawing.Brush textBrush = Drawing.Brushes.Black; public Drawing.Brush TextBrush { get { return textBrush; } set { textBrush = value; this.Invalidate(); this.Update(); } } public bool Visible { get { return this.visible; } set { this.visible = value; if (this.treeView != null) this.treeView.Refresh(); } } public Drawing.FontStyle FontStyle { get { return fontStyle; } set { fontStyle = value; this.Invalidate(); this.Update(); } } public object Tag { get { return tag; } set { tag = value; } } public string ToolTipText { get { return toolTipText; } set { toolTipText = value; } } public WinForms.ContextMenu ContextMenu { get { return this.contextMenu; } set { this.contextMenu = value; } } public int CollapsedImageIndex { get { return collapsedImageIndex; } set { if (value < 0) throw new IndexOutOfRangeException("Image index must be greated than zero"); if (value != this.collapsedImageIndex && this.treeView != null) { this.Invalidate(); this.Update(); } this.collapsedImageIndex = value; } } public int ExpandedImageIndex { get { return this.expandedImageIndex; } set { if (value < 0) throw new IndexOutOfRangeException("Image index must be greated than zero"); if (value != this.expandedImageIndex && this.treeView != null) { this.Invalidate(); this.Update(); } this.expandedImageIndex = value; } } internal void ExecuteSelected(EventArgs e) { if (Selected != null) Selected(this, e); } public TreeViewEx TreeView { get { return treeView; } } internal TreeViewEx iTreeView { get { return treeView; } set { treeView = value; foreach (TreeNodeEx node in this.Nodes) { node.iTreeView = value; } } } public TreeNodeEx Parent { get { return parent; } } internal TreeNodeEx iParent { get { return parent; } set { parent = value; } } public Drawing.Point Location { get { return location; } set { location = value; } } public Drawing.Size Size { get { return size; } set { size = value; } } public Drawing.Rectangle Rectangle { get { return new Drawing.Rectangle(location, size); } } public void Invalidate() { if (this.treeView != null) { Drawing.Rectangle rect = this.Rectangle; rect.X -= 4; rect.Y -= 4; rect.Width += 8; rect.Height += 8; this.treeView.Invalidate(rect); } } public TreeNodeCollectionEx Nodes { get { return nodes; } } public string Text { get { return text; } set { text = value; } } public bool Expanded { get { return isExpanded; } } public bool Collapsed { get { return !isExpanded; } } public void Toggle() { if (!this.isExpanded) this.Expand(); else this.Collapse(); } public void Expand() { this.isExpanded = true; if (this.treeView != null) { this.treeView.Invalidate(); this.treeView.Update(); this.treeView.ExecuteExpand(this); } } public void Collapse() { this.isExpanded = false; if (this.treeView != null) { this.treeView.Invalidate(); this.treeView.Update(); this.treeView.ExecuteCollapse(this); } } public void Remove() { if (this.parent != null) this.parent.Nodes.Remove(this); else if (this.treeView != null) this.treeView.Nodes.Remove(this); if (this.treeView != null) { this.treeView.Invalidate(); this.treeView.Update(); } } public void Update() { if (this.treeView != null) this.treeView.Update(); } /// <summary> /// Checks if this node is either a direct or indirect parent of /// the parameter node. /// </summary> /// <param name="node">Child node to check</param> /// <returns>True if this node is a parent to the parameter node</returns> public bool IsParent(TreeNodeEx node) { if (node == this) return true; foreach (TreeNodeEx child in this.Nodes) { if (child.IsParent(node)) return true; } return false; } public TreeNodeEx() { this.nodes = new TreeNodeCollectionEx(this); } public TreeNodeEx(string text) : this() { this.text = text; } public TreeNodeEx(string text, string tooltip) : this(text) { this.toolTipText = tooltip; } public object Clone() { return this.MemberwiseClone(); } }
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs) //#define ProfileAstar //@SHOWINEDITOR //#define ASTAR_UNITY_PRO_PROFILER //@SHOWINEDITOR Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler. using System.Collections.Generic; using System; using UnityEngine; using Pathfinding; namespace Pathfinding { public class AstarProfiler { public class ProfilePoint { //public DateTime lastRecorded; //public TimeSpan totalTime; public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); public int totalCalls; public long tmpBytes; public long totalBytes; } private static Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>(); private static DateTime startTime = DateTime.UtcNow; public static ProfilePoint[] fastProfiles; public static string[] fastProfileNames; private AstarProfiler() { } [System.Diagnostics.Conditional ("ProfileAstar")] public static void InitializeFastProfile (string[] profileNames) { fastProfileNames = new string[profileNames.Length+2]; Array.Copy (profileNames,fastProfileNames, profileNames.Length); fastProfileNames[fastProfileNames.Length-2] = "__Control1__"; fastProfileNames[fastProfileNames.Length-1] = "__Control2__"; fastProfiles = new ProfilePoint[fastProfileNames.Length]; for (int i=0;i<fastProfiles.Length;i++) fastProfiles[i] = new ProfilePoint(); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartFastProfile(int tag) { //profiles.TryGetValue(tag, out point); fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow; } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndFastProfile(int tag) { /*if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; }*/ ProfilePoint point = fastProfiles[tag]; point.totalCalls++; point.watch.Stop (); //DateTime now = DateTime.UtcNow; //point.totalTime += now - point.lastRecorded; //fastProfiles[tag] = point; } [System.Diagnostics.Conditional ("ASTAR_UNITY_PRO_PROFILER")] public static void EndProfile () { Profiler.EndSample (); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartProfile(string tag) { //Console.WriteLine ("Profile Start - " + tag); ProfilePoint point; profiles.TryGetValue(tag, out point); if (point == null) { point = new ProfilePoint(); profiles[tag] = point; } point.tmpBytes = System.GC.GetTotalMemory (false); point.watch.Start(); //point.lastRecorded = DateTime.UtcNow; //Debug.Log ("Starting " + tag); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndProfile(string tag) { if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; } //Console.WriteLine ("Profile End - " + tag); //DateTime now = DateTime.UtcNow; ProfilePoint point = profiles[tag]; //point.totalTime += now - point.lastRecorded; ++point.totalCalls; point.watch.Stop(); point.totalBytes += System.GC.GetTotalMemory (false) - point.tmpBytes; //profiles[tag] = point; //Debug.Log ("Ending " + tag); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void Reset() { profiles.Clear(); startTime = DateTime.UtcNow; if (fastProfiles != null) { for (int i=0;i<fastProfiles.Length;i++) { fastProfiles[i] = new ProfilePoint (); } } } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintFastResults() { StartFastProfile (fastProfiles.Length-2); for (int i=0;i<1000;i++) { StartFastProfile (fastProfiles.Length-1); EndFastProfile (fastProfiles.Length-1); } EndFastProfile (fastProfiles.Length-2); double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0; TimeSpan endTime = DateTime.UtcNow - startTime; System.Text.StringBuilder output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); output.Append ("Name | Total Time | Total Calls | Avg/Call | Bytes"); //foreach(KeyValuePair<string, ProfilePoint> pair in profiles) for (int i=0;i<fastProfiles.Length;i++) { string name = fastProfileNames[i]; ProfilePoint value = fastProfiles[i]; int totalCalls = value.totalCalls; double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls; if (totalCalls < 1) continue; output.Append ("\n").Append(name.PadLeft(10)).Append("| "); output.Append (totalTime.ToString("0.0 ").PadLeft (10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append ("| "); output.Append (totalCalls.ToString().PadLeft (10)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadLeft(10)); /* output.Append("\nProfile"); output.Append(name); output.Append(" took \t"); output.Append(totalTime.ToString("0.0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging \t"); output.Append((totalTime / totalCalls).ToString("0.000")); output.Append(" ms per call"); */ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintResults() { TimeSpan endTime = DateTime.UtcNow - startTime; System.Text.StringBuilder output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); int maxLength = 5; foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { maxLength = Math.Max (pair.Key.Length,maxLength); } output.Append (" Name ".PadRight (maxLength)). Append("|").Append(" Total Time ".PadRight(20)). Append("|").Append(" Total Calls ".PadRight(20)). Append("|").Append(" Avg/Call ".PadRight(20)); foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds; int totalCalls = pair.Value.totalCalls; if (totalCalls < 1) continue; string name = pair.Key; output.Append ("\n").Append(name.PadRight(maxLength)).Append("| "); output.Append (totalTime.ToString("0.0").PadRight (20)).Append ("| "); output.Append (totalCalls.ToString().PadRight (20)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadRight(20)); output.Append (Pathfinding.AstarMath.FormatBytesBinary ((int)pair.Value.totalBytes).PadLeft(10)); /*output.Append("\nProfile "); output.Append(pair.Key); output.Append(" took "); output.Append(totalTime.ToString("0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging "); output.Append((totalTime / totalCalls).ToString("0.0")); output.Append(" ms per call");*/ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using Microsoft.Win32; using PermissionSet = System.Security.PermissionSet; using System.Security.Permissions; /*=================================JapaneseCalendar========================== ** ** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as ** Gregorian calendar. However, the year value is an offset to the Gregorian ** year based on the era. ** ** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor, ** and the era begins on the day an emperor ascends the throne and continues until his death. ** The era changes at 12:00AM. ** ** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st. ** 1989/1/8 A.D. is also Heisei 1st 1/8. ** ** Any date in the year during which era is changed can be reckoned in either era. For example, ** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year. ** ** Note: ** The DateTime can be represented by the JapaneseCalendar are limited to two factors: ** 1. The min value and max value of DateTime class. ** 2. The available era information. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1868/09/08 9999/12/31 ** Japanese Meiji 01/01 Heisei 8011/12/31 ============================================================================*/ [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class JapaneseCalendar : Calendar { internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8); [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Japanese calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. static internal volatile EraInfo[] japaneseEraInfo; #if !__APPLE__ private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras"; private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive; #endif // // Read our era info // // m_EraInfo must be listed in reverse chronological order. The most recent era // should be the first element. // That is, m_EraInfo[0] contains the most recent era. // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. // internal static EraInfo[] GetEraInfo() { // See if we need to build it if (japaneseEraInfo == null) { #if !__APPLE__ // See if we have any eras from the registry japaneseEraInfo = GetErasFromRegistry(); #endif // See if we have to use the built-in eras if (japaneseEraInfo == null) { // We know about some built-in ranges EraInfo[] defaultEraRanges = new EraInfo[4]; defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988, "\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925, "\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911, "\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867, "\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear // Remember the ranges we built japaneseEraInfo = defaultEraRanges; } } // return the era we found/made return japaneseEraInfo; } #if !__APPLE__ // // GetErasFromRegistry() // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. [System.Security.SecuritySafeCritical] // auto-generated private static EraInfo[] GetErasFromRegistry() { // Look in the registry key and see if we can find any ranges int iFoundEras = 0; EraInfo[] registryEraRanges = null; try { // Need to access registry PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new RegistryPermission(RegistryPermissionAccess.Read, c_japaneseErasHivePermissionList)); permSet.Assert(); RegistryKey key = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE).OpenSubKey(c_japaneseErasHive, false); // Abort if we didn't find anything if (key == null) return null; // Look up the values in our reg key String[] valueNames = key.GetValueNames(); if (valueNames != null && valueNames.Length > 0) { registryEraRanges = new EraInfo[valueNames.Length]; // Loop through the registry and read in all the values for (int i = 0; i < valueNames.Length; i++) { // See if the era is a valid date EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString()); // continue if not valid if (era == null) continue; // Remember we found one. registryEraRanges[iFoundEras] = era; iFoundEras++; } } } catch (System.Security.SecurityException) { // If we weren't allowed to read, then just ignore the error return null; } catch (System.IO.IOException) { // If key is being deleted just ignore the error return null; } catch (System.UnauthorizedAccessException) { // Registry access rights permissions, just ignore the error return null; } // // If we didn't have valid eras, then fail // should have at least 4 eras // if (iFoundEras < 4) return null; // // Now we have eras, clean them up. // // Clean up array length Array.Resize(ref registryEraRanges, iFoundEras); // Sort them Array.Sort(registryEraRanges, CompareEraRanges); // Clean up era information for (int i = 0; i < registryEraRanges.Length; i++) { // eras count backwards from length to 1 (and are 1 based indexes into string arrays) registryEraRanges[i].era = registryEraRanges.Length - i; // update max era year if (i == 0) { // First range is 'til the end of the calendar registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset; } else { // Rest are until the next era (remember most recent era is first in array) registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset; } } // Return our ranges return registryEraRanges; } // // Compare two era ranges, eg just the ticks // Remember the era array is supposed to be in reverse chronological order // private static int CompareEraRanges(EraInfo a, EraInfo b) { return b.ticks.CompareTo(a.ticks); } // // GetEraFromValue // // Parse the registry value name/data pair into an era // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. private static EraInfo GetEraFromValue(String value, String data) { // Need inputs if (value == null || data == null) return null; // // Get Date // // Need exactly 10 characters in name for date // yyyy.mm.dd although the . can be any character if (value.Length != 10) return null; int year; int month; int day; if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) || !Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) || !Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day)) { // Couldn't convert integer, fail return null; } // // Get Strings // // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups) String[] names = data.Split(new char[] {'_'}); // Should have exactly 4 parts // 0 - Era Name // 1 - Abbreviated Era Name // 2 - English Era Name // 3 - Abbreviated English Era Name if (names.Length != 4) return null; // Each part should have data in it if (names[0].Length == 0 || names[1].Length == 0 || names[2].Length == 0 || names[3].Length == 0) return null; // // Now we have an era we can build // Note that the era # and max era year need cleaned up after sorting // Don't use the full English Era Name (names[2]) // return new EraInfo( 0, year, month, day, year - 1, 1, 0, names[0], names[1], names[3]); } #endif // !__APPLE__ internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new JapaneseCalendar(); } return (s_defaultInstance); } public JapaneseCalendar() { try { new CultureInfo("ja-JP"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().FullName, e); } helper = new GregorianCalendarHelper(this, GetEraInfo()); } internal override int ID { get { return (CAL_JAPAN); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } /*=================================GetDaysInMonth========================== **Action: Returns the number of days in the month given by the year and month arguments. **Returns: The number of days in the given month. **Arguments: ** year The year in Japanese calendar. ** month The month ** era The Japanese era value. **Exceptions ** ArgumentException If month is less than 1 or greater * than 12. ============================================================================*/ public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } /*=================================GetEra========================== **Action: Get the era value of the specified time. **Returns: The era value for the specified time. **Arguments: ** time the specified date time. **Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges. ============================================================================*/ public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } // For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, helper.MaxYear)); } return (year); } public override int[] Eras { get { return (helper.Eras); } } // // Return the various era strings // Note: The arrays are backwards of the eras // internal static String[] EraNames() { EraInfo[] eras = GetEraInfo(); String[] eraNames = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. eraNames[i] = eras[eras.Length - i - 1].eraName; } return eraNames; } internal static String[] AbbrevEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasAbbrev = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName; } return erasAbbrev; } internal static String[] EnglishEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasEnglish = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasEnglish[i] = eras[eras.Length - i - 1].englishEraName; } return erasEnglish; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; internal override bool IsValidYear(int year, int era) { return helper.IsValidYear(year, era); } public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, helper.MaxYear)); } twoDigitYearMax = value; } } } }
//! \file ArcMBL.cs //! \date Fri Mar 27 23:11:19 2015 //! \brief Marble Engine archive implementation. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using GameRes.Compression; using GameRes.Formats.Strings; namespace GameRes.Formats.Marble { public class MblOptions : ResourceOptions { public string PassPhrase; } public class MblArchive : ArcFile { public readonly byte[] Key; public MblArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, string password) : base (arc, impl, dir) { Key = Encodings.cp932.GetBytes (password); } } [Serializable] public class MblScheme : ResourceScheme { public Dictionary<string, string> KnownKeys; } [Export(typeof(ArchiveFormat))] public class MblOpener : ArchiveFormat { public override string Tag { get { return "MBL"; } } public override string Description { get { return "Marble engine resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public MblOpener () { Extensions = new string[] { "mbl", "dns" }; } public override ArcFile TryOpen (ArcView file) { int count = file.View.ReadInt32 (0); if (!IsSaneCount (count)) return null; ArcFile arc = null; uint filename_len = file.View.ReadUInt32 (4); if (filename_len > 0 && filename_len <= 0xff) arc = ReadIndex (file, count, filename_len, 8); if (null == arc) arc = ReadIndex (file, count, 0x10, 4); if (null == arc) arc = ReadIndex (file, count, 0x38, 4); return arc; } static readonly ResourceInstance<ImageFormat> PrsFormat = new ResourceInstance<ImageFormat> ("PRS"); static readonly ResourceInstance<ImageFormat> YpFormat = new ResourceInstance<ImageFormat> ("PRS/YP"); private ArcFile ReadIndex (ArcView file, int count, uint filename_len, uint index_offset) { uint index_size = (8u + filename_len) * (uint)count; if (index_size > file.View.Reserve (index_offset, index_size)) return null; try { bool contains_scripts = Path.GetFileNameWithoutExtension (file.Name).EndsWith ("_data", StringComparison.OrdinalIgnoreCase); var dir = new List<Entry> (count); for (int i = 0; i < count; ++i) { string name = file.View.ReadString (index_offset, filename_len); if (0 == name.Length) break; if (filename_len-name.Length > 1) { string ext = file.View.ReadString (index_offset+name.Length+1, filename_len-(uint)name.Length-1); if (0 != ext.Length) name = Path.ChangeExtension (name, ext); } name = name.ToLowerInvariant(); index_offset += (uint)filename_len; uint offset = file.View.ReadUInt32 (index_offset); string type = null; if (contains_scripts || name.EndsWith (".s")) { type = "script"; } else if (4 == Path.GetExtension (name).Length) { type = FormatCatalog.Instance.GetTypeFromName (name); } Entry entry; if (string.IsNullOrEmpty (type)) { entry = new AutoEntry (name, () => { uint signature = file.View.ReadUInt32 (offset); if (0x4259 == (0xFFFF & signature)) return PrsFormat.Value; else if (0x5059 == (0xFFFF & signature)) return YpFormat.Value; else if (0 != signature) return FormatCatalog.Instance.LookupSignature (signature).FirstOrDefault(); else return null; }); } else { entry = new Entry { Name = name, Type = type }; } entry.Offset = offset; entry.Size = file.View.ReadUInt32 (index_offset+4); if (offset < index_size || !entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); index_offset += 8; } if (0 == dir.Count || (1 == dir.Count && count > 1)) return null; contains_scripts = contains_scripts || dir.Any (e => e.Name.EndsWith (".s")); if (contains_scripts) { var password = QueryPassPhrase (file.Name); if (!string.IsNullOrEmpty (password)) return new MblArchive (file, this, dir, password); } return new ArcFile (file, this, dir); } catch { return null; } } public static Dictionary<string, string> KnownKeys = new Dictionary<string, string>(); public override ResourceScheme Scheme { get { return new MblScheme { KnownKeys = KnownKeys }; } set { KnownKeys = ((MblScheme)value).KnownKeys; } } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (entry.Type != "script") return arc.File.CreateStream (entry.Offset, entry.Size); var marc = arc as MblArchive; var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); if (null == marc || null == marc.Key) { for (int i = 0; i < data.Length; ++i) { data[i] = (byte)-data[i]; } } else if (marc.Key.Length > 0) { for (int i = 0; i < data.Length; ++i) { data[i] ^= marc.Key[i % marc.Key.Length]; } } return new BinMemoryStream (data, entry.Name); } string QueryPassPhrase (string arc_name) { var title = FormatCatalog.Instance.LookupGame (arc_name); if (!string.IsNullOrEmpty (title) && KnownKeys.ContainsKey (title)) return KnownKeys[title]; var options = Query<MblOptions> (arcStrings.MBLNotice); return options.PassPhrase; } public override ResourceOptions GetDefaultOptions () { return new MblOptions { PassPhrase = Properties.Settings.Default.MBLPassPhrase }; } public override object GetAccessWidget () { return new GUI.WidgetMBL(); } } [Export(typeof(ArchiveFormat))] public class GraMblOpener : ArchiveFormat { public override string Tag { get { return "MBL/GRA"; } } public override string Description { get { return "Marble engine graphics archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public override ArcFile TryOpen (ArcView file) { uint filename_len = file.View.ReadUInt32 (0); int count = file.View.ReadInt32 (4); if (filename_len < 8 || filename_len > 0x40 || !IsSaneCount (count)) return null; var arc_name = Path.GetFileNameWithoutExtension (file.Name); if (!arc_name.Equals ("mg_gra", StringComparison.InvariantCultureIgnoreCase)) return null; uint index_offset = 8; uint index_size = (8u + filename_len) * (uint)count; if (index_size > file.View.Reserve (index_offset, index_size)) return null; var dir = new List<Entry> (count); for (int i = 0; i < count; ++i) { string name = file.View.ReadString (index_offset, filename_len); if (0 == name.Length) break; name = name.ToLowerInvariant(); index_offset += filename_len; var entry = new Entry { Name = Path.ChangeExtension (name, "bmp"), Type = "image", Offset = file.View.ReadUInt32 (index_offset), Size = file.View.ReadUInt32 (index_offset+4), }; if (entry.Offset < index_size || !entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); index_offset += 8; } if (0 == dir.Count || (1 == dir.Count && count > 1)) return null; return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { var input = arc.File.CreateStream (entry.Offset, entry.Size); if (input.PeekByte() != 0x78) return input; return new ZLibStream (input, CompressionMode.Decompress); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System.Threading.Tasks; using System.Net.Test.Common; using System.Text; using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Sockets.Tests { public class TcpClientTest { private readonly ITestOutputHelper _log; public TcpClientTest(ITestOutputHelper output) { _log = output; } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] public async Task Connect_DnsEndPoint_Success(int mode) { using (TcpClient client = new TcpClient()) { Assert.False(client.Connected); string host = Configuration.Sockets.SocketServer.IdnHost; int port = Configuration.Sockets.SocketServer.Port; if (mode == 0) { await client.ConnectAsync(host, port); } else { IPAddress[] addresses = await Dns.GetHostAddressesAsync(host); await (mode == 1 ? client.ConnectAsync(addresses[0], port) : client.ConnectAsync(addresses, port)); } Assert.True(client.Connected); Assert.NotNull(client.Client); Assert.Same(client.Client, client.Client); using (NetworkStream s = client.GetStream()) { byte[] getRequest = Encoding.ASCII.GetBytes("GET / HTTP/1.1\r\n\r\n"); await s.WriteAsync(getRequest, 0, getRequest.Length); Assert.NotEqual(-1, s.ReadByte()); // just verify we successfully get any data back } } } [OuterLoop] // TODO: Issue #11345 [Fact] public void ConnectedAvailable_InitialValues_Default() { using (TcpClient client = new TcpClient()) { Assert.False(client.Connected); Assert.Equal(0, client.Available); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void ConnectedAvailable_NullClient() { using (TcpClient client = new TcpClient()) { client.Client = null; Assert.False(client.Connected); Assert.Equal(0, client.Available); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(PlatformID.Windows)] public void ExclusiveAddressUse_NullClient() { using (TcpClient client = new TcpClient()) { client.Client = null; Assert.False(client.ExclusiveAddressUse); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(PlatformID.Windows)] public void Roundtrip_ExclusiveAddressUse_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.ExclusiveAddressUse = true; Assert.True(client.ExclusiveAddressUse); client.ExclusiveAddressUse = false; Assert.False(client.ExclusiveAddressUse); } } [OuterLoop] // TODO: Issue #11345 [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void ExclusiveAddressUse_NotSupported() { using (TcpClient client = new TcpClient()) { Assert.Throws<SocketException>(() => client.ExclusiveAddressUse); Assert.Throws<SocketException>(() => { client.ExclusiveAddressUse = true; }); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Roundtrip_LingerOption_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.LingerState = new LingerOption(true, 42); Assert.True(client.LingerState.Enabled); Assert.Equal(42, client.LingerState.LingerTime); client.LingerState = new LingerOption(false, 0); Assert.False(client.LingerState.Enabled); Assert.Equal(0, client.LingerState.LingerTime); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Roundtrip_NoDelay_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.NoDelay = true; Assert.True(client.NoDelay); client.NoDelay = false; Assert.False(client.NoDelay); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Roundtrip_ReceiveBufferSize_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.ReceiveBufferSize = 4096; Assert.Equal(4096, client.ReceiveBufferSize); client.ReceiveBufferSize = 8192; Assert.Equal(8192, client.ReceiveBufferSize); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Roundtrip_SendBufferSize_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.SendBufferSize = 4096; Assert.Equal(4096, client.SendBufferSize); client.SendBufferSize = 8192; Assert.Equal(8192, client.SendBufferSize); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Roundtrip_ReceiveTimeout_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.ReceiveTimeout = 1; Assert.Equal(1, client.ReceiveTimeout); client.ReceiveTimeout = 0; Assert.Equal(0, client.ReceiveTimeout); } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Roundtrip_SendTimeout_GetEqualsSet() { using (TcpClient client = new TcpClient()) { client.SendTimeout = 1; Assert.Equal(1, client.SendTimeout); client.SendTimeout = 0; Assert.Equal(0, client.SendTimeout); } } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task Properties_PersistAfterConnect() { using (TcpClient client = new TcpClient()) { // Set a few properties client.LingerState = new LingerOption(true, 1); client.ReceiveTimeout = 42; client.SendTimeout = 84; await client.ConnectAsync(Configuration.Sockets.SocketServer.IdnHost, Configuration.Sockets.SocketServer.Port); // Verify their values remain as were set before connecting Assert.True(client.LingerState.Enabled); Assert.Equal(1, client.LingerState.LingerTime); Assert.Equal(42, client.ReceiveTimeout); Assert.Equal(84, client.SendTimeout); // Note: not all properties can be tested for this on all OSes, as some // properties are modified by the OS, e.g. Linux will double whatever // buffer size you set and return that double value. OSes may also enforce // minimums and maximums, silently capping to those amounts. } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public async Task Dispose_CancelsConnectAsync(bool connectByName) { using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // Set up a server socket to which to connect server.Bind(new IPEndPoint(IPAddress.Loopback, 0)); server.Listen(1); var endpoint = (IPEndPoint)server.LocalEndPoint; // Connect asynchronously... var client = new TcpClient(); Task connectTask = connectByName ? client.ConnectAsync("localhost", endpoint.Port) : client.ConnectAsync(endpoint.Address, endpoint.Port); // ...and hopefully before it's completed connecting, dispose. var sw = Stopwatch.StartNew(); client.Dispose(); // There is a race condition here. If the connection succeeds before the // disposal, then the task will complete successfully. Otherwise, it should // fail with an ObjectDisposedException. try { await connectTask; } catch (ObjectDisposedException) { } sw.Stop(); Assert.Null(client.Client); // should be nulled out after Dispose } } } }
using System; using System.Collections.Generic; using Moq; using NUnit.Framework; using PopForums.Models; using PopForums.Repositories; using PopForums.Services; namespace PopForums.Test.Services { [TestFixture] public class LastReadServiceTests { private LastReadService GetService() { _lastReadRepo = new Mock<ILastReadRepository>(); _postRepo = new Mock<IPostRepository>(); return new LastReadService(_lastReadRepo.Object, _postRepo.Object); } private Mock<ILastReadRepository> _lastReadRepo; private Mock<IPostRepository> _postRepo; [Test] public void MarkForumReadSetsReadTime() { var service = GetService(); var forum = new Forum(123); var user = new User(456, DateTime.MinValue); service.MarkForumRead(user, forum); _lastReadRepo.Verify(l => l.SetForumRead(user.UserID, forum.ForumID, It.IsAny<DateTime>()), Times.Exactly(1)); } [Test] public void MarkForumReadDeletesOldTopicReadTimes() { var service = GetService(); var forum = new Forum(123); var user = new User(456, DateTime.MinValue); service.MarkForumRead(user, forum); _lastReadRepo.Verify(l => l.DeleteTopicReadsInForum(user.UserID, forum.ForumID), Times.Exactly(1)); } [Test] public void MarkTopicReadThrowsWithoutUser() { var service = GetService(); Assert.Throws<ArgumentNullException>(() => service.MarkTopicRead(null, new Topic(1))); } [Test] public void MarkTopicReadThrowsWithoutTopic() { var service = GetService(); Assert.Throws<ArgumentNullException>(() => service.MarkTopicRead(new User(123, DateTime.MaxValue), null)); } [Test] public void MarkAllForumReadThrowsWithoutUser() { var service = GetService(); Assert.Throws<ArgumentNullException>(() => service.MarkAllForumsRead(null)); } [Test] public void MarkForumReadThrowsWithoutUser() { var service = GetService(); Assert.Throws<ArgumentNullException>(() => service.MarkForumRead(null, new Forum(1))); } [Test] public void MarkForumReadThrowsWithoutForum() { var service = GetService(); Assert.Throws<ArgumentNullException>(() => service.MarkForumRead(new User(1, DateTime.MaxValue), null)); } [Test] public void MarkAllForumReadSetsReadTimes() { var service = GetService(); var user = new User(456, DateTime.MinValue); service.MarkAllForumsRead(user); _lastReadRepo.Verify(l => l.SetAllForumsRead(user.UserID, It.IsAny<DateTime>()), Times.Exactly(1)); } [Test] public void MarkAllForumReadDeletesAllOldTopicReadTimes() { var service = GetService(); var user = new User(456, DateTime.MinValue); service.MarkAllForumsRead(user); _lastReadRepo.Verify(l => l.DeleteAllTopicReads(user.UserID), Times.Exactly(1)); } [Test] public void ForumReadStatusForNoUser() { var service = GetService(); var forum1 = new Forum(1); var forum2 = new Forum(2) { IsArchived = true }; var forum3 = new Forum(3); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum1, forum2, forum3 }); service.GetForumReadStatus(null, container); Assert.AreEqual(3, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NoNewPosts, container.ReadStatusLookup[1]); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Closed, container.ReadStatusLookup[2]); Assert.AreEqual(ReadStatus.NoNewPosts, container.ReadStatusLookup[3]); } [Test] public void ForumReadStatusUserNewPosts() { var service = GetService(); var forum = new Forum(1) { LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) }; var user = new User(2, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(2)).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 3, 0, 0) } }); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum }); service.GetForumReadStatus(user, container); Assert.AreEqual(1, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NewPosts, container.ReadStatusLookup[1]); } [Test] public void ForumReadStatusUserNewPostsButNoTopicRecords() { var service = GetService(); var forum = new Forum(1) { LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) }; var user = new User(2, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(2)).Returns(new Dictionary<int, DateTime>()); _lastReadRepo.Setup(l => l.GetLastReadTimesForForum(user.UserID, forum.ForumID)).Returns(new DateTime(2000, 1, 1, 3, 0, 0)); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum }); service.GetForumReadStatus(user, container); Assert.AreEqual(1, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NewPosts, container.ReadStatusLookup[1]); } [Test] public void ForumReadStatusUserNewPostsNoLastReadRecords() { var service = GetService(); var forum = new Forum(1) { LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) }; var user = new User(2, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(2)).Returns(new Dictionary<int, DateTime>()); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum }); service.GetForumReadStatus(user, container); Assert.AreEqual(1, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NewPosts, container.ReadStatusLookup[1]); } [Test] public void ForumReadStatusUserNoNewPosts() { var service = GetService(); var forum = new Forum(1) { LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) }; var user = new User(2, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(2)).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 7, 0, 0) } }); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum }); service.GetForumReadStatus(user, container); Assert.AreEqual(1, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NoNewPosts, container.ReadStatusLookup[1]); } [Test] public void ForumReadStatusUserNewPostsArchived() { var service = GetService(); var forum = new Forum(1) { LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0), IsArchived = true }; var user = new User(2, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(2)).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 3, 0, 0) } }); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum }); service.GetForumReadStatus(user, container); Assert.AreEqual(1, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Closed, container.ReadStatusLookup[1]); } [Test] public void ForumReadStatusUserNoNewPostsArchived() { var service = GetService(); var forum = new Forum(1) { LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0), IsArchived = true }; var user = new User(2, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(2)).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 7, 0, 0) } }); var container = new CategorizedForumContainer(new List<Category>(), new[] { forum }); service.GetForumReadStatus(user, container); Assert.AreEqual(1, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Closed, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusForNoUser() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> {new Topic(1), new Topic(2) {IsClosed = true}, new Topic(3) {IsPinned = true}}; service.GetTopicReadStatus(null, container); Assert.AreEqual(3, container.ReadStatusLookup.Count); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Closed | ReadStatus.NotPinned, container.ReadStatusLookup[2]); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.Pinned, container.ReadStatusLookup[3]); } [Test] public void TopicReadStatusWithUserNewNoForumRecordNoTopicRecord() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime>()); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNewNoForumRecordWithTopicRecord() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime>()); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 3, 0, 0) } }); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNewWithForumRecordNoTopicRecord() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 2, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNewWithForumRecordWithTopicRecord() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 2, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 3, 0, 0) } }); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNotNewWithForumRecordNoTopicRecord() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 7, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNotNewNoForumRecordWithTopicRecord() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime>()); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 7, 0, 0) } }); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNotNewWithForumRecordWithTopicRecordForumNewer() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 7, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 3, 0, 0) } }); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserNotNewWithForumRecordWithTopicRecordTopicNewer() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 3, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime> { { 1, new DateTime(2000, 1, 1, 7, 0, 0) } }); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserOpenNewPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, IsPinned = true, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 3, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new [] {1})).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Open | ReadStatus.Pinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserOpenNewNotPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 3, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserOpenNotNewPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, IsPinned = true, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 7, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.Pinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserOpenNotNewNotPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 7, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Open | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserClosedNewPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, IsClosed = true, IsPinned = true, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 3, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Closed | ReadStatus.Pinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserClosedNewNotPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, IsClosed = true, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 3, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NewPosts | ReadStatus.Closed | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserClosedNoNewPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, IsClosed = true, IsPinned = true, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 7, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Closed | ReadStatus.Pinned, container.ReadStatusLookup[1]); } [Test] public void TopicReadStatusWithUserClosedNoNewNotPinned() { var service = GetService(); var container = new PagedTopicContainer(); container.Topics = new List<Topic> { new Topic(1) { ForumID = 2, IsClosed = true, LastPostTime = new DateTime(2000, 1, 1, 5, 0, 0) } }; var user = new User(123, DateTime.MinValue); _lastReadRepo.Setup(l => l.GetLastReadTimesForForums(user.UserID)).Returns(new Dictionary<int, DateTime> { { 2, new DateTime(2000, 1, 1, 7, 0, 0) } }); _lastReadRepo.Setup(l => l.GetLastReadTimesForTopics(user.UserID, new[] { 1 })).Returns(new Dictionary<int, DateTime>()); service.GetTopicReadStatus(user, container); Assert.AreEqual(ReadStatus.NoNewPosts | ReadStatus.Closed | ReadStatus.NotPinned, container.ReadStatusLookup[1]); } [Test] public void MarkTopicReadCallsRepo() { var service = GetService(); var user = new User(1, DateTime.MinValue); var topic = new Topic(2); service.MarkTopicRead(user, topic); _lastReadRepo.Verify(l => l.SetTopicRead(user.UserID, topic.TopicID, It.IsAny<DateTime>()), Times.Exactly(1)); } } }
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API using System; using System.Collections.Generic; using UnityEngine; namespace PlayFab.Public { /// <summary> /// Interface which can be used to implement class responsible for gathering and sending information about session. /// </summary> public interface IScreenTimeTracker { // Unity MonoBehaviour callbacks void OnEnable(); void OnDisable(); void OnDestroy(); void OnApplicationQuit(); void OnApplicationFocus(bool isFocused); // Class specific methods void ClientSessionStart(string entityId, string entityType, string playFabUserId); void Send(); } /// <summary> /// Class responsible for gathering and sending information about session, for example: focus duration, device info, etc. /// </summary> public class ScreenTimeTracker : IScreenTimeTracker { private Guid focusId; private Guid gameSessionID; private bool initialFocus = true; private bool isSending = false; private DateTime focusOffDateTime = DateTime.UtcNow; private DateTime focusOnDateTime = DateTime.UtcNow; private Queue<EventsModels.EventContents> eventsRequests = new Queue<EventsModels.EventContents>(); private EventsModels.EntityKey entityKey = new EventsModels.EntityKey(); private const string eventNamespace = "com.playfab.events.sessions"; private const int maxBatchSizeInEvents = 10; private PlayFabEventsInstanceAPI eventApi; public ScreenTimeTracker() { eventApi = new PlayFabEventsInstanceAPI(PlayFabSettings.staticPlayer); } /// <summary> /// Start session, the function responsible for creating SessionID and gathering information about user and device /// </summary> /// <param name="playFabUserId">Result of the user's login, represent user ID</param> public void ClientSessionStart(string entityId, string entityType, string playFabUserId) { gameSessionID = Guid.NewGuid(); entityKey.Id = entityId; entityKey.Type = entityType; EventsModels.EventContents eventInfo = new EventsModels.EventContents(); eventInfo.Name = "client_session_start"; eventInfo.EventNamespace = eventNamespace; eventInfo.Entity = entityKey; eventInfo.OriginalTimestamp = DateTime.UtcNow; var payload = new Dictionary<string, object> { { "UserID", playFabUserId}, { "DeviceType", SystemInfo.deviceType}, { "DeviceModel", SystemInfo.deviceModel}, { "OS", SystemInfo.operatingSystem }, { "ClientSessionID", gameSessionID }, }; eventInfo.Payload = payload; eventsRequests.Enqueue(eventInfo); // Fake a focus-on event at the time of the first login: OnApplicationFocus(true); } /// <summary> /// Gather information about user's focus. Calculates interaction durations. /// Name mimics MonoBehaviour method, for ease of integration. /// </summary> /// <param name="isFocused">State of focus</param> public void OnApplicationFocus(bool isFocused) { EventsModels.EventContents eventInfo = new EventsModels.EventContents(); DateTime currentUtcDateTime = DateTime.UtcNow; eventInfo.Name = "client_focus_change"; eventInfo.EventNamespace = eventNamespace; eventInfo.Entity = entityKey; double focusStateDuration = 0.0; if (initialFocus) { focusId = Guid.NewGuid(); } if (isFocused) { // start counting focus-on time focusOnDateTime = currentUtcDateTime; // new id per focus focusId = Guid.NewGuid(); if (!initialFocus) { focusStateDuration = (currentUtcDateTime - focusOffDateTime).TotalSeconds; // this check safeguards from manual time changes while app is running if (focusStateDuration < 0) { focusStateDuration = 0; } } } else { focusStateDuration = (currentUtcDateTime - focusOnDateTime).TotalSeconds; // this check safeguards from manual time changes while app is running if (focusStateDuration < 0) { focusStateDuration = 0; } // start counting focus-off time focusOffDateTime = currentUtcDateTime; } var payload = new Dictionary<string, object> { { "FocusID", focusId }, { "FocusState", isFocused }, { "FocusStateDuration", focusStateDuration }, { "EventTimestamp", currentUtcDateTime }, { "ClientSessionID", gameSessionID }, }; eventInfo.OriginalTimestamp = currentUtcDateTime; eventInfo.Payload = payload; eventsRequests.Enqueue(eventInfo); initialFocus = false; if (!isFocused) { // Force the eventsRequests queue to empty. // If we are losing focus we should make an attempt to push out a focus lost event ASAP Send(); } } /// <summary> /// Sends events to server. /// </summary> public void Send() { if (PlayFabSettings.staticPlayer.IsClientLoggedIn() && (isSending == false)) { isSending = true; EventsModels.WriteEventsRequest request = new EventsModels.WriteEventsRequest(); request.Events = new List<EventsModels.EventContents>(); while ((eventsRequests.Count > 0) && (request.Events.Count < maxBatchSizeInEvents)) { EventsModels.EventContents eventInfo = eventsRequests.Dequeue(); request.Events.Add(eventInfo); } if (request.Events.Count > 0) { eventApi.WriteEvents(request, EventSentSuccessfulCallback, EventSentErrorCallback); } isSending = false; } } /// <summary> /// Callback to handle successful server interaction. /// </summary> /// <param name="response">Server response</param> private void EventSentSuccessfulCallback(EventsModels.WriteEventsResponse response) { // add code to work with successful callback } /// <summary> /// Callback to handle unsuccessful server interaction. /// </summary> /// <param name="response">Server response</param> private void EventSentErrorCallback(PlayFabError response) { Debug.LogWarning("Failed to send session data. Error: " + response.GenerateErrorReport()); } #region Unused MonoBehaviour compatibility methods /// <summary> /// Unused /// Name mimics MonoBehaviour method, for ease of integration. /// </summary> public void OnEnable() { // add code sending events on enable } /// <summary> /// Unused /// Name mimics MonoBehaviour method, for ease of integration. /// </summary> public void OnDisable() { // add code sending events on disable } /// <summary> /// Unused /// Name mimics MonoBehaviour method, for ease of integration. /// </summary> public void OnDestroy() { // add code sending events on destroy } #endregion /// <summary> /// Trying to send event during game exit. Note: works only on certain platforms. /// Name mimics MonoBehaviour method, for ease of integration. /// </summary> public void OnApplicationQuit() { // trying to send events during game exit Send(); } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Redis { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// REST API for Azure Redis Cache Service /// </summary> public partial class RedisManagementClient : Microsoft.Rest.ServiceClient<RedisManagementClient>, IRedisManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IRedisOperations. /// </summary> public virtual IRedisOperations Redis { get; private set; } /// <summary> /// Gets the IPatchSchedulesOperations. /// </summary> public virtual IPatchSchedulesOperations PatchSchedules { get; private set; } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected RedisManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected RedisManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected RedisManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected RedisManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RedisManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RedisManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RedisManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public RedisManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Redis = new RedisOperations(this); this.PatchSchedules = new PatchSchedulesOperations(this); this.BaseUri = new System.Uri("https://management.azure.com"); this.ApiVersion = "2016-04-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter()); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Airguitar.Areas.HelpPage.ModelDescriptions; using Airguitar.Areas.HelpPage.Models; namespace Airguitar.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using Microsoft.Ccr.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using W3C.Soap; namespace TrackRoamer.Robotics.Hardware.PololuMaestroService { /// <summary> /// Pololu Maestro Service contract class /// </summary> public sealed class Contract { /// <summary> /// DSS contract identifer for Pololu Maestro Service /// </summary> [DataMember] public const string Identifier = "http://schemas.trackroamer.com/2012/02/pololumaestroservice.html"; } [DataContract] public class SafePosition { [DataMember] public byte channel { get; set; } // Channel number - from 0 to 23 [DataMember] public ushort positionUs { get; set; } // microseconds, typically 850...2150 } /// <summary> /// Pololu Maestro Service state /// </summary> [DataContract] public class PololuMaestroServiceState { [DataMember] public List<SafePosition> SafePositions { get; set; } } /// <summary> /// Pololu Maestro Service main operations port /// </summary> [ServicePort] public class PololuMaestroServiceOperations : PortSet<DsspDefaultLookup, DsspDefaultDrop, Get, HttpGet, HttpPost, SendPololuMaestroCommand, Subscribe> { } /// <summary> /// Pololu Maestro Service get operation /// </summary> public class Get : Get<GetRequestType, PortSet<PololuMaestroServiceState, Fault>> { /// <summary> /// Creates a new instance of Get /// </summary> public Get() { } /// <summary> /// Creates a new instance of Get /// </summary> /// <param name="body">the request message body</param> public Get(GetRequestType body) : base(body) { } /// <summary> /// Creates a new instance of Get /// </summary> /// <param name="body">the request message body</param> /// <param name="responsePort">the response port for the request</param> public Get(GetRequestType body, PortSet<PololuMaestroServiceState, Fault> responsePort) : base(body, responsePort) { } } /// <summary> /// Sends a command to the Pololu Maestro Device. /// </summary> [DisplayName("(User) Send Pololu Maestro Device Command")] [Description("Sends a command to the Pololu Maestro Device, sets value on servo pins.")] public class SendPololuMaestroCommand : Update<PololuMaestroCommand, PortSet<DefaultUpdateResponseType, Fault>> { /// <summary> /// Sends a command to the Pololu Maestro Device. /// </summary> public SendPololuMaestroCommand() { } /// <summary> /// Sends a command to the Pololu Maestro Device. /// </summary> /// <param name="body"></param> public SendPololuMaestroCommand(PololuMaestroCommand body) : base(body) { } /// <summary> /// Sends a command to the Pololu Maestro Device. /// </summary> /// <param name="body"></param> /// <param name="responsePort"></param> public SendPololuMaestroCommand(PololuMaestroCommand body, Microsoft.Ccr.Core.PortSet<Microsoft.Dss.ServiceModel.Dssp.DefaultUpdateResponseType, W3C.Soap.Fault> responsePort) : base(body, responsePort) { } } /// <summary> /// A Pololu Maestro channel-value pair /// <remarks>Use with SendPololuMaestroCommand()</remarks> /// </summary> [DataContract] [Description("A Pololu Maestro channel-value pair")] public class ChannelValuePair { [DataMember] public byte Channel { get; set; } // Channel number - from 0 to 23, crosses over connected devices. // Target, in units of quarter microseconds. For typical servos, // 6000 is neutral and the acceptable range is 4000-8000. // A good servo will take 880 to 2200 us (3520 to 8800 in quarters) [DataMember] public ushort Target { get; set; } public override string ToString() { return string.Format("{0}:{1}", Channel, Target); } } /// <summary> /// A Pololu Maestro Device Command /// <remarks>Use with SendPololuMaestroCommand)</remarks> /// </summary> [DataContract] [Description("A Pololu Maestro Device Command")] public class PololuMaestroCommand { [DataMember] public string Command { get; set; } // "set" [DataMember] public List<ChannelValuePair> ChannelValues { get; set; } public override string ToString() { StringBuilder sbValues = new StringBuilder(); foreach (ChannelValuePair cvp in ChannelValues) { sbValues.AppendFormat("{0} ", cvp.ToString()); } return string.Format("{0} - {1}", Command, sbValues.ToString().Trim()); } } /// <summary> /// Pololu Maestro Service subscribe operation /// </summary> public class Subscribe : Subscribe<SubscribeRequestType, PortSet<SubscribeResponseType, Fault>> { /// <summary> /// Creates a new instance of Subscribe /// </summary> public Subscribe() { } /// <summary> /// Creates a new instance of Subscribe /// </summary> /// <param name="body">the request message body</param> public Subscribe(SubscribeRequestType body) : base(body) { } /// <summary> /// Creates a new instance of Subscribe /// </summary> /// <param name="body">the request message body</param> /// <param name="responsePort">the response port for the request</param> public Subscribe(SubscribeRequestType body, PortSet<SubscribeResponseType, Fault> responsePort) : base(body, responsePort) { } } }
// // DiscUtils Copyright (c) 2008-2011, Kenneth Bell // // Original NativeFileSystem contributed by bsobel: // http://discutils.codeplex.com/workitem/5190 // // 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 { using System; using System.IO; /// <summary> /// Provides an implementation for OS-mounted file systems. /// </summary> public class NativeFileSystem : DiscFileSystem { private string _basePath; private bool _readOnly; /// <summary> /// Initializes a new instance of the NativeFileSystem class. /// </summary> /// <param name="basePath">The 'root' directory of the new instance.</param> /// <param name="readOnly">Only permit 'read' activities.</param> public NativeFileSystem(string basePath, bool readOnly) : base() { _basePath = basePath; if (!_basePath.EndsWith(@"\", StringComparison.OrdinalIgnoreCase)) { _basePath += @"\"; } _readOnly = readOnly; } /// <summary> /// Gets the base path used to create the file system. /// </summary> public string BasePath { get { return _basePath; } } /// <summary> /// Provides a friendly description of the file system type. /// </summary> public override string FriendlyName { get { return "Native"; } } /// <summary> /// Indicates whether the file system is read-only or read-write. /// </summary> /// <returns>true if the file system is read-write.</returns> public override bool CanWrite { get { return !_readOnly; } } /// <summary> /// Gets the root directory of the file system. /// </summary> public override DiscDirectoryInfo Root { get { return new DiscDirectoryInfo(this, string.Empty); } } /// <summary> /// Gets the volume label. /// </summary> public override string VolumeLabel { get { return string.Empty; } } /// <summary> /// Gets a value indicating whether the file system is thread-safe. /// </summary> /// <remarks>The Native File System is thread safe.</remarks> public override bool IsThreadSafe { get { return true; } } /// <summary> /// Copies an existing file to a new file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> public override void CopyFile(string sourceFile, string destinationFile) { CopyFile(sourceFile, destinationFile, true); } /// <summary> /// Copies an existing file to a new file, allowing overwriting of an existing file. /// </summary> /// <param name="sourceFile">The source file.</param> /// <param name="destinationFile">The destination file.</param> /// <param name="overwrite">Whether to permit over-writing of an existing file.</param> public override void CopyFile(string sourceFile, string destinationFile, bool overwrite) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (sourceFile.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { sourceFile = sourceFile.Substring(1); } if (destinationFile.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { destinationFile = destinationFile.Substring(1); } File.Copy(Path.Combine(_basePath, sourceFile), Path.Combine(_basePath, destinationFile), true); } /// <summary> /// Creates a directory. /// </summary> /// <param name="path">The path of the new directory.</param> public override void CreateDirectory(string path) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } Directory.CreateDirectory(Path.Combine(_basePath, path)); } /// <summary> /// Deletes a directory. /// </summary> /// <param name="path">The path of the directory to delete.</param> public override void DeleteDirectory(string path) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } Directory.Delete(Path.Combine(_basePath, path)); } /// <summary> /// Deletes a directory, optionally with all descendants. /// </summary> /// <param name="path">The path of the directory to delete.</param> /// <param name="recursive">Determines if the all descendants should be deleted.</param> public override void DeleteDirectory(string path, bool recursive) { if (recursive) { foreach (string dir in GetDirectories(path)) { DeleteDirectory(dir, true); } foreach (string file in GetFiles(path)) { DeleteFile(file); } } DeleteDirectory(path); } /// <summary> /// Deletes a file. /// </summary> /// <param name="path">The path of the file to delete.</param> public override void DeleteFile(string path) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.Delete(Path.Combine(_basePath, path)); } /// <summary> /// Indicates if a directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the directory exists.</returns> public override bool DirectoryExists(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return Directory.Exists(Path.Combine(_basePath, path)); } /// <summary> /// Indicates if a file exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file exists.</returns> public override bool FileExists(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.Exists(Path.Combine(_basePath, path)); } /// <summary> /// Indicates if a file or directory exists. /// </summary> /// <param name="path">The path to test.</param> /// <returns>true if the file or directory exists.</returns> public override bool Exists(string path) { return FileExists(path) || DirectoryExists(path); } /// <summary> /// Gets the names of subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of directories.</returns> public override string[] GetDirectories(string path) { return GetDirectories(path, "*.*", SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern) { return GetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of subdirectories in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of directories matching the search pattern.</returns> public override string[] GetDirectories(string path, string searchPattern, SearchOption searchOption) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } try { return CleanItems(Directory.GetDirectories(Path.Combine(_basePath, path), searchPattern, searchOption)); } catch (System.IO.IOException) { return new string[0]; } catch (System.UnauthorizedAccessException) { return new string[0]; } } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files.</returns> public override string[] GetFiles(string path) { return GetFiles(path, "*.*", SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of files in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern) { return GetFiles(path, searchPattern, SearchOption.TopDirectoryOnly); } /// <summary> /// Gets the names of files in a specified directory matching a specified /// search pattern, using a value to determine whether to search subdirectories. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <param name="searchOption">Indicates whether to search subdirectories.</param> /// <returns>Array of files matching the search pattern.</returns> public override string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } try { return CleanItems(Directory.GetFiles(Path.Combine(_basePath, path), searchPattern, searchOption)); } catch (System.IO.IOException) { return new string[0]; } catch (System.UnauthorizedAccessException) { return new string[0]; } } /// <summary> /// Gets the names of all files and subdirectories in a specified directory. /// </summary> /// <param name="path">The path to search.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path) { return GetFileSystemEntries(path, "*.*"); } /// <summary> /// Gets the names of files and subdirectories in a specified directory matching a specified /// search pattern. /// </summary> /// <param name="path">The path to search.</param> /// <param name="searchPattern">The search string to match against.</param> /// <returns>Array of files and subdirectories matching the search pattern.</returns> public override string[] GetFileSystemEntries(string path, string searchPattern) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } try { return CleanItems(Directory.GetFileSystemEntries(Path.Combine(_basePath, path), searchPattern)); } catch (System.IO.IOException) { return new string[0]; } catch (System.UnauthorizedAccessException) { return new string[0]; } } /// <summary> /// Moves a directory. /// </summary> /// <param name="sourceDirectoryName">The directory to move.</param> /// <param name="destinationDirectoryName">The target directory name.</param> public override void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (sourceDirectoryName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { sourceDirectoryName = sourceDirectoryName.Substring(1); } if (destinationDirectoryName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { destinationDirectoryName = destinationDirectoryName.Substring(1); } Directory.Move(Path.Combine(_basePath, sourceDirectoryName), Path.Combine(_basePath, destinationDirectoryName)); } /// <summary> /// Moves a file. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> public override void MoveFile(string sourceName, string destinationName) { MoveFile(sourceName, destinationName, false); } /// <summary> /// Moves a file, allowing an existing file to be overwritten. /// </summary> /// <param name="sourceName">The file to move.</param> /// <param name="destinationName">The target file name.</param> /// <param name="overwrite">Whether to permit a destination file to be overwritten.</param> public override void MoveFile(string sourceName, string destinationName, bool overwrite) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (destinationName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { destinationName = destinationName.Substring(1); } if (FileExists(Path.Combine(_basePath, destinationName))) { if (overwrite) { DeleteFile(Path.Combine(_basePath, destinationName)); } else { throw new IOException("File already exists"); } } if (sourceName.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { sourceName = sourceName.Substring(1); } File.Move(Path.Combine(_basePath, sourceName), Path.Combine(_basePath, destinationName)); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode) { return OpenFile(path, mode, FileAccess.ReadWrite); } /// <summary> /// Opens the specified file. /// </summary> /// <param name="path">The full path of the file to open.</param> /// <param name="mode">The file mode for the created stream.</param> /// <param name="access">The access permissions for the created stream.</param> /// <returns>The new stream.</returns> public override SparseStream OpenFile(string path, FileMode mode, FileAccess access) { if (_readOnly && access != FileAccess.Read) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } FileShare fileShare = FileShare.None; if (access == FileAccess.Read) { fileShare = FileShare.Read; } return SparseStream.FromStream(File.Open(Path.Combine(_basePath, path), mode, access, fileShare), Ownership.Dispose); } /// <summary> /// Gets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to inspect.</param> /// <returns>The attributes of the file or directory.</returns> public override FileAttributes GetAttributes(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetAttributes(Path.Combine(_basePath, path)); } /// <summary> /// Sets the attributes of a file or directory. /// </summary> /// <param name="path">The file or directory to change.</param> /// <param name="newValue">The new attributes of the file or directory.</param> public override void SetAttributes(string path, FileAttributes newValue) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetAttributes(Path.Combine(_basePath, path), newValue); } /// <summary> /// Gets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTime(string path) { return GetCreationTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the creation time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetCreationTime(string path, DateTime newTime) { SetCreationTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The creation time.</returns> public override DateTime GetCreationTimeUtc(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetCreationTimeUtc(Path.Combine(_basePath, path)); } /// <summary> /// Sets the creation time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetCreationTimeUtc(string path, DateTime newTime) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetCreationTimeUtc(Path.Combine(_basePath, path), newTime); } /// <summary> /// Gets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public override DateTime GetLastAccessTime(string path) { return GetLastAccessTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the last access time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastAccessTime(string path, DateTime newTime) { SetLastAccessTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last access time.</returns> public override DateTime GetLastAccessTimeUtc(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetLastAccessTimeUtc(Path.Combine(_basePath, path)); } /// <summary> /// Sets the last access time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastAccessTimeUtc(string path, DateTime newTime) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetLastAccessTimeUtc(Path.Combine(_basePath, path), newTime); } /// <summary> /// Gets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public override DateTime GetLastWriteTime(string path) { return GetLastWriteTimeUtc(path).ToLocalTime(); } /// <summary> /// Sets the last modification time (in local time) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastWriteTime(string path, DateTime newTime) { SetLastWriteTimeUtc(path, newTime.ToUniversalTime()); } /// <summary> /// Gets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <returns>The last write time.</returns> public override DateTime GetLastWriteTimeUtc(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return File.GetLastWriteTimeUtc(Path.Combine(_basePath, path)); } /// <summary> /// Sets the last modification time (in UTC) of a file or directory. /// </summary> /// <param name="path">The path of the file or directory.</param> /// <param name="newTime">The new time to set.</param> public override void SetLastWriteTimeUtc(string path, DateTime newTime) { if (_readOnly) { throw new UnauthorizedAccessException(); } if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } File.SetLastWriteTimeUtc(Path.Combine(_basePath, path), newTime); } /// <summary> /// Gets the length of a file. /// </summary> /// <param name="path">The path to the file.</param> /// <returns>The length in bytes.</returns> public override long GetFileLength(string path) { if (path.StartsWith(@"\", StringComparison.OrdinalIgnoreCase)) { path = path.Substring(1); } return new FileInfo(Path.Combine(_basePath, path)).Length; } /// <summary> /// Gets an object representing a possible file. /// </summary> /// <param name="path">The file path.</param> /// <returns>The representing object.</returns> /// <remarks>The file does not need to exist.</remarks> public override DiscFileInfo GetFileInfo(string path) { return new DiscFileInfo(this, path); } /// <summary> /// Gets an object representing a possible directory. /// </summary> /// <param name="path">The directory path.</param> /// <returns>The representing object.</returns> /// <remarks>The directory does not need to exist.</remarks> public override DiscDirectoryInfo GetDirectoryInfo(string path) { return new DiscDirectoryInfo(this, path); } /// <summary> /// Gets an object representing a possible file system object (file or directory). /// </summary> /// <param name="path">The file system path.</param> /// <returns>The representing object.</returns> /// <remarks>The file system object does not need to exist.</remarks> public override DiscFileSystemInfo GetFileSystemInfo(string path) { return new DiscFileSystemInfo(this, path); } /// <summary> /// Size of the Filesystem in bytes /// </summary> public override long Size { get { DriveInfo info = new DriveInfo(_basePath); return info.TotalSize; } } /// <summary> /// Used space of the Filesystem in bytes /// </summary> public override long UsedSpace { get { return Size - AvailableSpace; } } /// <summary> /// Available space of the Filesystem in bytes /// </summary> public override long AvailableSpace { get { DriveInfo info = new DriveInfo(_basePath); return info.AvailableFreeSpace; } } private string[] CleanItems(string[] dirtyItems) { string[] cleanList = new string[dirtyItems.Length]; for (int x = 0; x < dirtyItems.Length; x++) { cleanList[x] = dirtyItems[x].Substring(_basePath.Length - 1); } return cleanList; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Graphics.UserInterface; using osu.Game.Online.Multiplayer; using osu.Game.Overlays; using osu.Game.Overlays.Mods; using osu.Game.Overlays.Toolbar; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Screens.OnlinePlay.Components; using osu.Game.Screens.Play; using osu.Game.Screens.Ranking; using osu.Game.Screens.Select; using osu.Game.Screens.Select.Options; using osu.Game.Tests.Beatmaps.IO; using osu.Game.Tests.Visual.Multiplayer; using osuTK; using osuTK.Input; namespace osu.Game.Tests.Visual.Navigation { public class TestSceneScreenNavigation : OsuGameTestScene { private const float click_padding = 25; private Vector2 backButtonPosition => Game.ToScreenSpace(new Vector2(click_padding, Game.LayoutRectangle.Bottom - click_padding)); private Vector2 optionsButtonPosition => Game.ToScreenSpace(new Vector2(click_padding, click_padding)); [Test] public void TestExitSongSelectWithEscape() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show()); AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); pushEscape(); AddAssert("Overlay was hidden", () => songSelect.ModSelectOverlay.State.Value == Visibility.Hidden); exitViaEscapeAndConfirm(); } /// <summary> /// This tests that the F1 key will open the mod select overlay, and not be handled / blocked by the music controller (which has the same default binding /// but should be handled *after* song select). /// </summary> [Test] public void TestOpenModSelectOverlayUsingAction() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => InputManager.Key(Key.F1)); AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); } [Test] public void TestRetryCountIncrements() { Player player = null; PushAndConfirm(() => new TestPlaySongSelect()); AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait()); AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault); AddStep("press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("wait for player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null); AddAssert("retry count is 0", () => player.RestartCount == 0); AddStep("attempt to retry", () => player.ChildrenOfType<HotkeyRetryOverlay>().First().Action()); AddUntilStep("wait for old player gone", () => Game.ScreenStack.CurrentScreen != player); AddUntilStep("get new player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null); AddAssert("retry count is 1", () => player.RestartCount == 1); } [Test] public void TestRetryFromResults() { Player player = null; ResultsScreen results = null; WorkingBeatmap beatmap() => Game.Beatmap.Value; PushAndConfirm(() => new TestPlaySongSelect()); AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait()); AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault); AddStep("set mods", () => Game.SelectedMods.Value = new Mod[] { new OsuModNoFail(), new OsuModDoubleTime { SpeedChange = { Value = 2 } } }); AddStep("press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("wait for player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null); AddUntilStep("wait for track playing", () => beatmap().Track.IsRunning); AddStep("seek to near end", () => player.ChildrenOfType<GameplayClockContainer>().First().Seek(beatmap().Beatmap.HitObjects[^1].StartTime - 1000)); AddUntilStep("wait for pass", () => (results = Game.ScreenStack.CurrentScreen as ResultsScreen) != null && results.IsLoaded); AddStep("attempt to retry", () => results.ChildrenOfType<HotkeyRetryOverlay>().First().Action()); AddUntilStep("wait for player", () => Game.ScreenStack.CurrentScreen != player && Game.ScreenStack.CurrentScreen is Player); } [TestCase(true)] [TestCase(false)] public void TestSongContinuesAfterExitPlayer(bool withUserPause) { Player player = null; WorkingBeatmap beatmap() => Game.Beatmap.Value; PushAndConfirm(() => new TestPlaySongSelect()); AddStep("import beatmap", () => ImportBeatmapTest.LoadOszIntoOsu(Game, virtualTrack: true).Wait()); AddUntilStep("wait for selected", () => !Game.Beatmap.IsDefault); if (withUserPause) AddStep("pause", () => Game.Dependencies.Get<MusicController>().Stop(true)); AddStep("press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("wait for player", () => (player = Game.ScreenStack.CurrentScreen as Player) != null); AddUntilStep("wait for fail", () => player.HasFailed); AddUntilStep("wait for track stop", () => !Game.MusicController.IsPlaying); AddAssert("Ensure time before preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().Metadata.PreviewTime); pushEscape(); AddUntilStep("wait for track playing", () => Game.MusicController.IsPlaying); AddAssert("Ensure time wasn't reset to preview point", () => Game.MusicController.CurrentTrack.CurrentTime < beatmap().Metadata.PreviewTime); } [Test] public void TestMenuMakesMusic() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddUntilStep("wait for no track", () => Game.MusicController.CurrentTrack.IsDummyDevice); AddStep("return to menu", () => songSelect.Exit()); AddUntilStep("wait for track", () => !Game.MusicController.CurrentTrack.IsDummyDevice && Game.MusicController.IsPlaying); } [Test] public void TestPushSongSelectAndPressBackButtonImmediately() { AddStep("push song select", () => Game.ScreenStack.Push(new TestPlaySongSelect())); AddStep("press back button", () => Game.ChildrenOfType<BackButton>().First().Action()); AddWaitStep("wait two frames", 2); } [Test] public void TestExitSongSelectWithClick() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show()); AddAssert("Overlay was shown", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); AddStep("Move mouse to backButton", () => InputManager.MoveMouseTo(backButtonPosition)); // BackButton handles hover using its child button, so this checks whether or not any of BackButton's children are hovered. AddUntilStep("Back button is hovered", () => Game.ChildrenOfType<BackButton>().First().Children.Any(c => c.IsHovered)); AddStep("Click back button", () => InputManager.Click(MouseButton.Left)); AddUntilStep("Overlay was hidden", () => songSelect.ModSelectOverlay.State.Value == Visibility.Hidden); exitViaBackButtonAndConfirm(); } [Test] public void TestExitMultiWithEscape() { PushAndConfirm(() => new Screens.OnlinePlay.Playlists.Playlists()); exitViaEscapeAndConfirm(); } [Test] public void TestExitMultiWithBackButton() { PushAndConfirm(() => new Screens.OnlinePlay.Playlists.Playlists()); exitViaBackButtonAndConfirm(); } [Test] public void TestOpenOptionsAndExitWithEscape() { AddUntilStep("Wait for options to load", () => Game.Settings.IsLoaded); AddStep("Enter menu", () => InputManager.Key(Key.Enter)); AddStep("Move mouse to options overlay", () => InputManager.MoveMouseTo(optionsButtonPosition)); AddStep("Click options overlay", () => InputManager.Click(MouseButton.Left)); AddAssert("Options overlay was opened", () => Game.Settings.State.Value == Visibility.Visible); AddStep("Hide options overlay using escape", () => InputManager.Key(Key.Escape)); AddAssert("Options overlay was closed", () => Game.Settings.State.Value == Visibility.Hidden); } [Test] public void TestWaitForNextTrackInMenu() { bool trackCompleted = false; AddUntilStep("Wait for music controller", () => Game.MusicController.IsLoaded); AddStep("Seek close to end", () => { Game.MusicController.SeekTo(Game.MusicController.CurrentTrack.Length - 1000); Game.MusicController.CurrentTrack.Completed += () => trackCompleted = true; }); AddUntilStep("Track was completed", () => trackCompleted); AddUntilStep("Track was restarted", () => Game.MusicController.IsPlaying); } [Test] public void TestModSelectInput() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show mods overlay", () => songSelect.ModSelectOverlay.Show()); AddStep("Change ruleset to osu!taiko", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.Number2); InputManager.ReleaseKey(Key.ControlLeft); }); AddAssert("Ruleset changed to osu!taiko", () => Game.Toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single().Current.Value.ID == 1); AddAssert("Mods overlay still visible", () => songSelect.ModSelectOverlay.State.Value == Visibility.Visible); } [Test] public void TestBeatmapOptionsInput() { TestPlaySongSelect songSelect = null; PushAndConfirm(() => songSelect = new TestPlaySongSelect()); AddStep("Show options overlay", () => songSelect.BeatmapOptionsOverlay.Show()); AddStep("Change ruleset to osu!taiko", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.Number2); InputManager.ReleaseKey(Key.ControlLeft); }); AddAssert("Ruleset changed to osu!taiko", () => Game.Toolbar.ChildrenOfType<ToolbarRulesetSelector>().Single().Current.Value.ID == 1); AddAssert("Options overlay still visible", () => songSelect.BeatmapOptionsOverlay.State.Value == Visibility.Visible); } [Test] public void TestSettingsViaHotkeyFromMainMenu() { AddAssert("toolbar not displayed", () => Game.Toolbar.State.Value == Visibility.Hidden); AddStep("press settings hotkey", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.O); InputManager.ReleaseKey(Key.ControlLeft); }); AddUntilStep("settings displayed", () => Game.Settings.State.Value == Visibility.Visible); } [Test] public void TestToolbarHiddenByUser() { AddStep("Enter menu", () => InputManager.Key(Key.Enter)); AddUntilStep("Wait for toolbar to load", () => Game.Toolbar.IsLoaded); AddStep("Hide toolbar", () => { InputManager.PressKey(Key.ControlLeft); InputManager.Key(Key.T); InputManager.ReleaseKey(Key.ControlLeft); }); pushEscape(); AddStep("Enter menu", () => InputManager.Key(Key.Enter)); AddAssert("Toolbar is hidden", () => Game.Toolbar.State.Value == Visibility.Hidden); AddStep("Enter song select", () => { InputManager.Key(Key.Enter); InputManager.Key(Key.Enter); }); AddAssert("Toolbar is hidden", () => Game.Toolbar.State.Value == Visibility.Hidden); } [Test] public void TestPushMatchSubScreenAndPressBackButtonImmediately() { TestMultiplayer multiplayer = null; PushAndConfirm(() => multiplayer = new TestMultiplayer()); AddStep("open room", () => multiplayer.OpenNewRoom()); AddStep("press back button", () => Game.ChildrenOfType<BackButton>().First().Action()); AddWaitStep("wait two frames", 2); } private void pushEscape() => AddStep("Press escape", () => InputManager.Key(Key.Escape)); private void exitViaEscapeAndConfirm() { pushEscape(); ConfirmAtMainMenu(); } private void exitViaBackButtonAndConfirm() { AddStep("Move mouse to backButton", () => InputManager.MoveMouseTo(backButtonPosition)); AddStep("Click back button", () => InputManager.Click(MouseButton.Left)); ConfirmAtMainMenu(); } public class TestPlaySongSelect : PlaySongSelect { public ModSelectOverlay ModSelectOverlay => ModSelect; public BeatmapOptionsOverlay BeatmapOptionsOverlay => BeatmapOptions; protected override bool DisplayStableImportPrompt => false; } private class TestMultiplayer : Screens.OnlinePlay.Multiplayer.Multiplayer { [Cached(typeof(MultiplayerClient))] public readonly TestMultiplayerClient Client; public TestMultiplayer() { Client = new TestMultiplayerClient((TestMultiplayerRoomManager)RoomManager); } protected override RoomManager CreateRoomManager() => new TestMultiplayerRoomManager(); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for ProtectedItemsOperations. /// </summary> public static partial class ProtectedItemsOperationsExtensions { /// <summary> /// Provides a pageable list of all items that can be backed up within a /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> public static Microsoft.Rest.Azure.IPage<ProtectedItemResource> List(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject>), string skipToken = default(string)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).ListAsync(vaultName, resourceGroupName, odataQuery, skipToken), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Provides a pageable list of all items that can be backed up within a /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<ProtectedItemResource>> ListAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<ProtectedItemQueryObject>), string skipToken = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(vaultName, resourceGroupName, odataQuery, skipToken, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Provides the details of the backed up item. This is an asynchronous /// operation. To know the status of the operation, call the /// GetItemOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up item. /// </param> /// <param name='containerName'> /// Container name associated with the backed up item. /// </param> /// <param name='protectedItemName'> /// Backed up item name whose details are to be fetched. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static ProtectedItemResource Get(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject>)) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).GetAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Provides the details of the backed up item. This is an asynchronous /// operation. To know the status of the operation, call the /// GetItemOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up item. /// </param> /// <param name='containerName'> /// Container name associated with the backed up item. /// </param> /// <param name='protectedItemName'> /// Backed up item name whose details are to be fetched. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<ProtectedItemResource> GetAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<GetProtectedItemQueryObject>), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Enables backup of an item or to modifies the backup policy information of /// an already backed up item. This is an asynchronous operation. To know the /// status of the operation, call the GetItemOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backup item. /// </param> /// <param name='containerName'> /// Container name associated with the backup item. /// </param> /// <param name='protectedItemName'> /// Item name to be backed up. /// </param> /// <param name='resourceProtectedItem'> /// resource backed up item /// </param> public static void CreateOrUpdate(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ProtectedItemResource resourceProtectedItem) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).CreateOrUpdateAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, resourceProtectedItem), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables backup of an item or to modifies the backup policy information of /// an already backed up item. This is an asynchronous operation. To know the /// status of the operation, call the GetItemOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backup item. /// </param> /// <param name='containerName'> /// Container name associated with the backup item. /// </param> /// <param name='protectedItemName'> /// Item name to be backed up. /// </param> /// <param name='resourceProtectedItem'> /// resource backed up item /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task CreateOrUpdateAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, ProtectedItemResource resourceProtectedItem, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.CreateOrUpdateWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, resourceProtectedItem, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Used to disable backup of an item within a container. This is an /// asynchronous operation. To know the status of the request, call the /// GetItemOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up item. /// </param> /// <param name='containerName'> /// Container name associated with the backed up item. /// </param> /// <param name='protectedItemName'> /// Backed up item to be deleted. /// </param> public static void Delete(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).DeleteAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Used to disable backup of an item within a container. This is an /// asynchronous operation. To know the status of the request, call the /// GetItemOperationResult API. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up item. /// </param> /// <param name='containerName'> /// Container name associated with the backed up item. /// </param> /// <param name='protectedItemName'> /// Backed up item to be deleted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this IProtectedItemsOperations operations, string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(vaultName, resourceGroupName, fabricName, containerName, protectedItemName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Provides a pageable list of all items that can be backed up within a /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static Microsoft.Rest.Azure.IPage<ProtectedItemResource> ListNext(this IProtectedItemsOperations operations, string nextPageLink) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IProtectedItemsOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Provides a pageable list of all items that can be backed up within a /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Microsoft.Rest.Azure.IPage<ProtectedItemResource>> ListNextAsync(this IProtectedItemsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Threading; using Microsoft.Extensions.Options; using Microsoft.Extensions.Logging; using Orleans.Configuration; using Orleans.Runtime; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions { public class TransactionManager : ITransactionManager { private const int MaxCheckpointBatchSize = 200; private static readonly TimeSpan DefaultLogMaintenanceInterval = TimeSpan.FromSeconds(1); private readonly TransactionsOptions options; private readonly TransactionLog transactionLog; private readonly ActiveTransactionsTracker activeTransactionsTracker; private readonly TimeSpan logMaintenanceInterval; // Index of transactions by transactionId. private readonly ConcurrentDictionary<long, Transaction> transactionsTable; // Transactions that have validated dependencies. private readonly ConcurrentQueue<Transaction> dependencyQueue; // Transactions that are waiting on group commit. private readonly ConcurrentQueue<Tuple<CommitRecord, Transaction>> groupCommitQueue; // Queue of committed transactions in commit order. private readonly ConcurrentQueue<Transaction> checkpointQueue; private readonly Queue<Transaction> checkpointRetryQueue = new Queue<Transaction>(MaxCheckpointBatchSize); private readonly InterlockedExchangeLock dependencyLock; private readonly InterlockedExchangeLock commitLock; private readonly InterlockedExchangeLock checkpointLock; private readonly Dictionary<ITransactionalResource, long> resources; private readonly List<Transaction> transactions; private long checkpointedLSN; protected readonly ILogger logger; private bool IsRunning; private Task transactionLogMaintenanceTask; private TransactionManagerMetrics metrics; public TransactionManager( TransactionLog transactionLog, IOptions<TransactionsOptions> configOption, ILoggerFactory loggerFactory, ITelemetryProducer telemetryProducer, IOptions<SiloStatisticsOptions> statisticsOptions, TimeSpan? logMaintenanceInterval = null) { this.transactionLog = transactionLog; this.options = configOption.Value; this.logger = loggerFactory.CreateLogger<TransactionManager>(); this.logMaintenanceInterval = logMaintenanceInterval ?? DefaultLogMaintenanceInterval; activeTransactionsTracker = new ActiveTransactionsTracker(configOption, this.transactionLog, loggerFactory); transactionsTable = new ConcurrentDictionary<long, Transaction>(2, 1000000); dependencyQueue = new ConcurrentQueue<Transaction>(); groupCommitQueue = new ConcurrentQueue<Tuple<CommitRecord, Transaction>>(); checkpointQueue = new ConcurrentQueue<Transaction>(); this.dependencyLock = new InterlockedExchangeLock(); this.commitLock = new InterlockedExchangeLock(); this.checkpointLock = new InterlockedExchangeLock(); this.resources = new Dictionary<ITransactionalResource, long>(); this.transactions = new List<Transaction>(); this.metrics = new TransactionManagerMetrics(telemetryProducer, configOption.Value.MetricsWritePeriod); this.checkpointedLSN = 0; this.IsRunning = false; } #region ITransactionManager public async Task StartAsync() { await transactionLog.Initialize(); CommitRecord record = await transactionLog.GetFirstCommitRecord(); long prevLSN = 0; while (record != null) { Transaction tx = new Transaction(record.TransactionId) { State = TransactionState.Committed, LSN = record.LSN, Info = new TransactionInfo(record.TransactionId) }; if (prevLSN == 0) { checkpointedLSN = record.LSN - 1; } prevLSN = record.LSN; foreach (var resource in record.Resources) { tx.Info.WriteSet.Add(resource, 1); } transactionsTable[record.TransactionId] = tx; checkpointQueue.Enqueue(tx); this.SignalCheckpointEnqueued(); record = await transactionLog.GetNextCommitRecord(); } await transactionLog.EndRecovery(); var maxAllocatedTransactionId = await transactionLog.GetStartRecord(); activeTransactionsTracker.Start(maxAllocatedTransactionId); this.BeginDependencyCompletionLoop(); this.BeginGroupCommitLoop(); this.BeginCheckpointLoop(); this.IsRunning = true; this.transactionLogMaintenanceTask = MaintainTransactionLog(); this.transactionLogMaintenanceTask.Ignore(); // protect agains unhandled exception in unexpected cases. } public async Task StopAsync() { this.IsRunning = false; if (this.transactionLogMaintenanceTask != null) { await this.transactionLogMaintenanceTask; } this.activeTransactionsTracker.Dispose(); } public long StartTransaction(TimeSpan timeout) { this.metrics.StartTransactionRequestCounter++; var transactionId = activeTransactionsTracker.GetNewTransactionId(); Transaction tx = new Transaction(transactionId) { State = TransactionState.Started, ExpirationTime = DateTime.UtcNow.Ticks + timeout.Ticks, }; transactionsTable[transactionId] = tx; return tx.TransactionId; } public void AbortTransaction(long transactionId, OrleansTransactionAbortedException reason) { this.metrics.AbortTransactionRequestCounter++; this.metrics.AbortedTransactionCounter++; if(this.logger.IsEnabled(LogLevel.Debug)) this.logger.LogDebug($"Abort transaction {transactionId} due to reason {reason}"); if (transactionsTable.TryGetValue(transactionId, out Transaction tx)) { bool justAborted = false; lock (tx) { if (tx.State == TransactionState.Started || tx.State == TransactionState.PendingDependency) { tx.State = TransactionState.Aborted; justAborted = true; } } if (justAborted) { foreach (var waiting in tx.WaitingTransactions) { var cascading = new OrleansCascadingAbortException(waiting.Info.TransactionId.ToString(), tx.TransactionId.ToString()); AbortTransaction(waiting.Info.TransactionId, cascading); } tx.CompletionTimeUtc = DateTime.UtcNow; tx.AbortingException = reason; } } } public void CommitTransaction(TransactionInfo transactionInfo) { this.metrics.CommitTransactionRequestCounter++; if (transactionsTable.TryGetValue(transactionInfo.TransactionId, out Transaction tx)) { bool abort = false; long cascadingDependentId = 0; bool pending = false; bool signal = false; lock (tx) { if (tx.State == TransactionState.Started) { tx.Info = transactionInfo; // Check our dependent transactions. // - If all dependent transactions committed, put transaction in validating queue // (dependencyQueue) // - If at least one dependent transaction aborted, abort. // - If at least one dependent transaction is still pending, put in pending queue // (dependentTx.WaitingTransactions) foreach (var dependentId in tx.Info.DependentTransactions) { // Transaction does not exist in the transaction table; // therefore, presumed abort. if (!transactionsTable.TryGetValue(dependentId, out Transaction dependentTx)) { abort = true; if(this.logger.IsEnabled(LogLevel.Debug)) this.logger.LogDebug($"Will abort transaction {transactionInfo.TransactionId} because it doesn't exist in the transaction table"); cascadingDependentId = dependentId; this.metrics.AbortedTransactionDueToMissingInfoInTransactionTableCounter++; break; } // NOTE: our deadlock prevention mechanism ensures that we are acquiring // the locks in proper order and there is no risk of deadlock. lock (dependentTx) { // Dependent transactions has aborted; therefore, abort. if (dependentTx.State == TransactionState.Aborted) { abort = true; if(this.logger.IsEnabled(LogLevel.Debug)) this.logger.LogDebug($"Will abort transaction {transactionInfo.TransactionId} because one of its dependent transaction {dependentTx.TransactionId} has aborted"); cascadingDependentId = dependentId; this.metrics.AbortedTransactionDueToDependencyCounter++; break; } // Dependent transaction is still executing or has a pending dependency. if (dependentTx.State == TransactionState.Started || dependentTx.State == TransactionState.PendingDependency) { pending = true; dependentTx.WaitingTransactions.Add(tx); tx.PendingCount++; } } } if (abort) { AbortTransaction(transactionInfo.TransactionId, new OrleansCascadingAbortException(transactionInfo.TransactionId.ToString(), cascadingDependentId.ToString())); } else if (pending) { tx.State = TransactionState.PendingDependency; } else { tx.State = TransactionState.Validated; dependencyQueue.Enqueue(tx); signal = true; } } } if (signal) { this.SignalDependencyEnqueued(); } } else { // Don't have a record of the transaction any more so presumably it's aborted. throw new OrleansTransactionAbortedException(transactionInfo.TransactionId.ToString(), "Transaction presumed to be aborted"); } } public TransactionStatus GetTransactionStatus(long transactionId, out OrleansTransactionAbortedException abortingException) { abortingException = null; if (transactionsTable.TryGetValue(transactionId, out Transaction tx)) { if (tx.State == TransactionState.Aborted) { lock (tx) { abortingException = tx.AbortingException; } return TransactionStatus.Aborted; } else if (tx.State == TransactionState.Committed || tx.State == TransactionState.Checkpointed) { return TransactionStatus.Committed; } else { return TransactionStatus.InProgress; } } return TransactionStatus.Unknown; } public long GetReadOnlyTransactionId() { long readId = activeTransactionsTracker.GetSmallestActiveTransactionId(); if (readId > 0) { readId--; } return readId; } #endregion private void BeginDependencyCompletionLoop() { BeginDependencyCompletionLoopAsync().Ignore(); } private void BeginGroupCommitLoop() { BeginGroupCommitLoopAsync().Ignore(); } private void BeginCheckpointLoop() { BeginCheckpointLoopAsync().Ignore(); } private void SignalDependencyEnqueued() { BeginDependencyCompletionLoop(); } private void SignalGroupCommitEnqueued() { BeginGroupCommitLoop(); } private void SignalCheckpointEnqueued() { BeginCheckpointLoop(); } private async Task BeginDependencyCompletionLoopAsync() { bool gotLock = false; try { if (!(gotLock = dependencyLock.TryGetLock())) { return; } while (this.CheckDependenciesCompleted()) { // force yield thread await Task.Delay(TimeSpan.FromTicks(1)); } } finally { if (gotLock) dependencyLock.ReleaseLock(); } } private async Task BeginGroupCommitLoopAsync() { bool gotLock = false; try { if (!(gotLock = commitLock.TryGetLock())) { return; } while (await this.GroupCommit()) { // force yield thread await Task.Delay(TimeSpan.FromTicks(1)); } } finally { if (gotLock) commitLock.ReleaseLock(); } } private async Task BeginCheckpointLoopAsync() { bool gotLock = false; try { if (!(gotLock = checkpointLock.TryGetLock())) { return; } while (await this.Checkpoint(resources, transactions)) { } } finally { if (gotLock) checkpointLock.ReleaseLock(); } } private bool CheckDependenciesCompleted() { bool processed = false; while (dependencyQueue.TryDequeue(out Transaction tx)) { processed = true; CommitRecord commitRecord = new CommitRecord { TransactionId = tx.TransactionId }; foreach (var resource in tx.Info.WriteSet.Keys) { commitRecord.Resources.Add(resource); } groupCommitQueue.Enqueue(new Tuple<CommitRecord, Transaction>(commitRecord, tx)); this.SignalGroupCommitEnqueued(); // We don't need to hold the transaction lock any more to access // the WaitingTransactions set, since nothing can be added to it // after this point. // If a transaction is waiting on us, decrement their waiting count; // - if they are no longer waiting, mark as validated. // TODO: Can't we clear WaitingTransactions here and no longer track it? foreach (var waiting in tx.WaitingTransactions) { bool signal = false; lock (waiting) { if (waiting.State != TransactionState.Aborted) { waiting.PendingCount--; if (waiting.PendingCount == 0) { waiting.State = TransactionState.Validated; dependencyQueue.Enqueue(waiting); signal = true; } } } if (signal) { this.SignalDependencyEnqueued(); } } } return processed; } private async Task<bool> GroupCommit() { bool processed = false; int batchSize = groupCommitQueue.Count; List<CommitRecord> records = new List<CommitRecord>(batchSize); List<Transaction> transactions = new List<Transaction>(batchSize); while (batchSize > 0) { processed = true; if (groupCommitQueue.TryDequeue(out Tuple<CommitRecord, Transaction> t)) { records.Add(t.Item1); transactions.Add(t.Item2); batchSize--; } else { break; } } try { await transactionLog.Append(records); } catch (Exception e) { this.logger.Error(OrleansTransactionsErrorCode.TransactionManager_GroupCommitError, "Group Commit error", e); // Failure to get an acknowledgment of the commits from the log (e.g. timeout exception) // will put the transactions in doubt. We crash and let this be handled in recovery. // TODO: handle other exceptions more gracefuly throw; } for (int i = 0; i < transactions.Count; i++) { var transaction = transactions[i]; lock (transaction) { transaction.State = TransactionState.Committed; transaction.LSN = records[i].LSN; transaction.CompletionTimeUtc = DateTime.UtcNow; } checkpointQueue.Enqueue(transaction); this.SignalCheckpointEnqueued(); } return processed; } private async Task<bool> Checkpoint(Dictionary<ITransactionalResource, long> resources, List<Transaction> transactions) { // Rather than continue processing forever, only process the number of transactions which were waiting at invocation time. var total = this.checkpointRetryQueue.Count + checkpointQueue.Count; // The maximum number of transactions checkpointed in each batch. int batchSize = Math.Min(total, MaxCheckpointBatchSize); long lsn = 0; try { var processed = 0; while (processed < total && (this.checkpointRetryQueue.Count > 0 || !checkpointQueue.IsEmpty)) { resources.Clear(); transactions.Clear(); // Take a batch of transactions to checkpoint. var currentBatchSize = 0; while (currentBatchSize < batchSize) { currentBatchSize++; Transaction tx; // If some previous operation had failed, retry it before proceeding with new work. if (this.checkpointRetryQueue.Count > 0) tx = this.checkpointRetryQueue.Dequeue(); else if (!checkpointQueue.TryDequeue(out tx)) break; foreach (var resource in tx.Info.WriteSet.Keys) { resources[resource] = tx.Info.TransactionId; } lsn = Math.Max(lsn, tx.LSN); transactions.Add(tx); } processed += currentBatchSize; // If the transaction involved writes, send a commit notification to each resource which performed // a write and wait for acknowledgement. if (resources.Count > 0) { // Send commit notifications to all of the resources involved. var completion = new MultiCompletionSource(resources.Count); foreach (var resource in resources) { NotifyResourceOfCommit(resource.Key, resource.Value, completion); } // Wait for the commit notifications to be acknowledged by the resources. await completion.Task; } // Mark the transactions as checkpointed. foreach (var tx in transactions) { lock (tx) { tx.State = TransactionState.Checkpointed; tx.HighestActiveTransactionIdAtCheckpoint = activeTransactionsTracker.GetHighestActiveTransactionId(); } } // Allow the transaction log to be truncated. this.checkpointedLSN = lsn; } } catch (Exception e) { // Retry all failed checkpoint operations. foreach (var tx in transactions) this.checkpointRetryQueue.Enqueue(tx); this.logger.Error(OrleansTransactionsErrorCode.TransactionManager_CheckpointError, "Failure during checkpoint", e); throw; } return total > 0; } private static void NotifyResourceOfCommit(ITransactionalResource resource, long transaction, MultiCompletionSource completionSource) { resource.Commit(transaction) .ContinueWith( (result, state) => { var completion = (MultiCompletionSource)state; if (result.Exception != null) completion.SetException(result.Exception); else completion.SetOneResult(); }, completionSource, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } private async Task MaintainTransactionLog() { while(this.IsRunning) { try { await TransactionLogMaintenance(); } catch(Exception ex) { this.logger.Error(OrleansTransactionsErrorCode.TransactionManager_TransactionLogMaintenanceError, $"Error while maintaining transaction log.", ex); } this.metrics.TryReportMetrics(); await Task.Delay(this.logMaintenanceInterval); } } private async Task TransactionLogMaintenance() { // // Truncate log // if (checkpointedLSN > 0) { try { await transactionLog.TruncateLog(checkpointedLSN - 1); } catch (Exception e) { this.logger.Error(OrleansTransactionsErrorCode.TransactionManager_TransactionLogTruncationError, $"Failed to truncate log. LSN: {checkpointedLSN}", e); } } // // Timeout expired transactions // long now = DateTime.UtcNow.Ticks; foreach (var txRecord in transactionsTable) { if (txRecord.Value.State == TransactionState.Started && txRecord.Value.ExpirationTime < now) { AbortTransaction(txRecord.Key, new OrleansTransactionTimeoutException(txRecord.Key.ToString())); } } // // Find the oldest active transaction // long lowestActiveId = activeTransactionsTracker.GetSmallestActiveTransactionId(); long highestActiveId = activeTransactionsTracker.GetHighestActiveTransactionId(); while (lowestActiveId <= highestActiveId) { if (transactionsTable.TryGetValue(lowestActiveId, out Transaction tx)) { if (tx.State != TransactionState.Aborted && tx.State != TransactionState.Checkpointed) { break; } } lowestActiveId++; activeTransactionsTracker.PopSmallestActiveTransactionId(); } // // Remove transactions that we no longer need to keep a record of from transactions table. // a transaction is presumed to be aborted if we try to look it up and it does not exist in the // table. // foreach (var txRecord in transactionsTable) { if (txRecord.Value.State == TransactionState.Aborted && txRecord.Value.CompletionTimeUtc + this.options.TransactionRecordPreservationDuration < DateTime.UtcNow) { transactionsTable.TryRemove(txRecord.Key, out Transaction temp); } else if (txRecord.Value.State == TransactionState.Checkpointed) { lock (txRecord.Value) { if (txRecord.Value.HighestActiveTransactionIdAtCheckpoint < activeTransactionsTracker.GetSmallestActiveTransactionId() && txRecord.Value.CompletionTimeUtc + this.options.TransactionRecordPreservationDuration < DateTime.UtcNow) { // The oldest active transaction started after this transaction was checkpointed // so no in progress transaction is going to take a dependency on this transaction // which means we can safely forget about it. // When receiving an arbitrarily delayed message, a transaction that may have committed // will appear to have aborted, causing the delayed transaction to abort. transactionsTable.TryRemove(txRecord.Key, out Transaction temp); } } } } } } }
namespace System.Workflow.Activities.Rules.Design { partial class BasicBrowserDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BasicBrowserDialog)); this.cancelButton = new System.Windows.Forms.Button(); this.okButton = new System.Windows.Forms.Button(); this.rulesListView = new System.Windows.Forms.ListView(); this.nameColumnHeader = new System.Windows.Forms.ColumnHeader(); this.validColumnHeader = new System.Windows.Forms.ColumnHeader(); this.rulesPanel = new System.Windows.Forms.Panel(); this.rulesToolStrip = new System.Windows.Forms.ToolStrip(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.newRuleToolStripButton = new System.Windows.Forms.ToolStripButton(); this.editToolStripButton = new System.Windows.Forms.ToolStripButton(); this.renameToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.deleteToolStripButton = new System.Windows.Forms.ToolStripButton(); this.preiviewPanel = new System.Windows.Forms.Panel(); this.previewRichEditBoxPanel = new System.Windows.Forms.Panel(); this.previewRichTextBox = new System.Windows.Forms.TextBox(); this.previewLabel = new System.Windows.Forms.Label(); this.descriptionLabel = new System.Windows.Forms.Label(); this.headerPictureBox = new System.Windows.Forms.PictureBox(); this.okCancelTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.rulesPanel.SuspendLayout(); this.rulesToolStrip.SuspendLayout(); this.preiviewPanel.SuspendLayout(); this.previewRichEditBoxPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.headerPictureBox)).BeginInit(); this.okCancelTableLayoutPanel.SuspendLayout(); this.SuspendLayout(); // // cancelButton // resources.ApplyResources(this.cancelButton, "cancelButton"); this.cancelButton.CausesValidation = false; this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Name = "cancelButton"; this.cancelButton.Click += new System.EventHandler(this.OnCancel); // // okButton // resources.ApplyResources(this.okButton, "okButton"); this.okButton.Name = "okButton"; this.okButton.Click += new System.EventHandler(this.OnOk); // // rulesListView // this.rulesListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.nameColumnHeader, this.validColumnHeader}); resources.ApplyResources(this.rulesListView, "rulesListView"); this.rulesListView.FullRowSelect = true; this.rulesListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.rulesListView.HideSelection = false; this.rulesListView.MultiSelect = false; this.rulesListView.Name = "rulesListView"; this.rulesListView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.rulesListView.UseCompatibleStateImageBehavior = false; this.rulesListView.View = System.Windows.Forms.View.Details; this.rulesListView.DoubleClick += new System.EventHandler(this.OnDoubleClick); this.rulesListView.ItemSelectionChanged += new System.Windows.Forms.ListViewItemSelectionChangedEventHandler(this.OnItemSelectionChanged); // // nameColumnHeader // resources.ApplyResources(this.nameColumnHeader, "nameColumnHeader"); // // validColumnHeader // resources.ApplyResources(this.validColumnHeader, "validColumnHeader"); // // rulesPanel // resources.ApplyResources(this.rulesPanel, "rulesPanel"); this.rulesPanel.Controls.Add(this.rulesToolStrip); this.rulesPanel.Controls.Add(this.rulesListView); this.rulesPanel.Name = "rulesPanel"; // // rulesToolStrip // this.rulesToolStrip.BackColor = System.Drawing.SystemColors.Control; this.rulesToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.rulesToolStrip.ImageList = this.imageList; this.rulesToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newRuleToolStripButton, this.editToolStripButton, this.renameToolStripButton, this.toolStripSeparator1, this.deleteToolStripButton}); resources.ApplyResources(this.rulesToolStrip, "rulesToolStrip"); this.rulesToolStrip.Name = "rulesToolStrip"; this.rulesToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.rulesToolStrip.TabStop = true; // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, "NewRule.bmp"); this.imageList.Images.SetKeyName(1, "EditRule.bmp"); this.imageList.Images.SetKeyName(2, "RenameRule.bmp"); this.imageList.Images.SetKeyName(3, "Delete.bmp"); // // newRuleToolStripButton // resources.ApplyResources(this.newRuleToolStripButton, "newRuleToolStripButton"); this.newRuleToolStripButton.Name = "newRuleToolStripButton"; this.newRuleToolStripButton.Click += new System.EventHandler(this.OnNew); // // editToolStripButton // resources.ApplyResources(this.editToolStripButton, "editToolStripButton"); this.editToolStripButton.Name = "editToolStripButton"; this.editToolStripButton.Click += new System.EventHandler(this.OnEdit); // // renameToolStripButton // resources.ApplyResources(this.renameToolStripButton, "renameToolStripButton"); this.renameToolStripButton.Name = "renameToolStripButton"; this.renameToolStripButton.Click += new System.EventHandler(this.OnRename); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // deleteToolStripButton // resources.ApplyResources(this.deleteToolStripButton, "deleteToolStripButton"); this.deleteToolStripButton.Name = "deleteToolStripButton"; this.deleteToolStripButton.Click += new System.EventHandler(this.OnDelete); // // preiviewPanel // this.preiviewPanel.Controls.Add(this.previewRichEditBoxPanel); this.preiviewPanel.Controls.Add(this.previewLabel); resources.ApplyResources(this.preiviewPanel, "preiviewPanel"); this.preiviewPanel.Name = "preiviewPanel"; // // previewRichEditBoxPanel // resources.ApplyResources(this.previewRichEditBoxPanel, "previewRichEditBoxPanel"); this.previewRichEditBoxPanel.BackColor = System.Drawing.SystemColors.GradientInactiveCaption; this.previewRichEditBoxPanel.Controls.Add(this.previewRichTextBox); this.previewRichEditBoxPanel.Name = "previewRichEditBoxPanel"; // // previewRichTextBox // this.previewRichTextBox.BackColor = System.Drawing.SystemColors.Control; this.previewRichTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; resources.ApplyResources(this.previewRichTextBox, "previewRichTextBox"); this.previewRichTextBox.Name = "previewRichTextBox"; this.previewRichTextBox.ReadOnly = true; this.previewRichTextBox.TabStop = false; // // previewLabel // resources.ApplyResources(this.previewLabel, "previewLabel"); this.previewLabel.Name = "previewLabel"; // // descriptionLabel // resources.ApplyResources(this.descriptionLabel, "descriptionLabel"); this.descriptionLabel.Name = "descriptionLabel"; // // headerPictureBox // resources.ApplyResources(this.headerPictureBox, "headerPictureBox"); this.headerPictureBox.Name = "headerPictureBox"; this.headerPictureBox.TabStop = false; // // okCancelTableLayoutPanel // resources.ApplyResources(this.okCancelTableLayoutPanel, "okCancelTableLayoutPanel"); this.okCancelTableLayoutPanel.Controls.Add(this.okButton, 0, 0); this.okCancelTableLayoutPanel.Controls.Add(this.cancelButton, 1, 0); this.okCancelTableLayoutPanel.Name = "okCancelTableLayoutPanel"; // // BasicBrowserDialog // this.AcceptButton = this.okButton; resources.ApplyResources(this, "$this"); this.CancelButton = this.cancelButton; this.Controls.Add(this.okCancelTableLayoutPanel); this.Controls.Add(this.headerPictureBox); this.Controls.Add(this.descriptionLabel); this.Controls.Add(this.preiviewPanel); this.Controls.Add(this.rulesPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpButton = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "BasicBrowserDialog"; this.ShowInTaskbar = false; this.rulesPanel.ResumeLayout(false); this.rulesPanel.PerformLayout(); this.rulesToolStrip.ResumeLayout(false); this.rulesToolStrip.PerformLayout(); this.preiviewPanel.ResumeLayout(false); this.preiviewPanel.PerformLayout(); this.previewRichEditBoxPanel.ResumeLayout(false); this.previewRichEditBoxPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.headerPictureBox)).EndInit(); this.okCancelTableLayoutPanel.ResumeLayout(false); this.okCancelTableLayoutPanel.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.ListView rulesListView; private System.Windows.Forms.Panel rulesPanel; private System.Windows.Forms.ToolStrip rulesToolStrip; private System.Windows.Forms.Panel preiviewPanel; private System.Windows.Forms.Label previewLabel; private System.Windows.Forms.ToolStripButton newRuleToolStripButton; private System.Windows.Forms.ToolStripButton renameToolStripButton; private System.Windows.Forms.ColumnHeader nameColumnHeader; private System.Windows.Forms.Label descriptionLabel; private System.Windows.Forms.PictureBox headerPictureBox; private System.Windows.Forms.ToolStripButton editToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton deleteToolStripButton; private System.Windows.Forms.Panel previewRichEditBoxPanel; private System.Windows.Forms.TextBox previewRichTextBox; private System.Windows.Forms.ImageList imageList; private System.Windows.Forms.ColumnHeader validColumnHeader; private System.Windows.Forms.TableLayoutPanel okCancelTableLayoutPanel; } }
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) .Configure<ClusterMembershipOptions>(options => { options.ExpectedClusterSize = int.Parse(configuration["InitialSilosCount"]); }) .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); ConfigureAppServices(configuration, builder); builder.ConfigureServices(services => { TryConfigureTestClusterMembership(configuration, services); TryConfigureFileLogging(configuration, services, hostName); }); 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; }); } 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<GrainBasedMembershipTable>() .AddFromExisting<IMembershipTable, GrainBasedMembershipTable>(); } } 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); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using CC.MT.Public.Election.Areas.HelpPage.ModelDescriptions; using CC.MT.Public.Election.Areas.HelpPage.Models; namespace CC.MT.Public.Election.Areas.HelpPage { /// <summary> /// HelpPageConfigurationExtensions /// </summary> public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.CodeGeneration; using Orleans.Internal; namespace Orleans.Runtime.ReminderService { internal sealed class LocalReminderService : GrainService, IReminderService { private const int InitialReadRetryCountBeforeFastFailForUpdates = 2; private static readonly TimeSpan InitialReadMaxWaitTimeForUpdates = TimeSpan.FromSeconds(20); private static readonly TimeSpan InitialReadRetryPeriod = TimeSpan.FromSeconds(30); private readonly ILogger logger; private readonly Dictionary<ReminderIdentity, LocalReminderData> localReminders = new(); private readonly IReminderTable reminderTable; private readonly TaskCompletionSource<bool> startedTask; private readonly AverageTimeSpanStatistic tardinessStat; private readonly CounterStatistic ticksDeliveredStat; private readonly TimeSpan initTimeout; private readonly IAsyncTimerFactory asyncTimerFactory; private readonly IAsyncTimer listRefreshTimer; // timer that refreshes our list of reminders to reflect global reminder table private long localTableSequence; private uint initialReadCallCount = 0; private Task runTask; internal LocalReminderService( Silo silo, IReminderTable reminderTable, TimeSpan initTimeout, ILoggerFactory loggerFactory, IAsyncTimerFactory asyncTimerFactory) : base(SystemTargetGrainId.CreateGrainServiceGrainId(GrainInterfaceUtils.GetGrainClassTypeCode(typeof(IReminderService)), null, silo.SiloAddress), silo, loggerFactory) { this.reminderTable = reminderTable; this.initTimeout = initTimeout; this.asyncTimerFactory = asyncTimerFactory; tardinessStat = AverageTimeSpanStatistic.FindOrCreate(StatisticNames.REMINDERS_AVERAGE_TARDINESS_SECONDS); IntValueStatistic.FindOrCreate(StatisticNames.REMINDERS_NUMBER_ACTIVE_REMINDERS, () => localReminders.Count); ticksDeliveredStat = CounterStatistic.FindOrCreate(StatisticNames.REMINDERS_COUNTERS_TICKS_DELIVERED); startedTask = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); this.logger = loggerFactory.CreateLogger<LocalReminderService>(); this.listRefreshTimer = asyncTimerFactory.Create(Constants.RefreshReminderList, "ReminderService.ReminderListRefresher"); } /// <summary> /// Attempt to retrieve reminders, that are my responsibility, from the global reminder table when starting this silo (reminder service instance) /// </summary> /// <returns></returns> public override async Task Start() { // confirm that it can access the underlying store, as after this the ReminderService will load in the background, without the opportunity to prevent the Silo from starting await reminderTable.Init().WithTimeout(initTimeout, $"ReminderTable Initialization failed due to timeout {initTimeout}"); await base.Start(); } public async override Task Stop() { await base.Stop(); if (listRefreshTimer != null) { listRefreshTimer.Dispose(); if (this.runTask is Task task) { await task; } } foreach (LocalReminderData r in localReminders.Values) { r.StopReminder(); } // for a graceful shutdown, also handover reminder responsibilities to new owner, and update the ReminderTable // currently, this is taken care of by periodically reading the reminder table } public async Task<IGrainReminder> RegisterOrUpdateReminder(GrainReference grainRef, string reminderName, TimeSpan dueTime, TimeSpan period) { var entry = new ReminderEntry { GrainRef = grainRef, ReminderName = reminderName, StartAt = DateTime.UtcNow.Add(dueTime), Period = period, }; if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_RegisterOrUpdate, "RegisterOrUpdateReminder: {0}", entry.ToString()); await DoResponsibilitySanityCheck(grainRef, "RegisterReminder"); var newEtag = await reminderTable.UpsertRow(entry); if (newEtag != null) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Registered reminder {0} in table, assigned localSequence {1}", entry, localTableSequence); entry.ETag = newEtag; StartAndAddTimer(entry); if (logger.IsEnabled(LogLevel.Trace)) PrintReminders(); return new ReminderData(grainRef, reminderName, newEtag) as IGrainReminder; } var msg = string.Format("Could not register reminder {0} to reminder table due to a race. Please try again later.", entry); logger.Error(ErrorCode.RS_Register_TableError, msg); throw new ReminderException(msg); } /// <summary> /// Stop the reminder locally, and remove it from the external storage system /// </summary> /// <param name="reminder"></param> /// <returns></returns> public async Task UnregisterReminder(IGrainReminder reminder) { var remData = (ReminderData)reminder; if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Unregister, "UnregisterReminder: {0}, LocalTableSequence: {1}", remData, localTableSequence); GrainReference grainRef = remData.GrainRef; string reminderName = remData.ReminderName; string eTag = remData.ETag; await DoResponsibilitySanityCheck(grainRef, "RemoveReminder"); // it may happen that we dont have this reminder locally ... even then, we attempt to remove the reminder from the reminder // table ... the periodic mechanism will stop this reminder at any silo's LocalReminderService that might have this reminder locally // remove from persistent/memory store var success = await reminderTable.RemoveRow(grainRef, reminderName, eTag); if (success) { bool removed = TryStopPreviousTimer(grainRef, reminderName); if (removed) { if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Stop, "Stopped reminder {0}", reminder); if (logger.IsEnabled(LogLevel.Trace)) PrintReminders(string.Format("After removing {0}.", reminder)); } else { // no-op if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_RemoveFromTable, "Removed reminder from table which I didn't have locally: {0}.", reminder); } } else { var msg = string.Format("Could not unregister reminder {0} from the reminder table, due to tag mismatch. You can retry.", reminder); logger.Error(ErrorCode.RS_Unregister_TableError, msg); throw new ReminderException(msg); } } public async Task<IGrainReminder> GetReminder(GrainReference grainRef, string reminderName) { if(logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_GetReminder,"GetReminder: GrainReference={0} ReminderName={1}", grainRef.ToString(), reminderName); var entry = await reminderTable.ReadRow(grainRef, reminderName); return entry == null ? null : entry.ToIGrainReminder(); } public async Task<List<IGrainReminder>> GetReminders(GrainReference grainRef) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_GetReminders, "GetReminders: GrainReference={0}", grainRef.ToString()); var tableData = await reminderTable.ReadRows(grainRef); return tableData.Reminders.Select(entry => entry.ToIGrainReminder()).ToList(); } /// <summary> /// Attempt to retrieve reminders from the global reminder table /// </summary> private Task ReadAndUpdateReminders() { if (StoppedCancellationTokenSource.IsCancellationRequested) return Task.CompletedTask; RemoveOutOfRangeReminders(); // try to retrieve reminders from all my subranges var rangeSerialNumberCopy = RangeSerialNumber; if (logger.IsEnabled(LogLevel.Trace)) logger.Trace($"My range= {RingRange}, RangeSerialNumber {RangeSerialNumber}. Local reminders count {localReminders.Count}"); var acks = new List<Task>(); foreach (var range in RangeFactory.GetSubRanges(RingRange)) { acks.Add(ReadTableAndStartTimers(range, rangeSerialNumberCopy)); } var task = Task.WhenAll(acks); if (logger.IsEnabled(LogLevel.Trace)) task.ContinueWith(_ => PrintReminders(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.ExecuteSynchronously); return task; } private void RemoveOutOfRangeReminders() { var remindersOutOfRange = localReminders.Where(r => !RingRange.InRange(r.Key.GrainRef)).Select(r => r.Value).ToArray(); foreach (var reminder in remindersOutOfRange) { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in my range anymore, so removing. {0}", reminder); // remove locally reminder.StopReminder(); localReminders.Remove(reminder.Identity); } if (logger.IsEnabled(LogLevel.Information) && remindersOutOfRange.Length > 0) logger.Info($"Removed {remindersOutOfRange.Length} local reminders that are now out of my range."); } public override Task OnRangeChange(IRingRange oldRange, IRingRange newRange, bool increased) { _ = base.OnRangeChange(oldRange, newRange, increased); if (Status == GrainServiceStatus.Started) return ReadAndUpdateReminders(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Ignoring range change until ReminderService is Started -- Current status = {0}", Status); return Task.CompletedTask; } private async Task RunAsync() { TimeSpan? overrideDelay = ThreadSafeRandom.NextTimeSpan(InitialReadRetryPeriod); while (await listRefreshTimer.NextTick(overrideDelay)) { try { overrideDelay = null; switch (Status) { case GrainServiceStatus.Booting: await DoInitialReadAndUpdateReminders(); break; case GrainServiceStatus.Started: await ReadAndUpdateReminders(); break; default: listRefreshTimer.Dispose(); return; } } catch (Exception exception) { this.logger.LogWarning(exception, "Exception while reading reminders: {Exception}", exception); overrideDelay = ThreadSafeRandom.NextTimeSpan(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20)); } } } protected override async Task StartInBackground() { await DoInitialReadAndUpdateReminders(); this.runTask = RunAsync(); } private async Task DoInitialReadAndUpdateReminders() { try { if (StoppedCancellationTokenSource.IsCancellationRequested) return; initialReadCallCount++; await this.ReadAndUpdateReminders(); Status = GrainServiceStatus.Started; startedTask.TrySetResult(true); } catch (Exception ex) { if (StoppedCancellationTokenSource.IsCancellationRequested) return; if (initialReadCallCount <= InitialReadRetryCountBeforeFastFailForUpdates) { logger.Warn( ErrorCode.RS_ServiceInitialLoadFailing, string.Format("ReminderService failed initial load of reminders and will retry. Attempt #{0}", this.initialReadCallCount), ex); } else { const string baseErrorMsg = "ReminderService failed initial load of reminders and cannot guarantee that the service will be eventually start without manual intervention or restarting the silo."; var logErrorMessage = string.Format(baseErrorMsg + " Attempt #{0}", this.initialReadCallCount); logger.Error(ErrorCode.RS_ServiceInitialLoadFailed, logErrorMessage, ex); startedTask.TrySetException(new OrleansException(baseErrorMsg, ex)); } } } private async Task ReadTableAndStartTimers(IRingRange range, int rangeSerialNumberCopy) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Reading rows from {0}", range.ToString()); localTableSequence++; long cachedSequence = localTableSequence; try { var srange = range as ISingleRange; if (srange == null) throw new InvalidOperationException("LocalReminderService must be dealing with SingleRange"); ReminderTableData table = await reminderTable.ReadRows(srange.Begin, srange.End); // get all reminders, even the ones we already have if (rangeSerialNumberCopy < RangeSerialNumber) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"My range changed while reading from the table, ignoring the results. Another read has been started. RangeSerialNumber {RangeSerialNumber}, RangeSerialNumberCopy {rangeSerialNumberCopy}."); return; } if (StoppedCancellationTokenSource.IsCancellationRequested) return; // if null is a valid value, it means that there's nothing to do. if (null == table && reminderTable is MockReminderTable) return; var remindersNotInTable = localReminders.Where(r => range.InRange(r.Key.GrainRef)).ToDictionary(r => r.Key, r => r.Value); // shallow copy if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("For range {0}, I read in {1} reminders from table. LocalTableSequence {2}, CachedSequence {3}", range.ToString(), table.Reminders.Count, localTableSequence, cachedSequence); foreach (ReminderEntry entry in table.Reminders) { var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName); LocalReminderData localRem; if (localReminders.TryGetValue(key, out localRem)) { if (cachedSequence > localRem.LocalSequenceNumber) // info read from table is same or newer than local info { if (localRem.IsRunning) // if ticking { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Old, & Ticking {0}", localRem); // it might happen that our local reminder is different than the one in the table, i.e., eTag is different // if so, stop the local timer for the old reminder, and start again with new info if (!localRem.ETag.Equals(entry.ETag)) // this reminder needs a restart { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("{0} Needs a restart", localRem); localRem.StopReminder(); localReminders.Remove(localRem.Identity); StartAndAddTimer(entry); } } else // if not ticking { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Old, & Not Ticking {0}", localRem); } } else // cachedSequence < localRem.LocalSequenceNumber ... // info read from table is older than local info { if (localRem.IsRunning) // if ticking { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Newer, & Ticking {0}", localRem); } else // if not ticking { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, In local, Newer, & Not Ticking {0}", localRem); } } } else // exists in table, but not locally { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("In table, Not in local, {0}", entry); // create and start the reminder StartAndAddTimer(entry); } // keep a track of extra reminders ... this 'reminder' is useful, so remove it from extra list remindersNotInTable.Remove(key); } // foreach reminder read from table int remindersCountBeforeRemove = localReminders.Count; // foreach reminder that is not in global table, but exists locally foreach (var reminder in remindersNotInTable.Values) { if (cachedSequence < reminder.LocalSequenceNumber) { // no-op if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in table, In local, Newer, {0}", reminder); } else // cachedSequence > reminder.LocalSequenceNumber { if (logger.IsEnabled(LogLevel.Trace)) logger.Trace("Not in table, In local, Old, so removing. {0}", reminder); // remove locally reminder.StopReminder(); localReminders.Remove(reminder.Identity); } } if (logger.IsEnabled(LogLevel.Debug)) logger.Debug($"Removed {localReminders.Count - remindersCountBeforeRemove} reminders from local table"); } catch (Exception exc) { logger.Error(ErrorCode.RS_FailedToReadTableAndStartTimer, "Failed to read rows from table.", exc); throw; } } private void StartAndAddTimer(ReminderEntry entry) { // it might happen that we already have a local reminder with a different eTag // if so, stop the local timer for the old reminder, and start again with new info // Note: it can happen here that we restart a reminder that has the same eTag as what we just registered ... its a rare case, and restarting it doesn't hurt, so we don't check for it var key = new ReminderIdentity(entry.GrainRef, entry.ReminderName); LocalReminderData prevReminder; if (localReminders.TryGetValue(key, out prevReminder)) // if found locally { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_LocalStop, "Locally stopping reminder {0} as it is different than newly registered reminder {1}", prevReminder, entry); prevReminder.StopReminder(); localReminders.Remove(prevReminder.Identity); } var newReminder = new LocalReminderData(entry, this); localTableSequence++; newReminder.LocalSequenceNumber = localTableSequence; localReminders.Add(newReminder.Identity, newReminder); newReminder.StartTimer(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.RS_Started, "Started reminder {0}.", entry.ToString()); } // stop without removing it. will remove later. private bool TryStopPreviousTimer(GrainReference grainRef, string reminderName) { // we stop the locally running timer for this reminder var key = new ReminderIdentity(grainRef, reminderName); LocalReminderData localRem; if (!localReminders.TryGetValue(key, out localRem)) return false; // if we have it locally localTableSequence++; // move to next sequence localRem.LocalSequenceNumber = localTableSequence; localRem.StopReminder(); return true; } private Task DoResponsibilitySanityCheck(GrainReference grainRef, string debugInfo) { switch (Status) { case GrainServiceStatus.Booting: // if service didn't finish the initial load, it could still be loading normally or it might have already // failed a few attempts and callers should not be hold waiting for it to complete var task = this.startedTask.Task; if (task.IsCompleted) { // task at this point is already Faulted task.GetAwaiter().GetResult(); } else { return WaitForInitCompletion(); async Task WaitForInitCompletion() { try { // wait for the initial load task to complete (with a timeout) await task.WithTimeout(InitialReadMaxWaitTimeForUpdates); } catch (TimeoutException ex) { throw new OrleansException("Reminder Service is still initializing and it is taking a long time. Please retry again later.", ex); } CheckRange(); } } break; case GrainServiceStatus.Started: break; case GrainServiceStatus.Stopped: throw new OperationCanceledException("ReminderService has been stopped."); default: throw new InvalidOperationException("status"); } CheckRange(); return Task.CompletedTask; void CheckRange() { if (!RingRange.InRange(grainRef)) { logger.Warn(ErrorCode.RS_NotResponsible, "I shouldn't have received request '{0}' for {1}. It is not in my responsibility range: {2}", debugInfo, grainRef.ToString(), RingRange); // For now, we still let the caller proceed without throwing an exception... the periodical mechanism will take care of reminders being registered at the wrong silo // otherwise, we can either reject the request, or re-route the request } } } // Note: The list of reminders can be huge in production! private void PrintReminders(string msg = null) { if (!logger.IsEnabled(LogLevel.Trace)) return; var str = String.Format("{0}{1}{2}", (msg ?? "Current list of reminders:"), Environment.NewLine, Utils.EnumerableToString(localReminders, null, Environment.NewLine)); logger.Trace(str); } private class LocalReminderData { private readonly IRemindable remindable; private readonly DateTime firstTickTime; // time for the first tick of this reminder private readonly TimeSpan period; private readonly LocalReminderService reminderService; private readonly IAsyncTimer timer; private ValueStopwatch stopwatch; private Task runTask; internal LocalReminderData(ReminderEntry entry, LocalReminderService reminderService) { Identity = new ReminderIdentity(entry.GrainRef, entry.ReminderName); firstTickTime = entry.StartAt; period = entry.Period; remindable = entry.GrainRef.Cast<IRemindable>(); ETag = entry.ETag; LocalSequenceNumber = -1; this.reminderService = reminderService; this.timer = reminderService.asyncTimerFactory.Create(period, ""); } public ReminderIdentity Identity { get; } public string ETag { get; } /// <summary> /// Locally, we use this for resolving races between the periodic table reader, and any concurrent local register/unregister requests /// </summary> public long LocalSequenceNumber { get; set; } /// <summary> /// Gets a value indicating whether this instance is running. /// </summary> public bool IsRunning => runTask is Task task && !task.IsCompleted; public void StartTimer() { if (runTask is null) { this.runTask = this.RunAsync(); } else { throw new InvalidOperationException($"{nameof(StartTimer)} may only be called once per instance and has already been called on this instance."); } } public void StopReminder() { timer.Dispose(); } private async Task RunAsync() { TimeSpan? dueTimeSpan = CalculateDueTime(); while (await this.timer.NextTick(dueTimeSpan)) { try { await OnTimerTick(); this.reminderService.ticksDeliveredStat.Increment(); } catch (Exception exception) { this.reminderService.logger.LogWarning( exception, "Exception firing reminder \"{ReminderName}\" for grain {GrainId}: {Exception}", this.Identity.ReminderName, this.Identity.GrainRef?.GrainId, exception); } dueTimeSpan = CalculateDueTime(); } } private TimeSpan CalculateDueTime() { TimeSpan dueTimeSpan; var now = DateTime.UtcNow; if (now < firstTickTime) // if the time for first tick hasn't passed yet { dueTimeSpan = firstTickTime.Subtract(now); // then duetime is duration between now and the first tick time } else // the first tick happened in the past ... compute duetime based on the first tick time, and period { // formula used: // due = period - 'time passed since last tick (==sinceLast)' // due = period - ((Now - FirstTickTime) % period) // explanation of formula: // (Now - FirstTickTime) => gives amount of time since first tick happened // (Now - FirstTickTime) % period => gives amount of time passed since the last tick should have triggered var sinceFirstTick = now.Subtract(firstTickTime); var sinceLastTick = TimeSpan.FromTicks(sinceFirstTick.Ticks % period.Ticks); dueTimeSpan = period.Subtract(sinceLastTick); // in corner cases, dueTime can be equal to period ... so, take another mod dueTimeSpan = TimeSpan.FromTicks(dueTimeSpan.Ticks % period.Ticks); } return dueTimeSpan; } public async Task OnTimerTick() { var before = DateTime.UtcNow; var status = TickStatus.NewStruct(firstTickTime, period, before); var logger = this.reminderService.logger; if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Triggering tick for {0}, status {1}, now {2}", this.ToString(), status, before); } try { if (stopwatch.IsRunning) { stopwatch.Stop(); var tardiness = stopwatch.Elapsed - period; this.reminderService.tardinessStat.AddSample(Math.Max(0, tardiness.Ticks)); } await remindable.ReceiveReminder(Identity.ReminderName, status); stopwatch.Restart(); var after = DateTime.UtcNow; if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Tick triggered for {0}, dt {1} sec, next@~ {2}", this.ToString(), (after - before).TotalSeconds, // the next tick isn't actually scheduled until we return control to // AsyncSafeTimer but we can approximate it by adding the period of the reminder // to the after time. after + this.period); } } catch (Exception exc) { var after = DateTime.UtcNow; logger.Error( ErrorCode.RS_Tick_Delivery_Error, string.Format("Could not deliver reminder tick for {0}, next {1}.", this.ToString(), after + this.period), exc); // What to do with repeated failures to deliver a reminder's ticks? } } public override string ToString() { return string.Format("[{0}, {1}, {2}, {3}, {4}, {5}, {6}]", Identity.ReminderName, Identity.GrainRef?.ToString(), period, LogFormatter.PrintDate(firstTickTime), ETag, LocalSequenceNumber, timer == null ? "Not_ticking" : "Ticking"); } } private readonly struct ReminderIdentity : IEquatable<ReminderIdentity> { public readonly GrainReference GrainRef { get; } public readonly string ReminderName { get; } public ReminderIdentity(GrainReference grainRef, string reminderName) { if (grainRef == null) throw new ArgumentNullException("grainRef"); if (string.IsNullOrWhiteSpace(reminderName)) throw new ArgumentException("The reminder name is either null or whitespace.", "reminderName"); this.GrainRef = grainRef; this.ReminderName = reminderName; } public readonly bool Equals(ReminderIdentity other) { return GrainRef.Equals(other.GrainRef) && ReminderName.Equals(other.ReminderName); } public override readonly bool Equals(object other) { return (other is ReminderIdentity) && Equals((ReminderIdentity)other); } public override readonly int GetHashCode() { return unchecked((int)((uint)GrainRef.GetHashCode() + (uint)ReminderName.GetHashCode())); } } } }
// Copyright 2014 Jacob Trimble // // 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.Reflection; using System.Reflection.Emit; using ModMaker.Lua.Parser; using ModMaker.Lua.Parser.Items; using ModMaker.Lua.Runtime; using ModMaker.Lua.Runtime.LuaValues; namespace ModMaker.Lua.Compiler { /// <summary> /// Defines a visitor object that helps compile code with CodeCompiler. /// </summary> sealed class CompilerVisitor : IParseItemVisitor { readonly ChunkBuilder _compiler; readonly Dictionary<LabelItem, Label> _labels = new Dictionary<LabelItem, Label>(new ReferenceEqualsComparer<LabelItem>()); /// <summary> /// A Helper used for compiling function call. This is used to fake the prefix in an indexer /// item. This simply reads from the prefix local. /// </summary> sealed class IndexerHelper : IParseExp { readonly ILGenerator _gen; readonly LocalBuilder _prefix; public IndexerHelper(ILGenerator gen, LocalBuilder prefix) { _gen = gen; _prefix = prefix; } public DebugInfo Debug { get; set; } public IParseItem Accept(IParseItemVisitor visitor) { _gen.Emit(OpCodes.Ldloc, _prefix); return this; } } /// <summary> /// Creates a new instance of CompilerVisitor. /// </summary> /// <param name="compiler">The creating object used to help generate code.</param> public CompilerVisitor(ChunkBuilder compiler) { _compiler = compiler; } public IParseItem Visit(BinOpItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; if (target.OperationType == BinaryOperationType.And || target.OperationType == BinaryOperationType.Or) { // object temp = {Lhs}; var end = gen.DefineLabel(); var temp = _compiler.CreateTemporary(typeof(ILuaValue)); target.Lhs.Accept(this); gen.Emit(OpCodes.Stloc, temp); // Push Lhs onto the stack, if going to end, this will be the result. gen.Emit(OpCodes.Ldloc, temp); // if (temp.IsTrue) goto end; gen.Emit(OpCodes.Ldloc, temp); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetProperty(nameof(ILuaValue.IsTrue)).GetGetMethod()); if (target.OperationType == BinaryOperationType.And) { // We want to break if the value is truthy and it's an OR, or it's falsy and it's an AND. // Boolean negation. gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); } gen.Emit(OpCodes.Brtrue, end); // Replace Lhs on stack with Rhs. gen.Emit(OpCodes.Pop); target.Rhs.Accept(this); // :end gen.MarkLabel(end); } else { //! push {Lhs}.Arithmetic({OperationType}, {Rhs}) target.Lhs.Accept(this); gen.Emit(OpCodes.Ldc_I4, (int)target.OperationType); target.Rhs.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Arithmetic))); } return target; } public IParseItem Visit(BlockItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } using (_compiler.LocalBlock()) { foreach (IParseItem child in target.Children) { child.Accept(this); } if (target.Return != null) { // return {Return}; target.Return.Accept(this); _compiler.CurrentGenerator.Emit(OpCodes.Ret); } } return target; } public IParseItem Visit(ClassDefItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; _compiler.MarkSequencePoint(target.Debug); // string[] loc = new string[{implements.Count}]; LocalBuilder loc = _compiler.CreateArray(typeof(string), target.Implements.Count); int i = 0; foreach (var item in target.Implements) { // loc[{i}] = {implements[i]}; gen.Emit(OpCodes.Ldloc, loc); gen.Emit(OpCodes.Ldc_I4, (i++)); gen.Emit(OpCodes.Ldstr, item); gen.Emit(OpCodes.Stelem, typeof(string)); } // E.Runtime.CreateClassValue(loc, {name}); gen.Emit(OpCodes.Ldarg_1); gen.Emit( OpCodes.Callvirt, typeof(ILuaEnvironment).GetProperty(nameof(ILuaEnvironment.Runtime)).GetGetMethod()); gen.Emit(OpCodes.Ldloc, loc); gen.Emit(OpCodes.Ldstr, target.Name); gen.Emit(OpCodes.Callvirt, typeof(ILuaRuntime).GetMethod(nameof(ILuaRuntime.CreateClassValue))); _compiler.RemoveTemporary(loc); return target; } public IParseItem Visit(ForGenItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; if (!_labels.ContainsKey(target.Break)) _labels.Add(target.Break, gen.DefineLabel()); Label start = gen.DefineLabel(); Label end = _labels[target.Break]; LocalBuilder ret = _compiler.CreateTemporary(typeof(LuaMultiValue)); LocalBuilder enumerable = _compiler.CreateTemporary(typeof(IEnumerable<LuaMultiValue>)); LocalBuilder enumerator = _compiler.CreateTemporary(typeof(IEnumerator<LuaMultiValue>)); using (_compiler.LocalBlock()) { // temp = new ILuaValue[...]; _compiler.MarkSequencePoint(target.ForDebug); var temp = _compiler.CreateArray(typeof(ILuaValue), target.Expressions.Length); for (int i = 0; i < target.Expressions.Length; i++) { // temp[{i}] = {item}; gen.Emit(OpCodes.Ldloc, temp); gen.Emit(OpCodes.Ldc_I4, i); target.Expressions[i].Accept(this); gen.Emit(OpCodes.Stelem, typeof(ILuaValue)); } // enumerable = E.Runtime.GenericLoop(E, new LuaMultiValue(temp)); gen.Emit(OpCodes.Ldarg_1); gen.Emit( OpCodes.Callvirt, typeof(ILuaEnvironment).GetProperty(nameof(ILuaEnvironment.Runtime)).GetGetMethod()); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Ldloc, temp); gen.Emit(OpCodes.Newobj, typeof(LuaMultiValue).GetConstructor(new[] { typeof(ILuaValue[]) })); gen.Emit(OpCodes.Callvirt, typeof(ILuaRuntime).GetMethod(nameof(ILuaRuntime.GenericLoop))); gen.Emit(OpCodes.Stloc, enumerable); _compiler.RemoveTemporary(temp); // enumerator = enumerable.GetEnumerator(); gen.Emit(OpCodes.Ldloc, enumerable); gen.Emit( OpCodes.Callvirt, typeof(IEnumerable<LuaMultiValue>).GetMethod(nameof(IEnumerable.GetEnumerator))); gen.Emit(OpCodes.Stloc, enumerator); // try { Label endTry = gen.BeginExceptionBlock(); gen.MarkLabel(start); // if (!enumerator.MoveNext) goto end; gen.Emit(OpCodes.Ldloc, enumerator); gen.Emit(OpCodes.Callvirt, typeof(IEnumerator).GetMethod(nameof(IEnumerator.MoveNext))); gen.Emit(OpCodes.Brfalse, end); // ILuaMultiValue ret = enumerator.Current; gen.Emit(OpCodes.Ldloc, enumerator); gen.Emit( OpCodes.Callvirt, typeof(IEnumerator<LuaMultiValue>) .GetProperty(nameof(IEnumerator<LuaMultiValue>.Current)).GetGetMethod()); gen.Emit(OpCodes.Stloc, ret); _compiler.RemoveTemporary(enumerator); for (int i = 0; i < target.Names.Length; i++) { // {_names[i]} = ret[{i}]; var field = _compiler.DefineLocal(target.Names[i]); field.StartSet(); gen.Emit(OpCodes.Ldloc, ret); gen.Emit(OpCodes.Ldc_I4, i); gen.Emit(OpCodes.Call, typeof(LuaMultiValue).GetMethod("get_Item")); field.EndSet(); } _compiler.RemoveTemporary(ret); // {Block} target.Block.Accept(this); // goto start; gen.Emit(OpCodes.Br, start); // end: _compiler.MarkSequencePoint(target.EndDebug); gen.MarkLabel(end); // } finally { gen.Emit(OpCodes.Leave, endTry); gen.BeginFinallyBlock(); // if (enumerable != null) enumerable.Dispose(); Label endFinally = gen.DefineLabel(); gen.Emit(OpCodes.Ldloc, enumerable); gen.Emit(OpCodes.Brfalse, endFinally); gen.Emit(OpCodes.Ldloc, enumerable); gen.Emit(OpCodes.Callvirt, typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose))); gen.MarkLabel(endFinally); _compiler.RemoveTemporary(enumerable); // } gen.EndExceptionBlock(); } return target; } public IParseItem Visit(ForNumItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; if (!_labels.ContainsKey(target.Break)) _labels.Add(target.Break, gen.DefineLabel()); Label start = gen.DefineLabel(); Label end = _labels[target.Break]; Label sj = gen.DefineLabel(); Label err = gen.DefineLabel(); LocalBuilder d = _compiler.CreateTemporary(typeof(double?)); LocalBuilder val = _compiler.CreateTemporary(typeof(double)); LocalBuilder step = _compiler.CreateTemporary(typeof(double)); LocalBuilder limit = _compiler.CreateTemporary(typeof(double)); using (_compiler.LocalBlock()) { _compiler.MarkSequencePoint(target.ForDebug); // d = {Start}.AsDouble(); target.Start.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.AsDouble))); gen.Emit(OpCodes.Stloc, d); // if (d.HasValue) goto sj; gen.Emit(OpCodes.Ldloca, d); gen.Emit(OpCodes.Callvirt, typeof(double?).GetProperty(nameof(Nullable<double>.HasValue)).GetGetMethod()); gen.Emit(OpCodes.Brtrue, sj); // err: gen.MarkLabel(err); // throw new InvalidOperationException( // "The Start, Limit, and Step of a for loop must result in numbers."); gen.Emit(OpCodes.Ldstr, Resources.LoopMustBeNumbers); gen.Emit(OpCodes.Newobj, typeof(InvalidOperationException).GetConstructor(new Type[] { typeof(string) })); gen.Emit(OpCodes.Throw); // sj: gen.MarkLabel(sj); // val = d.Value; gen.Emit(OpCodes.Ldloca, d); gen.Emit(OpCodes.Callvirt, typeof(double?).GetProperty(nameof(Nullable<double>.Value)).GetGetMethod()); gen.Emit(OpCodes.Stloc, val); if (target.Step != null) { // d = {Step}.AsDouble(); target.Step.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.AsDouble))); gen.Emit(OpCodes.Stloc, d); // if (!d.HasValue) goto err; gen.Emit(OpCodes.Ldloca, d); gen.Emit(OpCodes.Callvirt, typeof(double?).GetProperty(nameof(Nullable<double>.HasValue)).GetGetMethod()); gen.Emit(OpCodes.Brfalse, err); // step = d.Value; gen.Emit(OpCodes.Ldloca, d); gen.Emit(OpCodes.Callvirt, typeof(double?).GetProperty(nameof(Nullable<double>.Value)).GetGetMethod()); } else { // step = 1.0; gen.Emit(OpCodes.Ldc_R8, 1.0); } gen.Emit(OpCodes.Stloc, step); // d = {Limit}.AsDouble(); target.Limit.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.AsDouble))); gen.Emit(OpCodes.Stloc, d); // if (!d.HasValue) goto err; gen.Emit(OpCodes.Ldloca, d); gen.Emit(OpCodes.Callvirt, typeof(double?).GetProperty(nameof(Nullable<double>.HasValue)).GetGetMethod()); gen.Emit(OpCodes.Brfalse, err); // limit = d.Value; gen.Emit(OpCodes.Ldloca, d); gen.Emit(OpCodes.Callvirt, typeof(double?).GetProperty(nameof(Nullable<double>.Value)).GetGetMethod()); gen.Emit(OpCodes.Stloc, limit); _compiler.RemoveTemporary(d); // start: gen.MarkLabel(start); // if (!((step > 0) & (val <= limit)) | ((step <= 0) & (val >= limit))) goto end; gen.Emit(OpCodes.Ldloc, step); gen.Emit(OpCodes.Ldc_R8, 0.0); gen.Emit(OpCodes.Cgt); gen.Emit(OpCodes.Ldloc, val); gen.Emit(OpCodes.Ldloc, limit); gen.Emit(OpCodes.Cgt); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); gen.Emit(OpCodes.And); gen.Emit(OpCodes.Ldloc, step); gen.Emit(OpCodes.Ldc_R8, 0.0); gen.Emit(OpCodes.Cgt); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); gen.Emit(OpCodes.Ldloc, val); gen.Emit(OpCodes.Ldloc, limit); gen.Emit(OpCodes.Clt); gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Xor); gen.Emit(OpCodes.And); gen.Emit(OpCodes.Or); gen.Emit(OpCodes.Brfalse, end); // {name} = LuaValueBase.CreateValue((object)val); var field = _compiler.DefineLocal(target.Name); field.StartSet(); gen.Emit(OpCodes.Ldloc, val); gen.Emit(OpCodes.Box, typeof(double)); gen.Emit(OpCodes.Call, typeof(LuaValueBase).GetMethod(nameof(LuaValueBase.CreateValue))); field.EndSet(); // {Block} target.Block.Accept(this); // val += step; gen.Emit(OpCodes.Ldloc, val); gen.Emit(OpCodes.Ldloc, step); gen.Emit(OpCodes.Add); gen.Emit(OpCodes.Stloc, val); _compiler.RemoveTemporary(val); _compiler.RemoveTemporary(step); _compiler.RemoveTemporary(limit); // goto start; gen.Emit(OpCodes.Br, start); // end: _compiler.MarkSequencePoint(target.EndDebug); gen.MarkLabel(end); // Insert no-op so debugger can step on the "end" token. gen.Emit(OpCodes.Nop); } return target; } public IParseItem Visit(FuncCallItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } //// load the args into an array. ILGenerator gen = _compiler.CurrentGenerator; LocalBuilder f = _compiler.CreateTemporary(typeof(ILuaValue)); LocalBuilder self = _compiler.CreateTemporary(typeof(object)); if (target.Statement) { _compiler.MarkSequencePoint(target.Debug); } /* add 'self' if instance call */ if (target.InstanceName != null) { // self = {Prefix}; target.Prefix.Accept(this); gen.Emit(OpCodes.Stloc, self); // f = self.GetIndex(LuaValueBase.CreateValue({InstanceName})); gen.Emit(OpCodes.Ldloc, self); gen.Emit(OpCodes.Ldstr, target.InstanceName); gen.Emit(OpCodes.Call, typeof(LuaValueBase).GetMethod(nameof(LuaValueBase.CreateValue))); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.GetIndex))); gen.Emit(OpCodes.Stloc, f); } else if (target.Prefix is IndexerItem item) { // self = {Prefix}; item.Prefix.Accept(this); gen.Emit(OpCodes.Stloc, self); // Store the old value to restore later, add a dummy. var tempPrefix = item.Prefix; item.Prefix = new IndexerHelper(gen, self); // f = {Prefix}; target.Prefix.Accept(this); gen.Emit(OpCodes.Stloc, f); // Restore the old value item.Prefix = tempPrefix; } else { // self = LuaNil.Nil; gen.Emit(OpCodes.Ldnull); gen.Emit( OpCodes.Ldfld, typeof(LuaNil).GetField(nameof(LuaNil.Nil), BindingFlags.Static | BindingFlags.Public)); gen.Emit(OpCodes.Stloc, self); // f = {Prefix}; target.Prefix.Accept(this); gen.Emit(OpCodes.Stloc, f); } // var args = new ILuaValue[...]; LocalBuilder args = _compiler.CreateArray(typeof(ILuaValue), target.Arguments.Length); for (int i = 0; i < target.Arguments.Length; i++) { // args[i] = {item}; gen.Emit(OpCodes.Ldloc, args); gen.Emit(OpCodes.Ldc_I4, i); target.Arguments[i].Expression.Accept(this); if (i + 1 == target.Arguments.Length && target.IsLastArgSingle) { gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Single))); } gen.Emit(OpCodes.Stelem, typeof(ILuaValue)); } // var rargs = new LuaMultiValue(args); var rargs = _compiler.CreateTemporary(typeof(LuaMultiValue)); gen.Emit(OpCodes.Ldloc, args); gen.Emit(OpCodes.Newobj, typeof(LuaMultiValue).GetConstructor(new[] { typeof(ILuaValue[]) })); gen.Emit(OpCodes.Stloc, rargs); _compiler.RemoveTemporary(args); //! push f.Invoke(self, {!!InstanceName}, rargs); gen.Emit(OpCodes.Ldloc, f); gen.Emit(OpCodes.Ldloc, self); gen.Emit(target.InstanceName != null ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ldloc, rargs); if (target.IsTailCall) { gen.Emit(OpCodes.Tailcall); } gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Invoke))); _compiler.RemoveTemporary(f); _compiler.RemoveTemporary(self); //! pop if (target.Statement) { gen.Emit(OpCodes.Pop); } // support byRef for (int i = 0; i < target.Arguments.Length; i++) { if (target.Arguments[i].IsByRef) { _assignValue(target.Arguments[i].Expression, false, null, () => { // $value = rargs[{i}]; gen.Emit(OpCodes.Ldloc, rargs); gen.Emit(OpCodes.Ldc_I4, i); gen.Emit(OpCodes.Call, typeof(LuaMultiValue).GetMethod("get_Item")); }); } } _compiler.RemoveTemporary(rargs); return target; } public IParseItem Visit(FuncDefItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } var gen = _compiler.CurrentGenerator; ChunkBuilder.IVarDefinition field = null; string name = null; bool store = false; _compiler.MarkSequencePoint(target.Debug); if (target.Local) { // Local function definition if (target.InstanceName != null) { throw new CompilerMessage(MessageLevel.Fatal, MessageId.LocalInstanceName, target.Debug); } if (!(target.Prefix is NameItem)) { throw new CompilerMessage(MessageLevel.Fatal, MessageId.LocalMethodIndexer, target.Debug); } NameItem namei = (NameItem)target.Prefix; name = namei.Name; field = _compiler.DefineLocal(namei); field.StartSet(); } else if (target.Prefix != null) { if (target.InstanceName != null) { // Instance function definition name = null; if (target.Prefix is NameItem nameItem) { name = nameItem.Name; } else { name = (string)((LiteralItem)((IndexerItem)target.Prefix).Expression).Value; } name += ":" + target.InstanceName; // {Prefix}.SetIndex(LuaValueBase.CreateValue({InstanceName}), {ImplementFunction(...)}) target.Prefix.Accept(this); gen.Emit(OpCodes.Ldstr, target.InstanceName); gen.Emit(OpCodes.Call, typeof(LuaValueBase).GetMethod(nameof(LuaValueBase.CreateValue))); store = true; } else if (target.Prefix is IndexerItem index) { // Global function definition with indexer // {Prefix}.SetIndex({Expression}, {ImplementFunction(..)}) name = (string)((LiteralItem)index.Expression).Value; index.Prefix.Accept(this); index.Expression.Accept(this); store = true; } else { // Global function definition with name name = ((NameItem)target.Prefix).Name; field = _compiler.FindVariable((NameItem)target.Prefix); field.StartSet(); } } _compiler.ImplementFunction(this, target, name); if (field != null) { field.EndSet(); } else if (store) { gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.SetIndex))); } return target; } public IParseItem Visit(GotoItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (target.Target == null) { throw new InvalidOperationException(Resources.ErrorResolveLabel); } _compiler.MarkSequencePoint(target.Debug); _compiler.CurrentGenerator.Emit(OpCodes.Br, _labels[target.Target]); return target; } public IParseItem Visit(IfItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; Label next = gen.DefineLabel(); Label end = gen.DefineLabel(); // if (!{Exp}.IsTrue) goto next; _compiler.MarkSequencePoint(target.IfDebug); target.Expression.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetProperty(nameof(ILuaValue.IsTrue)).GetGetMethod()); gen.Emit(OpCodes.Brfalse, next); // {Block} target.Block.Accept(this); // goto end; gen.Emit(OpCodes.Br, end); // next: gen.MarkLabel(next); foreach (var item in target.Elses) { // if (!{item.Item1}.IsTrue) goto next; _compiler.MarkSequencePoint(item.Debug); next = gen.DefineLabel(); item.Expression.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetProperty(nameof(ILuaValue.IsTrue)).GetGetMethod()); gen.Emit(OpCodes.Brfalse, next); // {item.Item2} item.Block.Accept(this); // goto end; gen.Emit(OpCodes.Br, end); // next: gen.MarkLabel(next); } if (target.ElseBlock != null) { _compiler.MarkSequencePoint(target.ElseDebug); target.ElseBlock.Accept(this); } // end: _compiler.MarkSequencePoint(target.EndDebug); gen.MarkLabel(end); gen.Emit(OpCodes.Nop); // Insert no-op so debugger can step on the "end" token. return target; } public IParseItem Visit(IndexerItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } //! push {Prefix}.GetIndex({Expression}) var gen = _compiler.CurrentGenerator; target.Prefix.Accept(this); target.Expression.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.GetIndex))); return target; } public IParseItem Visit(LabelItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } if (!_labels.ContainsKey(target)) _labels.Add(target, _compiler.CurrentGenerator.DefineLabel()); _compiler.CurrentGenerator.MarkLabel(_labels[target]); return target; } public IParseItem Visit(LiteralItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; object value = target.Value; if (value is null) { gen.Emit(OpCodes.Ldnull); } else if (value is bool b) { gen.Emit(b ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Box, typeof(bool)); } else if (value is double d) { gen.Emit(OpCodes.Ldc_R8, d); gen.Emit(OpCodes.Box, typeof(double)); } else if (value is string s) { gen.Emit(OpCodes.Ldstr, s); } else { throw new InvalidOperationException(Resources.InvalidLiteralType); } gen.Emit(OpCodes.Call, typeof(LuaValueBase).GetMethod(nameof(LuaValueBase.CreateValue))); return target; } public IParseItem Visit(NameItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } // Get the value of the given name and push onto stack var field = _compiler.FindVariable(target); field.Get(); return target; } public IParseItem Visit(RepeatItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; if (!_labels.ContainsKey(target.Break)) _labels.Add(target.Break, gen.DefineLabel()); Label start = gen.DefineLabel(); Label end = _labels[target.Break]; // start: _compiler.MarkSequencePoint(target.RepeatDebug); gen.MarkLabel(start); gen.Emit(OpCodes.Nop); // So the debugger can stop on "repeat". // {Block} target.Block.Accept(this); // if (!{Exp}.IsTrue) goto start; _compiler.MarkSequencePoint(target.UntilDebug); target.Expression.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetProperty(nameof(ILuaValue.IsTrue)).GetGetMethod()); gen.Emit(OpCodes.Brfalse, start); // end: gen.MarkLabel(end); return target; } public IParseItem Visit(ReturnItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } _compiler.MarkSequencePoint(target.Debug); ILGenerator gen = _compiler.CurrentGenerator; if (target.Expressions.Length == 1 && !target.IsLastExpressionSingle && target.Expressions[0] is FuncCallItem func) { func.IsTailCall = true; target.Expressions[0].Accept(this); return target; } // ILuaValue[] loc = new ILuaValue[{Expressions.Count}]; LocalBuilder loc = _compiler.CreateArray(typeof(ILuaValue), target.Expressions.Length); for (int i = 0; i < target.Expressions.Length; i++) { // loc[{i}] = {Expressions[i]}; gen.Emit(OpCodes.Ldloc, loc); gen.Emit(OpCodes.Ldc_I4, i); target.Expressions[i].Accept(this); if (i + 1 == target.Expressions.Length && target.IsLastExpressionSingle) { gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Single))); } gen.Emit(OpCodes.Stelem, typeof(ILuaValue)); } //! push new LuaMultiValue(loc) gen.Emit(OpCodes.Ldloc, loc); gen.Emit(OpCodes.Newobj, typeof(LuaMultiValue).GetConstructor(new[] { typeof(ILuaValue[]) })); _compiler.RemoveTemporary(loc); return target; } public IParseItem Visit(TableItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } var gen = _compiler.CurrentGenerator; var loc = _compiler.CreateTemporary(typeof(ILuaValue)); // loc = new LuaTable(); gen.Emit(OpCodes.Newobj, typeof(LuaTable).GetConstructor(Type.EmptyTypes)); gen.Emit(OpCodes.Stloc, loc); foreach (var item in target.Fields) { // Does not need to use SetItemRaw because there is no Metatable. // loc.SetIndex({item.Item1}, {item.Item2}); gen.Emit(OpCodes.Ldloc, loc); item.Key.Accept(this); item.Value.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.SetIndex))); } //! push loc; gen.Emit(OpCodes.Ldloc, loc); _compiler.RemoveTemporary(loc); return target; } public IParseItem Visit(UnOpItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; //! push {Target}.Minus(); target.Target.Accept(this); switch (target.OperationType) { case UnaryOperationType.Minus: gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Minus))); break; case UnaryOperationType.Not: gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Not))); break; case UnaryOperationType.Length: gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Length))); break; } return target; } public IParseItem Visit(AssignmentItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; _compiler.MarkSequencePoint(target.Debug); // ILuaValue[] loc = new ILuaValue[{target.Expressions.Count}]; LocalBuilder loc = _compiler.CreateArray(typeof(ILuaValue), target.Expressions.Length); // ILuaValue[] names = new ILuaValue[{target.Names.Count}]; LocalBuilder names = _compiler.CreateArray(typeof(ILuaValue), target.Names.Length); // Have to evaluate the name indexer expressions before setting the values otherwise the // following will fail: // i, t[i] = i+1, 20 for (int i = 0; i < target.Names.Length; i++) { if (target.Names[i] is IndexerItem item) { gen.Emit(OpCodes.Ldloc, names); gen.Emit(OpCodes.Ldc_I4, i); item.Expression.Accept(this); gen.Emit(OpCodes.Stelem, typeof(ILuaValue)); } } for (int i = 0; i < target.Expressions.Length; i++) { // loc[{i}] = {exps[i]}; gen.Emit(OpCodes.Ldloc, loc); gen.Emit(OpCodes.Ldc_I4, i); target.Expressions[i].Accept(this); if (i + 1 == target.Expressions.Length && target.IsLastExpressionSingle) { gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.Single))); } gen.Emit(OpCodes.Stelem, typeof(ILuaValue)); } // LuaMultiValue exp = new LuaMultiValue(loc); LocalBuilder exp = _compiler.CreateTemporary(typeof(LuaMultiValue)); gen.Emit(OpCodes.Ldloc, loc); gen.Emit(OpCodes.Newobj, typeof(LuaMultiValue).GetConstructor(new[] { typeof(ILuaValue[]) })); gen.Emit(OpCodes.Stloc, exp); _compiler.RemoveTemporary(loc); for (int i = 0; i < target.Names.Length; i++) { _assignValue( target.Names[i], target.Local, !(target.Names[i] is IndexerItem) ? (Action)null : () => { // Only called if the target object is an indexer item // $index = names[{i}]; gen.Emit(OpCodes.Ldloc, names); gen.Emit(OpCodes.Ldc_I4, i); gen.Emit(OpCodes.Ldelem, typeof(ILuaValue)); }, () => { // $value = exp[{i}]; gen.Emit(OpCodes.Ldloc, exp); gen.Emit(OpCodes.Ldc_I4, i); gen.Emit(OpCodes.Callvirt, typeof(LuaMultiValue).GetMethod("get_Item")); }); } _compiler.RemoveTemporary(exp); _compiler.RemoveTemporary(names); return target; } public IParseItem Visit(WhileItem target) { if (target == null) { throw new ArgumentNullException(nameof(target)); } ILGenerator gen = _compiler.CurrentGenerator; if (!_labels.ContainsKey(target.Break)) _labels.Add(target.Break, gen.DefineLabel()); Label start = gen.DefineLabel(); Label end = _labels[target.Break]; // start: _compiler.MarkSequencePoint(target.WhileDebug); gen.MarkLabel(start); // if (!{Exp}.IsTrue) goto end; target.Expression.Accept(this); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetProperty(nameof(ILuaValue.IsTrue)).GetGetMethod()); gen.Emit(OpCodes.Brfalse, end); // {Block} target.Block.Accept(this); // goto start; gen.Emit(OpCodes.Br, start); // end: _compiler.MarkSequencePoint(target.EndDebug); gen.MarkLabel(end); gen.Emit(OpCodes.Nop); // So the debugger can stop on "end". return target; } /// <summary> /// Assigns the values of the parse item to the given value. /// </summary> /// <param name="target">The item to assign the value to (e.g. NameItem).</param> /// <param name="local">Whether this is a local definition.</param> /// <param name="getIndex"> /// A function to get the index of the object, pass null to use the default. /// </param> /// <param name="getValue">A function to get the value to set to.</param> void _assignValue(IParseItem target, bool local, Action getIndex, Action getValue) { ILGenerator gen = _compiler.CurrentGenerator; ChunkBuilder.IVarDefinition field; if (local) { field = _compiler.DefineLocal((NameItem)target); } else if (target is IndexerItem name) { // {name.Prefix}.SetIndex({name.Expression}, value); name.Prefix.Accept(this); if (getIndex != null) { getIndex(); } else { name.Expression.Accept(this); } getValue(); gen.Emit(OpCodes.Callvirt, typeof(ILuaValue).GetMethod(nameof(ILuaValue.SetIndex))); return; } else { // names[i] is NameItem NameItem item = (NameItem)target; field = _compiler.FindVariable(item); } // envField = value; field.StartSet(); getValue(); field.EndSet(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace NeedDotNet.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type int with 2 columns and 4 rows. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct imat2x4 : IEnumerable<int>, IEquatable<imat2x4> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> public int m00; /// <summary> /// Column 0, Rows 1 /// </summary> public int m01; /// <summary> /// Column 0, Rows 2 /// </summary> public int m02; /// <summary> /// Column 0, Rows 3 /// </summary> public int m03; /// <summary> /// Column 1, Rows 0 /// </summary> public int m10; /// <summary> /// Column 1, Rows 1 /// </summary> public int m11; /// <summary> /// Column 1, Rows 2 /// </summary> public int m12; /// <summary> /// Column 1, Rows 3 /// </summary> public int m13; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public imat2x4(int m00, int m01, int m02, int m03, int m10, int m11, int m12, int m13) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; } /// <summary> /// Constructs this matrix from a imat2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a imat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a imat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a imat4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(imat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(ivec2 c0, ivec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0; this.m03 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(ivec3 c0, ivec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat2x4(ivec4 c0, ivec4 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = c0.w; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = c1.w; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public int[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public int[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public ivec4 Column0 { get { return new ivec4(m00, m01, m02, m03); } set { m00 = value.x; m01 = value.y; m02 = value.z; m03 = value.w; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public ivec4 Column1 { get { return new ivec4(m10, m11, m12, m13); } set { m10 = value.x; m11 = value.y; m12 = value.z; m13 = value.w; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public ivec2 Row0 { get { return new ivec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public ivec2 Row1 { get { return new ivec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public ivec2 Row2 { get { return new ivec2(m02, m12); } set { m02 = value.x; m12 = value.y; } } /// <summary> /// Gets or sets the row nr 3 /// </summary> public ivec2 Row3 { get { return new ivec2(m03, m13); } set { m03 = value.x; m13 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static imat2x4 Zero { get; } = new imat2x4(0, 0, 0, 0, 0, 0, 0, 0); /// <summary> /// Predefined all-ones matrix /// </summary> public static imat2x4 Ones { get; } = new imat2x4(1, 1, 1, 1, 1, 1, 1, 1); /// <summary> /// Predefined identity matrix /// </summary> public static imat2x4 Identity { get; } = new imat2x4(1, 0, 0, 0, 0, 1, 0, 0); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static imat2x4 AllMaxValue { get; } = new imat2x4(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static imat2x4 DiagonalMaxValue { get; } = new imat2x4(int.MaxValue, 0, 0, 0, 0, int.MaxValue, 0, 0); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static imat2x4 AllMinValue { get; } = new imat2x4(int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static imat2x4 DiagonalMinValue { get; } = new imat2x4(int.MinValue, 0, 0, 0, 0, int.MinValue, 0, 0); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<int> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m03; yield return m10; yield return m11; yield return m12; yield return m13; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 4 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public int this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m03; case 4: return m10; case 5: return m11; case 6: return m12; case 7: return m13; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m03 = value; break; case 4: this.m10 = value; break; case 5: this.m11 = value; break; case 6: this.m12 = value; break; case 7: this.m13 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public int this[int col, int row] { get { return this[col * 4 + row]; } set { this[col * 4 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(imat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is imat2x4 && Equals((imat2x4) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(imat2x4 lhs, imat2x4 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(imat2x4 lhs, imat2x4 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public imat4x2 Transposed => new imat4x2(m00, m10, m01, m11, m02, m12, m03, m13); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public int MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public int MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public float LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))); /// <summary> /// Returns the sum of all fields. /// </summary> public int Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public int NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication imat2x4 * imat2 -> imat2x4. /// </summary> public static imat2x4 operator*(imat2x4 lhs, imat2 rhs) => new imat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication imat2x4 * imat3x2 -> imat3x4. /// </summary> public static imat3x4 operator*(imat2x4 lhs, imat3x2 rhs) => new imat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication imat2x4 * imat4x2 -> imat4. /// </summary> public static imat4 operator*(imat2x4 lhs, imat4x2 rhs) => new imat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static ivec4 operator*(imat2x4 m, ivec2 v) => new ivec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y)); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static imat2x4 CompMul(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static imat2x4 CompDiv(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat2x4 CompAdd(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat2x4 CompSub(imat2x4 A, imat2x4 B) => new imat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat2x4 operator+(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat2x4 operator+(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat2x4 operator+(int lhs, imat2x4 rhs) => new imat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat2x4 operator-(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat2x4 operator-(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat2x4 operator-(int lhs, imat2x4 rhs) => new imat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat2x4 operator/(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat2x4 operator/(int lhs, imat2x4 rhs) => new imat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat2x4 operator*(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat2x4 operator*(int lhs, imat2x4 rhs) => new imat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static imat2x4 operator%(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m02 % rhs.m02, lhs.m03 % rhs.m03, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m12 % rhs.m12, lhs.m13 % rhs.m13); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat2x4 operator%(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m02 % rhs, lhs.m03 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m12 % rhs, lhs.m13 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat2x4 operator%(int lhs, imat2x4 rhs) => new imat2x4(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m02, lhs % rhs.m03, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m12, lhs % rhs.m13); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static imat2x4 operator^(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m02 ^ rhs.m02, lhs.m03 ^ rhs.m03, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m12 ^ rhs.m12, lhs.m13 ^ rhs.m13); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat2x4 operator^(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m02 ^ rhs, lhs.m03 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m12 ^ rhs, lhs.m13 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat2x4 operator^(int lhs, imat2x4 rhs) => new imat2x4(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m02, lhs ^ rhs.m03, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m12, lhs ^ rhs.m13); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static imat2x4 operator|(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m02 | rhs.m02, lhs.m03 | rhs.m03, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m12 | rhs.m12, lhs.m13 | rhs.m13); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat2x4 operator|(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m02 | rhs, lhs.m03 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m12 | rhs, lhs.m13 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat2x4 operator|(int lhs, imat2x4 rhs) => new imat2x4(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m02, lhs | rhs.m03, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m12, lhs | rhs.m13); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static imat2x4 operator&(imat2x4 lhs, imat2x4 rhs) => new imat2x4(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m02 & rhs.m02, lhs.m03 & rhs.m03, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m12 & rhs.m12, lhs.m13 & rhs.m13); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat2x4 operator&(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m02 & rhs, lhs.m03 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m12 & rhs, lhs.m13 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat2x4 operator&(int lhs, imat2x4 rhs) => new imat2x4(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m02, lhs & rhs.m03, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m12, lhs & rhs.m13); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static imat2x4 operator<<(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m02 << rhs, lhs.m03 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m12 << rhs, lhs.m13 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static imat2x4 operator>>(imat2x4 lhs, int rhs) => new imat2x4(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m02 >> rhs, lhs.m03 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m12 >> rhs, lhs.m13 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat2x4 operator<(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2x4 operator<(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2x4 operator<(int lhs, imat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat2x4 operator<=(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator<=(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator<=(int lhs, imat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat2x4 operator>(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2x4 operator>(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2x4 operator>(int lhs, imat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat2x4 operator>=(imat2x4 lhs, imat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator>=(imat2x4 lhs, int rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator>=(int lhs, imat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13); } }
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Diagnostics; using System.Runtime.InteropServices; using EnvDTE; using VSLangProj; using Microsoft.VisualStudio.Designer.Interfaces; using WmcSoft.ComponentModel; using WmcSoft.Interop; using IServiceProvider = System.IServiceProvider; using IOleServiceProvider = WmcSoft.Interop.IServiceProvider; using System.Collections.Generic; using Microsoft.VisualStudio.Shell.Interop; using System.ComponentModel.Design; using Microsoft.VisualStudio.Shell.Design; namespace WmcSoft.VisualStudio { /// <summary> /// This class exists to be cocreated a in a preprocessor build step. /// </summary> public abstract class BaseCodeGeneratorWithSite : BaseCodeGenerator, IObjectWithSite, IServiceProvider { private object site = null; private CodeDomProvider codeDomProvider = null; private static Guid CodeDomInterfaceGuid = new Guid("{73E59688-C7C4-4a85-AF64-A538754784C5}"); private static Guid CodeDomServiceGuid = CodeDomInterfaceGuid; private ComServiceProvider serviceProvider = null; /// <summary> /// demand-creates a CodeDomProvider /// </summary> protected virtual CodeDomProvider CodeProvider { get { if (codeDomProvider == null) { IVSMDCodeDomProvider vsmdCodeDomProvider = (IVSMDCodeDomProvider)GetService(CodeDomServiceGuid); if (vsmdCodeDomProvider != null) { codeDomProvider = (CodeDomProvider)vsmdCodeDomProvider.CodeDomProvider; } Debug.Assert(codeDomProvider != null, "Get CodeDomProvider Interface failed. GetService(QueryService(CodeDomProvider) returned Null."); } return codeDomProvider; } set { if (value == null) { throw new ArgumentNullException(); } codeDomProvider = value; } } protected IEnumerable<Type> GetAvailableTypes(IServiceProvider provider, bool includeReferences) { DynamicTypeService typeService = (DynamicTypeService)provider.GetService(typeof(DynamicTypeService)); Debug.Assert(typeService != null, "No dynamic type service registered."); IVsHierarchy hier = VsHelper.GetCurrentHierarchy(provider); Debug.Assert(hier != null, "No active hierarchy is selected."); ITypeDiscoveryService discovery = typeService.GetTypeDiscoveryService(hier); Project dteProject = VsHelper.ToDteProject(hier); Dictionary<string, Type> availableTypes = new Dictionary<string, Type>(); foreach (Type type in discovery.GetTypes(typeof(object), includeReferences)) { // We will never allow non-public types selection, as it's terrible practice. if (type.IsPublic) { if (!availableTypes.ContainsKey(type.FullName)) { availableTypes.Add(type.FullName, type); } } } return availableTypes.Values; } /// <summary> /// demand-creates a ServiceProvider given an IOleServiceProvider /// </summary> private ComServiceProvider SiteServiceProvider { get { if (serviceProvider == null) { IOleServiceProvider oleServiceProvider = site as IOleServiceProvider; serviceProvider = new ComServiceProvider(oleServiceProvider); } return serviceProvider; } } /// <summary> /// method to get a service by its GUID /// </summary> /// <param name="serviceGuid">GUID of service to retrieve</param> /// <returns>an object that implements the requested service</returns> protected object GetService(Guid serviceGuid) { return SiteServiceProvider.GetService(serviceGuid); } /// <summary> /// method to get a service by its Type /// </summary> /// <param name="serviceType">Type of service to retrieve</param> /// <returns>an object that implements the requested service</returns> public virtual object GetService(Type serviceType) { return SiteServiceProvider.GetService(serviceType); } /// <summary> /// gets the default extension of the output file by asking the CodeDomProvider /// what its default extension is. /// </summary> /// <returns></returns> public override string GetDefaultExtension() { CodeDomProvider codeDom = CodeProvider; Debug.Assert(codeDom != null, "CodeDomProvider is NULL."); string extension = codeDom.FileExtension; if (extension != null && extension.Length > 0) { if (extension[0] != '.') { extension = "." + extension; } } return extension; } /// <summary> /// Method to get an ICodeGenerator with which this class can create code. /// </summary> /// <returns></returns> [Obsolete("Callers should not use the ICodeGenerator interface and should instead use the methods directly on the CodeDomProvider class. Those inheriting from CodeDomProvider must still implement this interface, and should exclude this warning or also obsolete this method.")] protected virtual ICodeGenerator GetCodeWriter() { CodeDomProvider codeDom = CodeProvider; if (codeDom != null) { return codeDom.CreateGenerator(); } return null; } /// <summary> /// SetSite method of IOleObjectWithSite /// </summary> /// <param name="pUnkSite">site for this object to use</param> public virtual void SetSite(object pUnkSite) { site = pUnkSite; codeDomProvider = null; serviceProvider = null; } /// <summary> /// GetSite method of IOleObjectWithSite /// </summary> /// <param name="riid">interface to get</param> /// <param name="ppvSite">array in which to stuff return value</param> public virtual void GetSite(ref Guid riid, object[] ppvSite) { if (ppvSite == null) { throw new ArgumentNullException("ppvSite"); } if (ppvSite.Length < 1) { throw new ArgumentException("ppvSite array must have at least 1 member", "ppvSite"); } if (site == null) { throw new COMException("object is not sited", Helpers.E_FAIL); } IntPtr pUnknownPointer = Marshal.GetIUnknownForObject(site); IntPtr intPointer = IntPtr.Zero; Marshal.QueryInterface(pUnknownPointer, ref riid, out intPointer); if (intPointer == IntPtr.Zero) { throw new COMException("site does not support requested interface", Helpers.E_NOINTERFACE); } ppvSite[0] = Marshal.GetObjectForIUnknown(intPointer); } /// <summary> /// gets a string containing the DLL names to add. /// </summary> /// <param name="DLLToAdd"></param> /// <returns></returns> private string GetDLLNames(string[] DLLToAdd) { if (DLLToAdd == null || DLLToAdd.Length == 0) { return string.Empty; } string dllNames = DLLToAdd[0]; for (int i = 1; i < DLLToAdd.Length; i++) { dllNames = dllNames + ", " + DLLToAdd[i]; } return dllNames; } /// <summary> /// adds a reference to the project for each required DLL /// </summary> /// <param name="referenceDLL"></param> protected void AddReferenceDLLToProject(string[] referenceDLL) { if (referenceDLL.Length == 0) { return; } object serviceObject = GetService(typeof(ProjectItem)); Debug.Assert(serviceObject != null, "Unable to get Project Item."); if (serviceObject == null) { string errorMessage = String.Format("Unable to add DLL to project references: {0}. Please Add them manually.", GetDLLNames(referenceDLL)); GeneratorErrorCallback(false, 1, errorMessage, 0, 0); return; } Project containingProject = ((ProjectItem)serviceObject).ContainingProject; Debug.Assert(containingProject != null, "GetService(typeof(Project)) return null."); if (containingProject == null) { string errorMessage = String.Format("Unable to add DLL to project references: {0}. Please Add them manually.", GetDLLNames(referenceDLL)); GeneratorErrorCallback(false, 1, errorMessage, 0, 0); return; } VSProject vsProj = containingProject.Object as VSProject; Debug.Assert(vsProj != null, "Unable to ADD DLL to current project. Project.Object does not implement VSProject."); if (vsProj == null) { string errorMessage = String.Format("Unable to add DLL to project references: {0}. Please Add them manually.", GetDLLNames(referenceDLL)); GeneratorErrorCallback(false, 1, errorMessage, 0, 0); return; } try { for (int i = 0; i < referenceDLL.Length; i++) { vsProj.References.Add(referenceDLL[i]); } } catch (Exception e) { Debug.Fail("**** ERROR: vsProj.References.Add() throws exception: " + e.ToString()); string errorMessage = String.Format("Unable to add DLL to project references: {0}. Please Add them manually.", GetDLLNames(referenceDLL)); GeneratorErrorCallback(false, 1, errorMessage, 0, 0); return; } } /// <summary> /// method to create an exception message given an exception /// </summary> /// <param name="e">exception caught</param> /// <returns>message to display to the user</returns> protected virtual string CreateExceptionMessage(Exception e) { string message = (e.Message != null ? e.Message : string.Empty); Exception innerException = e.InnerException; while (innerException != null) { string innerMessage = innerException.Message; if (innerMessage != null && innerMessage.Length > 0) { message = message + " " + innerMessage; } innerException = innerException.InnerException; } return message; } /// <summary> /// method to create a version comment /// </summary> /// <param name="codeNamespace"></param> protected virtual void GenerateVersionComment(System.CodeDom.CodeNamespace codeNamespace) { codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); codeNamespace.Comments.Add(new CodeCommentStatement(String.Format("This source code was auto-generated by {0}, Version {1}.", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name, System.Environment.Version.ToString()))); codeNamespace.Comments.Add(new CodeCommentStatement(string.Empty)); } } }
// 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using SVsServiceProvider = Microsoft.VisualStudio.Shell.SVsServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Packaging { /// <summary> /// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces. /// We want to be able to make queries about packages from any thread. For example, the /// add-NuGet-reference feature wants to know what packages a project already has /// references to. NuGet.VisualStudio provides this information, but only in a COM STA /// manner. As we don't want our background work to bounce and block on the UI thread /// we have this helper class which queries the information on the UI thread and caches /// the data so it can be read from the background. /// </summary> [ExportWorkspaceService(typeof(IPackageInstallerService)), Shared] internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback { private readonly object _gate = new object(); private readonly VisualStudioWorkspaceImpl _workspace; private readonly SVsServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; // We refer to the package services through proxy types so that we can // delay loading their DLLs until we actually need them. private IPackageServicesProxy _packageServices; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); // We keep track of what types of changes we've seen so we can then determine what to // refresh on the UI thread. If we hear about project changes, we only refresh that // project. If we hear about a solution level change, we'll refresh all projects. private bool _solutionChanged; private HashSet<ProjectId> _changedProjects = new HashSet<ProjectId>(); private readonly ConcurrentDictionary<ProjectId, Dictionary<string, string>> _projectToInstalledPackageAndVersion = new ConcurrentDictionary<ProjectId, Dictionary<string, string>>(); [ImportingConstructor] public PackageInstallerService( VisualStudioWorkspaceImpl workspace, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(workspace, SymbolSearchOptions.Enabled, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInNuGetPackages) { _workspace = workspace; _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; } public ImmutableArray<PackageSource> PackageSources { get; private set; } = ImmutableArray<PackageSource>.Empty; public event EventHandler PackageSourcesChanged; public bool IsEnabled => _packageServices != null; protected override void EnableService() { // Our service has been enabled. Now load the VS package dlls. var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var packageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().FirstOrDefault(); var packageInstaller = componentModel.GetExtensions<IVsPackageInstaller2>().FirstOrDefault(); var packageUninstaller = componentModel.GetExtensions<IVsPackageUninstaller>().FirstOrDefault(); var packageSourceProvider = componentModel.GetExtensions<IVsPackageSourceProvider>().FirstOrDefault(); if (packageInstallerServices == null || packageInstaller == null || packageUninstaller == null || packageSourceProvider == null) { return; } _packageServices = new PackageServicesProxy( packageInstallerServices, packageInstaller, packageUninstaller, packageSourceProvider); // Start listening to additional events workspace changes. _workspace.WorkspaceChanged += OnWorkspaceChanged; _packageServices.SourcesChanged += OnSourceProviderSourcesChanged; } protected override void StartWorking() { this.AssertIsForeground(); if (!this.IsEnabled) { return; } OnSourceProviderSourcesChanged(this, EventArgs.Empty); OnWorkspaceChanged(null, new WorkspaceChangeEventArgs( WorkspaceChangeKind.SolutionAdded, null, null)); } private void OnSourceProviderSourcesChanged(object sender, EventArgs e) { if (!this.IsForeground()) { this.InvokeBelowInputPriority(() => OnSourceProviderSourcesChanged(sender, e)); return; } this.AssertIsForeground(); PackageSources = _packageServices.GetSources(includeUnOfficial: true, includeDisabled: false) .Select(r => new PackageSource(r.Key, r.Value)) .ToImmutableArrayOrEmpty(); PackageSourcesChanged?.Invoke(this, EventArgs.Empty); } public bool TryInstallPackage( Workspace workspace, DocumentId documentId, string source, string packageName, string versionOpt, bool includePrerelease, CancellationToken cancellationToken) { this.AssertIsForeground(); // The 'workspace == _workspace' line is probably not necessary. However, we include // it just to make sure that someone isn't trying to install a package into a workspace // other than the VisualStudioWorkspace. if (workspace == _workspace && _workspace != null && _packageServices != null) { var projectId = documentId.ProjectId; var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(SDTE)); var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject != null) { var description = string.Format(ServicesVSResources.Install_0, packageName); var undoManager = _editorAdaptersFactoryService.TryGetUndoManager( workspace, documentId, cancellationToken); return TryInstallAndAddUndoAction( source, packageName, versionOpt, includePrerelease, dte, dteProject, undoManager); } } return false; } private bool TryInstallPackage( string source, string packageName, string versionOpt, bool includePrerelease, EnvDTE.DTE dte, EnvDTE.Project dteProject) { try { if (!_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0, packageName); if (versionOpt == null) { _packageServices.InstallLatestPackage( source, dteProject, packageName, includePrerelease, ignoreDependencies: false); } else { _packageServices.InstallPackage( source, dteProject, packageName, versionOpt, ignoreDependencies: false); } var installedVersion = GetInstalledVersion(packageName, dteProject); dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private static string GetStatusBarText(string packageName, string installedVersion) { return installedVersion == null ? packageName : $"{packageName} - {installedVersion}"; } private bool TryUninstallPackage( string packageName, EnvDTE.DTE dte, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { if (_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0, packageName); var installedVersion = GetInstalledVersion(packageName, dteProject); _packageServices.UninstallPackage(dteProject, packageName, removeDependencies: true); dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private string GetInstalledVersion(string packageName, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { var installedPackages = _packageServices.GetInstalledPackages(dteProject); var metadata = installedPackages.FirstOrDefault(m => m.Id == packageName); return metadata?.VersionString; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return null; } } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { ThisCanBeCalledOnAnyThread(); bool localSolutionChanged = false; ProjectId localChangedProject = null; switch (e.Kind) { default: // Nothing to do for any other events. return; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: localChangedProject = e.ProjectId; break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: localSolutionChanged = true; break; } lock (_gate) { // Augment the data that the foreground thread will process. _solutionChanged |= localSolutionChanged; if (localChangedProject != null) { _changedProjects.Add(localChangedProject); } // Now cancel any inflight work that is processing the data. _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); // And enqueue a new job to process things. Wait one second before starting. // That way if we get a flurry of events we'll end up processing them after // they've all come in. var cancellationToken = _tokenSource.Token; Task.Delay(TimeSpan.FromSeconds(1), cancellationToken) .ContinueWith(_ => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler); } } private void ProcessBatchedChangesOnForeground(CancellationToken cancellationToken) { this.AssertIsForeground(); // If we've been asked to stop, then there's no point proceeding. if (cancellationToken.IsCancellationRequested) { return; } // If we've been disconnected, then there's no point proceeding. if (_workspace == null || _packageServices == null) { return; } // Get a project to process. var solution = _workspace.CurrentSolution; var projectId = DequeueNextProject(solution); if (projectId == null) { // No project to process, nothing to do. return; } // Process this single project. ProcessProjectChange(solution, projectId); // After processing this single project, yield so the foreground thread // can do more work. Then go and loop again so we can process the // rest of the projects. Task.Factory.SafeStartNew( () => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, ForegroundTaskScheduler); } private ProjectId DequeueNextProject(Solution solution) { this.AssertIsForeground(); lock (_gate) { // If we detected a solution change, then we need to process all projects. // This includes all the projects that we already know about, as well as // all the projects in the current workspace solution. if (_solutionChanged) { _changedProjects.AddRange(solution.ProjectIds); _changedProjects.AddRange(_projectToInstalledPackageAndVersion.Keys); } _solutionChanged = false; // Remove and return the first project in the list. var projectId = _changedProjects.FirstOrDefault(); _changedProjects.Remove(projectId); return projectId; } } private void ProcessProjectChange(Solution solution, ProjectId projectId) { this.AssertIsForeground(); // Remove anything we have associated with this project. _projectToInstalledPackageAndVersion.TryRemove(projectId, out var installedPackages); var project = solution.GetProject(projectId); if (project == null) { // Project was removed. Nothing needs to be done. return; } // We really only need to know the NuGet status for managed language projects. // Also, the NuGet APIs may throw on some projects that don't implement the // full set of DTE APIs they expect. So we filter down to just C# and VB here // as we know these languages are safe to build up this index for. if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { return; } // Project was changed in some way. Let's go find the set of installed packages for it. var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject == null) { // Don't have a DTE project for this project ID. not something we can query NuGet for. return; } installedPackages = new Dictionary<string, string>(); // Calling into NuGet. Assume they may fail for any reason. try { var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject); installedPackages.AddRange(installedPackageMetadata.Select(m => new KeyValuePair<string, string>(m.Id, m.VersionString))); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } _projectToInstalledPackageAndVersion.AddOrUpdate(projectId, installedPackages, (_1, _2) => installedPackages); } public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName) { ThisCanBeCalledOnAnyThread(); return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out var installedPackages) && installedPackages.ContainsKey(packageName); } public ImmutableArray<string> GetInstalledVersions(string packageName) { ThisCanBeCalledOnAnyThread(); var installedVersions = new HashSet<string>(); foreach (var installedPackages in _projectToInstalledPackageAndVersion.Values) { string version = null; if (installedPackages?.TryGetValue(packageName, out version) == true && version != null) { installedVersions.Add(version); } } // Order the versions with a weak heuristic so that 'newer' versions come first. // Essentially, we try to break the version on dots, and then we use a LogicalComparer // to try to more naturally order the things we see between the dots. var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList(); versionsAndSplits.Sort((v1, v2) => { var diff = CompareSplit(v1.Split, v2.Split); return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version); }); return versionsAndSplits.Select(v => v.Version).ToImmutableArray(); } private int CompareSplit(string[] split1, string[] split2) { ThisCanBeCalledOnAnyThread(); for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++) { // Prefer things that look larger. i.e. 7 should come before 6. // Use a logical string comparer so that 10 is understood to be // greater than 3. var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]); if (diff != 0) { return diff; } } // Choose the one with more parts. return split2.Length - split1.Length; } public IEnumerable<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version) { ThisCanBeCalledOnAnyThread(); var result = new List<Project>(); foreach (var kvp in this._projectToInstalledPackageAndVersion) { var installedPackageAndVersion = kvp.Value; if (installedPackageAndVersion != null) { if (installedPackageAndVersion.TryGetValue(packageName, out var installedVersion) && installedVersion == version) { var project = solution.GetProject(kvp.Key); if (project != null) { result.Add(project); } } } } return result; } public void ShowManagePackagesDialog(string packageName) { this.AssertIsForeground(); var shell = (IVsShell)_serviceProvider.GetService(typeof(SVsShell)); if (shell == null) { return; } var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc"); shell.LoadPackage(ref nugetGuid, out var nugetPackage); if (nugetPackage == null) { return; } // We're able to launch the package manager (with an item in its search box) by // using the IVsSearchProvider API that the NuGet package exposes. // // We get that interface for it and then pass it a SearchQuery that effectively // wraps the package name we're looking for. The NuGet package will then read // out that string and populate their search box with it. var extensionProvider = (IVsPackageExtensionProvider)nugetPackage; var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892"); var emptyGuid = Guid.Empty; var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid); var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this); task.Start(); } public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress) { } public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound) { } public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult) { pSearchItemResult.InvokeAction(); } public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults) { } private class SearchQuery : IVsSearchQuery { public SearchQuery(string packageName) { this.SearchString = packageName; } public string SearchString { get; } public uint ParseError => 0; public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) { return 0; } } private class PackageServicesProxy : IPackageServicesProxy { private readonly IVsPackageInstaller2 _packageInstaller; private readonly IVsPackageInstallerServices _packageInstallerServices; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly IVsPackageUninstaller _packageUninstaller; public PackageServicesProxy( IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller2 packageInstaller, IVsPackageUninstaller packageUninstaller, IVsPackageSourceProvider packageSourceProvider) { _packageInstallerServices = packageInstallerServices; _packageInstaller = packageInstaller; _packageUninstaller = packageUninstaller; _packageSourceProvider = packageSourceProvider; } public event EventHandler SourcesChanged { add { _packageSourceProvider.SourcesChanged += value; } remove { _packageSourceProvider.SourcesChanged -= value; } } public IEnumerable<PackageMetadata> GetInstalledPackages(EnvDTE.Project project) { return _packageInstallerServices.GetInstalledPackages(project) .Select(m => new PackageMetadata(m.Id, m.VersionString)) .ToList(); } public bool IsPackageInstalled(EnvDTE.Project project, string id) => _packageInstallerServices.IsPackageInstalled(project, id); public void InstallPackage(string source, EnvDTE.Project project, string packageId, string version, bool ignoreDependencies) => _packageInstaller.InstallPackage(source, project, packageId, version, ignoreDependencies); public void InstallLatestPackage(string source, EnvDTE.Project project, string packageId, bool includePrerelease, bool ignoreDependencies) => _packageInstaller.InstallLatestPackage(source, project, packageId, includePrerelease, ignoreDependencies); public IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled) => _packageSourceProvider.GetSources(includeUnOfficial, includeDisabled); public void UninstallPackage(EnvDTE.Project project, string packageId, bool removeDependencies) => _packageUninstaller.UninstallPackage(project, packageId, removeDependencies); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; namespace Microsoft.Windows.PowerShell.ScriptAnalyzer { /// <summary> /// Class to represent lines in a text. /// /// An instance of this class inserts and deletes an item (line) in O(1) time complexity as it uses /// a linkedlist as the underlying type to store the items. A drawback of using linkedlist as the /// underlying data type is that each indexed operations can be of the order of O(n), where n is the number of /// items in the list. To mitigate this inefficiency, each instance maintains state of the last accessed /// index and linkedlist node. Typically, successive text edits happen around a neighborhood of lines and as such /// each subsequent indexed operations can take advantage of previous state to minimize linkedlist /// traversal to find the requested item. /// </summary> internal class TextLines : IList<string> { private LinkedList<string> lines; private int lastAccessedIndex; private LinkedListNode<string> lastAccessedNode; /// <summary> /// Construct an instance of TextLines type. /// </summary> public TextLines() { lines = new LinkedList<string>(); Count = 0; InvalidateLastAccessed(); } /// <summary> /// Construct an instance for TextLines type from an IEnumerable type. /// </summary> /// <param name="inputLines">An IEnumerable type that represent lines in a text.</param> public TextLines(IEnumerable<string> inputLines) : this() { ThrowIfNull(inputLines, nameof(inputLines)); if (inputLines.Any(line => line == null)) { throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Strings.TextLinesNoNullItem)); } lines = new LinkedList<string>(inputLines); Count = lines.Count; } /// <summary> /// A readonly property describing how many elements are in the list. /// </summary> public int Count { get; private set; } /// <summary> /// If the object is ReadOnly or not. /// </summary> public bool IsReadOnly => false; /// <summary> /// Sets or gets the element at the given index. /// </summary> public string this[int index] { get { ValidateIndex(index); return GetNodeAt(index).Value; } set { ValidateIndex(index); Insert(index, value); RemoveAt(index); } } /// <summary> /// Return a readonly collection of the current object. /// </summary> /// <returns>A readonly collection of the current object.</returns> public ReadOnlyCollection<string> ReadOnly() { return new ReadOnlyCollection<string>(this); } /// <summary> /// Adds the given string to the end of the list. /// </summary> /// <param name="item">A non null object of type String.</param> public void Add(string item) { Insert(Count, item); } /// <summary> /// Clears the contents of the list. /// </summary> public void Clear() { lines.Clear(); } /// <summary> /// Returns true if the specified element is in the list. /// Equality is determined by calling item.Equals(). /// </summary> /// <param name="item">An item of type string.</param> /// <returns>true if item is contained in the list, otherwise false.</returns> public bool Contains(string item) { return lines.Contains(item); } /// <summary> /// Copies the list into an array, which must be of a compatible array type. /// </summary> /// <param name="array">An array of size TextLines.Count - arrayIndex</param> /// <param name="arrayIndex">Start index of the list from which to start copying into array.</param> public void CopyTo(string[] array, int arrayIndex) { lines.CopyTo(array, arrayIndex); } /// <summary> /// Returns an enumerator for this list. /// </summary> public IEnumerator<string> GetEnumerator() { return lines.GetEnumerator(); } /// <summary> /// Returns the first occurrence of a given value in a range of this list. /// </summary> /// <param name="item">Item to be searched.</param> /// <returns>The index if there is a match of the item in the list, otherwise -1.</returns> public int IndexOf(string item) { var node = lines.First; int index = 0; while (node != null) { if (node.Value.Equals(item)) { return index; } node = node.Next; index++; } return -1; } /// <summary> /// Inserts an element into this list at a given index. /// </summary> public void Insert(int index, string item) { ThrowIfNull(item, nameof(item)); LinkedListNode<string> itemInserted; if (Count == 0 && index == 0) { itemInserted = lines.AddFirst(item); } else if (Count == index) { itemInserted = lines.AddLast(item); } else { ValidateIndex(index); itemInserted = lines.AddBefore(GetNodeAt(index), item); } SetLastAccessed(index, itemInserted); Count++; } /// <summary> /// Remove an item from the list. /// </summary> /// <returns>true if removal is successful, otherwise false.</returns> public bool Remove(string item) { var itemIndex = IndexOf(item); if (itemIndex == -1) { return false; } RemoveAt(itemIndex); return true; } /// <summary> /// Removes the element at the given index. /// </summary> public void RemoveAt(int index) { ValidateIndex(index); var node = GetNodeAt(index); if (node.Next != null) { SetLastAccessed(index, node.Next); } else if (node.Previous != null) { SetLastAccessed(index - 1, node.Previous); } else { InvalidateLastAccessed(); } lines.Remove(node); Count--; } /// <summary> /// Returns an enumerator over the elements in the list. /// </summary> IEnumerator IEnumerable.GetEnumerator() { return lines.GetEnumerator(); } /// <summary> /// Returns the string representation of the object. /// </summary> public override string ToString() { return string.Join(Environment.NewLine, lines); } private void ValidateIndex(int index) { if (index >= Count || index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } } private void SetLastAccessed(int index, LinkedListNode<string> node) { lastAccessedIndex = index; lastAccessedNode = node; } private void InvalidateLastAccessed() { lastAccessedIndex = -1; lastAccessedNode = null; } private bool IsLastAccessedValid() { return lastAccessedIndex != -1; } private LinkedListNode<string> GetNodeAt(int index) { LinkedListNode<string> nodeAtIndex; if (index == 0) { nodeAtIndex = lines.First; } else if (index == Count - 1) { nodeAtIndex = lines.Last; } else { int searchDirection; int refIndex; GetClosestReference(index, out nodeAtIndex, out refIndex, out searchDirection); while (nodeAtIndex != null) { if (refIndex == index) { break; } refIndex += searchDirection; if (searchDirection > 0) { nodeAtIndex = nodeAtIndex.Next; } else { nodeAtIndex = nodeAtIndex.Previous; } } if (nodeAtIndex == null) { throw new InvalidOperationException(); } } SetLastAccessed(index, nodeAtIndex); return nodeAtIndex; } private void GetClosestReference( int index, out LinkedListNode<string> refNode, out int refIndex, out int searchDirection) { var delta = index - lastAccessedIndex; var deltaAbs = Math.Abs(delta); // lastAccessedIndex is closer to index than that to 0 if (IsLastAccessedValid() && deltaAbs < index) { // lastAccessedIndex is closer to index than to (Count - 1) if (deltaAbs < (Count - 1 - index)) { refNode = lastAccessedNode; refIndex = lastAccessedIndex; searchDirection = Math.Sign(delta); } else { refNode = lines.Last; refIndex = Count - 1; searchDirection = -1; } } else { refNode = lines.First; refIndex = 0; searchDirection = 1; } } private static void ThrowIfNull<T>(T param, string paramName) { if (param == null) { throw new ArgumentNullException(paramName); } } } }
namespace XenAdmin.TabPages { partial class GeneralTabPage { /// <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)) { if (licenseStatus != null) licenseStatus.Dispose(); 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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GeneralTabPage)); this.buttonProperties = new System.Windows.Forms.Button(); this.buttonViewConsole = new System.Windows.Forms.Button(); this.buttonViewLog = new System.Windows.Forms.Button(); this.linkLabelExpand = new System.Windows.Forms.LinkLabel(); this.linkLabelCollapse = new System.Windows.Forms.LinkLabel(); this.panel2 = new XenAdmin.Controls.PanelNoFocusScroll(); this.panelReadCaching = new System.Windows.Forms.Panel(); this.pdSectionReadCaching = new XenAdmin.Controls.PDSection(); this.panelDockerInfo = new System.Windows.Forms.Panel(); this.pdSectionDockerInfo = new XenAdmin.Controls.PDSection(); this.panelDockerVersion = new System.Windows.Forms.Panel(); this.pdSectionDockerVersion = new XenAdmin.Controls.PDSection(); this.panelStorageLinkSystemCapabilities = new System.Windows.Forms.Panel(); this.pdSectionStorageLinkSystemCapabilities = new XenAdmin.Controls.PDSection(); this.panelMultipathBoot = new System.Windows.Forms.Panel(); this.pdSectionMultipathBoot = new XenAdmin.Controls.PDSection(); this.panelStorageLink = new System.Windows.Forms.Panel(); this.pdStorageLink = new XenAdmin.Controls.PDSection(); this.panelMemoryAndVCPUs = new System.Windows.Forms.Panel(); this.pdSectionVCPUs = new XenAdmin.Controls.PDSection(); this.panelMultipathing = new System.Windows.Forms.Panel(); this.pdSectionMultipathing = new XenAdmin.Controls.PDSection(); this.panelStatus = new System.Windows.Forms.Panel(); this.pdSectionStatus = new XenAdmin.Controls.PDSection(); this.panelHighAvailability = new System.Windows.Forms.Panel(); this.pdSectionHighAvailability = new XenAdmin.Controls.PDSection(); this.panelBootOptions = new System.Windows.Forms.Panel(); this.pdSectionBootOptions = new XenAdmin.Controls.PDSection(); this.panelCPU = new System.Windows.Forms.Panel(); this.pdSectionCPU = new XenAdmin.Controls.PDSection(); this.panelMemory = new System.Windows.Forms.Panel(); this.pdSectionMemory = new XenAdmin.Controls.PDSection(); this.panelManagementInterfaces = new System.Windows.Forms.Panel(); this.pdSectionManagementInterfaces = new XenAdmin.Controls.PDSection(); this.panelUpdates = new System.Windows.Forms.Panel(); this.pdSectionUpdates = new XenAdmin.Controls.PDSection(); this.panelVersion = new System.Windows.Forms.Panel(); this.pdSectionVersion = new XenAdmin.Controls.PDSection(); this.panelLicense = new System.Windows.Forms.Panel(); this.pdSectionLicense = new XenAdmin.Controls.PDSection(); this.panelCustomFields = new System.Windows.Forms.Panel(); this.pdSectionCustomFields = new XenAdmin.Controls.PDSection(); this.panelGeneral = new System.Windows.Forms.Panel(); this.pdSectionGeneral = new XenAdmin.Controls.PDSection(); this.tableLayoutPanelButtons = new System.Windows.Forms.TableLayoutPanel(); this.pageContainerPanel.SuspendLayout(); this.panel2.SuspendLayout(); this.panelReadCaching.SuspendLayout(); this.panelDockerInfo.SuspendLayout(); this.panelDockerVersion.SuspendLayout(); this.panelStorageLinkSystemCapabilities.SuspendLayout(); this.panelMultipathBoot.SuspendLayout(); this.panelStorageLink.SuspendLayout(); this.panelMemoryAndVCPUs.SuspendLayout(); this.panelMultipathing.SuspendLayout(); this.panelStatus.SuspendLayout(); this.panelHighAvailability.SuspendLayout(); this.panelBootOptions.SuspendLayout(); this.panelCPU.SuspendLayout(); this.panelMemory.SuspendLayout(); this.panelManagementInterfaces.SuspendLayout(); this.panelUpdates.SuspendLayout(); this.panelVersion.SuspendLayout(); this.panelLicense.SuspendLayout(); this.panelCustomFields.SuspendLayout(); this.panelGeneral.SuspendLayout(); this.tableLayoutPanelButtons.SuspendLayout(); this.SuspendLayout(); // // pageContainerPanel // this.pageContainerPanel.Controls.Add(this.panel2); this.pageContainerPanel.Controls.Add(this.tableLayoutPanelButtons); resources.ApplyResources(this.pageContainerPanel, "pageContainerPanel"); // // buttonProperties // resources.ApplyResources(this.buttonProperties, "buttonProperties"); this.buttonProperties.Name = "buttonProperties"; this.buttonProperties.UseVisualStyleBackColor = true; this.buttonProperties.Click += new System.EventHandler(this.EditButton_Click); // // buttonViewConsole // resources.ApplyResources(this.buttonViewConsole, "buttonViewConsole"); this.buttonViewConsole.Name = "buttonViewConsole"; this.buttonViewConsole.UseVisualStyleBackColor = true; this.buttonViewConsole.Click += new System.EventHandler(this.buttonViewConsole_Click); // // buttonViewLog // resources.ApplyResources(this.buttonViewLog, "buttonViewLog"); this.buttonViewLog.Name = "buttonViewLog"; this.buttonViewLog.UseVisualStyleBackColor = true; this.buttonViewLog.Click += new System.EventHandler(this.buttonViewLog_Click); // // linkLabelExpand // resources.ApplyResources(this.linkLabelExpand, "linkLabelExpand"); this.linkLabelExpand.Name = "linkLabelExpand"; this.linkLabelExpand.TabStop = true; this.linkLabelExpand.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelExpand_LinkClicked); // // linkLabelCollapse // resources.ApplyResources(this.linkLabelCollapse, "linkLabelCollapse"); this.linkLabelCollapse.Name = "linkLabelCollapse"; this.linkLabelCollapse.TabStop = true; this.linkLabelCollapse.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelCollapse_LinkClicked); // // panel2 // resources.ApplyResources(this.panel2, "panel2"); this.panel2.Controls.Add(this.panelReadCaching); this.panel2.Controls.Add(this.panelDockerInfo); this.panel2.Controls.Add(this.panelDockerVersion); this.panel2.Controls.Add(this.panelStorageLinkSystemCapabilities); this.panel2.Controls.Add(this.panelMultipathBoot); this.panel2.Controls.Add(this.panelStorageLink); this.panel2.Controls.Add(this.panelMemoryAndVCPUs); this.panel2.Controls.Add(this.panelMultipathing); this.panel2.Controls.Add(this.panelStatus); this.panel2.Controls.Add(this.panelHighAvailability); this.panel2.Controls.Add(this.panelBootOptions); this.panel2.Controls.Add(this.panelCPU); this.panel2.Controls.Add(this.panelMemory); this.panel2.Controls.Add(this.panelManagementInterfaces); this.panel2.Controls.Add(this.panelUpdates); this.panel2.Controls.Add(this.panelVersion); this.panel2.Controls.Add(this.panelLicense); this.panel2.Controls.Add(this.panelCustomFields); this.panel2.Controls.Add(this.panelGeneral); this.panel2.Name = "panel2"; // // panelReadCaching // resources.ApplyResources(this.panelReadCaching, "panelReadCaching"); this.panelReadCaching.Controls.Add(this.pdSectionReadCaching); this.panelReadCaching.Name = "panelReadCaching"; // // pdSectionReadCaching // this.pdSectionReadCaching.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionReadCaching, "pdSectionReadCaching"); this.pdSectionReadCaching.Name = "pdSectionReadCaching"; this.pdSectionReadCaching.ShowCellToolTips = false; this.pdSectionReadCaching.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelDockerInfo // resources.ApplyResources(this.panelDockerInfo, "panelDockerInfo"); this.panelDockerInfo.Controls.Add(this.pdSectionDockerInfo); this.panelDockerInfo.Name = "panelDockerInfo"; // // pdSectionDockerInfo // this.pdSectionDockerInfo.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionDockerInfo, "pdSectionDockerInfo"); this.pdSectionDockerInfo.Name = "pdSectionDockerInfo"; this.pdSectionDockerInfo.ShowCellToolTips = false; // // panelDockerVersion // resources.ApplyResources(this.panelDockerVersion, "panelDockerVersion"); this.panelDockerVersion.Controls.Add(this.pdSectionDockerVersion); this.panelDockerVersion.Name = "panelDockerVersion"; // // pdSectionDockerVersion // this.pdSectionDockerVersion.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionDockerVersion, "pdSectionDockerVersion"); this.pdSectionDockerVersion.Name = "pdSectionDockerVersion"; this.pdSectionDockerVersion.ShowCellToolTips = false; // // panelStorageLinkSystemCapabilities // resources.ApplyResources(this.panelStorageLinkSystemCapabilities, "panelStorageLinkSystemCapabilities"); this.panelStorageLinkSystemCapabilities.Controls.Add(this.pdSectionStorageLinkSystemCapabilities); this.panelStorageLinkSystemCapabilities.Name = "panelStorageLinkSystemCapabilities"; // // pdSectionStorageLinkSystemCapabilities // this.pdSectionStorageLinkSystemCapabilities.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionStorageLinkSystemCapabilities, "pdSectionStorageLinkSystemCapabilities"); this.pdSectionStorageLinkSystemCapabilities.Name = "pdSectionStorageLinkSystemCapabilities"; this.pdSectionStorageLinkSystemCapabilities.ShowCellToolTips = false; // // panelMultipathBoot // resources.ApplyResources(this.panelMultipathBoot, "panelMultipathBoot"); this.panelMultipathBoot.Controls.Add(this.pdSectionMultipathBoot); this.panelMultipathBoot.Name = "panelMultipathBoot"; // // pdSectionMultipathBoot // this.pdSectionMultipathBoot.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionMultipathBoot, "pdSectionMultipathBoot"); this.pdSectionMultipathBoot.Name = "pdSectionMultipathBoot"; this.pdSectionMultipathBoot.ShowCellToolTips = false; // // panelStorageLink // resources.ApplyResources(this.panelStorageLink, "panelStorageLink"); this.panelStorageLink.Controls.Add(this.pdStorageLink); this.panelStorageLink.Name = "panelStorageLink"; // // pdStorageLink // this.pdStorageLink.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdStorageLink, "pdStorageLink"); this.pdStorageLink.Name = "pdStorageLink"; this.pdStorageLink.ShowCellToolTips = false; this.pdStorageLink.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelMemoryAndVCPUs // resources.ApplyResources(this.panelMemoryAndVCPUs, "panelMemoryAndVCPUs"); this.panelMemoryAndVCPUs.Controls.Add(this.pdSectionVCPUs); this.panelMemoryAndVCPUs.Name = "panelMemoryAndVCPUs"; // // pdSectionVCPUs // this.pdSectionVCPUs.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionVCPUs, "pdSectionVCPUs"); this.pdSectionVCPUs.Name = "pdSectionVCPUs"; this.pdSectionVCPUs.ShowCellToolTips = false; this.pdSectionVCPUs.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelMultipathing // resources.ApplyResources(this.panelMultipathing, "panelMultipathing"); this.panelMultipathing.Controls.Add(this.pdSectionMultipathing); this.panelMultipathing.Name = "panelMultipathing"; // // pdSectionMultipathing // this.pdSectionMultipathing.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionMultipathing, "pdSectionMultipathing"); this.pdSectionMultipathing.Name = "pdSectionMultipathing"; this.pdSectionMultipathing.ShowCellToolTips = false; this.pdSectionMultipathing.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelStatus // resources.ApplyResources(this.panelStatus, "panelStatus"); this.panelStatus.Controls.Add(this.pdSectionStatus); this.panelStatus.Name = "panelStatus"; // // pdSectionStatus // this.pdSectionStatus.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionStatus, "pdSectionStatus"); this.pdSectionStatus.Name = "pdSectionStatus"; this.pdSectionStatus.ShowCellToolTips = false; this.pdSectionStatus.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelHighAvailability // resources.ApplyResources(this.panelHighAvailability, "panelHighAvailability"); this.panelHighAvailability.Controls.Add(this.pdSectionHighAvailability); this.panelHighAvailability.Name = "panelHighAvailability"; // // pdSectionHighAvailability // this.pdSectionHighAvailability.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionHighAvailability, "pdSectionHighAvailability"); this.pdSectionHighAvailability.Name = "pdSectionHighAvailability"; this.pdSectionHighAvailability.ShowCellToolTips = false; this.pdSectionHighAvailability.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelBootOptions // resources.ApplyResources(this.panelBootOptions, "panelBootOptions"); this.panelBootOptions.Controls.Add(this.pdSectionBootOptions); this.panelBootOptions.Name = "panelBootOptions"; // // pdSectionBootOptions // this.pdSectionBootOptions.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionBootOptions, "pdSectionBootOptions"); this.pdSectionBootOptions.Name = "pdSectionBootOptions"; this.pdSectionBootOptions.ShowCellToolTips = false; this.pdSectionBootOptions.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelCPU // resources.ApplyResources(this.panelCPU, "panelCPU"); this.panelCPU.Controls.Add(this.pdSectionCPU); this.panelCPU.Name = "panelCPU"; // // pdSectionCPU // this.pdSectionCPU.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionCPU, "pdSectionCPU"); this.pdSectionCPU.Name = "pdSectionCPU"; this.pdSectionCPU.ShowCellToolTips = false; this.pdSectionCPU.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelMemory // resources.ApplyResources(this.panelMemory, "panelMemory"); this.panelMemory.Controls.Add(this.pdSectionMemory); this.panelMemory.Name = "panelMemory"; // // pdSectionMemory // this.pdSectionMemory.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionMemory, "pdSectionMemory"); this.pdSectionMemory.Name = "pdSectionMemory"; this.pdSectionMemory.ShowCellToolTips = false; this.pdSectionMemory.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelManagementInterfaces // resources.ApplyResources(this.panelManagementInterfaces, "panelManagementInterfaces"); this.panelManagementInterfaces.Controls.Add(this.pdSectionManagementInterfaces); this.panelManagementInterfaces.Name = "panelManagementInterfaces"; // // pdSectionManagementInterfaces // this.pdSectionManagementInterfaces.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionManagementInterfaces, "pdSectionManagementInterfaces"); this.pdSectionManagementInterfaces.Name = "pdSectionManagementInterfaces"; this.pdSectionManagementInterfaces.ShowCellToolTips = false; this.pdSectionManagementInterfaces.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelUpdates // resources.ApplyResources(this.panelUpdates, "panelUpdates"); this.panelUpdates.Controls.Add(this.pdSectionUpdates); this.panelUpdates.Name = "panelUpdates"; // // pdSectionUpdates // this.pdSectionUpdates.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionUpdates, "pdSectionUpdates"); this.pdSectionUpdates.Name = "pdSectionUpdates"; this.pdSectionUpdates.ShowCellToolTips = false; this.pdSectionUpdates.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelVersion // resources.ApplyResources(this.panelVersion, "panelVersion"); this.panelVersion.Controls.Add(this.pdSectionVersion); this.panelVersion.Name = "panelVersion"; // // pdSectionVersion // this.pdSectionVersion.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionVersion, "pdSectionVersion"); this.pdSectionVersion.Name = "pdSectionVersion"; this.pdSectionVersion.ShowCellToolTips = false; this.pdSectionVersion.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelLicense // resources.ApplyResources(this.panelLicense, "panelLicense"); this.panelLicense.Controls.Add(this.pdSectionLicense); this.panelLicense.Name = "panelLicense"; // // pdSectionLicense // this.pdSectionLicense.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionLicense, "pdSectionLicense"); this.pdSectionLicense.Name = "pdSectionLicense"; this.pdSectionLicense.ShowCellToolTips = false; this.pdSectionLicense.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelCustomFields // resources.ApplyResources(this.panelCustomFields, "panelCustomFields"); this.panelCustomFields.Controls.Add(this.pdSectionCustomFields); this.panelCustomFields.Name = "panelCustomFields"; // // pdSectionCustomFields // this.pdSectionCustomFields.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionCustomFields, "pdSectionCustomFields"); this.pdSectionCustomFields.Name = "pdSectionCustomFields"; this.pdSectionCustomFields.ShowCellToolTips = true; this.pdSectionCustomFields.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // panelGeneral // resources.ApplyResources(this.panelGeneral, "panelGeneral"); this.panelGeneral.Controls.Add(this.pdSectionGeneral); this.panelGeneral.Name = "panelGeneral"; // // pdSectionGeneral // this.pdSectionGeneral.BackColor = System.Drawing.Color.Gainsboro; resources.ApplyResources(this.pdSectionGeneral, "pdSectionGeneral"); this.pdSectionGeneral.Name = "pdSectionGeneral"; this.pdSectionGeneral.ShowCellToolTips = false; this.pdSectionGeneral.ExpandedChanged += new System.Action<XenAdmin.Controls.PDSection>(this.pdSection_ExpandedChanged); // // tableLayoutPanelButtons // resources.ApplyResources(this.tableLayoutPanelButtons, "tableLayoutPanelButtons"); this.tableLayoutPanelButtons.Controls.Add(this.buttonViewLog, 2, 0); this.tableLayoutPanelButtons.Controls.Add(this.buttonViewConsole, 1, 0); this.tableLayoutPanelButtons.Controls.Add(this.buttonProperties, 0, 0); this.tableLayoutPanelButtons.Controls.Add(this.linkLabelCollapse, 5, 0); this.tableLayoutPanelButtons.Controls.Add(this.linkLabelExpand, 4, 0); this.tableLayoutPanelButtons.Name = "tableLayoutPanelButtons"; // // GeneralTabPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.DoubleBuffered = true; this.Name = "GeneralTabPage"; this.pageContainerPanel.ResumeLayout(false); this.pageContainerPanel.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panelReadCaching.ResumeLayout(false); this.panelDockerInfo.ResumeLayout(false); this.panelDockerVersion.ResumeLayout(false); this.panelStorageLinkSystemCapabilities.ResumeLayout(false); this.panelMultipathBoot.ResumeLayout(false); this.panelStorageLink.ResumeLayout(false); this.panelMemoryAndVCPUs.ResumeLayout(false); this.panelMultipathing.ResumeLayout(false); this.panelStatus.ResumeLayout(false); this.panelHighAvailability.ResumeLayout(false); this.panelBootOptions.ResumeLayout(false); this.panelCPU.ResumeLayout(false); this.panelMemory.ResumeLayout(false); this.panelManagementInterfaces.ResumeLayout(false); this.panelUpdates.ResumeLayout(false); this.panelVersion.ResumeLayout(false); this.panelLicense.ResumeLayout(false); this.panelCustomFields.ResumeLayout(false); this.panelGeneral.ResumeLayout(false); this.tableLayoutPanelButtons.ResumeLayout(false); this.tableLayoutPanelButtons.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonProperties; private XenAdmin.Controls.PanelNoFocusScroll panel2; private System.Windows.Forms.Panel panelGeneral; private XenAdmin.Controls.PDSection pdSectionGeneral; private System.Windows.Forms.Panel panelMemoryAndVCPUs; private XenAdmin.Controls.PDSection pdSectionVCPUs; private System.Windows.Forms.Panel panelBootOptions; private XenAdmin.Controls.PDSection pdSectionBootOptions; private System.Windows.Forms.Panel panelMultipathing; private XenAdmin.Controls.PDSection pdSectionMultipathing; private System.Windows.Forms.Panel panelStatus; private XenAdmin.Controls.PDSection pdSectionStatus; private System.Windows.Forms.Panel panelHighAvailability; private XenAdmin.Controls.PDSection pdSectionHighAvailability; private System.Windows.Forms.Panel panelCustomFields; private XenAdmin.Controls.PDSection pdSectionCustomFields; private System.Windows.Forms.Panel panelManagementInterfaces; private XenAdmin.Controls.PDSection pdSectionManagementInterfaces; private System.Windows.Forms.Panel panelCPU; private XenAdmin.Controls.PDSection pdSectionCPU; private System.Windows.Forms.Panel panelVersion; private XenAdmin.Controls.PDSection pdSectionVersion; private System.Windows.Forms.Panel panelLicense; private XenAdmin.Controls.PDSection pdSectionLicense; private System.Windows.Forms.Panel panelMemory; private XenAdmin.Controls.PDSection pdSectionMemory; private System.Windows.Forms.Panel panelUpdates; private XenAdmin.Controls.PDSection pdSectionUpdates; private System.Windows.Forms.LinkLabel linkLabelExpand; private System.Windows.Forms.LinkLabel linkLabelCollapse; private System.Windows.Forms.Panel panelStorageLink; private XenAdmin.Controls.PDSection pdStorageLink; private System.Windows.Forms.Panel panelMultipathBoot; private XenAdmin.Controls.PDSection pdSectionMultipathBoot; private System.Windows.Forms.Panel panelStorageLinkSystemCapabilities; private XenAdmin.Controls.PDSection pdSectionStorageLinkSystemCapabilities; private System.Windows.Forms.Panel panelDockerInfo; private System.Windows.Forms.Panel panelDockerVersion; private Controls.PDSection pdSectionDockerVersion; private Controls.PDSection pdSectionDockerInfo; private System.Windows.Forms.Panel panelReadCaching; private Controls.PDSection pdSectionReadCaching; private System.Windows.Forms.Button buttonViewConsole; private System.Windows.Forms.Button buttonViewLog; private System.Windows.Forms.TableLayoutPanel tableLayoutPanelButtons; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Sprite container with frames that can have different sizes /// </summary> public class OTSpriteAtlas : OTContainer { public Vector2 _sheetSize = Vector2.zero; /// <summary> /// Spritesheet's texture /// </summary> public Texture texture; /// <summary> /// Info about the frames on the atlas /// </summary> public OTAtlasData[] atlasData = new OTAtlasData[] {}; [HideInInspector] /// <summary> /// Use position offset and sizing with trimmed frames /// </summary> /// <remarks> /// If set to false, no offsetting and resizing will be implemented, /// the vertices of the frames image locations will be pre-rendered /// and assigned when this frame is requested. /// </remarks> public bool offsetSizing = true; [HideInInspector] public string metaType = ""; [HideInInspector] public OTAtlasMetaData[] metaData; Vector2 _sheetSize_ = Vector2.zero; Texture _texture = null; /// <summary> /// Original sheet size /// </summary> /// <remarks> /// This setting is optional and only used in combination with frameSize when /// the frames do not exactly fill up the texture horizontally and/or vertically. /// <br></br><br></br> /// Sometimes a sheet has some left over space to the right or bottom of the /// texture that was used. By setting the original sheetSize and the frameSize, /// the empty left-over space can be calculated and taken into account when /// setting the texture scaling and frame texture offsetting. /// </remarks> public Vector2 sheetSize { get { return _sheetSize; } set { _sheetSize = value; dirtyContainer = true; } } protected bool atlasReady = true; protected bool _offsetSizing = true; Dictionary<string, OTAtlasData> dataByName = new Dictionary<string, OTAtlasData>(); public OTAtlasData DataByName(string dataName) { if (dataByName.ContainsKey(dataName)) return dataByName[dataName]; return null; } override public Texture GetTexture() { return texture; } override protected Frame[] GetFrames() { if (texture == null) return new Frame[] { }; Vector2 texSize = sheetSize; if (Vector2.Equals(texSize, Vector2.zero) && texture != null) texSize = new Vector2(texture.width, texture.height); if (Vector2.Equals(texSize, Vector2.zero)) return new Frame[] { }; if (atlasReady && atlasData.Length > 0) { // convert atlasData to frames Frame[] frames = new Frame[atlasData.Length]; dataByName.Clear(); for (int a = 0; a < atlasData.Length; a++) { OTAtlasData data = atlasData[a]; Frame frame = new Frame(); frame.name = data.name; if (!dataByName.ContainsKey(data.name)) dataByName.Add(data.name,data); if (offsetSizing) { frame.offset = data.offset; frame.size = data.size; } else { frame.offset = Vector2.zero; frame.size = data.frameSize; Vector2 vOffset = new Vector2(data.offset.x / frame.size.x, data.offset.y / frame.size.y); Vector2 vSize = new Vector2(data.size.x / frame.size.x, data.size.y / frame.size.y); Vector3 tl = new Vector3(((1f / 2f) * -1) + vOffset.x, (1f / 2f) - vOffset.y, 0); frame.vertices = new Vector3[] { tl, tl + new Vector3(vSize.x,0,0), tl + new Vector3(vSize.x,vSize.y * -1,0), tl + new Vector3(0,vSize.y * -1,0) }; } frame.imageSize = data.frameSize; frame.uv = new Vector2[4]; float sx = data.position.x / texSize.x; float sy = 1 - ((data.position.y + data.size.y) / texSize.y); float scx = data.size.x / texSize.x; float scy = data.size.y / texSize.y; if (data.rotated) { sy = 1 - ((data.position.y + data.size.x) / texSize.y); scx = data.size.y / texSize.x; scy = data.size.x / texSize.y; frame.uv[3] = new Vector2(sx, sy + scy); frame.uv[0] = new Vector2(sx + scx, sy + scy); frame.uv[1] = new Vector2(sx + scx, sy); frame.uv[2] = new Vector2(sx, sy); } else { frame.uv[0] = new Vector2(sx, sy + scy); frame.uv[1] = new Vector2(sx + scx, sy + scy); frame.uv[2] = new Vector2(sx + scx, sy); frame.uv[3] = new Vector2(sx, sy); } frames[a] = frame; } return frames; } return new Frame[] { }; } new protected void Start() { _sheetSize_ = sheetSize; _offsetSizing = offsetSizing; _texture = texture; base.Start(); } protected virtual void LocateAtlasData() { } protected void AddMeta(string key, string value) { if (metaData==null) metaData = new OTAtlasMetaData[] {}; System.Array.Resize<OTAtlasMetaData>(ref metaData, metaData.Length+1); metaData[metaData.Length-1] = new OTAtlasMetaData(); metaData[metaData.Length-1].key = key; metaData[metaData.Length-1].value = value; } new protected void Update() { if (!Vector2.Equals(_sheetSize, _sheetSize_) || _offsetSizing!=offsetSizing || _texture!=texture) { if (texture!=_texture && texture!=null) LocateAtlasData(); _sheetSize_ = _sheetSize; _offsetSizing = offsetSizing; _texture = texture; dirtyContainer = true; } base.Update(); } public string GetMeta(string key) { if (metaData == null) return ""; for (int k=0; k<metaData.Length; k++) { if (metaData[k].key == key) return metaData[k].value; } return ""; } } [System.Serializable] public class OTAtlasMetaData { public string key; public string value; }
using Xunit; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BracketPipe.Core.Tests { public class SanitizeTests { private void TestSanitize(string input, string expected, HtmlSanitizeSettings settings = null, HtmlWriterSettings writerSettings = null) { using (var reader = new HtmlReader(input)) { var rendered = reader.Sanitize(settings ?? HtmlSanitizeSettings.Default()).ToHtml(writerSettings); Assert.Equal(expected, rendered); } } [Fact] public void Sanitize_Basic() { TestSanitize(@"<div><p>stuff <img src=""javascript:alert('hit')"" /> <img data-test=""something"" src=""thing.png"" /> <img src=""http://www.google.com/thing.png"" /> and more</p></div><div><script>alert('bad stuff');</script>With content</div>" , "<div><p>stuff <img src=\"thing.png\"> <img src=\"http://www.google.com/thing.png\"> and more</p></div><div>With content</div>"); } [Fact] public void Sanitize_CheatSheet_Anchor() { TestSanitize("<a href=\"'';!--\"<XSS>=&{()}\">", @"<a href=""'';!--"">=&amp;{()}""&gt;"); TestSanitize(@"<p><a onmouseover=""alert(document.cookie)"">xxs link</a></p>", "<p><a>xxs link</a></p>"); TestSanitize(@"<p><a onmouseover=alert(document.cookie)>xxs link</a></p>", "<p><a>xxs link</a></p>"); TestSanitize("<A HREF=\"javascript:document.location='http://www.google.com/'\">XSS</A>", "<a>XSS</a>"); TestSanitize("<A HREF=\"http://www.codeplex.com?url=<SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>\">XSS</A>", @"<a href=""http://www.codeplex.com/?url=%3CSCRIPT/XSS%20SRC="">""&gt;XSS</a>"); TestSanitize("<A HREF=\"http://www.codeplex.com?url=<<SCRIPT>alert(\"XSS\");//<</SCRIPT>\">XSS</A>", @"<a href=""http://www.codeplex.com/?url=%3C%3CSCRIPT%3Ealert("">""&gt;XSS</a>"); } [Fact] public void Sanitize_CheatSheet_Script() { TestSanitize(@"<p><SCRIPT SRC=http://xss.rocks/xss.js></SCRIPT></p>", "<p></p>"); TestSanitize(@"<p><SCR\0IPT SRC=http://xss.rocks/xss.js></SCR\0IPT></p>", "<p></p>"); TestSanitize(@"<p><SCRIPT/XSS SRC=""http://xss.rocks/xss.js""></SCRIPT></p>", "<p></p>"); TestSanitize(@"<p><SCRIPT/SRC=""http://xss.rocks/xss.js""></SCRIPT></p>", "<p></p>"); TestSanitize(@"<p><<SCRIPT>alert(""XSS"");//<</SCRIPT></p>", "<p>&lt;</p>"); TestSanitize(@"<p><SCRIPT SRC=http://xss.rocks/xss.js?< B ></p>", "<p>"); TestSanitize(@"<p><SCRIPT SRC=//xss.rocks/.j></SCRIPT></p>", "<p></p>"); } [Fact] public void Sanitize_CheatSheet_Img() { TestSanitize(@"<p><IMG SRC=""javascript:alert('XSS');""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""javascript: alert('XSS'); ""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=javascript:alert('XSS')></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=JaVaScRiPt:alert('XSS')></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=javascript:alert(""XSS"")></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=javascript:alert(&quot;XSS&quot;)></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=`javascript:alert(""RSnake says, 'XSS'"")`></p>", "<p></p>"); TestSanitize(@"<p><IMG """"""><SCRIPT>alert(""XSS"")</SCRIPT>""></p>", "<p>\"&gt;</p>"); TestSanitize(@"<p><IMG SRC=javascript:alert(String.fromCharCode(88,83,83))></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=# onmouseover=""alert('xxs')""></p>", "<p><img src=\"#\"></p>"); TestSanitize(@"<p><IMG SRC= onmouseover=""alert('xxs')""></p>", "<p><img src=\"onmouseover=%22alert('xxs')%22\"></p>"); TestSanitize(@"<p><IMG onmouseover=""alert('xxs')""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=/ onerror=""alert(String.fromCharCode(88, 83, 83))""></img></p>", "<p><img src=\"/\"></p>"); TestSanitize(@"<p><img src=x onerror=""&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041""></p>", "<p><img src=\"x\"></p>"); TestSanitize(@"<p><IMG SRC=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#39;&#88;&#83;&#83;&#39;&#41;></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x27&#x58&#x53&#x53&#x27&#x29></p>", "<p></p>"); TestSanitize("<p><IMG SRC=\"jav\tascript:alert('XSS');\"></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""jav&#x09;ascript:alert('XSS');""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""jav&#x0A;ascript:alert('XSS');""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""jav&#x0D;ascript:alert('XSS');""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC = "" j a v a s c r i p t : a l e r t ( ' X S S ' ) "" ></p>", "<p></p>"); TestSanitize("<p><IMG SRC=\"java\0script:alert('XSS');\"></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC="" &#14; javascript:alert('XSS');""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""javascript:alert('XSS')""</p>", "<p>"); TestSanitize(@"<p><IMG DYNSRC=""javascript:alert('XSS')""></p>", "<p></p>"); TestSanitize(@"<p><IMG LOWSRC=""javascript:alert('XSS')""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC='vbscript:msgbox(""XSS"")'></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""mocha:[code]""></p>", "<p></p>"); TestSanitize(@"<p><IMG SRC=""livescript:[code]""></p>", "<p></p>"); TestSanitize(@"<p><IMAGE src=http://xss.rocks/scriptlet.html <</p>", "<p>"); } [Fact] public void Sanitize_CheatSheet_Body() { TestSanitize(@"<p><BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert(""XSS"")></BODY></p>", "<p></p>"); var bodySettings = HtmlSanitizeSettings.Default(); bodySettings.AllowedTags.Add("body"); TestSanitize(@"<BODY BACKGROUND=""javascript:alert('XSS')""></BODY>", "<body></body>", bodySettings); TestSanitize(@"<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert(""XSS"")></BODY>", "<body></body>", bodySettings); TestSanitize(@"<BODY ONLOAD=alert('XSS')></BODY>", "<body></body>", bodySettings); } [Fact] public void Sanitize_CheatSheet_StyleAttr() { TestSanitize(@"<IMG src=""#"" STYLE=""width:100px;xss:5px;background:expr/*XSS*/ession(alert('XSS'));height:100px;"">", @"<img src=""#"" style=""width:100px;height:100px;"">"); TestSanitize(@"<IMG src=""#"" STYLE=""xss:expr/*XSS*/ession(alert('XSS'))"">", @"<img src=""#"">"); TestSanitize("<div style=\"\";alert('XSS');//\"></div>", "<div></div>"); TestSanitize(@"<XSS STYLE=""xss:expression(alert('XSS'))"">", @""); TestSanitize(@"<XSS STYLE=""behavior: url(xss.htc);"">", @""); TestSanitize(@"<p STYLE=""behavior: url(xss.htc);""></p>", @"<p></p>"); TestSanitize(@"<DIV STYLE=""background-image: url(javascript:alert('XSS'))""></div>", @"<div></div>"); TestSanitize(@"<DIV STYLE=""background-image:\0075\0072\006C\0028'\006a\0061\0076\0061\0073\0063\0072\0069\0070\0074\003a\0061\006c\0065\0072\0074\0028.1027\0058.1053\0053\0027\0029'\0029""></div>", @"<div></div>"); TestSanitize(@"<DIV STYLE=""background-image: url(&#1;javascript:alert('XSS'))""></div>", @"<div></div>"); TestSanitize(@"<DIV STYLE=""width: expression(alert('XSS'));""></div>", @"<div></div>"); TestSanitize("exp/*<A STYLE='no\\xss:noxss(\"*//*\");xss:&#101;x&#x2F;*XSS*//*/*/pression(alert(\"XSS\"))'>", "exp/*<a>"); TestSanitize("<Div style=\"background-color: http://www.codeplex.com?url=<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>\">", "<div>"); TestSanitize("<Div style=\"background-color: expression(<SCRIPT SRC=http://ha.ckers.org/xss.js></SCRIPT>)\">", "<div>"); TestSanitize("<Div style=\"background-color: http://www.codeplex.com?url=<SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>\">", "<div>\"&gt;"); TestSanitize("<Div style=\"background-color: expression(<SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>)\">", "<div>)\"&gt;"); TestSanitize("<Div style=\"background-color: http://www.codeplex.com?url=<SCRIPT/SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>\">", "<div>\"&gt;"); TestSanitize("<Div style=\"background-color: expression(<SCRIPT/SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>)\">", "<div>)\"&gt;"); } [Fact] public void Sanitize_CheatSheetStyleSheet() { var styleSettings = HtmlSanitizeSettings.Default(); styleSettings.AllowedTags.Add("style"); TestSanitize(@"<STYLE>@import'http://xss.rocks/xss.css';</STYLE>", @"<style></style>", styleSettings); TestSanitize(@"<STYLE>BODY{-moz-binding:url(""http://xss.rocks/xssmoz.xml#xss"")}</STYLE>", @"<style>BODY{}</style>", styleSettings); TestSanitize(@"<STYLE>@im\port'\ja\vasc\ript:alert(""XSS"")';</STYLE>", @"<style></style>", styleSettings); TestSanitize(@"<STYLE TYPE=""text/javascript"">alert('XSS');</STYLE>", @"<style type=""text/javascript"">;</style>", styleSettings); TestSanitize(@"<STYLE>.XSS{background-image:url(""javascript:alert('XSS')"");}</STYLE><A CLASS=XSS></A>", @"<style>.XSS{}</style><a></a>", styleSettings); TestSanitize(@"<STYLE type=""text/css"">BODY{background:url(""javascript:alert('XSS')"")}</STYLE>", @"<style type=""text/css"">BODY{}</style>", styleSettings); } [Fact] public void Sanitize_CheatSheet_Meta() { TestSanitize(@"<p><LINK REL=""stylesheet"" HREF=""javascript:alert('XSS');""></p>", @"<p></p>"); TestSanitize(@"<p><LINK REL=""stylesheet"" HREF=""http://xss.rocks/xss.css""></p>", @"<p></p>"); TestSanitize(@"<p><META HTTP-EQUIV=""Link"" Content=""<http://xss.rocks/xss.css>; REL=stylesheet""></p>", @"<p></p>"); TestSanitize(@"<p><META HTTP-EQUIV=""refresh"" CONTENT=""0;url=javascript:alert('XSS');""></p>", @"<p></p>"); TestSanitize(@"<p><META HTTP-EQUIV=""refresh"" CONTENT=""0;url=data:text/html base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K""></p>", @"<p></p>"); TestSanitize(@"<p><META HTTP-EQUIV=""refresh"" CONTENT=""0; URL=http://;URL=javascript:alert('XSS');""></p>", @"<p></p>"); } [Fact] public void Sanitize_CheatSheet_Other() { TestSanitize(@"<p><iframe src=http://xss.rocks/scriptlet.html <</p>", "<p>"); TestSanitize(@"<p><INPUT TYPE=""IMAGE"" SRC=""javascript:alert('XSS');""></p>", "<p><input type=\"IMAGE\"></p>"); TestSanitize(@"<p><BGSOUND SRC=""javascript:alert('XSS');""></p>", "<p></p>"); TestSanitize(@"<p><IFRAME SRC=""javascript:alert('XSS');""></IFRAME></p>", "<p></p>"); TestSanitize(@"<p><IFRAME SRC=# onmouseover=""alert(document.cookie)""></IFRAME></p>", "<p></p>"); TestSanitize(@"<p><FRAMESET><FRAME SRC=""javascript:alert('XSS');""></FRAMESET></p>", "<p></p>"); TestSanitize(@"<p><TABLE BACKGROUND=""javascript:alert('XSS')""></TABLE></p>", "<p><table></table></p>"); TestSanitize(@"<p><TABLE><TD BACKGROUND=""javascript:alert('XSS')""></TD></TABLE></p>", "<p><table><td></td></table></p>"); TestSanitize(@"<p><!--[if gte IE 4]> <SCRIPT>alert('XSS');</SCRIPT> <![endif]--></p>", "<p></p>"); TestSanitize(@"<p><BASE HREF=""javascript:alert('XSS');//""></p>", "<p></p>"); TestSanitize(@"<p><OBJECT TYPE=""text/x-scriptlet"" DATA=""http://xss.rocks/scriptlet.html""></OBJECT></p>", "<p></p>"); TestSanitize(@"<p><EMBED SRC=""http://ha.ckers.org/xss.swf"" AllowScriptAccess=""always""></p>", "<p></p>"); TestSanitize(@"<p><XML ID=""xss""><I><B><IMG SRC=""javas<!-- -->cript:alert('XSS')""></B></I></XML></p>", "<p></p>"); TestSanitize(@"<HTML><BODY> <?xml:namespace prefix=""t"" ns=""urn:schemas-microsoft-com:time""> <?import namespace=""t"" implementation=""#default#time2""> <t:set attributeName=""innerHTML"" to=""XSS<SCRIPT DEFER>alert(""XSS"")</SCRIPT>""> </BODY></HTML>", ""); TestSanitize("<EMBED SRC=\"data:image/svg+xml;base64,PHN2ZyB4bWxuczpzdmc9Imh0dH A6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv MjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hs aW5rIiB2ZXJzaW9uPSIxLjAiIHg9IjAiIHk9IjAiIHdpZHRoPSIxOTQiIGhlaWdodD0iMjAw IiBpZD0ieHNzIj48c2NyaXB0IHR5cGU9InRleHQvZWNtYXNjcmlwdCI+YWxlcnQoIlh TUyIpOzwvc2NyaXB0Pjwvc3ZnPg==\" type=\"image/svg+xml\" AllowScriptAccess=\"always\"></EMBED>", ""); TestSanitize("<HTML xmlns:xss><?import namespace=\"xss\" implementation=\"http://ha.ckers.org/xss.htc\"><xss:xss>XSS</xss:xss></HTML>", ""); var bgsoundSettings = HtmlSanitizeSettings.Default(); bgsoundSettings.AllowedTags.Add("BGSOUND"); TestSanitize(@"<p><BGSOUND SRC=""javascript:alert('XSS');""></p>", "<p><bgsound></p>", bgsoundSettings); } [Fact] public void Sanitize_StyleSheet() { var sheet = @"<style>@import 'custom.css'; @import url(""chrome://communicator/skin/""); @import ""common.css"" screen, projection; @import url('landscape.css') screen and(orientation: landscape); .XSS { background-image:url(""javascript: alert('XSS')""); color:red } @media (min-width:476px) { .PageHeader .menu { display:inline-block; float:right; } }</style>"; var expected = "<style>\r\n\r\n\r\n\r\n\r\n.XSS {\r\n \r\n color:red\r\n}\r\n\r\n@media (min-width:476px)\r\n{\r\n .PageHeader .menu\r\n {\r\n display:inline-block;\r\n float:right;\r\n }\r\n}</style>"; var styleSettings = HtmlSanitizeSettings.Default(); styleSettings.AllowedTags.Add("style"); TestSanitize(sheet, expected, styleSettings); } [Fact] public void Sanitize_DontEncodeUrls() { const string input = "<div><img src=\"data:image/png;base64, iVBORw0KGgoAAAANSU\"></div>"; var settings = HtmlSanitizeSettings.Default(); settings.AllowedSchemes.Add("data"); settings.UriFormat = UriFormat.SafeUnescaped; TestSanitize(input, input, settings); } [Fact] public void Sanitize_WeirdEmailTags() { var input = @"<div> To: Melissa Last <name.ext@example.com><br> Subject: RE: Expedia Ads <br><br> <http: www.marriott..com bosnt> <br><br>Check out the riverbend Restaurant <http: www.marriott.com hotels hotel-information restaurant bosnt-boston-marriott-newton></http:> <br><br>[FB-FindUsonFacebook-online-1024] <https: www.facebook.com bostonmarriottnewton></https:> </div>"; var settings = HtmlSanitizeSettings.Default(); settings.EmailLinkPseudoTags = SanitizeBehavior.Allow; TestSanitize(input, input, settings); settings.EmailLinkPseudoTags = SanitizeBehavior.Encode; TestSanitize(input, @"<div> To: Melissa Last &lt;name.ext@example.com&gt;<br> Subject: RE: Expedia Ads <br><br> &lt;http: www.marriott..com bosnt&gt; <br><br>Check out the riverbend Restaurant &lt;http: www.marriott.com hotels hotel-information restaurant bosnt-boston-marriott-newton&gt;&lt;/http:&gt; <br><br>[FB-FindUsonFacebook-online-1024] &lt;https: www.facebook.com bostonmarriottnewton&gt;&lt;/https:&gt; </div>", settings); settings.EmailLinkPseudoTags = SanitizeBehavior.Discard; TestSanitize(input, @"<div> To: Melissa Last <br> Subject: RE: Expedia Ads <br><br> <br><br>Check out the riverbend Restaurant <br><br>[FB-FindUsonFacebook-online-1024] </div>", settings); } } }
// Copyright (c) 2018-2019, 2021 Ubisoft Entertainment // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Sharpmake; using ProjConfiguration = Sharpmake.Project.Configuration; namespace QTFileCustomBuild { public class AdditionalDefinition { public Sharpmake.Platform Platform; public Sharpmake.DevEnv DevEnv; public Strings Defines; public AdditionalDefinition(Sharpmake.Platform platform, Sharpmake.DevEnv dev, params string[] defines) { Platform = platform; DevEnv = dev; Defines = new Strings(defines); } } public class QtSharpmakeMocTool { // Mapping of target name to all the files that should generate a moc call. public Dictionary<ProjConfiguration, List<MocSourceAndTargetFile>> MocTargetsPerConfiguration = new Dictionary<ProjConfiguration, List<MocSourceAndTargetFile>>(); // Mapping of target name to all the files that should generate a rcc call. public Dictionary<ProjConfiguration, List<RccSourceAndTargetFile>> RccTargetsPerConfiguration = new Dictionary<ProjConfiguration, List<RccSourceAndTargetFile>>(); // Mapping of target name to all the files that should generate a uic call. public Dictionary<ProjConfiguration, List<UicSourceAndTargetFile>> UicTargetsPerConfiguration = new Dictionary<ProjConfiguration, List<UicSourceAndTargetFile>>(); // Files that should be moc'd but should not be compiled alone (they will be included in another cpp file). public Strings ExcludeMocFromCompileRegex = new Strings(); // Files that should not be moc'd, skip scanning them. They may have a Q_OBJECT, but it's fake. public Strings ExcludeMocRegex = new Strings(); // A way to give defines to moc. public List<AdditionalDefinition> AdditionalDefines = new List<AdditionalDefinition>(); public QtSharpmakeMocTool() { AdditionalDefines.Add(new AdditionalDefinition(Sharpmake.Platform.win64 | Sharpmake.Platform.win32, Sharpmake.DevEnv.vs2017, "WIN32", "_MSC_VER=1910")); AdditionalDefines.Add(new AdditionalDefinition(Sharpmake.Platform.win64 | Sharpmake.Platform.win32, Sharpmake.DevEnv.vs2019, "WIN32", "_MSC_VER=1920")); } // Stores the source file and target file of a moc operation. public class MocSourceAndTargetFile : ProjConfiguration.CustomFileBuildStep { // Relative path of the input file. public string SourceFile; // Intermediate file used for a custom build step to produce the output from the input. public string IntermediateFile; // True if source file, false if header file. public bool IsCPPFile; // True if the output target file should never be compiled (For !IsCPPFile) public bool TargetFileNotCompiled; // List of includes to use. public Strings IncludePaths = new Strings(); // List of force-includes. The order matters. public List<string> ForceIncludes = new List<string>(); // Defines public string CombinedDefines = ""; public MocSourceAndTargetFile(string targetName, string mocExe, string baseOutputFolder, string outputFolder, string sourceFile) { Executable = mocExe; SourceFile = sourceFile; KeyInput = SourceFile; IsCPPFile = sourceFile.EndsWith(".cpp", StringComparison.InvariantCultureIgnoreCase); TargetFileNotCompiled = false; if (IsCPPFile) { // Put this one up one level, as it's just a boot strap file. IntermediateFile = baseOutputFolder + Path.GetFileNameWithoutExtension(sourceFile) + ".inl"; Output = outputFolder + Path.GetFileNameWithoutExtension(sourceFile) + ".moc"; // BFF only. Filter = ProjectFilter.BFFOnly; } else { ForceIncludes.Add(sourceFile); Output = outputFolder + "moc_" + Path.GetFileNameWithoutExtension(sourceFile) + ".cpp"; } Description = string.Format("Moc {0} {1}", targetName, Path.GetFileName(sourceFile)); ExecutableArguments = "[input] -o [output]"; } // Makes a Vcxproj rule from a BFFOnly rule. protected MocSourceAndTargetFile(MocSourceAndTargetFile reference) { Filter = ProjectFilter.ExcludeBFF; Executable = reference.Executable; // Input is SourceFile not KeyInput ExecutableArguments = " -o [output]"; // Input is the intermediate file. KeyInput = reference.IntermediateFile; // We also depend on the actual input file. AdditionalInputs.Add(reference.KeyInput); Output = reference.Output; Description = reference.Description; SourceFile = reference.SourceFile; IntermediateFile = reference.IntermediateFile; IsCPPFile = reference.IsCPPFile; TargetFileNotCompiled = reference.TargetFileNotCompiled; IncludePaths.AddRange(reference.IncludePaths); ForceIncludes.AddRange(reference.ForceIncludes); CombinedDefines = reference.CombinedDefines; } // We get built too late to handle the initial resolve (as we need the files built afterwards), but we get the other two events. public override ProjConfiguration.CustomFileBuildStepData MakePathRelative(Resolver resolver, Func<string, bool, string> MakeRelativeTool) { var relativeData = base.MakePathRelative(resolver, MakeRelativeTool); if (Filter == ProjectFilter.ExcludeBFF) { // Need to use the right input. relativeData.ExecutableArguments = MakeRelativeTool(SourceFile, true) + relativeData.ExecutableArguments; } // These are command line relative. Strings RelativeIncludePaths = new Strings(); foreach (string key in IncludePaths) RelativeIncludePaths.Add(MakeRelativeTool(key, true)); // These should be compiler relative instead of command line relative, but generally they're the same. var RelativeForceIncludes = new System.Text.StringBuilder(ForceIncludes.Count * 64); foreach (string key in ForceIncludes) { RelativeForceIncludes.Append(" -f"); RelativeForceIncludes.Append(MakeRelativeTool(key, false)); } RelativeIncludePaths.InsertPrefix("-I"); relativeData.ExecutableArguments = CombinedDefines + " " + RelativeIncludePaths.JoinStrings(" ") + " " + RelativeForceIncludes.ToString() + " " + relativeData.ExecutableArguments; return relativeData; } } // Needed for vcx when the input is a source file, we need to specify a different rule based on an intermediate file. // MocSourceAndTargetFile already setups up this data, we just need a non-bff rule. public class MocVcxprojBuildStep : MocSourceAndTargetFile { public MocVcxprojBuildStep(MocSourceAndTargetFile reference) : base(reference) { } } // Stores the source file and target file of a rcc operation public class RccSourceAndTargetFile : ProjConfiguration.CustomFileBuildStep { public RccSourceAndTargetFile(string targetName, string rccExe, string outputFolder, string sourceFile) { Executable = rccExe; KeyInput = sourceFile; string ResourceName = Path.GetFileNameWithoutExtension(sourceFile); Output = outputFolder + "qrc_" + ResourceName + ".cpp"; Description = string.Format("Rcc {0} {1}", targetName, Path.GetFileName(sourceFile)); ExecutableArguments = "-name " + ResourceName + " [input] -o [output]"; } } // Stores the source file and target file of a uic operation public class UicSourceAndTargetFile : ProjConfiguration.CustomFileBuildStep { public UicSourceAndTargetFile(string targetName, string uicExe, string outputFolder, string sourceFile) { Executable = uicExe; KeyInput = sourceFile; Output = outputFolder + "ui_" + Path.GetFileNameWithoutExtension(sourceFile) + ".h"; Description = string.Format("Uic {0} {1}", targetName, Path.GetFileName(sourceFile)); ExecutableArguments = "[input] -o [output]"; } } private bool FileIsPrecompiledHeader(string file, ProjConfiguration conf) { return (conf.PrecompHeader != null && file.EndsWith(conf.PrecompHeader, StringComparison.InvariantCultureIgnoreCase)) || (conf.PrecompSource != null && file.EndsWith(conf.PrecompSource, StringComparison.InvariantCultureIgnoreCase)); } private static int GetIndexMatchedAtEnd(string fileBuffer, string stringToFind) { int len = stringToFind.Length; int indexOfMatch = len > 0 ? len - 1 : 0; for (; indexOfMatch > 0; --indexOfMatch) { if (fileBuffer.EndsWith(stringToFind.Substring(0, indexOfMatch))) return indexOfMatch; } return 0; } private async Task<bool> FileContainsQObject(string file) { try { const int numBytesPerPage = 0x1000; using (StreamReader sourceStream = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: numBytesPerPage, useAsync: true))) { string[] stringsToFind = new string[2]; stringsToFind[0] = "Q_OBJECT"; stringsToFind[1] = "Q_GADGET"; int[] fractionsMatched = new int[2]; fractionsMatched[0] = 0; fractionsMatched[1] = 0; char[] buffer = new char[numBytesPerPage]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) != 0) { string text = new string(buffer); // If we partially matched the previous block, see if we match the rest. for (int i = 0; i < fractionsMatched.Length; ++i) { if (fractionsMatched[i] != 0) { if (text.StartsWith(stringsToFind[i].Substring(fractionsMatched[i]))) return true; } if (text.Contains(stringsToFind[i])) return true; fractionsMatched[i] = GetIndexMatchedAtEnd(text, stringsToFind[i]); } } return false; } } catch (Exception ex) { System.Console.WriteLine("While looking at file {0} encountered exception {1}, not mocing the file!", file, ex.Message); return false; } } // Call this from Project::ExcludeOutputFiles() to find the list of files we need to moc. // This is after resolving files, but before filtering them, and before they get mapped to // configurations, so this is a good spot to add additional files. public void GenerateListOfFilesToMoc(Project project, string QTExecFolder) { string mocExe = QTExecFolder + "moc.exe"; string rccExe = QTExecFolder + "rcc.exe"; string uicExe = QTExecFolder + "uic.exe"; // Filter all the files by the filters we've already specified, so we don't moc a file that's excluded from the solution. RegexOptions filterOptions = RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase; List<Regex> filters = project.SourceFilesExcludeRegex.Select(filter => new Regex(filter, filterOptions)).ToList(); filters.AddRange(ExcludeMocRegex.Select(filter => new Regex(filter, filterOptions))); var preFilteredFiles = project.ResolvedSourceFiles.Where(file => !filters.Any(filter => filter.IsMatch(file)) && !project.Configurations.Any(conf => FileIsPrecompiledHeader(file, conf))).ToList(); // Async load all the source files and look for Q_OBJECT that we want to keep. var answerSetTask = Task.WhenAll(preFilteredFiles.Select(async file => new { file = file, runMoc = await FileContainsQObject(file) })); // Compile a list of qrc and ui files. Strings qrcFiles = new Strings(preFilteredFiles.Where(file => file.EndsWith(".qrc", StringComparison.InvariantCultureIgnoreCase))); Strings uiFiles = new Strings(preFilteredFiles.Where(file => file.EndsWith(".ui", StringComparison.InvariantCultureIgnoreCase))); // Wait for the moc files. answerSetTask.Wait(); var filterPass = answerSetTask.Result; // These are the files we want to moc. Strings FilteredResolvedSourceFiles = new Strings(filterPass.Where(result => result.runMoc).Select(result => result.file)); // Compile a list of files where we don't want to compile the moc output. List<Regex> filesToExclude = ExcludeMocFromCompileRegex.Select(filter => new Regex(filter, filterOptions)).ToList(); foreach (ProjConfiguration conf in project.Configurations) { // Setup exclusions. string QTMocOutputBase = Path.GetDirectoryName(conf.IntermediatePath); string targetName = conf.Target.Name; string outputFolder = QTMocOutputBase + @"\qt\" + targetName.ToLowerInvariant() + @"\"; // We make the current output folder included directly so you can use the same #include directive to get the correct cpp file. conf.IncludePrivatePaths.Add(outputFolder); // Also include the project file folder, since the moc tool generates includes from this location. conf.IncludePrivatePaths.Add(conf.ProjectPath); // We need to exclude the generation files folder from the build on all targets except our own. string rootFolderForRegex = Util.GetCapitalizedPath(conf.ProjectPath); string outputRegex = Util.PathGetRelative(rootFolderForRegex, outputFolder); outputRegex = outputRegex.Replace("..\\", "").Replace("\\", "\\\\") + @"\\"; foreach (ProjConfiguration confToExclude in project.Configurations) { if (confToExclude == conf || confToExclude.ProjectFullFileNameWithExtension != conf.ProjectFullFileNameWithExtension) continue; confToExclude.SourceFilesBuildExcludeRegex.Add(outputRegex); } // Build a list of all files to moc in this configuration. var mocTargets = new List<MocSourceAndTargetFile>(); foreach (string file in FilteredResolvedSourceFiles) { var target = new MocSourceAndTargetFile(targetName, mocExe, outputFolder, outputFolder, file); if (filesToExclude.Any(filter => filter.IsMatch(file))) { target.TargetFileNotCompiled = true; } mocTargets.Add(target); if (target.IsCPPFile) { mocTargets.Add(new MocVcxprojBuildStep(target)); } } if (mocTargets.Count > 0) { MocTargetsPerConfiguration.Add(conf, mocTargets); } if (qrcFiles.Count > 0) { RccTargetsPerConfiguration.Add(conf, qrcFiles.Select(file => new RccSourceAndTargetFile(targetName, rccExe, outputFolder, file)).ToList()); } if (uiFiles.Count > 0) { UicTargetsPerConfiguration.Add(conf, uiFiles.Select(file => new UicSourceAndTargetFile(targetName, uicExe, outputFolder, file)).ToList()); } } // Add all the new source files to the project file. foreach (var values in MocTargetsPerConfiguration) { foreach (var target in values.Value) { // We only need to include outputs that have build steps. For source files, that's the intermediate file, for // header files, that's the target file, if it wasn't excluded. values.Key.CustomFileBuildSteps.Add(target); if (target.IsCPPFile) project.ResolvedSourceFiles.Add(target.IntermediateFile); else if (!target.TargetFileNotCompiled) project.ResolvedSourceFiles.Add(target.Output); } } foreach (var values in RccTargetsPerConfiguration) { var conf = values.Key; foreach (var target in values.Value) { conf.CustomFileBuildSteps.Add(target); // disable precomp in the files generated by rcc since they lack its include conf.PrecompSourceExclude.Add(target.Output); project.ResolvedSourceFiles.Add(target.Output); } } foreach (var values in UicTargetsPerConfiguration) { foreach (var target in values.Value) { values.Key.CustomFileBuildSteps.Add(target); // uic files generate header files - we don't need to run a build step on them, so don't include them in the vcxproj listing. //project.ResolvedSourceFiles.Add(target.Output); } } } private void CreateIntermediateFile(string sourceFile, string intermediateFile) { // Create the intermediate file if it doesn't already exist. Visual studio seems to ignore the custom build step unless the file already exists. if (!File.Exists(intermediateFile)) { try { string directory = Path.GetDirectoryName(intermediateFile); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (!File.Exists(intermediateFile)) { StreamWriter writer = File.CreateText(intermediateFile); writer.WriteLineAsync(sourceFile).ContinueWith(a => writer.Close()); System.Console.WriteLine(" Created {0}", intermediateFile); } } catch (IOException e) { // Sharing violation is fine, it means we're about to create the file on another thread. const int SharingViolation = 0x20; if ((e.HResult & 0xFFFF) != SharingViolation) { Console.WriteLine("Unable to generate intermediate file {0}: {1}", intermediateFile, e); } } catch (Exception e) { Console.WriteLine("Unable to generate intermediate file {0}: {1}", intermediateFile, e); } } } private void GenerateMocFileStepsForConfiguration(ProjConfiguration conf) { // Build a set of custom build steps from the source-target pairs. List<MocSourceAndTargetFile> mocTargets; if (!MocTargetsPerConfiguration.TryGetValue(conf, out mocTargets)) return; // Copy the defines and add -D in front of them. Strings confDefines = new Strings(conf.Defines.Select(define => define.Replace(" ", ""))); foreach (var additionalDefine in AdditionalDefines) { if ((conf.Target.GetPlatform() & additionalDefine.Platform) != 0 && (conf.Target.GetFragment<DevEnv>() & additionalDefine.DevEnv) != 0) { confDefines.AddRange(additionalDefine.Defines); } } confDefines.InsertPrefix("-D"); string combinedDefines = confDefines.JoinStrings(" "); // Combine all the different includes into a single string pool. Strings confIncludes = new Strings(conf.IncludePaths); confIncludes.AddRange(conf.DependenciesIncludePaths); confIncludes.AddRange(conf.IncludePrivatePaths); // Quote the include strings, if need be. List<string> includeValues = confIncludes.Values; foreach (string path in includeValues) { if (path.Contains(' ')) { confIncludes.UpdateValue(path, "\"" + path + "\""); } } string precompiledHeader = null; // Build the string we need to pass to moc for all calls. if (conf.PrecompHeader != null) { // If we have a precompiled header, we need the new cpp file to include this also. // Technically we don't need to do this if the file is in ExcludeMocFromCompileRegex precompiledHeader = conf.PrecompHeader; } // Apply these settings to all Moc targets. foreach (var target in mocTargets) { target.CombinedDefines = combinedDefines; target.IncludePaths.AddRange(confIncludes); // Precompiled header must go first in the force include list. if (!target.IsCPPFile && precompiledHeader != null) target.ForceIncludes.Insert(0, precompiledHeader); // VCX CPP file should create the intermediate file. else if (target.Filter == ProjConfiguration.CustomFileBuildStepData.ProjectFilter.ExcludeBFF) CreateIntermediateFile(target.SourceFile, target.KeyInput); } } // Call this in Project::PostLink(). We will build a list of custom build steps based on the resolved includes and defines. // At this point all of our includes and defines have been resolved, so now we can compute the arguments to moc. public void GenerateMocFileSteps(Project project) { foreach (ProjConfiguration conf in project.Configurations) { // Compute all the define and include parameters for this configuration. GenerateMocFileStepsForConfiguration(conf); } } } [Sharpmake.Generate] public class QTFileCustomBuildProject : Project { // Tool for generation moc commands. public QtSharpmakeMocTool mocTool; // Path the qt executables public string QTExeFolder; // Path to QT public string QTPath; protected override void ExcludeOutputFiles() { base.ExcludeOutputFiles(); mocTool.GenerateListOfFilesToMoc(this, QTExeFolder); } // At this point all of our includes and defines have been resolved, so now we can compute the arguments to moc. public override void PostLink() { mocTool.GenerateMocFileSteps(this); base.PostLink(); } public QTFileCustomBuildProject() { Name = "QTFileCustomBuild"; SourceRootPath = @"[project.SharpmakeCsPath]\codebase"; QTPath = Globals.Qt5_Dir; QTExeFolder = @"[project.QTPath]\bin\"; mocTool = new QtSharpmakeMocTool(); mocTool.ExcludeMocFromCompileRegex.Add("floatcosanglespinbox.h"); mocTool.ExcludeMocFromCompileRegex.Add("privatewidget.h"); SourceFilesExtensions.Add(".qrc", ".ui"); AddTargets(new Target( Platform.win64, DevEnv.vs2017, Optimization.Debug | Optimization.Release | Optimization.Retail, OutputType.Dll )); // Fast build fails regression tests because it embeds system and user paths, which aren't // the same on each user's machine. //AddTargets(new Target( // Platform.win64, // DevEnv.vs2017, // Optimization.Debug | Optimization.Release | Optimization.Retail, // OutputType.Dll, // Blob.FastBuildUnitys, // BuildSystem.FastBuild //)); } [Configure()] public void Configure(Configuration conf, Target target) { conf.ProjectFileName = "[project.Name]_[target.DevEnv]_[target.Platform]"; if (target.BuildSystem == BuildSystem.FastBuild) conf.ProjectFileName += "_fast"; conf.ProjectPath = @"[project.SharpmakeCsPath]\projects"; conf.Output = ProjConfiguration.OutputType.Exe; // if not set, no precompile option will be used. conf.PrecompHeader = "stdafx.h"; conf.PrecompSource = "stdafx.cpp"; conf.Defines.Add("_HAS_EXCEPTIONS=0"); conf.Defines.Add("QT_SHARED"); if (target.Optimization != Optimization.Debug) { conf.Defines.Add("QT_NO_DEBUG"); } conf.IncludePaths.Add(Path.Combine(QTPath, "include")); conf.LibraryPaths.Add(Path.Combine(QTPath, "lib")); conf.LibraryFiles.Add( "Qt5Core", "Qt5Gui", "Qt5Widgets" ); } [Configure(BuildSystem.FastBuild)] public void ConfigureFast(Configuration conf, Target target) { conf.IsFastBuild = true; } } [Sharpmake.Generate] public class QTFileCustomBuildSolution : Sharpmake.Solution { public QTFileCustomBuildSolution() { Name = "QTFileCustomBuild"; AddTargets(new Target( Platform.win64, DevEnv.vs2017, Optimization.Debug | Optimization.Release | Optimization.Retail, OutputType.Dll )); // Fast build fails regression tests because it embeds system and user paths, which aren't // the same on each user's machine. //AddTargets(new Target( // Platform.win64, // DevEnv.vs2017, // Optimization.Debug | Optimization.Release | Optimization.Retail, // OutputType.Dll, // Blob.FastBuildUnitys, // BuildSystem.FastBuild //)); } [Configure()] public void ConfigureAll(Configuration conf, Target target) { conf.SolutionFileName = "[solution.Name]_[target.DevEnv]_[target.Platform]"; if (target.BuildSystem == BuildSystem.FastBuild) conf.SolutionFileName += "_mf"; conf.SolutionPath = @"[solution.SharpmakeCsPath]\projects"; conf.AddProject<QTFileCustomBuildProject>(target); } } public static class Globals { public static string Qt5_Dir; } public static class Main { private static void ConfigureQt5Directory() { Util.GetEnvironmentVariable("Qt5_Dir", @"[project.SharpmakeCsPath]\qt\5.9.2\msvc2017_64", ref Globals.Qt5_Dir, silent: true); Util.LogWrite($"Qt5_Dir '{Globals.Qt5_Dir}'"); } [Sharpmake.Main] public static void SharpmakeMain(Sharpmake.Arguments arguments) { ConfigureQt5Directory(); FastBuildSettings.FastBuildMakeCommand = @"\tools\FastBuild\start-fbuild.bat"; KitsRootPaths.SetUseKitsRootForDevEnv(DevEnv.vs2017, KitsRootEnum.KitsRoot10, Options.Vc.General.WindowsTargetPlatformVersion.v10_0_17763_0); arguments.Generate<QTFileCustomBuildSolution>(); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using DotSpatial.Serialization; using GeoAPI.Geometries; using NetTopologySuite.Algorithm; using NetTopologySuite.Geometries; namespace DotSpatial.Data { /// <summary> /// The shape caries information about the raw vertices as well as a shapeRange. /// It is effectively away to move around a single shape. /// </summary> public class Shape : ICloneable { #region Fields private double[] _vertices; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class. /// </summary> public Shape() { } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class where the shaperange exists and has a type specified. /// </summary> /// <param name="featureType">Feature type of the shape range.</param> public Shape(FeatureType featureType) { Range = new ShapeRange(featureType); } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class based on the specified feature. /// This shape will be standing alone, all by itself. The fieldnames and field types will be null. /// </summary> /// <param name="feature">Feature used for creating the shape.</param> public Shape(IFeature feature) : this(feature.Geometry, feature.FeatureType) { if (Equals(feature, null)) throw new ArgumentNullException(nameof(feature)); if (feature.Geometry.NumPoints == 0) throw new ArgumentOutOfRangeException(nameof(feature), DataStrings.Shape_ZeroPointsError); if (feature.DataRow != null) Attributes = feature.DataRow.ItemArray; } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class based on the specified geometry. This shape will be standing alone, /// all by itself. The attributes will be null. /// </summary> /// <param name="geometry">The geometry to create a shape from.</param> /// <param name="featureType">Feature type of the shape range.</param> public Shape(IGeometry geometry, FeatureType featureType) { if (featureType == FeatureType.Unspecified) { switch (geometry.OgcGeometryType) { case OgcGeometryType.Point: featureType = FeatureType.Point; break; case OgcGeometryType.LineString: case OgcGeometryType.MultiLineString: featureType = FeatureType.Line; break; case OgcGeometryType.Polygon: case OgcGeometryType.MultiPolygon: featureType = FeatureType.Polygon; break; case OgcGeometryType.MultiPoint: featureType = FeatureType.MultiPoint; break; default: featureType = FeatureType.Unspecified; break; } } if (Equals(geometry, null)) throw new ArgumentNullException(nameof(geometry)); var coords = geometry.Coordinates; _vertices = new double[geometry.NumPoints * 2]; Z = new double[geometry.NumPoints]; M = new double[geometry.NumPoints]; for (var i = 0; i < coords.Length; i++) { var c = coords[i]; _vertices[i * 2] = c.X; _vertices[(i * 2) + 1] = c.Y; Z[i] = c.Z; M[i] = c.M; } Range = ShapeRangeFromGeometry(geometry, featureType, _vertices, 0); } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class. /// </summary> /// <param name="coord">Coordinate used for creating the point shape.</param> public Shape(Coordinate coord) { if (Equals(coord, null)) throw new ArgumentNullException(nameof(coord)); if (!double.IsNaN(coord.Z)) { Z = new[] { coord.Z }; } if (!double.IsNaN(coord.M)) { M = new[] { coord.M }; } Range = new ShapeRange(FeatureType.Point); _vertices = new[] { coord.X, coord.Y }; Range.Parts.Add( new PartRange(_vertices, 0, 0, FeatureType.Point) { NumVertices = 1 }); Range.Extent = new Extent(coord.X, coord.Y, coord.X, coord.Y); } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class. /// </summary> /// <param name="coord">Vertex that is used to create the point shape.</param> public Shape(Vertex coord) { Range = new ShapeRange(FeatureType.Point); _vertices = new[] { coord.X, coord.Y }; Range.Parts.Add( new PartRange(_vertices, 0, 0, FeatureType.Point) { NumVertices = 1 }); Range.Extent = new Extent(coord.X, coord.Y, coord.X, coord.Y); } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class that is a clockwise polygon. /// </summary> /// <param name="extent">Extent that is used to create the polygon shape.</param> public Shape(IExtent extent) { if (Equals(extent, null)) throw new ArgumentNullException(nameof(extent)); Range = new ShapeRange(FeatureType.Polygon); double xMin = extent.MinX; double yMin = extent.MinY; double xMax = extent.MaxX; double yMax = extent.MaxY; _vertices = new[] { xMin, yMax, xMax, yMax, xMax, yMin, xMin, yMin }; Range.Parts.Add( new PartRange(_vertices, 0, 0, FeatureType.Polygon) { NumVertices = 4 }); } /// <summary> /// Initializes a new instance of the <see cref="Shape"/> class that is a clockwise polygon. /// </summary> /// <param name="envelope">Envelope that is used to create the polygon shape.</param> public Shape(Envelope envelope) { if (Equals(envelope, null)) throw new ArgumentNullException(nameof(envelope)); Range = new ShapeRange(FeatureType.Polygon); double xMin = envelope.MinX; double yMin = envelope.MinY; double xMax = envelope.MaxX; double yMax = envelope.MaxY; _vertices = new[] { xMin, yMax, xMax, yMax, xMax, yMin, xMin, yMin }; Range.Parts.Add( new PartRange(_vertices, 0, 0, FeatureType.Polygon) { NumVertices = 4 }); } #endregion #region Properties /// <summary> /// Gets or sets the attributes. Since the most likely use is to copy values from one source to /// another, this should be an independant array in each shape and be deep-copied. /// </summary> public object[] Attributes { get; set; } /// <summary> /// Gets or sets the M values if any, organized in order. /// </summary> public double[] M { get; set; } /// <summary> /// Gets or sets the maximum M. /// </summary> public double MaxM { get; set; } /// <summary> /// Gets or sets the maximum Z. /// </summary> public double MaxZ { get; set; } /// <summary> /// Gets or sets the minimum M. /// </summary> public double MinM { get; set; } /// <summary> /// Gets or sets the minimum Z. /// </summary> public double MinZ { get; set; } /// <summary> /// Gets or sets the range. This gives a way to cycle through the vertices of this shape. /// </summary> public ShapeRange Range { get; set; } /// <summary> /// Gets or sets the double vertices in X1, Y1, X2, Y2, ..., Xn, Yn order. /// </summary> public double[] Vertices { get { return _vertices; } set { _vertices = value; foreach (PartRange part in Range.Parts) { part.Vertices = value; } } } /// <summary> /// Gets or sets the Z values if any. /// </summary> public double[] Z { get; set; } #endregion #region Methods /// <summary> /// Create a ShapeRange from a Feature to use in constructing a Shape. /// </summary> /// <param name="feature">Feature to use in constructing the shape.</param> /// <param name="vertices">The vertices of all the features.</param> /// <param name="offset">offset into vertices array where this feature starts</param> /// <returns>The shape range constructed from the given feature.</returns> public static ShapeRange ShapeRangeFromFeature(IFeature feature, double[] vertices, int offset) { return ShapeRangeFromGeometry(feature.Geometry, feature.FeatureType, vertices, offset); } /// <summary> /// Create a ShapeRange from a Feature to use in constructing a Shape. This assumes that vertices either contains only the vertices of this shape or this is the first shape. /// </summary> /// <param name="feature">Feature to use in constructing the shape.</param> /// <param name="vertices">The vertices of all the features.</param> /// <returns>The shape range constructed from the given feature.</returns> public static ShapeRange ShapeRangeFromFeature(IFeature feature, double[] vertices) { return ShapeRangeFromFeature(feature, vertices, 0); } /// <summary> /// Create a ShapeRange from a Geometry to use in constructing a Shape. /// </summary> /// <param name="geometry">The geometry used for constructing the shape.</param> /// <param name="featureType">The feature type of the shape.</param> /// <param name="vertices">The vertices of all the features.</param> /// <param name="offset">offset into vertices array where this feature starts</param> /// <returns>The shape range constructed from the given geometry.</returns> public static ShapeRange ShapeRangeFromGeometry(IGeometry geometry, FeatureType featureType, double[] vertices, int offset) { ShapeRange shx = new ShapeRange(featureType) { Extent = new Extent(geometry.EnvelopeInternal) }; int vIndex = offset / 2; int shapeStart = vIndex; for (int part = 0; part < geometry.NumGeometries; part++) { PartRange prtx = new PartRange(vertices, shapeStart, vIndex - shapeStart, featureType); IPolygon bp = geometry.GetGeometryN(part) as IPolygon; if (bp != null) { // Account for the Shell prtx.NumVertices = bp.Shell.NumPoints; vIndex += bp.Shell.NumPoints; // The part range should be adjusted to no longer include the holes foreach (var hole in bp.Holes) { PartRange holex = new PartRange(vertices, shapeStart, vIndex - shapeStart, featureType) { NumVertices = hole.NumPoints }; shx.Parts.Add(holex); vIndex += hole.NumPoints; } } else { int numPoints = geometry.GetGeometryN(part).NumPoints; // This is not a polygon, so just add the number of points. vIndex += numPoints; prtx.NumVertices = numPoints; } shx.Parts.Add(prtx); } return shx; } /// <summary> /// Without changing the feature type or anything else, simply update the local coordinates /// to include the new coordinates. All the new coordinates will be considered one part. /// Since point and multi-point shapes don't have parts, they will just be appended to the /// original part. /// </summary> /// <param name="coordinates">Coordinates that get added.</param> /// <param name="coordType">Coordinate type of the coordinates.</param> public void AddPart(IEnumerable<Coordinate> coordinates, CoordinateType coordType) { bool hasM = coordType == CoordinateType.M || coordType == CoordinateType.Z; bool hasZ = coordType == CoordinateType.Z; List<double> vertices = new List<double>(); List<double> z = new List<double>(); List<double> m = new List<double>(); int numPoints = 0; int oldNumPoints = _vertices?.Length / 2 ?? 0; foreach (Coordinate coordinate in coordinates) { if (Range.Extent == null) Range.Extent = new Extent(); Range.Extent.ExpandToInclude(coordinate.X, coordinate.Y); vertices.Add(coordinate.X); vertices.Add(coordinate.Y); if (hasM) m.Add(coordinate.M); if (hasZ) z.Add(coordinate.Z); numPoints++; } // Using public accessor also updates individual part references Vertices = _vertices?.Concat(vertices).ToArray() ?? vertices.ToArray(); if (hasZ) Z = Z?.Concat(z).ToArray() ?? z.ToArray(); if (hasM) M = M?.Concat(m).ToArray() ?? m.ToArray(); if (Range.FeatureType == FeatureType.MultiPoint || Range.FeatureType == FeatureType.Point) { // Only one part exists Range.Parts[0].NumVertices += numPoints; } else { PartRange part = new PartRange(_vertices, Range.StartIndex, oldNumPoints, Range.FeatureType) { NumVertices = numPoints }; Range.Parts.Add(part); } } /// <summary> /// This creates a duplicate shape, also copying the vertex array to /// a new array containing just this shape, as well as duplicating the attribute array. /// The FieldNames and FieldTypes are a shallow copy since this shouldn't change. /// </summary> /// <returns>The copy.</returns> public object Clone() { if (Range == null) return new Shape(); Shape copy = (Shape)MemberwiseClone(); int numPoints = Range.NumPoints; int start = Range.StartIndex; copy.Range = Range.Copy(); // Be sure to set vertex array AFTER the shape range to update part indices correctly. double[] verts = new double[numPoints * 2]; Array.Copy(_vertices, start, verts, 0, numPoints * 2); copy.Vertices = verts; if (Z != null && (Z.Length - start) >= numPoints) { copy.Z = new double[numPoints]; Array.Copy(Z, start, copy.Z, 0, numPoints); } if (M != null && (M.Length - start) >= numPoints) { copy.M = new double[numPoints]; Array.Copy(M, start, copy.M, 0, numPoints); } // Update the start-range to work like a stand-alone shape. copy.Range.StartIndex = 0; // Copy the attributes (handling the null case) if (Attributes == null) { copy.Attributes = null; } else { copy.Attributes = new object[Attributes.Length]; Array.Copy(Attributes, 0, copy.Attributes, 0, Attributes.Length); } return copy; } /// <summary> /// Copies the field names and types from the parent feature set if they are currently null. /// Attempts to copy the members of the feature's datarow. This assumes the features have been /// loaded into memory and are available on the feature's DataRow property. /// </summary> /// <param name="feature">An IFeature to copy the attributes from. If the schema is null, this will try to use the parent featureset schema.</param> public void CopyAttributes(IFeature feature) { object[] dr = feature.DataRow.ItemArray; Attributes = new object[dr.Length]; Array.Copy(dr, Attributes, dr.Length); } /// <summary> /// Converts this shape into a Geometry using the default factory. /// </summary> /// <returns>The geometry version of this shape.</returns> public IGeometry ToGeometry() { return ToGeometry(Geometry.DefaultFactory); } /// <summary> /// Converts this shape into a Geometry. /// </summary> /// <param name="factory">The geometry factory used for creating the geometry.</param> /// <returns>The geometry version of this shape.</returns> public IGeometry ToGeometry(IGeometryFactory factory) { if (Range.FeatureType == FeatureType.Polygon) { return FromPolygon(factory); } if (Range.FeatureType == FeatureType.Line) { return FromLine(factory); } if (Range.FeatureType == FeatureType.MultiPoint) { return FromMultiPoint(factory); } if (Range.FeatureType == FeatureType.Point) { return FromPoint(factory); } return null; } /// <summary> /// Converts this shape to a line geometry. /// </summary> /// <param name="factory">The geometry factory used for creating the geometry.</param> /// <returns>A LineString or MultiLineString geometry created from this shape.</returns> protected IGeometry FromLine(IGeometryFactory factory) { if (factory == null) factory = Geometry.DefaultFactory; var lines = new List<ILineString>(); foreach (var part in Range.Parts) { var coords = GetCoordinates(part); lines.Add(factory.CreateLineString(coords.ToArray())); } if (lines.Count == 1) return lines[0]; return factory.CreateMultiLineString(lines.ToArray()); } /// <summary> /// Creates a new MultiPoint geometry from a MultiPoint shape. /// </summary> /// <param name="factory">The IGeometryFactory to use to create the new shape.</param> /// <returns>The resulting multipoint.</returns> protected IGeometry FromMultiPoint(IGeometryFactory factory) { if (factory == null) factory = Geometry.DefaultFactory; var coords = new List<Coordinate>(); foreach (var part in Range.Parts) { GetCoordinates(part, coords); } return factory.CreateMultiPoint(coords.ToArray()); } /// <summary> /// Get the point for this shape if this is a point shape. /// </summary> /// <param name="factory">The geometry factory used for creating the geometry.</param> /// <returns>The resulting point geometry.</returns> protected IGeometry FromPoint(IGeometryFactory factory) { if (factory == null) factory = Geometry.DefaultFactory; foreach (PartRange part in Range.Parts) { foreach (Vertex vertex in part) { var c = new Coordinate(vertex.X, vertex.Y); return factory.CreatePoint(c); } } return null; } /// <summary> /// Creates a Polygon or MultiPolygon from this Polygon shape. /// </summary> /// <param name="factory">The IGeometryFactory to use to create the new IGeometry.</param> /// <returns>The IPolygon or IMultiPolygon created from this shape.</returns> protected IGeometry FromPolygon(IGeometryFactory factory) { if (factory == null) factory = Geometry.DefaultFactory; List<ILinearRing> shells = new List<ILinearRing>(); List<ILinearRing> holes = new List<ILinearRing>(); foreach (var part in Range.Parts) { var coords = GetCoordinates(part); var ring = factory.CreateLinearRing(coords.ToArray()); if (Range.Parts.Count == 1) { shells.Add(ring); } else { if (CGAlgorithms.IsCCW(ring.Coordinates)) { holes.Add(ring); } else { shells.Add(ring); } } } // Now we have a list of all shells and all holes List<ILinearRing>[] holesForShells = new List<ILinearRing>[shells.Count]; for (int i = 0; i < shells.Count; i++) { holesForShells[i] = new List<ILinearRing>(); } // Find holes foreach (ILinearRing t in holes) { ILinearRing testRing = t; ILinearRing minShell = null; Envelope minEnv = null; Envelope testEnv = testRing.EnvelopeInternal; Coordinate testPt = testRing.Coordinates[0]; for (int j = 0; j < shells.Count; j++) { ILinearRing tryRing = shells[j]; Envelope tryEnv = tryRing.EnvelopeInternal; if (minShell != null) minEnv = minShell.EnvelopeInternal; var isContained = tryEnv.Contains(testEnv) && (CGAlgorithms.IsPointInRing(testPt, tryRing.Coordinates) || PointInList(testPt, tryRing.Coordinates)); // Check if this new containing ring is smaller than the current minimum ring if (isContained) { if (minShell == null || minEnv.Contains(tryEnv)) { minShell = tryRing; } holesForShells[j].Add(t); } } } var polygons = new IPolygon[shells.Count]; for (int i = 0; i < shells.Count; i++) { polygons[i] = factory.CreatePolygon(shells[i], holesForShells[i].ToArray()); } if (polygons.Length == 1) { return polygons[0]; } // It's a multi part return factory.CreateMultiPolygon(polygons); } /// <summary> /// Test if a point is in a list of coordinates. /// </summary> /// <param name="testPoint">TestPoint the point to test for.</param> /// <param name="pointList">PointList the list of points to look through.</param> /// <returns>true if testPoint is a point in the pointList list.</returns> private static bool PointInList(Coordinate testPoint, IEnumerable<Coordinate> pointList) { return pointList.Any(p => p.Equals2D(testPoint)); } private List<Coordinate> GetCoordinates(VertexRange part, List<Coordinate> coords = null) { if (coords == null) { coords = new List<Coordinate>(); } int i = part.StartIndex; foreach (var d in part) { var c = new Coordinate(d.X, d.Y); if (M != null && M.Length > 0) c.M = M[i]; if (Z != null && Z.Length > 0) c.Z = Z[i]; i++; coords.Add(c); } return coords; } #endregion } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Runtime; using System.Xml; abstract class BufferedMessageData : IBufferedMessageData { ArraySegment<byte> buffer; BufferManager bufferManager; int refCount; int outstandingReaders; bool multipleUsers; RecycledMessageState messageState; SynchronizedPool<RecycledMessageState> messageStatePool; public BufferedMessageData(SynchronizedPool<RecycledMessageState> messageStatePool) { this.messageStatePool = messageStatePool; } public ArraySegment<byte> Buffer { get { return buffer; } } public BufferManager BufferManager { get { return bufferManager; } } public virtual XmlDictionaryReaderQuotas Quotas { get { return XmlDictionaryReaderQuotas.Max; } } public abstract MessageEncoder MessageEncoder { get; } object ThisLock { get { return this; } } public void EnableMultipleUsers() { multipleUsers = true; } public void Close() { if (multipleUsers) { lock (ThisLock) { if (--this.refCount == 0) { DoClose(); } } } else { DoClose(); } } void DoClose() { bufferManager.ReturnBuffer(buffer.Array); if (outstandingReaders == 0) { bufferManager = null; buffer = new ArraySegment<byte>(); OnClosed(); } } public void DoReturnMessageState(RecycledMessageState messageState) { if (this.messageState == null) { this.messageState = messageState; } else { messageStatePool.Return(messageState); } } void DoReturnXmlReader(XmlDictionaryReader reader) { ReturnXmlReader(reader); outstandingReaders--; } public RecycledMessageState DoTakeMessageState() { RecycledMessageState messageState = this.messageState; if (messageState != null) { this.messageState = null; return messageState; } else { return messageStatePool.Take(); } } XmlDictionaryReader DoTakeXmlReader() { XmlDictionaryReader reader = TakeXmlReader(); outstandingReaders++; return reader; } public XmlDictionaryReader GetMessageReader() { if (multipleUsers) { lock (ThisLock) { return DoTakeXmlReader(); } } else { return DoTakeXmlReader(); } } public void OnXmlReaderClosed(XmlDictionaryReader reader) { if (multipleUsers) { lock (ThisLock) { DoReturnXmlReader(reader); } } else { DoReturnXmlReader(reader); } } protected virtual void OnClosed() { } public RecycledMessageState TakeMessageState() { if (multipleUsers) { lock (ThisLock) { return DoTakeMessageState(); } } else { return DoTakeMessageState(); } } protected abstract XmlDictionaryReader TakeXmlReader(); public void Open() { lock (ThisLock) { this.refCount++; } } public void Open(ArraySegment<byte> buffer, BufferManager bufferManager) { this.refCount = 1; this.bufferManager = bufferManager; this.buffer = buffer; multipleUsers = false; } protected abstract void ReturnXmlReader(XmlDictionaryReader xmlReader); public void ReturnMessageState(RecycledMessageState messageState) { if (multipleUsers) { lock (ThisLock) { DoReturnMessageState(messageState); } } else { DoReturnMessageState(messageState); } } } }
//! \file GarCreate.cs //! \date Fri Jul 25 05:56:29 2014 //! \brief Create archive frontend. // // Copyright (C) 2014 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Input; using GameRes; using GARbro.GUI.Strings; using GARbro.GUI.Properties; namespace GARbro.GUI { public partial class MainWindow : Window { private void CreateArchiveExec (object sender, ExecutedRoutedEventArgs args) { StopWatchDirectoryChanges(); try { var archive_creator = new GarCreate (this); if (!archive_creator.Run()) ResumeWatchDirectoryChanges(); } catch (Exception X) { ResumeWatchDirectoryChanges(); PopupError (X.Message, guiStrings.TextCreateArchiveError); } } } internal class GarCreate : GarOperation { private string m_arc_name; private IList<Entry> m_file_list; private ArchiveFormat m_format; private ResourceOptions m_options; delegate void AddFilesEnumerator (IList<Entry> list, string path, DirectoryInfo path_info); public GarCreate (MainWindow parent) : base (parent, guiStrings.TextCreateArchiveError) { m_arc_name = Settings.Default.appLastCreatedArchive; } public bool Run () { Directory.SetCurrentDirectory (m_main.CurrentPath); var items = m_main.CurrentDirectory.SelectedItems.Cast<EntryViewModel> (); if (string.IsNullOrEmpty (m_arc_name)) { m_arc_name = Path.GetFileName (m_main.CurrentPath); if (!items.Skip (1).Any()) // items.Count() == 1 { var item = items.First(); if (item.IsDirectory) m_arc_name = Path.GetFileNameWithoutExtension (item.Name); } } var dialog = new CreateArchiveDialog (m_arc_name); dialog.Owner = m_main; if (!dialog.ShowDialog().Value) { return false; } if (string.IsNullOrEmpty (dialog.ArchiveName.Text)) { m_main.SetStatusText ("Archive name is empty"); return false; } m_format = dialog.ArchiveFormat.SelectedItem as ArchiveFormat; if (null == m_format) { m_main.SetStatusText ("Format is not selected"); return false; } m_options = dialog.ArchiveOptions; if (m_format.IsHierarchic) m_file_list = BuildFileList (items, AddFilesRecursive); else m_file_list = BuildFileList (items, AddFilesFromDir); m_arc_name = Path.GetFullPath (dialog.ArchiveName.Text); m_progress_dialog = new ProgressDialog () { WindowTitle = guiStrings.TextTitle, Text = string.Format (guiStrings.MsgCreatingArchive, Path.GetFileName (m_arc_name)), Description = "", MinimizeBox = true, }; m_progress_dialog.DoWork += CreateWorker; m_progress_dialog.RunWorkerCompleted += OnCreateComplete; m_progress_dialog.ShowDialog (m_main); return true; } private int m_total = 1; ArchiveOperation CreateEntryCallback (int i, Entry entry, string msg) { if (m_progress_dialog.CancellationPending) throw new OperationCanceledException(); if (null == entry && null == msg && 0 != i) { m_total = i; m_progress_dialog.ReportProgress (0); return ArchiveOperation.Continue; } int progress = i*100/m_total; if (progress > 100) progress = 100; string notice = msg; if (null != entry) { if (null != msg) notice = string.Format ("{0} {1}", msg, entry.Name); else notice = entry.Name; } m_progress_dialog.ReportProgress (progress, null, notice); return ArchiveOperation.Continue; } void CreateWorker (object sender, DoWorkEventArgs e) { m_pending_error = null; try { using (var tmp_file = new GARbro.Shell.TemporaryFile (Path.GetDirectoryName (m_arc_name), Path.GetRandomFileName ())) { m_total = m_file_list.Count() + 1; using (var file = File.Create (tmp_file.Name)) { m_format.Create (file, m_file_list, m_options, CreateEntryCallback); } if (!GARbro.Shell.File.Rename (tmp_file.Name, m_arc_name)) { throw new Win32Exception (GARbro.Shell.File.GetLastError()); } } } catch (Exception X) { m_pending_error = X; } } void OnCreateComplete (object sender, RunWorkerCompletedEventArgs e) { m_progress_dialog.Dispose(); m_main.Activate(); if (null == m_pending_error) { Settings.Default.appLastCreatedArchive = m_arc_name; m_main.Dispatcher.Invoke (() => { m_main.ChangePosition (new DirectoryPosition (m_arc_name)); }); } else { if (m_pending_error is OperationCanceledException) m_main.SetStatusText (m_pending_error.Message); else m_main.PopupError (m_pending_error.Message, guiStrings.TextCreateArchiveError); } } IList<Entry> BuildFileList (IEnumerable<EntryViewModel> files, AddFilesEnumerator add_files) { var list = new List<Entry>(); foreach (var entry in files) { if (entry.IsDirectory) { if (".." != entry.Name) { var dir = new DirectoryInfo (entry.Name); add_files (list, entry.Name, dir); } } else if (entry.Size < uint.MaxValue) { var e = new Entry { Name = entry.Name, Type = entry.Source.Type, Size = entry.Source.Size, }; list.Add (e); } } return list; } void AddFilesFromDir (IList<Entry> list, string path, DirectoryInfo dir) { foreach (var file in dir.EnumerateFiles()) { if (0 != (file.Attributes & (FileAttributes.Hidden | FileAttributes.System))) continue; if (file.Length >= uint.MaxValue) continue; string name = Path.Combine (path, file.Name); var e = FormatCatalog.Instance.Create<Entry> (name); e.Size = (uint)file.Length; list.Add (e); } } void AddFilesRecursive (IList<Entry> list, string path, DirectoryInfo info) { foreach (var dir in info.EnumerateDirectories()) { string subdir = Path.Combine (path, dir.Name); var subdir_info = new DirectoryInfo (subdir); AddFilesRecursive (list, subdir, subdir_info); } AddFilesFromDir (list, path, info); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using ScreenCasting.Controls; using ScreenCasting.Data.Azure; using ScreenCasting.Data.Common; using ScreenCasting.Util; using System; using Windows.ApplicationModel.Core; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; namespace ScreenCasting { public sealed partial class Scenario05 : Page { private MainPage rootPage; private DevicePicker picker; private VideoMetaData video = null; ProjectionViewBroker pvb = new ProjectionViewBroker(); DeviceInformation activeDevice = null; int thisViewId; public Scenario05() { this.InitializeComponent(); rootPage = MainPage.Current; //Subscribe to player events player.MediaOpened += Player_MediaOpened; player.MediaFailed += Player_MediaFailed; player.CurrentStateChanged += Player_CurrentStateChanged; // Get an Azure hosted video AzureDataProvider dataProvider = new AzureDataProvider(); video = dataProvider.GetRandomVideo(); //Set the source on the player rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage); this.player.Source = video.VideoLink; this.LicenseText.Text = "License: " + video.License; //Subscribe for the clicked event on the custom cast button ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked; // Instantiate the Device Picker picker = new DevicePicker (); // Get the device selecter for Miracast devices picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector()); //Hook up device selected event picker.DeviceSelected += Picker_DeviceSelected; //Hook up device disconnected event picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked; //Hook up picker dismissed event picker.DevicePickerDismissed += Picker_DevicePickerDismissed; // Hook up the events that are received when projection is stoppped pvb.ProjectionStopping += Pvb_ProjectionStopping; } private void TransportControls_CastButtonClicked(object sender, EventArgs e) { rootPage.NotifyUser("Custom Cast Button Clicked", NotifyType.StatusMessage); //Pause Current Playback player.Pause(); //Get the custom transport controls MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls; //Retrieve the location of the casting button GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement); Point pt = transform.TransformPoint(new Point(0, 0)); //Show the picker above our custom cast button picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above); } private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args) { //Casting must occur from the UI thread. This dispatches the casting calls to the UI thread. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { try { // Set status to Connecting picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress); // Getting the selected device improves debugging DeviceInformation selectedDevice = args.SelectedDevice; thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id; // If projection is already in progress, then it could be shown on the monitor again // Otherwise, we need to create a new view to show the presentation if (rootPage.ProjectionViewPageControl == null) { // First, create a new, blank view var thisDispatcher = Window.Current.Dispatcher; await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // ViewLifetimeControl is a wrapper to make sure the view is closed only // when the app is done with it rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView(); // Assemble some data necessary for the new page pvb.MainPageDispatcher = thisDispatcher; pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl; pvb.MainViewId = thisViewId; // Display the page in the view. Note that the view will not become visible // until "StartProjectingAsync" is called var rootFrame = new Frame(); rootFrame.Navigate(typeof(ProjectionViewPage), pvb); Window.Current.Content = rootFrame; Window.Current.Activate(); }); } try { // Start/StopViewInUse are used to signal that the app is interacting with the // view, so it shouldn't be closed yet, even if the user loses access to it rootPage.ProjectionViewPageControl.StartViewInUse(); try { await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, selectedDevice); } catch (Exception ex) { if (!ProjectionManager.ProjectionDisplayAvailable || pvb.ProjectedPage == null) throw ex; } // ProjectionManager currently can throw an exception even when projection has started.\ // Re-throw the exception when projection has not been started after calling StartProjectingAsync if (ProjectionManager.ProjectionDisplayAvailable && pvb.ProjectedPage != null) { this.player.Pause(); await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position); activeDevice = selectedDevice; // Set status to Connected picker.SetDisplayStatus(args.SelectedDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); picker.Hide(); } else { rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage); // Set status to Failed picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } } catch (Exception) { rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage); // Set status to Failed try { picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { } } } catch (Exception ex) { UnhandledExceptionPage.ShowUnhandledException(ex); } }); } private async void Picker_DevicePickerDismissed(DevicePicker sender, object args) { //Casting must occur from the UI thread. This dispatches the casting calls to the UI thread. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (activeDevice == null) { player.Play(); } }); } private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args) { //Casting must occur from the UI thread. This dispatches the casting calls to the UI thread. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage); //Update the display status for the selected device. sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress); if (this.pvb.ProjectedPage != null) this.pvb.ProjectedPage.StopProjecting(); //Update the display status for the selected device. sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); rootPage.NotifyUser("Disconnected", NotifyType.StatusMessage); // Set the active device variables to null activeDevice = null; }); } private async void Pvb_ProjectionStopping(object sender, EventArgs e) { ProjectionViewBroker broker = sender as ProjectionViewBroker; TimeSpan position = broker.ProjectedPage.Player.Position; Uri source = broker.ProjectedPage.Player.Source; await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Resuming playback on the first screen", NotifyType.StatusMessage); this.player.Source = source; this.player.Position = position; this.player.Play(); rootPage.ProjectionViewPageControl = null; }); } #region MediaElement Status Methods private void Player_CurrentStateChanged(object sender, RoutedEventArgs e) { // Update status rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage); } private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e) { rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage); } private void Player_MediaOpened(object sender, RoutedEventArgs e) { rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage); player.Play(); } #endregion protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } } }
// 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.Reflection; using System.Runtime.InteropServices; using System.Diagnostics; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// Holds property values of any type. For common value types, we have inline storage so that we don't need /// to box the values. For all other types, we store the value in a single object reference field. /// /// To get the value of a property quickly, use a delegate produced by <see cref="PropertyValue.GetPropertyGetter(PropertyInfo)"/>. /// </summary> #if ES_BUILD_PN [CLSCompliant(false)] public #else internal #endif unsafe readonly struct PropertyValue { /// <summary> /// Union of well-known value types, to avoid boxing those types. /// </summary> [StructLayout(LayoutKind.Explicit)] public struct Scalar { [FieldOffset(0)] public Boolean AsBoolean; [FieldOffset(0)] public Byte AsByte; [FieldOffset(0)] public SByte AsSByte; [FieldOffset(0)] public Char AsChar; [FieldOffset(0)] public Int16 AsInt16; [FieldOffset(0)] public UInt16 AsUInt16; [FieldOffset(0)] public Int32 AsInt32; [FieldOffset(0)] public UInt32 AsUInt32; [FieldOffset(0)] public Int64 AsInt64; [FieldOffset(0)] public UInt64 AsUInt64; [FieldOffset(0)] public IntPtr AsIntPtr; [FieldOffset(0)] public UIntPtr AsUIntPtr; [FieldOffset(0)] public Single AsSingle; [FieldOffset(0)] public Double AsDouble; [FieldOffset(0)] public Guid AsGuid; [FieldOffset(0)] public DateTime AsDateTime; [FieldOffset(0)] public DateTimeOffset AsDateTimeOffset; [FieldOffset(0)] public TimeSpan AsTimeSpan; [FieldOffset(0)] public Decimal AsDecimal; } // Anything not covered by the Scalar union gets stored in this reference. readonly object _reference; readonly Scalar _scalar; readonly int _scalarLength; private PropertyValue(object value) { _reference = value; _scalar = default(Scalar); _scalarLength = 0; } private PropertyValue(Scalar scalar, int scalarLength) { _reference = null; _scalar = scalar; _scalarLength = scalarLength; } private PropertyValue(Boolean value) : this(new Scalar() { AsBoolean = value }, sizeof(Boolean)) { } private PropertyValue(Byte value) : this(new Scalar() { AsByte = value }, sizeof(Byte)) { } private PropertyValue(SByte value) : this(new Scalar() { AsSByte = value }, sizeof(SByte)) { } private PropertyValue(Char value) : this(new Scalar() { AsChar = value }, sizeof(Char)) { } private PropertyValue(Int16 value) : this(new Scalar() { AsInt16 = value }, sizeof(Int16)) { } private PropertyValue(UInt16 value) : this(new Scalar() { AsUInt16 = value }, sizeof(UInt16)) { } private PropertyValue(Int32 value) : this(new Scalar() { AsInt32 = value }, sizeof(Int32)) { } private PropertyValue(UInt32 value) : this(new Scalar() { AsUInt32 = value }, sizeof(UInt32)) { } private PropertyValue(Int64 value) : this(new Scalar() { AsInt64 = value }, sizeof(Int64)) { } private PropertyValue(UInt64 value) : this(new Scalar() { AsUInt64 = value }, sizeof(UInt64)) { } private PropertyValue(IntPtr value) : this(new Scalar() { AsIntPtr = value }, sizeof(IntPtr)) { } private PropertyValue(UIntPtr value) : this(new Scalar() { AsUIntPtr = value }, sizeof(UIntPtr)) { } private PropertyValue(Single value) : this(new Scalar() { AsSingle = value }, sizeof(Single)) { } private PropertyValue(Double value) : this(new Scalar() { AsDouble = value }, sizeof(Double)) { } private PropertyValue(Guid value) : this(new Scalar() { AsGuid = value }, sizeof(Guid)) { } private PropertyValue(DateTime value) : this(new Scalar() { AsDateTime = value }, sizeof(DateTime)) { } private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffset = value }, sizeof(DateTimeOffset)) { } private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { } private PropertyValue(Decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(Decimal)) { } public static Func<object, PropertyValue> GetFactory(Type type) { if (type == typeof(Boolean)) return value => new PropertyValue((Boolean)value); if (type == typeof(Byte)) return value => new PropertyValue((Byte)value); if (type == typeof(SByte)) return value => new PropertyValue((SByte)value); if (type == typeof(Char)) return value => new PropertyValue((Char)value); if (type == typeof(Int16)) return value => new PropertyValue((Int16)value); if (type == typeof(UInt16)) return value => new PropertyValue((UInt16)value); if (type == typeof(Int32)) return value => new PropertyValue((Int32)value); if (type == typeof(UInt32)) return value => new PropertyValue((UInt32)value); if (type == typeof(Int64)) return value => new PropertyValue((Int64)value); if (type == typeof(UInt64)) return value => new PropertyValue((UInt64)value); if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value); if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value); if (type == typeof(Single)) return value => new PropertyValue((Single)value); if (type == typeof(Double)) return value => new PropertyValue((Double)value); if (type == typeof(Guid)) return value => new PropertyValue((Guid)value); if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value); if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value); if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value); if (type == typeof(Decimal)) return value => new PropertyValue((Decimal)value); return value => new PropertyValue(value); } public object ReferenceValue { get { Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type."); return _reference; } } public Scalar ScalarValue { get { Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalar; } } public int ScalarLength { get { Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type"); return _scalarLength; } } /// <summary> /// Gets a delegate that gets the value of a given property. /// </summary> public static Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property) { if (property.DeclaringType.GetTypeInfo().IsValueType) return GetBoxedValueTypePropertyGetter(property); else return GetReferenceTypePropertyGetter(property); } /// <summary> /// Gets a delegate that gets the value of a property of a value type. We unfortunately cannot avoid boxing the value type, /// without making this generic over the value type. That would result in a large number of generic instantiations, and furthermore /// does not work correctly on .Net Native (we cannot express the needed instantiations in an rd.xml file). We expect that user-defined /// value types will be rare, and in any case the boxing only happens for events that are actually enabled. /// </summary> private static Func<PropertyValue, PropertyValue> GetBoxedValueTypePropertyGetter(PropertyInfo property) { var type = property.PropertyType; if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); var factory = GetFactory(type); return container => factory(property.GetValue(container.ReferenceValue)); } /// <summary> /// For properties of reference types, we use a generic helper class to get the value. This enables us to use MethodInfo.CreateDelegate /// to build a fast getter. We can get away with this on .Net Native, because we really only need one runtime instantiation of the /// generic type, since it's only instantiated over reference types (and thus all instances are shared). /// </summary> /// <param name="property"></param> /// <returns></returns> private static Func<PropertyValue, PropertyValue> GetReferenceTypePropertyGetter(PropertyInfo property) { var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType)); return helper.GetPropertyGetter(property); } #if ES_BUILD_PN public #else private #endif abstract class TypeHelper { public abstract Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property); protected Delegate GetGetMethod(PropertyInfo property, Type propertyType) { return property.GetMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType, propertyType)); } } #if ES_BUILD_PN public #else private #endif sealed class ReferenceTypeHelper<TContainer> : TypeHelper where TContainer : class { public override Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property) { var type = property.PropertyType; if (!Statics.IsValueType(type)) { var getter = (Func<TContainer, object>)GetGetMethod(property, type); return container => new PropertyValue(getter((TContainer)container.ReferenceValue)); } else { if (type.GetTypeInfo().IsEnum) type = Enum.GetUnderlyingType(type); if (type == typeof(Boolean)) { var f = (Func<TContainer, Boolean>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Byte)) { var f = (Func<TContainer, Byte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(SByte)) { var f = (Func<TContainer, SByte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Char)) { var f = (Func<TContainer, Char>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Int16)) { var f = (Func<TContainer, Int16>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UInt16)) { var f = (Func<TContainer, UInt16>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Int32)) { var f = (Func<TContainer, Int32>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UInt32)) { var f = (Func<TContainer, UInt32>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Int64)) { var f = (Func<TContainer, Int64>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UInt64)) { var f = (Func<TContainer, UInt64>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(IntPtr)) { var f = (Func<TContainer, IntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(UIntPtr)) { var f = (Func<TContainer, UIntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Single)) { var f = (Func<TContainer, Single>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Double)) { var f = (Func<TContainer, Double>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Guid)) { var f = (Func<TContainer, Guid>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTime)) { var f = (Func<TContainer, DateTime>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(DateTimeOffset)) { var f = (Func<TContainer, DateTimeOffset>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(TimeSpan)) { var f = (Func<TContainer, TimeSpan>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } if (type == typeof(Decimal)) { var f = (Func<TContainer, Decimal>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); } return container => new PropertyValue(property.GetValue(container.ReferenceValue)); } } } } }
#region File Description //----------------------------------------------------------------------------- // BasicEffectShape.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using System.Diagnostics; #endregion namespace Spacewar { /// <summary> /// The shapes that this class can draw /// </summary> public enum BasicEffectShapes { /// <summary> /// Ship models used ingame and in selection screen /// </summary> Ship, /// <summary> /// Asteroid models /// </summary> Asteroid, /// <summary> /// Projectile models /// </summary> Projectile, /// <summary> /// Weapon models for the selection screen /// </summary> Weapon, } /// <summary> /// BasicEffect shapes represent the 3d models used by the evolved variation of the game. These shapes come through the Content Pipeline. /// They are all lit using the BasicEffect Shader and have similar input and construction methods /// </summary> class BasicEffectShape : Shape { //Materials private static Color white = Color.White; private static Color body = white; //body has texture so don't need material private static Color pipes = white; //pipes has texture so don't need material private static Color cockpit1 = new Color((byte)(.529f * 255), 255, 255, 0); private static Color cockpit2 = new Color(255, 255, (byte)(.373f * 255), 0); private static Color engines = new Color((byte)(.925f * 255), (byte)(.529f * 255), 255, 0); private Texture2D texture; private int skinNumber; private int shapeNumber; private BasicEffectShapes shape = BasicEffectShapes.Projectile; private PlayerIndex player; private Model model; //New content Pipeline Mesh private bool deviceCreated; string[] modelNames = null; string[] textureNames = null; private int scene; //0 is in game 1 is selection screens private Color[] material; private static Vector3 SunPosition = new Vector3(-0.5f, -0.5f, 100.0f); #region filenames private static string[,] shipMesh = new string[,] { { @"models\pencil_player1", @"models\saucer_player1", @"models\wedge_player1", }, { @"models\pencil_player2", @"models\saucer_player2", @"models\wedge_player2", } }; private static string[,] shipDiffuse = new string[,] { { @"textures\pencil_p1_diff_v{0}", @"textures\saucer_p1_diff_v{0}", @"textures\wedge_p1_diff_v{0}", }, { @"textures\pencil_p2_diff_v{0}", @"textures\saucer_p2_diff_v{0}", @"textures\wedge_p2_diff_v{0}", } }; private static string[,] shipNormal = new String[,] { { @"textures\pencil_p1_norm_1", @"textures\saucer_p1_norm_1", @"textures\wedge_p1_norm_1", }, { @"textures\pencil_p2_norm_1", @"textures\saucer_p2_norm_1", @"textures\wedge_p2_norm_1", } }; private static string[,] shipReflection = new String[,] { { @"textures\p1_reflection_cubemap", "", }, { @"textures\p2_reflection_cubemap1", @"textures\p2_reflection_cubemap2", } }; private static string[] projectileMeshes = new String[] { @"models\pea_proj", @"models\mgun_proj", @"models\mgun_proj", @"models\p1_rocket_proj", @"models\bfg_proj", }; private static string[] projectileDiffuse = new String[] { @"textures\pea_proj", @"textures\pea_proj", @"textures\mgun_proj", @"textures\rocket_proj", @"textures\bfg_proj", }; private static string[] asteroidMeshes = new String[] { @"models\asteroid1", @"models\asteroid2", }; private static string[] asteroidDiffuse = new String[] { @"textures\asteroid1", @"textures\asteroid2", }; private static string[][] weaponMeshes = new String[][] { new string[] { @"models\p1_pea", @"models\p1_mgun", @"models\p1_dual", @"models\p1_rocket", @"models\p1_bfg", }, new string[] { @"models\p2_pea", @"models\p2_mgun", @"models\p2_dual", @"models\p2_rocket", @"models\p2_bfg", } }; private static string[,][] weaponDiffuse = new String[,][] { { new string[] { @"textures\p1_back" // Used by p1_pea }, new string[] { @"textures\p1_back", @"textures\p1_dual" //Used by p1_mgun }, new string[] { @"textures\p1_dual", @"textures\p1_back" //Used by p1_dual }, new string[] { @"textures\p1_back", @"textures\p1_rocket" //Used by p1_rocket }, new string[] { @"textures\p1_bfg", "", @"textures\p1_back" //Used by the p1_bfg } }, { new string[] { @"textures\p2_back", @"textures\p2_back" // Used by p2_pea }, new string[] { @"textures\p2_back", @"textures\p2_back", @"textures\p2_dual" // Used by p2_mgun }, new string[] { @"textures\p2_back", @"textures\p2_back", @"textures\p2_dual" // Used by p2_dual }, new string[] { @"textures\p2_rocket", @"textures\p2_back", @"textures\p2_back" // Used by p2_rocket }, new string[] { @"textures\p2_back", @"textures\p2_back", @"textures\p2_bfg", @"textures\p2_back" // Used by p2_bfg } } }; private Color[,][] shipMaterials = new Color[,][] { { //player 1 ships new Color[] {body, engines, cockpit1, cockpit1}, new Color[] {body, cockpit1, engines}, new Color[] {body, cockpit1, engines}, }, { //player 2 ships new Color[] {cockpit2, pipes, body}, new Color[] {pipes, body, cockpit2}, new Color[] {pipes, cockpit2, body}, } }; private bool[,][] shipUsesReflection2 = new bool[,][] { { //player 1 ships - always use 1st reflection map new bool[] {false, false, false, false}, new bool[] {false, false, false}, new bool[] {false, false, false}, }, { //player 2 ships new bool[] {true, true, false}, new bool[] {true, false, true}, new bool[] {true, true, false}, } }; #endregion public BasicEffectShape(Game game, BasicEffectShapes shape, PlayerIndex player, int shipNumber, int skinNumber, LightingType scene) : base(game) { Debug.Assert(shape == BasicEffectShapes.Ship, "Constructor should only be called with Ship"); this.shape = shape; this.shapeNumber = shipNumber; this.skinNumber = skinNumber; this.player = player; this.scene = (int)scene; CreateShip(); } public BasicEffectShape(Game game, BasicEffectShapes shape, PlayerIndex player, int shapeNumber, LightingType scene) : base(game) { Debug.Assert(shape == BasicEffectShapes.Weapon, "Constructor should only be called with Weapon"); this.player = player; this.shape = shape; this.shapeNumber = shapeNumber; this.scene = (int)scene; CreateShape(); } public BasicEffectShape(Game game, BasicEffectShapes shape, int shapeNumber, LightingType scene) : base(game) { this.shape = shape; this.shapeNumber = shapeNumber; this.scene = (int)scene; CreateShape(); } public override void Create() { //Load the correct shader and set up the parameters OnCreateDevice(); } public override void OnCreateDevice() { deviceCreated = true; } public void CreateShip() { //Model model = SpacewarGame.ContentManager.Load<Model>(SpacewarGame.Settings.MediaPath + shipMesh[(int)player, shapeNumber]); //Matching Textures texture = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + String.Format(shipDiffuse[(int)player, shapeNumber], (skinNumber + 1))); //Point to the right material array for this ship material = shipMaterials[(int)player, shapeNumber]; SetupEffect(); } public void CreateShape() { switch (shape) { case BasicEffectShapes.Projectile: modelNames = projectileMeshes; textureNames = projectileDiffuse; break; case BasicEffectShapes.Asteroid: modelNames = asteroidMeshes; textureNames = asteroidDiffuse; break; case BasicEffectShapes.Weapon: modelNames = weaponMeshes[(int)player]; textureNames = weaponDiffuse[(int)player, shapeNumber]; break; default: //Should never get here Debug.Assert(true, "EvolvedShape:CreateShape - bad EvolvedShape passed in"); break; } //Model model = SpacewarGame.ContentManager.Load<Model>(SpacewarGame.Settings.MediaPath + modelNames[shapeNumber]); //Matching Textures if (shape == BasicEffectShapes.Asteroid || shape == BasicEffectShapes.Projectile) texture = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + textureNames[shapeNumber]); SetupEffect(); } private void SetupEffect() { int i = 0; foreach (ModelMesh modelMesh in model.Meshes) { foreach (BasicEffect effect in modelMesh.Effects) { //State effect.Alpha = 1.0f; effect.SpecularPower = 200.0f; effect.AmbientLightColor = new Vector3(0.15f, 0.15f, 0.15f); //Lighting effect.LightingEnabled = true; effect.DirectionalLight0.Enabled = true; effect.DirectionalLight0.DiffuseColor = new Vector3(SpacewarGame.Settings.ShipLights[scene].DirectionalColor.X, SpacewarGame.Settings.ShipLights[scene].DirectionalColor.Y, SpacewarGame.Settings.ShipLights[scene].DirectionalColor.Z); effect.DirectionalLight0.SpecularColor = new Vector3(0.1f, 0.1f, 0.1f); effect.DirectionalLight0.Direction = Vector3.Normalize(new Vector3(SpacewarGame.Settings.ShipLights[scene].DirectionalDirection.X, SpacewarGame.Settings.ShipLights[scene].DirectionalDirection.Y, SpacewarGame.Settings.ShipLights[scene].DirectionalDirection.Z)); effect.DirectionalLight1.Enabled = true; effect.DirectionalLight1.DiffuseColor = new Vector3(SpacewarGame.Settings.ShipLights[scene].PointColor.X, SpacewarGame.Settings.ShipLights[scene].PointColor.Y, SpacewarGame.Settings.ShipLights[scene].PointColor.Z); effect.DirectionalLight1.SpecularColor = new Vector3(0.1f, 0.1f, 0.1f); if (shape == BasicEffectShapes.Weapon) { if (string.IsNullOrEmpty(textureNames[i])) { texture = null; } else { texture = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + textureNames[i]); } } effect.Texture = texture; if (shape == BasicEffectShapes.Ship) { //Ships have materials and reflection maps effect.SpecularColor = effect.DiffuseColor = new Vector3(material[i].R / 255.0f, material[i].G / 255.0f, material[i].B / 255.0f); if (material[i] == Color.White) { effect.TextureEnabled = true; } else { effect.TextureEnabled = false; } } else { //Material is white effect.SpecularColor = effect.DiffuseColor = Vector3.One; effect.TextureEnabled = true; } } } } public override void Render() { base.Render(); IGraphicsDeviceService graphicsService = (IGraphicsDeviceService)GameInstance.Services.GetService(typeof(IGraphicsDeviceService)); graphicsService.GraphicsDevice.BlendState = BlendState.Opaque; graphicsService.GraphicsDevice.DepthStencilState = DepthStencilState.Default; if (shape == BasicEffectShapes.Ship) { //Model model = SpacewarGame.ContentManager.Load<Model>(SpacewarGame.Settings.MediaPath + shipMesh[(int)player, shapeNumber]); //Matching Textures texture = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + String.Format(shipDiffuse[(int)player, shapeNumber], (skinNumber + 1))); } else { //Model model = SpacewarGame.ContentManager.Load<Model>(SpacewarGame.Settings.MediaPath + modelNames[shapeNumber]); //Matching Textures if (shape == BasicEffectShapes.Asteroid || shape == BasicEffectShapes.Projectile) texture = SpacewarGame.ContentManager.Load<Texture2D>(SpacewarGame.Settings.MediaPath + textureNames[shapeNumber]); } if (deviceCreated) { SetupEffect(); deviceCreated = false; } foreach (ModelMesh modelMesh in model.Meshes) { foreach (BasicEffect effect in modelMesh.Effects) { //Transform effect.View = SpacewarGame.Camera.View; effect.Projection = SpacewarGame.Camera.Projection; effect.World = World; effect.Texture = texture; // "fake" a point light by shining the directional light from the sun on the shape. Vector3 direction = Position - SunPosition; direction.Normalize(); effect.DirectionalLight1.Direction = direction; } modelMesh.Draw(); } } /// <summary> /// Preloads all the in game meshes and textures /// </summary> public static void Preload() { } } }
/* ==================================================================== 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 TestCases.HSSF.UserModel { using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NUnit.Framework; using TestCases.HSSF; using TestCases.SS.UserModel; using System; using TestCases.HSSF.Model; using NPOI.HSSF.Record; using NPOI.DDF; using NPOI.Util; using NPOI.HSSF.Model; /** * Tests TestHSSFCellComment. * * @author Yegor Kozlov */ [TestFixture] public class TestHSSFComment:BaseTestCellComment { public TestHSSFComment(): base(HSSFITestDataProvider.Instance) { } [Test] public void DefaultShapeType() { HSSFComment comment = new HSSFComment((HSSFShape)null, new HSSFClientAnchor()); Assert.AreEqual(HSSFSimpleShape.OBJECT_TYPE_COMMENT, comment.ShapeType); } /** * HSSFCell#findCellComment should NOT rely on the order of records * when matching cells and their cell comments. The correct algorithm is to map */ [Test] public void Bug47924() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("47924.xls"); ISheet sheet = wb.GetSheetAt(0); ICell cell; IComment comment; cell = sheet.GetRow(0).GetCell(0); comment = cell.CellComment; Assert.AreEqual("a1", comment.String.String); cell = sheet.GetRow(1).GetCell(0); comment = cell.CellComment; Assert.AreEqual("a2", comment.String.String); cell = sheet.GetRow(2).GetCell(0); comment = cell.CellComment; Assert.AreEqual("a3", comment.String.String); cell = sheet.GetRow(2).GetCell(2); comment = cell.CellComment; Assert.AreEqual("c3", comment.String.String); cell = sheet.GetRow(4).GetCell(1); comment = cell.CellComment; Assert.AreEqual("b5", comment.String.String); cell = sheet.GetRow(5).GetCell(2); comment = cell.CellComment; Assert.AreEqual("c6", comment.String.String); wb.Close(); } [Test] public void TestBug56380InsertComments() { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); IDrawing drawing = sheet.CreateDrawingPatriarch(); int noOfRows = 1025; String comment = "c"; for (int i = 0; i < noOfRows; i++) { IRow row = sheet.CreateRow(i); ICell cell = row.CreateCell(0); insertComment(drawing, cell, comment + i); } // assert that the comments are Created properly before writing CheckComments(sheet, noOfRows, comment); /*// store in temp-file OutputStream fs = new FileOutputStream("/tmp/56380.xls"); try { sheet.Workbook.Write(fs); } finally { fs.Close(); }*/ // save and recreate the workbook from the saved file HSSFWorkbook workbookBack = HSSFTestDataSamples.WriteOutAndReadBack(workbook); sheet = workbookBack.GetSheetAt(0); // assert that the comments are Created properly After Reading back in CheckComments(sheet, noOfRows, comment); workbook.Close(); workbookBack.Close(); } [Test] public void TestBug56380InsertTooManyComments() { HSSFWorkbook workbook = new HSSFWorkbook(); try { ISheet sheet = workbook.CreateSheet(); IDrawing drawing = sheet.CreateDrawingPatriarch(); String comment = "c"; for (int rowNum = 0; rowNum < 258; rowNum++) { sheet.CreateRow(rowNum); } // should still work, for some reason DrawingManager2.AllocateShapeId() skips the first 1024... for (int count = 1025; count < 65535; count++) { int rowNum = count / 255; int cellNum = count % 255; ICell cell = sheet.GetRow(rowNum).CreateCell(cellNum); try { IComment commentObj = insertComment(drawing, cell, comment + cellNum); Assert.AreEqual(count, ((HSSFComment)commentObj).NoteRecord.ShapeId); } catch (ArgumentException e) { throw new ArgumentException("While Adding shape number " + count, e); } } // this should now fail to insert IRow row = sheet.CreateRow(257); ICell cell2 = row.CreateCell(0); insertComment(drawing, cell2, comment + 0); } finally { workbook.Close(); } } private void CheckComments(ISheet sheet, int noOfRows, String comment) { for (int i = 0; i < noOfRows; i++) { Assert.IsNotNull(sheet.GetRow(i)); Assert.IsNotNull(sheet.GetRow(i).GetCell(0)); Assert.IsNotNull(sheet.GetRow(i).GetCell(0).CellComment, "Did not Get a Cell Comment for row " + i); Assert.IsNotNull(sheet.GetRow(i).GetCell(0).CellComment.String); Assert.AreEqual(comment + i, sheet.GetRow(i).GetCell(0).CellComment.String.String); } } private IComment insertComment(IDrawing Drawing, ICell cell, String message) { ICreationHelper factory = cell.Sheet.Workbook.GetCreationHelper(); IClientAnchor anchor = factory.CreateClientAnchor(); anchor.Col1 = (/*setter*/cell.ColumnIndex); anchor.Col2 = (/*setter*/cell.ColumnIndex + 1); anchor.Row1 = (/*setter*/cell.RowIndex); anchor.Row2 = (/*setter*/cell.RowIndex + 1); anchor.Dx1 = (/*setter*/100); anchor.Dx2 = (/*setter*/100); anchor.Dy1 = (/*setter*/100); anchor.Dy2 = (/*setter*/100); IComment comment = Drawing.CreateCellComment(anchor); IRichTextString str = factory.CreateRichTextString(message); comment.String = (/*setter*/str); comment.Author = (/*setter*/"fanfy"); cell.CellComment = (/*setter*/comment); return comment; } [Test] public void ResultEqualsToNonExistingAbstractShape() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet() as HSSFSheet; HSSFPatriarch patriarch = sh.CreateDrawingPatriarch() as HSSFPatriarch; HSSFComment comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; HSSFRow row = sh.CreateRow(0) as HSSFRow; HSSFCell cell = row.CreateCell(0) as HSSFCell; cell.CellComment = (comment); Assert.AreEqual(comment.GetEscherContainer().ChildRecords.Count, 5); //sp record byte[] expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAAFvEw/WBg4GBgZEFSHAxMAAA9gX7nhAAAAA="); byte[] actual = comment.GetEscherContainer().GetChild(0).Serialize(); Assert.AreEqual(expected.Length, actual.Length); Assert.IsTrue(Arrays.Equals(expected, actual)); expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAAGNgEPggxIANAABK4+laGgAAAA=="); actual = comment.GetEscherContainer().GetChild(2).Serialize(); Assert.AreEqual(expected.Length, actual.Length); Assert.IsTrue(Arrays.Equals(expected, actual)); expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAAGNgEPzAAAQACl6c5QgAAAA="); actual = comment.GetEscherContainer().GetChild(3).Serialize(); Assert.AreEqual(expected.Length, actual.Length); Assert.IsTrue(Arrays.Equals(expected, actual)); expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAAGNg4P3AAAQA6pyIkQgAAAA="); actual = comment.GetEscherContainer().GetChild(4).Serialize(); Assert.AreEqual(expected.Length, actual.Length); Assert.IsTrue(Arrays.Equals(expected, actual)); ObjRecord obj = comment.GetObjRecord(); expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAAItlMGEQZRBikGRgZBF0YEACvAxiDLgBAJZsuoU4AAAA"); actual = obj.Serialize(); Assert.AreEqual(expected.Length, actual.Length); //assertArrayEquals(expected, actual); TextObjectRecord tor = comment.GetTextObjectRecord(); expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAANvGKMQgxMSABgBGi8T+FgAAAA=="); actual = tor.Serialize(); Assert.AreEqual(expected.Length, actual.Length); Assert.IsTrue(Arrays.Equals(expected, actual)); NoteRecord note = comment.NoteRecord; expected = TestDrawingAggregate.decompress("H4sIAAAAAAAAAJNh4GGAAEYWEAkAS0KXuRAAAAA="); actual = note.Serialize(); Assert.AreEqual(expected.Length, actual.Length); Assert.IsTrue(Arrays.Equals(expected, actual)); wb.Close(); } [Test] public void AddToExistingFile() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet() as HSSFSheet; HSSFPatriarch patriarch = sh.CreateDrawingPatriarch() as HSSFPatriarch; int idx = wb.AddPicture(new byte[] { 1, 2, 3 }, PictureType.PNG); HSSFComment comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; comment.Column = (5); comment.String = new HSSFRichTextString("comment1"); comment = patriarch.CreateCellComment(new HSSFClientAnchor(0, 0, 100, 100, (short)0, 0, (short)10, 10)) as HSSFComment; comment.Row = (5); comment.String = new HSSFRichTextString("comment2"); comment.SetBackgroundImage(idx); Assert.AreEqual(comment.GetBackgroundImageId(), idx); Assert.AreEqual(patriarch.Children.Count, 2); HSSFWorkbook wbBack = HSSFTestDataSamples.WriteOutAndReadBack(wb); sh = wbBack.GetSheetAt(0) as HSSFSheet; patriarch = sh.DrawingPatriarch as HSSFPatriarch; comment = (HSSFComment)patriarch.Children[(1)]; Assert.AreEqual(comment.GetBackgroundImageId(), idx); comment.ResetBackgroundImage(); Assert.AreEqual(comment.GetBackgroundImageId(), 0); Assert.AreEqual(patriarch.Children.Count, 2); comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; comment.String = new HSSFRichTextString("comment3"); Assert.AreEqual(patriarch.Children.Count, 3); HSSFWorkbook wbBack2 = HSSFTestDataSamples.WriteOutAndReadBack(wbBack); sh = wbBack2.GetSheetAt(0) as HSSFSheet; patriarch = sh.DrawingPatriarch as HSSFPatriarch; comment = (HSSFComment)patriarch.Children[1]; Assert.AreEqual(comment.GetBackgroundImageId(), 0); Assert.AreEqual(patriarch.Children.Count, 3); Assert.AreEqual(((HSSFComment)patriarch.Children[0]).String.String, "comment1"); Assert.AreEqual(((HSSFComment)patriarch.Children[1]).String.String, "comment2"); Assert.AreEqual(((HSSFComment)patriarch.Children[2]).String.String, "comment3"); wb.Close(); wbBack.Close(); wbBack2.Close(); } [Test] public void SetGetProperties() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet() as HSSFSheet; HSSFPatriarch patriarch = sh.CreateDrawingPatriarch() as HSSFPatriarch; HSSFComment comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; comment.String = new HSSFRichTextString("comment1"); Assert.AreEqual(comment.String.String, "comment1"); comment.Author = ("poi"); Assert.AreEqual(comment.Author, "poi"); comment.Column = (3); Assert.AreEqual(comment.Column, 3); comment.Row = (4); Assert.AreEqual(comment.Row, 4); comment.Visible = (false); Assert.AreEqual(comment.Visible, false); HSSFWorkbook wbBack = HSSFTestDataSamples.WriteOutAndReadBack(wb); sh = wbBack.GetSheetAt(0) as HSSFSheet; patriarch = sh.DrawingPatriarch as HSSFPatriarch; comment = (HSSFComment)patriarch.Children[0]; Assert.AreEqual(comment.String.String, "comment1"); Assert.AreEqual("poi", comment.Author); Assert.AreEqual(comment.Column, 3); Assert.AreEqual(comment.Row, 4); Assert.AreEqual(comment.Visible, false); comment.String = new HSSFRichTextString("comment12"); comment.Author = ("poi2"); comment.Column = (32); comment.Row = (42); comment.Visible = (true); HSSFWorkbook wbBack2 = HSSFTestDataSamples.WriteOutAndReadBack(wbBack); sh = wbBack2.GetSheetAt(0) as HSSFSheet; patriarch = sh.DrawingPatriarch as HSSFPatriarch; comment = (HSSFComment)patriarch.Children[0]; Assert.AreEqual(comment.String.String, "comment12"); Assert.AreEqual("poi2", comment.Author); Assert.AreEqual(comment.Column, 32); Assert.AreEqual(comment.Row, 42); Assert.AreEqual(comment.Visible, true); wb.Close(); wbBack.Close(); wbBack2.Close(); } [Test] public void ExistingFileWithComment() { HSSFWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("drawings.xls"); HSSFSheet sheet = wb.GetSheet("comments") as HSSFSheet; HSSFPatriarch Drawing = sheet.DrawingPatriarch as HSSFPatriarch; Assert.AreEqual(1, Drawing.Children.Count); HSSFComment comment = (HSSFComment)Drawing.Children[(0)]; Assert.AreEqual(comment.Author, "evgeniy"); Assert.AreEqual(comment.String.String, "evgeniy:\npoi test"); Assert.AreEqual(comment.Column, 1); Assert.AreEqual(comment.Row, 2); wb.Close(); } [Test] public void FindComments() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet() as HSSFSheet; HSSFPatriarch patriarch = sh.CreateDrawingPatriarch() as HSSFPatriarch; HSSFComment comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; HSSFRow row = sh.CreateRow(5) as HSSFRow; HSSFCell cell = row.CreateCell(4) as HSSFCell; cell.CellComment = (comment); Assert.IsNotNull(sh.FindCellComment(5, 4)); Assert.IsNull(sh.FindCellComment(5, 5)); HSSFWorkbook wbBack = HSSFTestDataSamples.WriteOutAndReadBack(wb); sh = wbBack.GetSheetAt(0) as HSSFSheet; Assert.IsNotNull(sh.FindCellComment(5, 4)); Assert.IsNull(sh.FindCellComment(5, 5)); wb.Close(); wbBack.Close(); } [Test] public void InitState() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet() as HSSFSheet; HSSFPatriarch patriarch = sh.CreateDrawingPatriarch() as HSSFPatriarch; EscherAggregate agg = HSSFTestHelper.GetEscherAggregate(patriarch); Assert.AreEqual(agg.TailRecords.Count, 0); HSSFComment comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; Assert.AreEqual(agg.TailRecords.Count, 1); HSSFSimpleShape shape = patriarch.CreateSimpleShape(new HSSFClientAnchor()); Assert.IsNotNull(shape); Assert.AreEqual(comment.GetOptRecord().EscherProperties.Count, 10); wb.Close(); } [Test] public void ShapeId() { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sh = wb.CreateSheet() as HSSFSheet; HSSFPatriarch patriarch = sh.CreateDrawingPatriarch() as HSSFPatriarch; HSSFComment comment = patriarch.CreateCellComment(new HSSFClientAnchor()) as HSSFComment; comment.ShapeId = 2024; Assert.AreEqual(comment.ShapeId, 2024); CommonObjectDataSubRecord cod = (CommonObjectDataSubRecord)comment.GetObjRecord().SubRecords[0]; Assert.AreEqual(2024, cod.ObjectId); EscherSpRecord spRecord = (EscherSpRecord)comment.GetEscherContainer().GetChild(0); Assert.AreEqual(2024, spRecord.ShapeId); Assert.AreEqual(2024, comment.ShapeId); Assert.AreEqual(2024, comment.NoteRecord.ShapeId); wb.Close(); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using ASC.ActiveDirectory.Base; using ASC.ActiveDirectory.Base.Data; using ASC.ActiveDirectory.Base.Expressions; using ASC.ActiveDirectory.Base.Settings; namespace ASC.ActiveDirectory.Novell { public class NovellLdapHelper : LdapHelper { public NovellLdapSearcher LDAPSearcher { get; private set; } public NovellLdapHelper(LdapSettings settings) : base(settings) { var password = string.IsNullOrEmpty(settings.Password) ? GetPassword(settings.PasswordBytes) : settings.Password; LDAPSearcher = new NovellLdapSearcher(settings.Login, password, settings.Server, settings.PortNumber, settings.StartTls, settings.Ssl, settings.AcceptCertificate, settings.AcceptCertificateHash); } public override bool IsConnected { get { return LDAPSearcher.IsConnected; } } public override void Connect() { LDAPSearcher.Connect(); Settings.AcceptCertificate = LDAPSearcher.AcceptCertificate; Settings.AcceptCertificateHash = LDAPSearcher.AcceptCertificateHash; } public override Dictionary<string, string[]> GetCapabilities() { return LDAPSearcher.GetCapabilities(); } public override string SearchDomain() { try { var capabilities = GetCapabilities(); if (capabilities.Any()) { if (capabilities.ContainsKey("defaultNamingContext")) { var dnList = capabilities["defaultNamingContext"]; var dn = dnList.FirstOrDefault(dc => !string.IsNullOrEmpty(dc) && dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1); var domain = LdapUtils.DistinguishedNameToDomain(dn); if (!string.IsNullOrEmpty(domain)) return domain; } if (capabilities.ContainsKey("rootDomainNamingContext")) { var dnList = capabilities["rootDomainNamingContext"]; var dn = dnList.FirstOrDefault(dc => !string.IsNullOrEmpty(dc) && dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1); var domain = LdapUtils.DistinguishedNameToDomain(dn); if (!string.IsNullOrEmpty(domain)) return domain; } if (capabilities.ContainsKey("namingContexts")) { var dnList = capabilities["namingContexts"]; var dn = dnList.FirstOrDefault(dc => !string.IsNullOrEmpty(dc) && dc.IndexOf("dc=", StringComparison.InvariantCultureIgnoreCase) != -1); var domain = LdapUtils.DistinguishedNameToDomain(dn); if (!string.IsNullOrEmpty(domain)) return domain; } } } catch (Exception e) { Log.WarnFormat("NovellLdapHelper->SearchDomain() failed. Error: {0}", e); } try { var searchResult = LDAPSearcher.Search(Settings.UserDN, NovellLdapSearcher.LdapScope.Sub, Settings.UserFilter, limit: 1) .FirstOrDefault(); return searchResult != null ? searchResult.GetDomainFromDn() : null; } catch (Exception e) { Log.WarnFormat("NovellLdapHelper->SearchDomain() failed. Error: {0}", e); } return null; } public override void CheckCredentials(string login, string password, string server, int portNumber, bool startTls, bool ssl, bool acceptCertificate, string acceptCertificateHash) { using (var novellLdapSearcher = new NovellLdapSearcher(login, password, server, portNumber, startTls, ssl, acceptCertificate, acceptCertificateHash)) { novellLdapSearcher.Connect(); } } public override bool CheckUserDn(string userDn) { string[] attributes = { LdapConstants.ADSchemaAttributes.OBJECT_CLASS }; var searchResult = LDAPSearcher.Search(userDn, NovellLdapSearcher.LdapScope.Base, LdapConstants.OBJECT_FILTER, attributes, 1); if (searchResult.Any()) return true; Log.ErrorFormat("NovellLdapHelper->CheckUserDn(userDn: {0}) Wrong User DN parameter", userDn); return false; } public override bool CheckGroupDn(string groupDn) { string[] attributes = { LdapConstants.ADSchemaAttributes.OBJECT_CLASS }; var searchResult = LDAPSearcher.Search(groupDn, NovellLdapSearcher.LdapScope.Base, LdapConstants.OBJECT_FILTER, attributes, 1); if (searchResult.Any()) return true; Log.ErrorFormat("NovellLdapHelper->CheckGroupDn(groupDn: {0}): Wrong Group DN parameter", groupDn); return false; } public override List<LdapObject> GetUsers(string filter = null, int limit = -1) { var list = new List<LdapObject>(); try { if (!string.IsNullOrEmpty(Settings.UserFilter) && !Settings.UserFilter.StartsWith("(") && !Settings.UserFilter.EndsWith(")")) { Settings.UserFilter = string.Format("({0})", Settings.UserFilter); } if (!string.IsNullOrEmpty(filter) && !filter.StartsWith("(") && !filter.EndsWith(")")) { filter = string.Format("({0})", Settings.UserFilter); } var searchfilter = string.IsNullOrEmpty(filter) ? Settings.UserFilter : string.Format("(&{0}{1})", Settings.UserFilter, filter); list = LDAPSearcher.Search(Settings.UserDN, NovellLdapSearcher.LdapScope.Sub, searchfilter, limit: limit); return list; } catch (Exception e) { Log.ErrorFormat("NovellLdapHelper->GetUsers(filter: '{0}' limit: {1}) failed. Error: {2}", filter, limit, e); } return list; } public override LdapObject GetUserBySid(string sid) { try { var ldapUniqueIdAttribute = ConfigurationManagerExtension.AppSettings["ldap.unique.id"]; Criteria criteria; if (ldapUniqueIdAttribute == null) { criteria = Criteria.Any( Expression.Equal(LdapConstants.RfcLDAPAttributes.ENTRY_UUID, sid), Expression.Equal(LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, sid), Expression.Equal(LdapConstants.RfcLDAPAttributes.GUID, sid), Expression.Equal(LdapConstants.ADSchemaAttributes.OBJECT_SID, sid) ); } else { criteria = Criteria.All(Expression.Equal(ldapUniqueIdAttribute, sid)); } var searchfilter = string.Format("(&{0}{1})", Settings.UserFilter, criteria); var list = LDAPSearcher.Search(Settings.UserDN, NovellLdapSearcher.LdapScope.Sub, searchfilter, limit: 1); return list.FirstOrDefault(); } catch (Exception e) { Log.ErrorFormat("NovellLdapHelper->GetUserBySid(sid: '{0}') failed. Error: {1}", sid, e); } return null; } public override List<LdapObject> GetGroups(Criteria criteria = null) { var list = new List<LdapObject>(); try { if (!string.IsNullOrEmpty(Settings.GroupFilter) && !Settings.GroupFilter.StartsWith("(") && !Settings.GroupFilter.EndsWith(")")) { Settings.GroupFilter = string.Format("({0})", Settings.GroupFilter); } var searchfilter = criteria == null ? Settings.GroupFilter : string.Format("(&{0}{1})", Settings.GroupFilter, criteria); list = LDAPSearcher.Search(Settings.GroupDN, NovellLdapSearcher.LdapScope.Sub, searchfilter); } catch (Exception e) { Log.ErrorFormat("NovellLdapHelper->GetGroups(criteria: '{0}') failed. Error: {1}", criteria, e); } return list; } public override void Dispose() { LDAPSearcher.Dispose(); } } }
// ZlibStream.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-31 14:53:33> // // ------------------------------------------------------------------ // // This module defines the ZlibStream class, which is similar in idea to // the System.IO.Compression.DeflateStream and // System.IO.Compression.GZipStream classes in the .NET BCL. // // ------------------------------------------------------------------ using System; using System.IO; namespace Ionic.Zlib { /// <summary> /// Represents a Zlib stream for compression or decompression. /// </summary> /// <remarks> /// /// <para> /// The ZlibStream is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a <see /// cref="System.IO.Stream"/>. It adds ZLIB compression or decompression to any /// stream. /// </para> /// /// <para> Using this stream, applications can compress or decompress data via /// stream <c>Read()</c> and <c>Write()</c> operations. Either compresssion or /// decompression can occur through either reading or writing. The compression /// format used is ZLIB, which is documented in <see /// href="http://www.ietf.org/rfc/rfc1950.txt">IETF RFC 1950</see>, "ZLIB Compressed /// Data Format Specification version 3.3". This implementation of ZLIB always uses /// DEFLATE as the compression method. (see <see /// href="http://www.ietf.org/rfc/rfc1951.txt">IETF RFC 1951</see>, "DEFLATE /// Compressed Data Format Specification version 1.3.") </para> /// /// <para> /// The ZLIB format allows for varying compression methods, window sizes, and dictionaries. /// This implementation always uses the DEFLATE compression method, a preset dictionary, /// and 15 window bits by default. /// </para> /// /// <para> /// This class is similar to <see cref="DeflateStream"/>, except that it adds the /// RFC1950 header and trailer bytes to a compressed stream when compressing, or expects /// the RFC1950 header and trailer bytes when decompressing. It is also similar to the /// <see cref="GZipStream"/>. /// </para> /// </remarks> /// <seealso cref="DeflateStream" /> /// <seealso cref="GZipStream" /> public class ZlibStream : System.IO.Stream { internal ZlibBaseStream _baseStream; bool _disposed; /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> /// will use the default compression level. The "captive" stream will be /// closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress a file, and writes the /// compressed data to another file. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is ignored. /// The "captive" stream will be closed when the <c>ZlibStream</c> is closed. /// </para> /// /// </remarks> /// /// <example> /// This example uses a <c>ZlibStream</c> to compress data from a file, and writes the /// compressed data to another file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (Stream compressor = new ZlibStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using compressor As Stream = New ZlibStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the captive stream should be left open after /// Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>ZlibStream</c> will use /// the default compression level. /// </para> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// <see cref="System.IO.MemoryStream"/> that will be re-read after /// compression. Specify true for the <paramref name="leaveOpen"/> parameter to leave the stream /// open. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream">The stream which will be read or written. This is called the /// "captive" stream in other places in this documentation.</param> /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain /// open after inflation/deflation.</param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>ZlibStream</c> using the specified <c>CompressionMode</c> /// and the specified <c>CompressionLevel</c>, and explicitly specify /// whether the stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive /// stream remain open after the deflation or inflation occurs. By /// default, after <c>Close()</c> is called on the stream, the captive /// stream is also closed. In some cases this is not desired, for example /// if the stream is a <see cref="System.IO.MemoryStream"/> that will be /// re-read after compression. Specify true for the <paramref /// name="leaveOpen"/> parameter to leave the stream open. /// </para> /// /// <para> /// When mode is <c>CompressionMode.Decompress</c>, the level parameter is /// ignored. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a ZlibStream to compress the data from a file, /// and store the result into another file. The filestream remains open to allow /// additional data to be written to it. /// /// <code> /// using (var output = System.IO.File.Create(fileToCompress + ".zlib")) /// { /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (Stream compressor = new ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// // can write additional data to the output stream here /// } /// </code> /// <code lang="VB"> /// Using output As FileStream = File.Create(fileToCompress &amp; ".zlib") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using compressor As Stream = New ZlibStream(output, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// ' can write additional data to the output stream here. /// End Using /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// /// <param name="mode">Indicates whether the ZlibStream will compress or decompress.</param> /// /// <param name="leaveOpen"> /// true if the application would like the stream to remain open after /// inflation/deflation. /// </param> /// /// <param name="level"> /// A tuning knob to trade speed for effectiveness. This parameter is /// effective only when mode is <c>CompressionMode.Compress</c>. /// </param> public ZlibStream(System.IO.Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.ZLIB, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// Sorry, though, not sure exactly how to describe all the various settings. /// </summary> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("ZlibStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region System.IO.Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// This method may be invoked in two distinct scenarios. If disposing /// == true, the method has been called directly or indirectly by a /// user's code, for example via the public Dispose() method. In this /// case, both managed and unmanaged resources can be referenced and /// disposed. If disposing == false, the method has been called by the /// runtime from inside the object finalizer and this method should not /// reference other objects; in that case only unmanaged resources must /// be referenced or disposed. /// </para> /// </remarks> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) this._baseStream.Dispose(); _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotSupportedException"/>. /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotSupportedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut; if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn; return 0; } set { throw new NotSupportedException(); } } /// <summary> /// Read data from the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while reading, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// providing an uncompressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data read will be compressed. If you wish to /// use the <c>ZlibStream</c> to decompress data while reading, you can create /// a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, providing a /// readable compressed data stream. Then call <c>Read()</c> on that /// <c>ZlibStream</c>, and the data will be decompressed as it is read. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but /// not both. /// </para> /// /// </remarks> /// /// <param name="buffer"> /// The buffer into which the read data should be placed.</param> /// /// <param name="offset"> /// the offset within that data array to put the first byte read.</param> /// /// <param name="count">the number of bytes to read.</param> /// /// <returns>the number of bytes read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); return _baseStream.Read(buffer, offset, count); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="offset"> /// The offset to seek to.... /// IF THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// <param name="origin"> /// The reference specifying how to apply the offset.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> /// /// <returns>nothing. This method always throws.</returns> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Calling this method always throws a <see cref="NotSupportedException"/>. /// </summary> /// <param name="value"> /// The new value for the stream length.... IF /// THIS METHOD ACTUALLY DID ANYTHING. /// </param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// /// <para> /// If you wish to use the <c>ZlibStream</c> to compress data while writing, /// you can create a <c>ZlibStream</c> with <c>CompressionMode.Compress</c>, /// and a writable output stream. Then call <c>Write()</c> on that /// <c>ZlibStream</c>, providing uncompressed data as input. The data sent to /// the output stream will be the compressed form of the data written. If you /// wish to use the <c>ZlibStream</c> to decompress data while writing, you /// can create a <c>ZlibStream</c> with <c>CompressionMode.Decompress</c>, and a /// writable output stream. Then call <c>Write()</c> on that stream, /// providing previously compressed data. The data sent to the output stream /// will be the decompressed form of the data written. /// </para> /// /// <para> /// A <c>ZlibStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not both. /// </para> /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("ZlibStream"); _baseStream.Write(buffer, offset, count); } #endregion /// <summary> /// Compress a string into a byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.CompressString(string)"/> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new MemoryStream()) { Stream compressor = new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using ZLIB. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="ZlibStream.CompressString(string)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new MemoryStream()) { Stream compressor = new ZlibStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a single string. /// </summary> /// /// <seealso cref="ZlibStream.CompressString(String)"/> /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a ZLIB-compressed byte array into a byte array. /// </summary> /// /// <seealso cref="ZlibStream.CompressBuffer(byte[])"/> /// <seealso cref="ZlibStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing ZLIB-compressed data. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new ZlibStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
using UnityEngine; using System.Collections.Generic; namespace EazyTools.SoundManager { public class SoundManager : MonoBehaviour { private static SoundManager _instance = null; private static float vol = 1f; private static float musicVol = 1f; private static float soundsVol = 1f; private static float UISoundsVol = 1f; private static Dictionary<int, Audio> musicAudio; private static Dictionary<int, Audio> soundsAudio; private static Dictionary<int, Audio> UISoundsAudio; private static bool initialized = false; private static SoundManager instance { get { if (_instance == null) { _instance = (SoundManager)FindObjectOfType(typeof(SoundManager)); if (_instance == null) { // Create gameObject and add component _instance = (new GameObject("EazySoundManager")).AddComponent<SoundManager>(); } } return _instance; } } /// <summary> /// The gameobject that the sound manager is attached to /// </summary> public static GameObject gameobject { get { return instance.gameObject; } } /// <summary> /// When set to true, new Audios that have the same audio clip as any other Audio, will be ignored /// </summary> public static bool ignoreDuplicateMusic { get; set; } /// <summary> /// When set to true, new Audios that have the same audio clip as any other Audio, will be ignored /// </summary> public static bool ignoreDuplicateSounds { get; set; } /// <summary> /// When set to true, new Audios that have the same audio clip as any other Audio, will be ignored /// </summary> public static bool ignoreDuplicateUISounds { get; set; } /// <summary> /// Global volume /// </summary> public static float globalVolume { get { return vol; } set { vol = value; } } /// <summary> /// Global music volume /// </summary> public static float globalMusicVolume { get { return musicVol; } set { musicVol = value; } } /// <summary> /// Global sounds volume /// </summary> public static float globalSoundsVolume { get { return soundsVol; } set { soundsVol = value; } } /// <summary> /// Global UI sounds volume /// </summary> public static float globalUISoundsVolume { get { return UISoundsVol; } set { UISoundsVol = value; } } void Awake() { instance.Init(); } void OnLevelWasLoaded(int level) { List<int> keys; // Stop and remove all non-persistent music audio keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { Audio audio = musicAudio[key]; if (!audio.persist && audio.activated) { Destroy(audio.audioSource); musicAudio.Remove(key); } } // Stop and remove all sound fx keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { Audio audio = soundsAudio[key]; Destroy(audio.audioSource); soundsAudio.Remove(key); } // Stop and remove all UI sound fx keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { Audio audio = UISoundsAudio[key]; Destroy(audio.audioSource); UISoundsAudio.Remove(key); } } void Update() { List<int> keys; // Update music keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { Audio audio = musicAudio[key]; audio.Update(); // Remove all music clips that are not playing if (!audio.playing && !audio.paused) { Destroy(audio.audioSource); //musicAudio.Remove(key); } } // Update sound fx keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { Audio audio = soundsAudio[key]; audio.Update(); // Remove all sound fx clips that are not playing if (!audio.playing && !audio.paused) { Destroy(audio.audioSource); //soundsAudio.Remove(key); } } // Update UI sound fx keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { Audio audio = UISoundsAudio[key]; audio.Update(); // Remove all UI sound fx clips that are not playing if (!audio.playing && !audio.paused) { Destroy(audio.audioSource); //UISoundsAudio.Remove(key); } } } void Init() { if (!initialized) { musicAudio = new Dictionary<int, Audio>(); soundsAudio = new Dictionary<int, Audio>(); UISoundsAudio = new Dictionary<int, Audio>(); ignoreDuplicateMusic = false; ignoreDuplicateSounds = false; ignoreDuplicateUISounds = false; initialized = true; DontDestroyOnLoad(this); } } #region GetAudio Functions /// <summary> /// Returns the Audio that has as its id the audioID if one is found, returns null if no such Audio is found /// </summary> /// <param name="audioID">The id of the Audio to be retrieved</param> /// <returns>Audio that has as its id the audioID, null if no such Audio is found</returns> public static Audio GetAudio(int audioID) { Audio audio; audio = GetMusicAudio(audioID); if (audio != null) { return audio; } audio = GetSoundAudio(audioID); if (audio != null) { return audio; } audio = GetUISoundAudio(audioID); if (audio != null) { return audio; } return null; } /// <summary> /// Returns the first occurrence of Audio that plays the given audioClip. Returns null if no such Audio is found /// </summary> /// <param name="audioClip">The audio clip of the Audio to be retrieved</param> /// <returns>First occurrence of Audio that has as plays the audioClip, null if no such Audio is found</returns> public static Audio GetAudio(AudioClip audioClip) { Audio audio = GetMusicAudio(audioClip); if (audio != null) { return audio; } audio = GetSoundAudio(audioClip); if (audio != null) { return audio; } audio = GetUISoundAudio(audioClip); if (audio != null) { return audio; } return null; } /// <summary> /// Returns the music Audio that has as its id the audioID if one is found, returns null if no such Audio is found /// </summary> /// <param name="audioID">The id of the music Audio to be returned</param> /// <returns>Music Audio that has as its id the audioID if one is found, null if no such Audio is found</returns> public static Audio GetMusicAudio(int audioID) { List<int> keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { if (audioID == key) { return musicAudio[key]; } } return null; } /// <summary> /// Returns the first occurrence of music Audio that plays the given audioClip. Returns null if no such Audio is found /// </summary> /// <param name="audioClip">The audio clip of the music Audio to be retrieved</param> /// <returns>First occurrence of music Audio that has as plays the audioClip, null if no such Audio is found</returns> public static Audio GetMusicAudio(AudioClip audioClip) { List<int> keys; keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { Audio audio = musicAudio[key]; if (audio.clip == audioClip) { return audio; } } return null; } /// <summary> /// Returns the sound fx Audio that has as its id the audioID if one is found, returns null if no such Audio is found /// </summary> /// <param name="audioID">The id of the sound fx Audio to be returned</param> /// <returns>Sound fx Audio that has as its id the audioID if one is found, null if no such Audio is found</returns> public static Audio GetSoundAudio(int audioID) { List<int> keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { if (audioID == key) { return soundsAudio[key]; } } return null; } /// <summary> /// Returns the first occurrence of sound Audio that plays the given audioClip. Returns null if no such Audio is found /// </summary> /// <param name="audioClip">The audio clip of the sound Audio to be retrieved</param> /// <returns>First occurrence of sound Audio that has as plays the audioClip, null if no such Audio is found</returns> public static Audio GetSoundAudio(AudioClip audioClip) { List<int> keys; keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { Audio audio = soundsAudio[key]; if (audio.clip == audioClip) { return audio; } } return null; } /// <summary> /// Returns the UI sound fx Audio that has as its id the audioID if one is found, returns null if no such Audio is found /// </summary> /// <param name="audioID">The id of the UI sound fx Audio to be returned</param> /// <returns>UI sound fx Audio that has as its id the audioID if one is found, null if no such Audio is found</returns> public static Audio GetUISoundAudio(int audioID) { List<int> keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { if (audioID == key) { return UISoundsAudio[key]; } } return null; } /// <summary> /// Returns the first occurrence of UI sound Audio that plays the given audioClip. Returns null if no such Audio is found /// </summary> /// <param name="audioClip">The audio clip of the UI sound Audio to be retrieved</param> /// <returns>First occurrence of UI sound Audio that has as plays the audioClip, null if no such Audio is found</returns> public static Audio GetUISoundAudio(AudioClip audioClip) { List<int> keys; keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { Audio audio = UISoundsAudio[key]; if (audio.clip == audioClip) { return audio; } } return null; } #endregion #region Play Functions /// <summary> /// Play background music /// </summary> /// <param name="clip">The audio clip to play</param> /// <returns>The ID of the created Audio object</returns> public static int PlayMusic(AudioClip clip) { return PlayMusic(clip, 1f, false, false, 1f, 1f, -1f, null); } /// <summary> /// Play background music /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <returns>The ID of the created Audio object</returns> public static int PlayMusic(AudioClip clip, float volume) { return PlayMusic(clip, volume, false, false, 1f, 1f, -1f, null); } /// <summary> /// Play background music /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <param name="loop">Wether the music is looped</param> /// <param name = "persist" > Whether the audio persists in between scene changes</param> /// <returns>The ID of the created Audio object</returns> public static int PlayMusic(AudioClip clip, float volume, bool loop, bool persist) { return PlayMusic(clip, volume, loop, persist, 1f, 1f, -1f, null); } /// <summary> /// Play background music /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <param name="loop">Wether the music is looped</param> /// <param name="persist"> Whether the audio persists in between scene changes</param> /// <param name="fadeInValue">How many seconds it needs for the audio to fade in/ reach target volume (if higher than current)</param> /// <param name="fadeOutValue"> How many seconds it needs for the audio to fade out/ reach target volume (if lower than current)</param> /// <returns>The ID of the created Audio object</returns> public static int PlayMusic(AudioClip clip, float volume, bool loop, bool persist, float fadeInSeconds, float fadeOutSeconds) { return PlayMusic(clip, volume, loop, persist, fadeInSeconds, fadeOutSeconds, -1f, null); } /// <summary> /// Play background music /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <param name="loop">Wether the music is looped</param> /// <param name="persist"> Whether the audio persists in between scene changes</param> /// <param name="fadeInValue">How many seconds it needs for the audio to fade in/ reach target volume (if higher than current)</param> /// <param name="fadeOutValue"> How many seconds it needs for the audio to fade out/ reach target volume (if lower than current)</param> /// <param name="currentMusicfadeOutSeconds"> How many seconds it needs for current music audio to fade out. It will override its own fade out seconds. If -1 is passed, current music will keep its own fade out seconds</param> /// <param name="sourceTransform">The transform that is the source of the music (will become 3D audio). If 3D audio is not wanted, use null</param> /// <returns>The ID of the created Audio object</returns> public static int PlayMusic(AudioClip clip, float volume, bool loop, bool persist, float fadeInSeconds, float fadeOutSeconds, float currentMusicfadeOutSeconds, Transform sourceTransform) { if (clip == null) { Debug.LogError("Sound Manager: Audio clip is null, cannot play music", clip); } if(ignoreDuplicateMusic) { List<int> keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { if (musicAudio[key].audioSource.clip == clip) { return musicAudio[key].audioID; } } } instance.Init(); // Stop all current music playing StopAllMusic(currentMusicfadeOutSeconds); // Create the audioSource //AudioSource audioSource = instance.gameObject.AddComponent<AudioSource>() as AudioSource; Audio audio = new Audio(Audio.AudioType.Music, clip, loop, persist, volume, fadeInSeconds, fadeOutSeconds, sourceTransform); // Add it to music list musicAudio.Add(audio.audioID, audio); return audio.audioID; } /// <summary> /// Play a sound fx /// </summary> /// <param name="clip">The audio clip to play</param> /// <returns>The ID of the created Audio object</returns> public static int PlaySound(AudioClip clip) { return PlaySound(clip, 1f, false, null); } /// <summary> /// Play a sound fx /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <returns>The ID of the created Audio object</returns> public static int PlaySound(AudioClip clip, float volume) { return PlaySound(clip, volume, false, null); } /// <summary> /// Play a sound fx /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="loop">Wether the sound is looped</param> /// <returns>The ID of the created Audio object</returns> public static int PlaySound(AudioClip clip, bool loop) { return PlaySound(clip, 1f, loop, null); } /// <summary> /// Play a sound fx /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <param name="loop">Wether the sound is looped</param> /// <param name="sourceTransform">The transform that is the source of the sound (will become 3D audio). If 3D audio is not wanted, use null</param> /// <returns>The ID of the created Audio object</returns> public static int PlaySound(AudioClip clip, float volume, bool loop, Transform sourceTransform) { if (clip == null) { Debug.LogError("Sound Manager: Audio clip is null, cannot play music", clip); } if (ignoreDuplicateSounds) { List<int> keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { if (soundsAudio[key].audioSource.clip == clip) { return soundsAudio[key].audioID; } } } instance.Init(); // Create the audioSource AudioSource audioSource = instance.gameObject.AddComponent<AudioSource>() as AudioSource; Audio audio = new Audio(Audio.AudioType.Sound, clip, loop, false, volume, 0f, 0f, sourceTransform); // Add it to music list soundsAudio.Add(audio.audioID, audio); return audio.audioID; } /// <summary> /// Play a UI sound fx /// </summary> /// <param name="clip">The audio clip to play</param> /// <returns>The ID of the created Audio object</returns> public static int PlayUISound(AudioClip clip) { return PlayUISound(clip, 1f); } /// <summary> /// Play a UI sound fx /// </summary> /// <param name="clip">The audio clip to play</param> /// <param name="volume"> The volume the music will have</param> /// <returns>The ID of the created Audio object</returns> public static int PlayUISound(AudioClip clip, float volume) { if (clip == null) { Debug.LogError("Sound Manager: Audio clip is null, cannot play music", clip); } if (ignoreDuplicateUISounds) { List<int> keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { if (UISoundsAudio[key].audioSource.clip == clip) { return UISoundsAudio[key].audioID; } } } instance.Init(); // Create the audioSource //AudioSource audioSource = instance.gameObject.AddComponent<AudioSource>() as AudioSource; Audio audio = new Audio(Audio.AudioType.UISound, clip, false, false, volume, 0f, 0f, null); // Add it to music list UISoundsAudio.Add(audio.audioID, audio); return audio.audioID; } #endregion #region Stop Functions /// <summary> /// Stop all audio playing /// </summary> public static void StopAll() { StopAll(-1f); } /// <summary> /// Stop all audio playing /// </summary> /// <param name="fadeOutSeconds"> How many seconds it needs for all music audio to fade out. It will override their own fade out seconds. If -1 is passed, all music will keep their own fade out seconds</param> public static void StopAll(float fadeOutSeconds) { StopAllMusic(fadeOutSeconds); StopAllSounds(); StopAllUISounds(); } /// <summary> /// Stop all music playing /// </summary> public static void StopAllMusic() { StopAllMusic(-1f); } /// <summary> /// Stop all music playing /// </summary> /// <param name="fadeOutSeconds"> How many seconds it needs for all music audio to fade out. It will override their own fade out seconds. If -1 is passed, all music will keep their own fade out seconds</param> public static void StopAllMusic(float fadeOutSeconds) { List<int> keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { Audio audio = musicAudio[key]; if (fadeOutSeconds > 0) { audio.fadeOutSeconds = fadeOutSeconds; } audio.Stop(); } } /// <summary> /// Stop all sound fx playing /// </summary> public static void StopAllSounds() { List<int> keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { Audio audio = soundsAudio[key]; audio.Stop(); } } /// <summary> /// Stop all UI sound fx playing /// </summary> public static void StopAllUISounds() { List<int> keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { Audio audio = UISoundsAudio[key]; audio.Stop(); } } #endregion #region Pause Functions /// <summary> /// Pause all audio playing /// </summary> public static void PauseAll() { PauseAllMusic(); PauseAllSounds(); PauseAllUISounds(); } /// <summary> /// Pause all music playing /// </summary> public static void PauseAllMusic() { List<int> keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { Audio audio = musicAudio[key]; audio.Pause(); } } /// <summary> /// Pause all sound fx playing /// </summary> public static void PauseAllSounds() { List<int> keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { Audio audio = soundsAudio[key]; audio.Pause(); } } /// <summary> /// Pause all UI sound fx playing /// </summary> public static void PauseAllUISounds() { List<int> keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { Audio audio = UISoundsAudio[key]; audio.Pause(); } } #endregion #region Resume Functions /// <summary> /// Resume all audio playing /// </summary> public static void ResumeAll() { ResumeAllMusic(); ResumeAllSounds(); ResumeAllUISounds(); } /// <summary> /// Resume all music playing /// </summary> public static void ResumeAllMusic() { List<int> keys = new List<int>(musicAudio.Keys); foreach (int key in keys) { Audio audio = musicAudio[key]; audio.Resume(); } } /// <summary> /// Resume all sound fx playing /// </summary> public static void ResumeAllSounds() { List<int> keys = new List<int>(soundsAudio.Keys); foreach (int key in keys) { Audio audio = soundsAudio[key]; audio.Resume(); } } /// <summary> /// Resume all UI sound fx playing /// </summary> public static void ResumeAllUISounds() { List<int> keys = new List<int>(UISoundsAudio.Keys); foreach (int key in keys) { Audio audio = UISoundsAudio[key]; audio.Resume(); } } #endregion } public class Audio { private static int audioCounter = 0; private float volume; private float targetVolume; private float initTargetVolume; private float tempFadeSeconds; private float fadeInterpolater; private float onFadeStartVolume; private AudioType audioType; private AudioClip initClip; private Transform sourceTransform; /// <summary> /// The ID of the Audio /// </summary> public int audioID { get; private set; } /// <summary> /// The audio source that is responsible for this audio /// </summary> public AudioSource audioSource { get; private set; } /// <summary> /// Audio clip to play/is playing /// </summary> public AudioClip clip { get { return audioSource == null ? initClip : audioSource.clip; } } /// <summary> /// Whether the audio will be lopped /// </summary> public bool loop { get; set; } /// <summary> /// Whether the audio persists in between scene changes /// </summary> public bool persist { get; set; } /// <summary> /// How many seconds it needs for the audio to fade in/ reach target volume (if higher than current) /// </summary> public float fadeInSeconds { get; set; } /// <summary> /// How many seconds it needs for the audio to fade out/ reach target volume (if lower than current) /// </summary> public float fadeOutSeconds { get; set; } /// <summary> /// Whether the audio is currently playing /// </summary> public bool playing { get; set; } /// <summary> /// Whether the audio is paused /// </summary> public bool paused { get; private set; } /// <summary> /// Whether the audio is stopping /// </summary> public bool stopping { get; private set; } /// <summary> /// Whether the audio is created and updated at least once. /// </summary> public bool activated { get; private set; } public enum AudioType { Music, Sound, UISound } public Audio(AudioType audioType, AudioClip clip, bool loop, bool persist, float volume, float fadeInValue, float fadeOutValue, Transform sourceTransform) { if (sourceTransform == null) { this.sourceTransform = SoundManager.gameobject.transform; } else { this.sourceTransform = sourceTransform; } this.audioID = audioCounter; audioCounter++; this.audioType = audioType; this.initClip = clip; this.loop = loop; this.persist = persist; this.targetVolume = volume; this.initTargetVolume = volume; this.tempFadeSeconds = -1; this.volume = 0f; this.fadeInSeconds = fadeInValue; this.fadeOutSeconds = fadeOutValue; this.playing = false; this.paused = false; this.activated = false; CreateAudiosource(clip, loop); Play(); } void CreateAudiosource(AudioClip clip, bool loop) { audioSource = sourceTransform.gameObject.AddComponent<AudioSource>() as AudioSource; audioSource.clip = clip; audioSource.loop = loop; audioSource.volume = 0f; if (sourceTransform != SoundManager.gameobject.transform) { audioSource.spatialBlend = 1; } } /// <summary> /// Start playing audio clip from the beggining /// </summary> public void Play() { Play(initTargetVolume); } /// <summary> /// Start playing audio clip from the beggining /// </summary> /// <param name="volume">The target volume</param> public void Play(float volume) { if(audioSource == null) { CreateAudiosource(initClip, loop); } audioSource.Play(); playing = true; fadeInterpolater = 0f; onFadeStartVolume = this.volume; targetVolume = volume; } /// <summary> /// Stop playing audio clip /// </summary> public void Stop() { fadeInterpolater = 0f; onFadeStartVolume = volume; targetVolume = 0f; stopping = true; } /// <summary> /// Pause playing audio clip /// </summary> public void Pause() { audioSource.Pause(); paused = true; } /// <summary> /// Resume playing audio clip /// </summary> public void UnPause() { audioSource.UnPause(); paused = false; } /// <summary> /// Resume playing audio clip /// </summary> public void Resume() { audioSource.UnPause(); paused = false; } /// <summary> /// Sets the audio volume /// </summary> /// <param name="volume">The target volume</param> public void SetVolume(float volume) { if(volume > targetVolume) { SetVolume(volume, fadeOutSeconds); } else { SetVolume(volume, fadeInSeconds); } } /// <summary> /// Sets the audio volume /// </summary> /// <param name="volume">The target volume</param> /// <param name="fadeSeconds">How many seconds it needs for the audio to fade in/out to reach target volume. If passed, it will override the Audio's fade in/out seconds, but only for this transition</param> public void SetVolume(float volume, float fadeSeconds) { SetVolume(volume, fadeSeconds, this.volume); } /// <summary> /// Sets the audio volume /// </summary> /// <param name="volume">The target volume</param> /// <param name="fadeSeconds">How many seconds it needs for the audio to fade in/out to reach target volume. If passed, it will override the Audio's fade in/out seconds, but only for this transition</param> /// <param name="startVolume">Immediately set the volume to this value before beginning the fade. If not passed, the Audio will start fading from the current volume towards the target volume</param> public void SetVolume(float volume, float fadeSeconds, float startVolume) { targetVolume = Mathf.Clamp01(volume); fadeInterpolater = 0; onFadeStartVolume = startVolume; tempFadeSeconds = fadeSeconds; } /// <summary> /// Sets the Audio 3D max distance /// </summary> /// <param name="max">the max distance</param> public void Set3DMaxDistance(float max) { audioSource.maxDistance = max; } /// <summary> /// Sets the Audio 3D min distance /// </summary> /// <param name="max">the min distance</param> public void Set3DMinDistance(float min) { audioSource.minDistance = min; } /// <summary> /// Sets the Audio 3D distances /// </summary> /// <param name="min">the min distance</param> /// <param name="max">the max distance</param> public void Set3DDistances(float min, float max) { Set3DMinDistance(min); Set3DMaxDistance(max); } public void Update() { if(audioSource == null) { return; } activated = true; if (volume != targetVolume) { float fadeValue; fadeInterpolater += Time.deltaTime; if (volume > targetVolume) { fadeValue = tempFadeSeconds != -1? tempFadeSeconds: fadeOutSeconds; } else { fadeValue = tempFadeSeconds != -1 ? tempFadeSeconds : fadeInSeconds; } volume = Mathf.Lerp(onFadeStartVolume, targetVolume, fadeInterpolater / fadeValue); } else if(tempFadeSeconds != -1) { tempFadeSeconds = -1; } switch (audioType) { case AudioType.Music: { audioSource.volume = volume * SoundManager.globalMusicVolume * SoundManager.globalVolume; break; } case AudioType.Sound: { audioSource.volume = volume * SoundManager.globalSoundsVolume * SoundManager.globalVolume; break; } case AudioType.UISound: { audioSource.volume = volume * SoundManager.globalUISoundsVolume * SoundManager.globalVolume; break; } } if (volume == 0f && stopping) { audioSource.Stop(); stopping = false; playing = false; paused = false; } // Update playing status if (audioSource.isPlaying != playing) { playing = audioSource.isPlaying; } } } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.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 using System.IO; using System.Reflection; using FluentMigrator.Infrastructure; using FluentMigrator.Model; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit { [TestFixture] public class DefaultMigrationConventionsTests { [Test] public void GetPrimaryKeyNamePrefixesTableNameWithPKAndUnderscore() { DefaultMigrationConventions.GetPrimaryKeyName("Foo").ShouldBe("PK_Foo"); } [Test] public void GetForeignKeyNameReturnsValidForeignKeyNameForSimpleForeignKey() { var foreignKey = new ForeignKeyDefinition { ForeignTable = "Users", ForeignColumns = new[] { "GroupId" }, PrimaryTable = "Groups", PrimaryColumns = new[] { "Id" } }; DefaultMigrationConventions.GetForeignKeyName(foreignKey).ShouldBe("FK_Users_GroupId_Groups_Id"); } [Test] public void GetForeignKeyNameReturnsValidForeignKeyNameForComplexForeignKey() { var foreignKey = new ForeignKeyDefinition { ForeignTable = "Users", ForeignColumns = new[] { "ColumnA", "ColumnB" }, PrimaryTable = "Groups", PrimaryColumns = new[] { "ColumnC", "ColumnD" } }; DefaultMigrationConventions.GetForeignKeyName(foreignKey).ShouldBe("FK_Users_ColumnA_ColumnB_Groups_ColumnC_ColumnD"); } [Test] public void GetIndexNameReturnsValidIndexNameForSimpleIndex() { var index = new IndexDefinition { TableName = "Bacon", Columns = { new IndexColumnDefinition { Name = "BaconName", Direction = Direction.Ascending } } }; DefaultMigrationConventions.GetIndexName(index).ShouldBe("IX_Bacon_BaconName"); } [Test] public void GetIndexNameReturnsValidIndexNameForComplexIndex() { var index = new IndexDefinition { TableName = "Bacon", Columns = { new IndexColumnDefinition { Name = "BaconName", Direction = Direction.Ascending }, new IndexColumnDefinition { Name = "BaconSpice", Direction = Direction.Descending } } }; DefaultMigrationConventions.GetIndexName(index).ShouldBe("IX_Bacon_BaconName_BaconSpice"); } [Test] public void TypeIsMigrationReturnsTrueIfTypeExtendsMigrationAndHasMigrationAttribute() { DefaultMigrationConventions.TypeIsMigration(typeof(DefaultConventionMigrationFake)) .ShouldBeTrue(); } [Test] public void TypeIsMigrationReturnsFalseIfTypeDoesNotExtendMigration() { DefaultMigrationConventions.TypeIsMigration(typeof(object)) .ShouldBeFalse(); } [Test] public void TypeIsMigrationReturnsFalseIfTypeDoesNotHaveMigrationAttribute() { DefaultMigrationConventions.TypeIsMigration(typeof(MigrationWithoutAttributeFake)) .ShouldBeFalse(); } [Test] public void MigrationInfoShouldRetainMigration() { var migration = new DefaultConventionMigrationFake(); var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migration); migrationinfo.Migration.ShouldBeSameAs(migration); } [Test] public void MigrationInfoShouldExtractVersion() { var migration = new DefaultConventionMigrationFake(); var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migration); migrationinfo.Version.ShouldBe(123); } [Test] public void MigrationInfoShouldExtractTransactionBehavior() { var migration = new DefaultConventionMigrationFake(); var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migration); migrationinfo.TransactionBehavior.ShouldBe(TransactionBehavior.None); } [Test] public void MigrationInfoShouldExtractTraits() { var migration = new DefaultConventionMigrationFake(); var migrationinfo = DefaultMigrationConventions.GetMigrationInfoFor(migration); migrationinfo.Trait("key").ShouldBe("test"); } [Test] [Category("Integration")] public void WorkingDirectoryConventionDefaultsToAssemblyFolder() { var defaultWorkingDirectory = DefaultMigrationConventions.GetWorkingDirectory(); defaultWorkingDirectory.ShouldNotBeNull(); defaultWorkingDirectory.Contains("bin").ShouldBeTrue(); } [Test] public void TypeHasTagsReturnTrueIfTypeHasTagsAttribute() { DefaultMigrationConventions.TypeHasTags(typeof(TaggedWithUk)) .ShouldBeTrue(); } [Test] public void TypeHasTagsReturnFalseIfTypeDoesNotHaveTagsAttribute() { DefaultMigrationConventions.TypeHasTags(typeof(HasNoTagsFake)) .ShouldBeFalse(); } public class TypeHasMatchingTags { [Test] [Category("Tagging")] public void WhenTypeHasTagAttributeWithNoTagNamesReturnsFalse() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(HasTagAttributeWithNoTagNames), new string[] { }) .ShouldBeFalse(); } [Test] [Category("Tagging")] public void WhenTypeHasOneTagThatDoesNotMatchSingleThenTagReturnsFalse() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "IE" }) .ShouldBeFalse(); } [Test] [Category("Tagging")] public void WhenTypeHasOneTagThatDoesMatchSingleTagThenReturnsTrue() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "UK" }) .ShouldBeTrue(); } [Test] [Category("Tagging")] public void WhenTypeHasOneTagThatPartiallyMatchesTagThenReturnsFalse() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "UK2" }) .ShouldBeFalse(); } [Test] [Category("Tagging")] public void WhenTypeHasOneTagThatDoesMatchMultipleTagsThenReturnsFalse() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithUk), new[] { "UK", "Production" }) .ShouldBeFalse(); } [Test] [Category("Tagging")] public void WhenTypeHasTagsInTwoAttributeThatDoesMatchSingleTagThenReturnsTrue() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes), new[] { "UK" }) .ShouldBeTrue(); } [Test] [Category("Tagging")] public void WhenTypeHasTagsInTwoAttributesThatDoesMatchMultipleTagsThenReturnsTrue() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes), new[] { "UK", "Production" }) .ShouldBeTrue(); } [Test] [Category("Tagging")] public void WhenTypeHasTagsInOneAttributeThatDoesMatchMultipleTagsThenReturnsTrue() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInOneTagsAttribute), new[] { "UK", "Production" }) .ShouldBeTrue(); } [Test] [Category("Tagging")] public void WhenTypeHasTagsInTwoAttributesThatDontNotMatchMultipleTagsThenReturnsFalse() { DefaultMigrationConventions.TypeHasMatchingTags(typeof(TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes), new[] { "UK", "IE" }) .ShouldBeFalse(); } } } [Tags("BE", "UK", "Staging", "Production")] public class TaggedWithBeAndUkAndProductionAndStagingInOneTagsAttribute { } [Tags("BE", "UK")] [Tags("Staging", "Production")] public class TaggedWithBeAndUkAndProductionAndStagingInTwoTagsAttributes { } [Tags("UK")] public class TaggedWithUk { } [Tags] public class HasTagAttributeWithNoTagNames { } public class HasNoTagsFake { } [Migration(123, TransactionBehavior.None)] [MigrationTrait("key", "test")] internal class DefaultConventionMigrationFake : Migration { public override void Up() { } public override void Down() { } } internal class MigrationWithoutAttributeFake : Migration { public override void Up() { } public override void Down() { } } }
using System; using System.Collections.Generic; using System.Text; //using NUnit.Framework; using System.IO; namespace SCSharp.Smk { public class Huffmantree { protected internal class Node { //"0"- branch private Node left; public Node Left { get { return left; } set { left = value; } } //"1"-branch private Node right; public Node Right { get { return right; } set { right = value; } } //Made public for more speed public bool isLeaf; public bool IsLeaf { get { return isLeaf; } set { isLeaf = value; } } private int value; public int Value { get { return this.value; } set { this.value = value; } } public void Print(string prefix) { System.Console.WriteLine(prefix + ((IsLeaf) ? "Leaf: " + Value.ToString() : "No Leaf")); if (left != null) left.Print(prefix + " L:"); if (right != null) right.Print(prefix + " R:"); } public void Print() { Print(""); } } /// <summary> /// Builds a new 8-bit huffmantree. The used algorithm is based on /// http://wiki.multimedia.cx/index.php?title=Smacker#Packed_Huffman_Trees /// </summary> /// <param name="m">The stream to build the tree from</param> public virtual void BuildTree(BitStream m) { //Read tag int tag = m.ReadBits(1); //If tag is zero, finish if (tag == 0) return; //Init tree rootNode = new Node(); BuildTree(m, rootNode); //For some reason we have to skip a bit m.ReadBits(1); } /// <summary> /// Decodes a value using this tree based on the next bits in the specified stream /// </summary> /// <param name="m">The stream to read bits from</param> public virtual int Decode(BitStream m) { Node currentNode = RootNode; if (currentNode == null) return 0; while (!currentNode.isLeaf) { int bit = m.ReadBits(1); if (bit == 0) { currentNode = currentNode.Left; } else { currentNode = currentNode.Right; } } return currentNode.Value; } protected virtual void BuildTree(BitStream m, Node current) { //Read flag int flag = m.ReadBits(1); //If flag is nonzero if (flag != 0) { //Advance to "0"-branch Node left = new Node(); //Recursive call BuildTree(m, left); //The first left-node is actually the root if (current == null) { rootNode = left; return; } else current.Left = left; } else //If flag is zero { if (current == null) { current = new Node(); rootNode = current; } //Read 8 bit leaf int leaf = m.ReadBits(8); //Console.WriteLine("Decoded :" + leaf); current.IsLeaf = true; current.Value = leaf; return; } //Continue on the "1"-branch current.Right = new Node(); BuildTree(m, current.Right); } Node rootNode; internal Node RootNode { get { return rootNode; } set { rootNode = value; } } public void PrintTree() { rootNode.Print(); } } public class BigHuffmanTree : Huffmantree { /// <summary> /// Decodes a value using this tree based on the next bits in the specified stream /// </summary> /// <param name="m">The stream to read bits from</param> public override int Decode(BitStream m) { //int v = base.Decode(m); Node currentNode = RootNode; if (currentNode == null) return 0; while (!currentNode.isLeaf) { int bit = m.ReadBits(1); if (bit == 0) { currentNode = currentNode.Left; } else { currentNode = currentNode.Right; } } int v = currentNode.Value; if (v != iMarker1) { iMarker3 = iMarker2; iMarker2 = iMarker1; iMarker1 = v; marker3.Value = marker2.Value; marker2.Value = marker1.Value; marker1.Value = v; } return v; } /// <summary> /// Resets the dynamic decoder markers to zero /// </summary> public void ResetDecoder() { marker1.Value = 0; marker2.Value = 0; marker3.Value = 0; iMarker1 = 0; iMarker2 = 0; iMarker3 = 0; } Huffmantree highByteTree; Huffmantree lowByteTree; Node marker1; Node marker2; Node marker3; int iMarker1, iMarker2, iMarker3; public override void BuildTree(BitStream m) { //Read tag int tag = m.ReadBits(1); //If tag is zero, finish if (tag == 0) return; lowByteTree = new Huffmantree(); lowByteTree.BuildTree(m); highByteTree = new Huffmantree(); highByteTree.BuildTree(m); iMarker1 = m.ReadBits(16); //System.Console.WriteLine("M1:" + iMarker1); iMarker2 = m.ReadBits(16); //System.Console.WriteLine("M2:" + iMarker2); iMarker3 = m.ReadBits(16); //System.Console.WriteLine("M3:" + iMarker3); RootNode = new Node(); BuildTree(m, RootNode); //For some reason we have to skip a bit m.ReadBits(1); if (marker1 == null) { // System.Console.WriteLine("Not using marker 1"); marker1 = new Node(); } if (marker2 == null) { // System.Console.WriteLine("Not using marker 2"); marker2 = new Node(); } if (marker3 == null) { // System.Console.WriteLine("Not using marker 3"); marker3 = new Node(); } } protected override void BuildTree(BitStream m, Node current) { //Read flag int flag = m.ReadBits(1); //If flag is nonzero if (flag != 0) { //Advance to "0"-branch Node left = new Node(); //Recursive call BuildTree(m, left); //The first left-node is actually the root if (current == null) { RootNode = left; return; } else current.Left = left; } else //If flag is zero { if (current == null) { current = new Node(); RootNode = current; } //Read 16 bit leaf by decoding the low byte, then the high byte int lower = lowByteTree.Decode(m); int higher = highByteTree.Decode(m); int leaf = lower | (higher << 8); //System.Console.WriteLine("Decoded: " + leaf); //If we found one of the markers, store pointers to those nodes. if (leaf == iMarker1) { leaf = 0; marker1 = current; } if (leaf == iMarker2) { leaf = 0; marker2 = current; } if (leaf == iMarker3) { leaf = 0; marker3 = current; } current.IsLeaf = true; current.Value = leaf; return; } //Continue on the "1"-branch current.Right = new Node(); BuildTree(m, current.Right); } } //This should move to another file // [TestFixture] // public class HuffmantreeTest // { // [Test] // public void TestBuild() // { //Set up a memory stream first // MemoryStream stream = new MemoryStream(); // stream.WriteByte(0x6F); //These bytes correspond to the example // stream.WriteByte(0x20); //bit-sequence on // stream.WriteByte(0x02); //http://wiki.multimedia.cx/index.php?title=Smacker#Packed_Huffman_Trees // stream.WriteByte(0x05); // stream.WriteByte(0x0C); // stream.WriteByte(0x3A); // stream.WriteByte(0x80); // stream.WriteByte(0x00); // BitStream bs = new BitStream(stream); // bs.Reset(); //Build a new tree // Huffmantree tree = new Huffmantree(); // tree.TestDecodeTree(bs); //Our tree should look like this: // Assert.AreEqual(tree.RootNode.Left.Left.Left.Value, 3); // Assert.AreEqual(tree.RootNode.Left.Left.Right.Left.Value, 4); // Assert.AreEqual(tree.RootNode.Left.Left.Right.Right.Value, 5); // Assert.AreEqual(tree.RootNode.Left.Right.Value, 6); // Assert.AreEqual(tree.RootNode.Right.Left.Value, 7); // Assert.AreEqual(tree.RootNode.Right.Right.Value, 8); // } // [Test] // public void TestDecode() // { //Set up a memory stream first // MemoryStream stream = new MemoryStream(); // stream.WriteByte(0x6F); //These bytes correspond to the example // stream.WriteByte(0x20); //bit-sequence on // stream.WriteByte(0x02); //http://wiki.multimedia.cx/index.php?title=Smacker#Packed_Huffman_Trees // stream.WriteByte(0x05); // stream.WriteByte(0x0C); // stream.WriteByte(0x3A); // stream.WriteByte(0x80); // stream.WriteByte(0x00); // BitStream bs = new BitStream(stream); // bs.Reset(); //Build a new tree // Huffmantree tree = new Huffmantree(); // tree.TestDecodeTree(bs); // stream = new MemoryStream(); // stream.WriteByte(0x20); //Bit stream that visits every leaf // stream.WriteByte(0xB6); //000 ->3 0010 ->4 0011->5 01 -> 6 10 -> 7 11 -> 8 // stream.WriteByte(0x01); // bs = new BitStream(stream); // bs.Reset(); // Assert.AreEqual(tree.Decode(bs), 3); // Assert.AreEqual(tree.Decode(bs), 4); // Assert.AreEqual(tree.Decode(bs), 5); // Assert.AreEqual(tree.Decode(bs), 6); // Assert.AreEqual(tree.Decode(bs), 7); // Assert.AreEqual(tree.Decode(bs), 8); // } // } }
using System; /// <summary> /// Char.IsWhiteSpace(string, int) /// Indicates whether the character at specifed position in a specified string is categorized /// as a whitespace. /// </summary> public class CharIsWhiteSpace { private const int c_MIN_STR_LEN = 2; private const int c_MAX_STR_LEN = 256; private static readonly char[] r_whiteSpaceChars = { (char)0x0009, (char)0x000A, (char)0x000B, (char)0x000C, (char)0x000D, (char)0x0020, (char)0x0085, (char)0x00A0, (char)0x1680, (char)0x180E, //compatibility with desktop (char)0x2000, (char)0x2001, (char)0x2002, (char)0x2003, (char)0x2004, (char)0x2005, (char)0x2006, (char)0x2007, (char)0x2008, (char)0x2009, (char)0x200A, //(char)0x200B, (char)0x2028, (char)0x2029, (char)0x202F, (char)0x205F, //compatibility with desktop (char)0x3000, //(char)0xFEFF }; public static int Main() { CharIsWhiteSpace testObj = new CharIsWhiteSpace(); TestLibrary.TestFramework.BeginTestCase("for method: Char.IsWhiteSpace(string ,int)"); if (testObj.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; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive tests public bool PosTest1() { //Generate the character for validate int index = TestLibrary.Generator.GetInt32(-55) % r_whiteSpaceChars.Length; char ch = r_whiteSpaceChars[index]; return this.DoTest("PosTest1: Whitespace character", "P001", "001", "002", ch, true); } public bool PosTest2() { //Generate a non separator character for validate char ch = TestLibrary.Generator.GetCharLetter(-55); return this.DoTest("PosTest2: Non-whitespace character.", "P002", "003", "004", ch, false); } #endregion #region Helper method for positive tests private bool DoTest(string testDesc, string testId, string errorNum1, string errorNum2, char ch, bool expectedResult) { bool retVal = true; string errorDesc; TestLibrary.TestFramework.BeginScenario(testDesc); try { string str = new string(ch, 1); bool actualResult = char.IsWhiteSpace(str, 0); if (expectedResult != actualResult) { if (expectedResult) { errorDesc = string.Format("Character \\u{0:x} should belong to whitespace.", (int)ch); } else { errorDesc = string.Format("Character \\u{0:x} does not belong to whitespace.", (int)ch); } TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nCharacter is \\u{0:x}", ch); TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc); retVal = false; } return retVal; } #endregion #region Negative tests //ArgumentNullException public bool NegTest1() { bool retVal = true; const string c_TEST_ID = "N001"; const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic)."; string errorDesc; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { index = TestLibrary.Generator.GetInt32(-55); char.IsWhiteSpace(null, index); errorDesc = "ArgumentNullException is not thrown as expected, index is " + index; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e + "\n Index is " + index; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } //ArgumentOutOfRangeException public bool NegTest2() { bool retVal = true; const string c_TEST_ID = "N002"; const string c_TEST_DESC = "NegTest2: Index is too great."; string errorDesc; string str = string.Empty; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN); index = str.Length + TestLibrary.Generator.GetInt16(-55); index = str.Length; char.IsWhiteSpace(str, index); errorDesc = "ArgumentOutOfRangeException is not thrown as expected"; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index); TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_ID = "N003"; const string c_TEST_DESC = "NegTest3: Index is a negative value"; string errorDesc; string str = string.Empty; int index = 0; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN); index = -1 * (TestLibrary.Generator.GetInt16(-55)); char.IsWhiteSpace(str, index); errorDesc = "ArgumentOutOfRangeException is not thrown as expected"; TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { errorDesc = "Unexpected exception: " + e; errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index); TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion }
#define SQLITE_ASCII #define SQLITE_DISABLE_LFS #define SQLITE_ENABLE_OVERSIZE_CELL_CHECK #define SQLITE_MUTEX_OMIT #define SQLITE_OMIT_AUTHORIZATION #define SQLITE_OMIT_DEPRECATED #define SQLITE_OMIT_GET_TABLE #define SQLITE_OMIT_INCRBLOB #define SQLITE_OMIT_LOOKASIDE #define SQLITE_OMIT_SHARED_CACHE #define SQLITE_OMIT_UTF16 #define SQLITE_OMIT_WAL #define SQLITE_OS_WIN #define SQLITE_SYSTEM_MALLOC #define VDBE_PROFILE_OFF #define WINDOWS_MOBILE #define NDEBUG #define _MSC_VER #define YYFALLBACK using System; using System.Diagnostics; using System.Threading; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2008 October 07 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes. ** ** This implementation in this file does not provide any mutual ** exclusion and is thus suitable for use only in applications ** that use SQLite in a single thread. The routines defined ** here are place-holders. Applications can substitute working ** mutex routines at start-time using the ** ** sqlite3_config(SQLITE_CONFIG_MUTEX,...) ** ** interface. ** ** If compiled with SQLITE_DEBUG, then additional logic is inserted ** that does error checking on mutexes to make sure they are being ** called correctly. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c ** ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_DEBUG /* ** Stub routines for all mutex methods. ** ** This routines provide no mutual exclusion or error checking. */ static int noopMutexHeld(sqlite3_mutex p){ return 1; } static int noopMutexNotheld(sqlite3_mutex p){ return 1; } static int noopMutexInit(){ return SQLITE_OK; } static int noopMutexEnd(){ return SQLITE_OK; } static sqlite3_mutex noopMutexAlloc(int id){ return new sqlite3_mutex(); } static void noopMutexFree(sqlite3_mutex p){ } static void noopMutexEnter(sqlite3_mutex p){ } static int noopMutexTry(sqlite3_mutex p){ return SQLITE_OK; } static void noopMutexLeave(sqlite3_mutex p){ } sqlite3_mutex_methods sqlite3DefaultMutex(){ sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods( (dxMutexInit)noopMutexInit, (dxMutexEnd)noopMutexEnd, (dxMutexAlloc)noopMutexAlloc, (dxMutexFree)noopMutexFree, (dxMutexEnter)noopMutexEnter, (dxMutexTry)noopMutexTry, (dxMutexLeave)noopMutexLeave, #if SQLITE_DEBUG (dxMutexHeld)noopMutexHeld, (dxMutexNotheld)noopMutexNotheld #else null, null #endif ); return sMutex; } #endif //* !SQLITE_DEBUG */ #if SQLITE_DEBUG && !SQLITE_MUTEX_OMIT /* ** In this implementation, error checking is provided for testing ** and debugging purposes. The mutexes still do not provide any ** mutual exclusion. */ /* ** The mutex object */ public class sqlite3_debug_mutex : sqlite3_mutex { //public int id; /* The mutex type */ public int cnt; /* Number of entries without a matching leave */ }; /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use inside Debug.Assert() statements. */ static bool debugMutexHeld( sqlite3_mutex pX ) { sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; return p == null || p.cnt > 0; } static bool debugMutexNotheld( sqlite3_mutex pX ) { sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; return p == null || p.cnt == 0; } /* ** Initialize and deinitialize the mutex subsystem. */ static int debugMutexInit() { return SQLITE_OK; } static int debugMutexEnd() { return SQLITE_OK; } /* ** The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. If it returns NULL ** that means that a mutex could not be allocated. */ static sqlite3_mutex debugMutexAlloc( int id ) { sqlite3_debug_mutex[] aStatic = new sqlite3_debug_mutex[6]; sqlite3_debug_mutex pNew = null; switch ( id ) { case SQLITE_MUTEX_FAST: case SQLITE_MUTEX_RECURSIVE: { pNew = new sqlite3_debug_mutex();//sqlite3Malloc(sizeof(*pNew)); if ( pNew != null ) { pNew.id = id; pNew.cnt = 0; } break; } default: { Debug.Assert( id - 2 >= 0 ); Debug.Assert( id - 2 < aStatic.Length );//(int)(sizeof(aStatic)/sizeof(aStatic[0])) ); pNew = aStatic[id - 2]; pNew.id = id; break; } } return pNew; } /* ** This routine deallocates a previously allocated mutex. */ static void debugMutexFree( sqlite3_mutex pX ) { sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; Debug.Assert( p.cnt == 0 ); Debug.Assert( p.id == SQLITE_MUTEX_FAST || p.id == SQLITE_MUTEX_RECURSIVE ); //sqlite3_free(ref p); } /* ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can ** be entered multiple times by the same thread. In such cases the, ** mutex must be exited an equal number of times before another thread ** can enter. If the same thread tries to enter any other kind of mutex ** more than once, the behavior is undefined. */ static void debugMutexEnter( sqlite3_mutex pX ) { sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) ); p.cnt++; } static int debugMutexTry( sqlite3_mutex pX ) { sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) ); p.cnt++; return SQLITE_OK; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was ** previously entered by the same thread. The behavior ** is undefined if the mutex is not currently entered or ** is not currently allocated. SQLite will never do either. */ static void debugMutexLeave( sqlite3_mutex pX ) { sqlite3_debug_mutex p = (sqlite3_debug_mutex)pX; Debug.Assert( debugMutexHeld( p ) ); p.cnt--; Debug.Assert( p.id == SQLITE_MUTEX_RECURSIVE || debugMutexNotheld( p ) ); } static sqlite3_mutex_methods sqlite3NoopMutex() { sqlite3_mutex_methods sMutex = new sqlite3_mutex_methods( (dxMutexInit)debugMutexInit, (dxMutexEnd)debugMutexEnd, (dxMutexAlloc)debugMutexAlloc, (dxMutexFree)debugMutexFree, (dxMutexEnter)debugMutexEnter, (dxMutexTry)debugMutexTry, (dxMutexLeave)debugMutexLeave, (dxMutexHeld)debugMutexHeld, (dxMutexNotheld)debugMutexNotheld ); return sMutex; } #endif //* SQLITE_DEBUG */ /* ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation ** is used regardless of the run-time threadsafety setting. */ #if SQLITE_MUTEX_NOOP sqlite3_mutex_methods const sqlite3DefaultMutex(void){ return sqlite3NoopMutex(); } #endif //* SQLITE_MUTEX_NOOP */ } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using Fusion; using Fusion.Core; using Fusion.Core.Mathematics; namespace Fusion.Engine.Audio { /// <summary> /// Represnts audio emitter, the entity that emit sound in physical world. /// </summary> public sealed class AudioEmitter { SoundEffectInstance soundInstance; /// <summary> /// /// </summary> internal AudioEmitter () { dopplerScale = 1.0f; Position = Vector3.Zero; Velocity = Vector3.Zero; DistanceScale = 1; } /// <summary> /// Starts playing sound /// </summary> /// <param name="soundEffect"></param> /// <param name="options"></param> /// <param name="volume"></param> /// <param name="pitch"></param> public void PlaySound ( SoundEffect soundEffect, PlayOptions options = PlayOptions.None ) { soundInstance = soundEffect.CreateInstance(); soundInstance.IsLooped = options.HasFlag(PlayOptions.Looped); soundInstance.Play(); } /// <summary> /// Stops playing sound /// </summary> /// <param name="immediate"></param> public void StopSound ( bool immediate ) { if (soundInstance!=null) { soundInstance.Stop( immediate ); soundInstance = null; } } internal void Pause () { if (soundInstance!=null) { soundInstance.Pause(); } } internal void Resume () { if (soundInstance!=null) { soundInstance.Resume(); } } /// <summary> /// Gets sound state. /// </summary> public SoundState SoundState { get { return soundInstance.State; } } /// <summary> /// Sets and gets Doppler scale. /// Value must be non-negative. /// </summary> public float DopplerScale { get { return dopplerScale; } set { if (value < 0.0f) { throw new ArgumentOutOfRangeException("AudioEmitter.DopplerScale must be greater than or equal to 0.0f"); } dopplerScale = value; } } float dopplerScale; /// <summary> /// Gets and sets whether sound should be played locally on applying 3D effects. /// </summary> public bool LocalSound { get; set; } /// <summary> /// Gets and sets emitter's position. /// </summary> public Vector3 Position { get; set; } /// <summary> /// Gets and sets absolute emitter velocity. /// </summary> public Vector3 Velocity { get; set; } /// <summary> /// Sets and gets local emitter distance scale /// </summary> public float DistanceScale { get; set; } /// <summary> /// Volume falloff curve. Null value means inverse square law. /// </summary> public CurvePoint[] VolumeCurve { set { volumeCurve = SharpDXHelper.Convert( value ); } get { return SharpDXHelper.Convert( volumeCurve ); } } private SharpDX.X3DAudio.CurvePoint[] volumeCurve = null; /// <summary> /// /// </summary> /// <param name="listener"></param> internal void Apply3D ( AudioListener listener, int operationSet ) { if (soundInstance!=null) { soundInstance.Apply3D( listener, this, operationSet ); } } /// <summary> /// Converts to X3DAudio emitter. /// </summary> /// <returns></returns> internal SharpDX.X3DAudio.Emitter ToEmitter() { // Pulling out Vector properties for efficiency. var pos = this.Position; var vel = this.Velocity; var fwd = Vector3.ForwardRH; var up = Vector3.Up; // From MSDN: // X3DAudio uses a left-handed Cartesian coordinate system, // with values on the x-axis increasing from left to right, on the y-axis from bottom to top, // and on the z-axis from near to far. // Azimuths are measured clockwise from a given reference direction. // // From MSDN: // The XNA Framework uses a right-handed coordinate system, // with the positive z-axis pointing toward the observer when the positive x-axis is pointing to the right, // and the positive y-axis is pointing up. // // Programmer Notes: // According to this description the z-axis (forward vector) is inverted between these two coordinate systems. // Therefore, we need to negate the z component of any position/velocity values, and negate any forward vectors. fwd *= -1.0f; pos.Z *= -1.0f; vel.Z *= -1.0f; var emitter = new SharpDX.X3DAudio.Emitter(); emitter.ChannelCount = 1; emitter.Position = SharpDXHelper.Convert( pos ); emitter.Velocity = SharpDXHelper.Convert( vel ); emitter.OrientFront = SharpDXHelper.Convert( fwd ); emitter.OrientTop = SharpDXHelper.Convert( up ); emitter.DopplerScaler = DopplerScale; emitter.CurveDistanceScaler = DistanceScale; emitter.VolumeCurve = volumeCurve; return emitter; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml; using Palaso.Lift.Validation; using Palaso.Xml; namespace Palaso.Lift.Merging { /// <summary> /// Class to merge two or more LIFT files that are created incrementally, such that /// 1) the data in previous ones is overwritten by data in newer ones /// 2) the *entire contents* of the new entry element replaces the previous contents /// I.e., merging is only on an entry level. /// </summary> public class SynchronicMerger { // private string _pathToBaseLiftFile; ///<summary></summary> public const string ExtensionOfIncrementalFiles = ".lift.update"; /// <summary> /// /// </summary> /// <exception cref="IOException">If file is locked</exception> /// <exception cref="LiftFormatException">If there is an error and then file is found to be non-conformant.</exception> /// <param name="pathToBaseLiftFile"></param> public bool MergeUpdatesIntoFile(string pathToBaseLiftFile) { // _pathToBaseLiftFile = pathToBaseLiftFile; FileInfo[] files = GetPendingUpdateFiles(pathToBaseLiftFile); return MergeUpdatesIntoFile(pathToBaseLiftFile, files); } /// <summary> /// Given a LIFT file and a set of .lift.update files, apply the changes to the LIFT file and delete the .lift.update files. /// </summary> /// <param name="pathToBaseLiftFile">The LIFT file containing all the lexical entries for a paticular language project</param> /// <param name="files">These files contain the changes the user has made. Changes to entries; New entries; Deleted entries</param> /// <returns></returns> /// <exception cref="IOException">If file is locked</exception> /// <exception cref="LiftFormatException">If there is an error and then file is found to be non-conformant.</exception> /// public bool MergeUpdatesIntoFile(string pathToBaseLiftFile, FileInfo[] files) { if (files.Length < 1) { return false; } Array.Sort(files, new FileInfoLastWriteTimeComparer()); int count = files.Length; string pathToMergeInTo = pathToBaseLiftFile; // files[0].FullName; FileAttributes fa = File.GetAttributes(pathToBaseLiftFile); if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { return false; } for (int i = 0; i < count; i++) { if (files[i].IsReadOnly) { //todo: "Cannot merge safely because at least one file is read only: {0} return true; } } bool mergedAtLeastOne = false; List<string> filesToDelete = new List<string>(); for (int i = 0; i < count; i++) { //let empty files be as if they didn't exist. They do represent that something //went wrong, but (at least in WeSay) we can detect that something by a more //accurate means, and these just get in the way if (files[i].Length < 100) //sometimes empty files register as having a few bytes { string contents = File.ReadAllText(files[i].FullName); if (contents.Trim().Length == 0) { File.Delete(files[i].FullName); continue; } } // We will want to call LiftSorter.SortLiftFile() with this temporary // filename, and it thus MUST end with ".lift". string outputPath = Path.GetTempFileName() + ".lift"; try { MergeInNewFile(pathToMergeInTo, files[i].FullName, outputPath); } catch (IOException) { // todo: "Cannot most likely one of the files is locked File.Delete(outputPath); throw; } catch (Exception) { try { Validator.CheckLiftWithPossibleThrow(files[i].FullName); } catch (Exception e2) { File.Delete(outputPath); throw new BadUpdateFileException(pathToMergeInTo, files[i].FullName, e2); } //eventually we'll just check everything before-hand. But for now our rng //validator is painfully slow in files which have date stamps, //because two formats are allowed an our mono rng validator //throws non-fatal exceptions for each one Validator.CheckLiftWithPossibleThrow(pathToBaseLiftFile); throw; //must have been something else } pathToMergeInTo = outputPath; filesToDelete.Add(outputPath); mergedAtLeastOne = true; } if (!mergedAtLeastOne) { return false; } //string pathToBaseLiftFile = Path.Combine(directory, BaseLiftFileName); Debug.Assert(File.Exists(pathToMergeInTo)); MakeBackup(pathToBaseLiftFile, pathToMergeInTo); //delete all the non-base paths foreach (FileInfo file in files) { if (file.FullName != pathToBaseLiftFile && File.Exists(file.FullName)) { file.Delete(); } } //delete all our temporary files foreach (string s in filesToDelete) { File.Delete(s); } return true; } private static void MakeBackup(string pathToBaseLiftFile, string pathToMergeInTo) { // File.Move works across volumes but the destination cannot exist. if (File.Exists(pathToBaseLiftFile)) { string backupOfBackup; do { backupOfBackup = pathToBaseLiftFile + Path.GetRandomFileName(); } while(File.Exists(backupOfBackup)); string bakPath = pathToBaseLiftFile+".bak"; if (File.Exists(bakPath)) { // move the backup out of the way, if something fails here we have nothing to do if ((File.GetAttributes(bakPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { bakPath = GetNextAvailableBakPath(bakPath); } else { try { File.Move(bakPath, backupOfBackup); } catch (IOException) { // back file is Locked. Create the next available backup Path bakPath = GetNextAvailableBakPath(bakPath); } } } try { File.Move(pathToBaseLiftFile, bakPath); try { File.Move(pathToMergeInTo, pathToBaseLiftFile); } catch { // roll back to prior state File.Move(bakPath, pathToBaseLiftFile); throw; } } catch { // roll back to prior state if (File.Exists(backupOfBackup)) { File.Move(backupOfBackup, bakPath); } throw; } //everything was successful so can get rid of backupOfBackup if (File.Exists(backupOfBackup)) { File.Delete(backupOfBackup); } } else { File.Move(pathToMergeInTo, pathToBaseLiftFile); } } ///<summary> ///</summary> ///<exception cref="ArgumentException"></exception> public static FileInfo[] GetPendingUpdateFiles(string pathToBaseLiftFile) { //see ws-1035 if(!pathToBaseLiftFile.Contains(Path.DirectorySeparatorChar.ToString())) { throw new ArgumentException("pathToBaseLiftFile must be a full path, not just a file name. Path was "+pathToBaseLiftFile); } // ReSharper disable AssignNullToNotNullAttribute var di = new DirectoryInfo(Path.GetDirectoryName(pathToBaseLiftFile)); // ReSharper restore AssignNullToNotNullAttribute var files = di.GetFiles("*"+ExtensionOfIncrementalFiles, SearchOption.TopDirectoryOnly); //files comes back unsorted, sort by creation time before returning. Array.Sort(files, new Comparison<FileInfo>((a, b) => a.CreationTime.CompareTo(b.CreationTime))); return files; } static private void TestWriting(XmlWriter w) { // w.WriteStartDocument(); w.WriteStartElement("start"); w.WriteElementString("one", "hello"); w.WriteElementString("two", "bye"); w.WriteEndElement(); // w.WriteEndDocument(); } ///<summary></summary> static public void TestWritingFile() { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; // nb: don't use XmlTextWriter.Create, that's broken. Ignores the indent setting using (XmlWriter writer = XmlWriter.Create("C:\\test.xml", settings)) { TestWriting(writer); } } private static string GetNextAvailableBakPath(string bakPath) { int i = 0; string newBakPath; do { i++; newBakPath = bakPath + i; } while (File.Exists(newBakPath)); bakPath = newBakPath; return bakPath; } private void MergeInNewFile(string olderFilePath, string newerFilePath, string outputPath) { XmlDocument newerDoc = new XmlDocument(); newerDoc.Load(newerFilePath); XmlWriterSettings settings = new XmlWriterSettings(); settings.NewLineOnAttributes = true; //ugly, but great for merging with revision control systems settings.NewLineChars = "\r\n"; settings.Indent = true; settings.IndentChars = "\t"; settings.CheckCharacters = false; // nb: don't use XmlTextWriter.Create, that's broken. Ignores the indent setting using (XmlWriter writer = XmlWriter.Create(outputPath /*Console.Out*/, settings)) { //For each entry in the new guy, read through the whole base file XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CheckCharacters = false;//without this, we die if we simply encounter a (properly escaped) other-wise illegal unicode character, e.g. &#x1F; readerSettings.IgnoreWhitespace = true; //if the reader returns whitespace, the writer ceases to format xml after that point using (XmlReader olderReader = XmlReader.Create(olderFilePath, readerSettings)) { //bool elementWasReplaced = false; while (!olderReader.EOF) { ProcessOlderNode(olderReader, newerDoc, writer); } } } // After writing the updated file, ensure that it ends up sorted correctly. LiftSorter.SortLiftFile(outputPath); } private void ProcessOlderNode(XmlReader olderReader, XmlDocument newerDoc, XmlWriter writer) { switch (olderReader.NodeType) { case XmlNodeType.EndElement: case XmlNodeType.Element: ProcessElement(olderReader, writer, newerDoc); break; default: Utilities.WriteShallowNode(olderReader, writer); break; } } private void ProcessElement(XmlReader olderReader, XmlWriter writer, XmlDocument newerDoc) { //empty lift file, write new elements if ( olderReader.Name == "lift" && olderReader.IsEmptyElement) //i.e., <lift/> { writer.WriteStartElement("lift"); writer.WriteAttributes(olderReader, true); if (newerDoc != null) { var nodes = newerDoc.SelectNodes("//entry"); if (nodes != null) { foreach (XmlNode n in nodes) { writer.WriteNode(n.CreateNavigator(), true /*REVIEW*/); //REVIEW CreateNavigator } } } //write out the closing lift element writer.WriteEndElement(); olderReader.Read(); } //hit the end, write out any remaing new elements else if (olderReader.Name == "lift" && olderReader.NodeType == XmlNodeType.EndElement) { var nodes = newerDoc.SelectNodes("//entry"); if (nodes != null) { foreach (XmlNode n in nodes) //REVIEW CreateNavigator { writer.WriteNode(n.CreateNavigator(), true /*REVIEW*/); } } //write out the closing lift element writer.WriteNode(olderReader, true); } else { if (olderReader.Name == "entry") { MergeLiftUpdateEntryIntoLiftFile(olderReader, writer, newerDoc); } else { Utilities.WriteShallowNode(olderReader, writer); } } } protected virtual void MergeLiftUpdateEntryIntoLiftFile(XmlReader olderReader, XmlWriter writer, XmlDocument newerDoc) { string oldId = olderReader.GetAttribute("guid"); if (String.IsNullOrEmpty(oldId)) { throw new ApplicationException("All entries must have guid attributes in order for merging to work. " + olderReader.Value); } XmlNode match = newerDoc.SelectSingleNode("//entry[@guid='" + oldId + "']"); if (match != null) { olderReader.Skip(); //skip the old one writer.WriteNode(match.CreateNavigator(), true); //REVIEW CreateNavigator if (match.ParentNode != null) match.ParentNode.RemoveChild(match); } else { // The default XmlWriter.WriteNode() method is insufficient to write <text> nodes // properly if they start with a <span> node! // See https://jira.palaso.org/issues/browse/WS-34794. var element = olderReader.ReadOuterXml(); XmlUtils.WriteNode(writer, element, LiftSorter.LiftSuppressIndentingChildren); } } internal class FileInfoLastWriteTimeComparer : IComparer<FileInfo> { public int Compare(FileInfo x, FileInfo y) { int timecomparison = DateTime.Compare(x.LastWriteTimeUtc, y.LastWriteTimeUtc); if (timecomparison == 0) { // if timestamps are the same, then sort by name return StringComparer.OrdinalIgnoreCase.Compare(x.FullName, y.FullName); } return timecomparison; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection.Runtime.General; using System.Reflection.Runtime.BindingFlagSupport; namespace System.Reflection.Runtime.TypeInfos { internal abstract partial class RuntimeTypeInfo { public sealed override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) => Query<ConstructorInfo>(bindingAttr).ToArray(); protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(types != null); QueryResult<ConstructorInfo> queryResult = Query<ConstructorInfo>(bindingAttr); ListBuilder<ConstructorInfo> candidates = new ListBuilder<ConstructorInfo>(); foreach (ConstructorInfo candidate in queryResult) { if (candidate.QualifiesBasedOnParameterCount(bindingAttr, callConvention, types)) candidates.Add(candidate); } // For perf and desktop compat, fast-path these specific checks before calling on the binder to break ties. if (candidates.Count == 0) return null; if (types.Length == 0 && candidates.Count == 1) { ConstructorInfo firstCandidate = candidates[0]; ParameterInfo[] parameters = firstCandidate.GetParametersNoCopy(); if (parameters.Length == 0) return firstCandidate; } if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactBinding(candidates.ToArray(), types, modifiers) as ConstructorInfo; if (binder == null) binder = DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as ConstructorInfo; } public sealed override EventInfo[] GetEvents(BindingFlags bindingAttr) => Query<EventInfo>(bindingAttr).ToArray(); public sealed override EventInfo GetEvent(string name, BindingFlags bindingAttr) => Query<EventInfo>(name, bindingAttr).Disambiguate(); public sealed override FieldInfo[] GetFields(BindingFlags bindingAttr) => Query<FieldInfo>(bindingAttr).ToArray(); public sealed override FieldInfo GetField(string name, BindingFlags bindingAttr) => Query<FieldInfo>(name, bindingAttr).Disambiguate(); public sealed override MethodInfo[] GetMethods(BindingFlags bindingAttr) => Query<MethodInfo>(bindingAttr).ToArray(); protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMethodImplCommon(name, GenericParameterCountAny, bindingAttr, binder, callConvention, types, modifiers); } protected sealed override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMethodImplCommon(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers); } private MethodInfo GetMethodImplCommon(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(name != null); // GetMethodImpl() is a funnel for two groups of api. We can distinguish by comparing "types" to null. if (types == null) { // Group #1: This group of api accept only a name and BindingFlags. The other parameters are hard-wired by the non-virtual api entrypoints. Debug.Assert(genericParameterCount == GenericParameterCountAny); Debug.Assert(binder == null); Debug.Assert(callConvention == CallingConventions.Any); Debug.Assert(modifiers == null); return Query<MethodInfo>(name, bindingAttr).Disambiguate(); } else { // Group #2: This group of api takes a set of parameter types and an optional binder. QueryResult<MethodInfo> queryResult = Query<MethodInfo>(name, bindingAttr); ListBuilder<MethodInfo> candidates = new ListBuilder<MethodInfo>(); foreach (MethodInfo candidate in queryResult) { if (genericParameterCount != GenericParameterCountAny && genericParameterCount != candidate.GenericParameterCount) continue; if (candidate.QualifiesBasedOnParameterCount(bindingAttr, callConvention, types)) candidates.Add(candidate); } if (candidates.Count == 0) return null; // For perf and desktop compat, fast-path these specific checks before calling on the binder to break ties. if (types.Length == 0 && candidates.Count == 1) return candidates[0]; if (binder == null) binder = DefaultBinder; return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo; } } public sealed override Type[] GetNestedTypes(BindingFlags bindingAttr) => Query<Type>(bindingAttr).ToArray(); public sealed override Type GetNestedType(string name, BindingFlags bindingAttr) => Query<Type>(name, bindingAttr).Disambiguate(); public sealed override PropertyInfo[] GetProperties(BindingFlags bindingAttr) => Query<PropertyInfo>(bindingAttr).ToArray(); protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(name != null); // GetPropertyImpl() is a funnel for two groups of api. We can distinguish by comparing "types" to null. if (types == null && returnType == null) { // Group #1: This group of api accept only a name and BindingFlags. The other parameters are hard-wired by the non-virtual api entrypoints. Debug.Assert(binder == null); Debug.Assert(modifiers == null); return Query<PropertyInfo>(name, bindingAttr).Disambiguate(); } else { // Group #2: This group of api takes a set of parameter types, a return type (both cannot be null) and an optional binder. QueryResult<PropertyInfo> queryResult = Query<PropertyInfo>(name, bindingAttr); ListBuilder<PropertyInfo> candidates = new ListBuilder<PropertyInfo>(); foreach (PropertyInfo candidate in queryResult) { if (types == null || (candidate.GetIndexParameters().Length == types.Length)) { candidates.Add(candidate); } } if (candidates.Count == 0) return null; // For perf and desktop compat, fast-path these specific checks before calling on the binder to break ties. if (types == null || types.Length == 0) { // no arguments if (candidates.Count == 1) { PropertyInfo firstCandidate = candidates[0]; if ((object)returnType != null && !returnType.IsEquivalentTo(firstCandidate.PropertyType)) return null; return firstCandidate; } else { if ((object)returnType == null) // if we are here we have no args or property type to select over and we have more than one property with that name throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } } if ((bindingAttr & BindingFlags.ExactBinding) != 0) return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers); if (binder == null) binder = DefaultBinder; return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers); } } private QueryResult<M> Query<M>(BindingFlags bindingAttr) where M : MemberInfo { return Query<M>(null, bindingAttr, null); } private QueryResult<M> Query<M>(string name, BindingFlags bindingAttr) where M : MemberInfo { if (name == null) throw new ArgumentNullException(nameof(name)); return Query<M>(name, bindingAttr, null); } private QueryResult<M> Query<M>(string optionalName, BindingFlags bindingAttr, Func<M, bool> optionalPredicate) where M : MemberInfo { MemberPolicies<M> policies = MemberPolicies<M>.Default; bindingAttr = policies.ModifyBindingFlags(bindingAttr); bool ignoreCase = (bindingAttr & BindingFlags.IgnoreCase) != 0; TypeComponentsCache cache = Cache; QueriedMemberList<M> queriedMembers; if (optionalName == null) queriedMembers = cache.GetQueriedMembers<M>(); else queriedMembers = cache.GetQueriedMembers<M>(optionalName, ignoreCase: ignoreCase); if (optionalPredicate != null) queriedMembers = queriedMembers.Filter(optionalPredicate); return new QueryResult<M>(bindingAttr, queriedMembers); } private TypeComponentsCache Cache => _lazyCache ?? (_lazyCache = new TypeComponentsCache(this)); private volatile TypeComponentsCache _lazyCache; private const int GenericParameterCountAny = -1; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Reflection; namespace System.ComponentModel { /// <summary> /// The TypeDescriptionProvider class can be thought of as a "plug-in" for /// TypeDescriptor. There can be multiple type description provider classes /// all offering metadata to TypeDescriptor /// </summary> public abstract class TypeDescriptionProvider { private readonly TypeDescriptionProvider _parent; private EmptyCustomTypeDescriptor _emptyDescriptor; /// <summary> /// There are two versions of the constructor for this class. The empty /// constructor is identical to using TypeDescriptionProvider(null). /// If a child type description provider is passed into the constructor, /// the "base" versions of all methods will call to this parent provider. /// If no such provider is given, the base versions of the methods will /// return empty, but valid values. /// </summary> protected TypeDescriptionProvider() { } /// <summary> /// There are two versions of the constructor for this class. The empty /// constructor is identical to using TypeDescriptionProvider(null). /// If a child type description provider is passed into the constructor, /// the "base" versions of all methods will call to this parent provider. /// If no such provider is given, the base versions of the methods will /// return empty, but valid values. /// </summary> protected TypeDescriptionProvider(TypeDescriptionProvider parent) { _parent = parent; } /// <summary> /// This method is used to create an instance that can substitute for another /// data type. If the method is not interested in providing a substitute /// instance, it should call base. /// /// This method is prototyped as virtual, and by default returns null if no /// parent provider was passed. If a parent provider was passed, this /// method will invoke the parent provider's CreateInstance method. /// </summary> public virtual object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { if (_parent != null) { return _parent.CreateInstance(provider, objectType, argTypes, args); } if (objectType == null) { throw new ArgumentNullException(nameof(objectType)); } return Activator.CreateInstance(objectType, args); } /// <summary> /// TypeDescriptor may need to perform complex operations on collections of metadata. /// Since types are not unloaded for the life of a domain, TypeDescriptor will /// automatically cache the results of these operations based on type. There are a /// number of operations that use live object instances, however. These operations /// cannot be cached within TypeDescriptor because caching them would prevent the /// object from garbage collecting. Instead, TypeDescriptor allows for a per-object /// cache, accessed as an IDictionary of key/value pairs, to exist on an object. /// The GetCache method returns an instance of this cache. GetCache will return /// null if there is no supported cache for an object. /// </summary> public virtual IDictionary GetCache(object instance) { if (_parent != null) { return _parent.GetCache(instance); } return null; } /// <summary> /// This method returns an extended custom type descriptor for the given object. /// An extended type descriptor is a custom type descriptor that offers properties /// that other objects have added to this object, but are not actually defined on /// the object. For example, in the .NET Framework Component Model, objects that /// implement the interface IExtenderProvider can "attach" properties to other /// objects that reside in the same logical container. The GetTypeDescriptor /// method does not return a type descriptor that provides these extra extended /// properties. GetExtendedTypeDescriptor returns the set of these extended /// properties. TypeDescriptor will automatically merge the results of these /// two property collections. Note that while the .NET Framework component /// model only supports extended properties this API can be used for extended /// attributes and events as well, if the type description provider supports it. /// </summary> public virtual ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { if (_parent != null) { return _parent.GetExtendedTypeDescriptor(instance); } if (_emptyDescriptor == null) { _emptyDescriptor = new EmptyCustomTypeDescriptor(); } return _emptyDescriptor; } protected internal virtual IExtenderProvider[] GetExtenderProviders(object instance) { if (_parent != null) { return _parent.GetExtenderProviders(instance); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return new IExtenderProvider[0]; } /// <summary> /// The name of the specified component, or null if the component has no name. /// In many cases this will return the same value as GetComponentName. If the /// component resides in a nested container or has other nested semantics, it may /// return a different fully qualfied name. /// /// If not overridden, the default implementation of this method will call /// GetTypeDescriptor.GetComponentName. /// </summary> public virtual string GetFullComponentName(object component) { if (_parent != null) { return _parent.GetFullComponentName(component); } return GetTypeDescriptor(component).GetComponentName(); } /// <summary> /// The GetReflection method is a lower level version of GetTypeDescriptor. /// If no custom type descriptor can be located for an object, GetReflectionType /// is called to perform normal reflection against the object. /// </summary> public Type GetReflectionType(Type objectType) { return GetReflectionType(objectType, null); } /// <summary> /// The GetReflection method is a lower level version of GetTypeDescriptor. /// If no custom type descriptor can be located for an object, GetReflectionType /// is called to perform normal reflection against the object. /// /// This method is prototyped as virtual, and by default returns the /// object type if no parent provider was passed. If a parent provider was passed, this /// method will invoke the parent provider's GetReflectionType method. /// </summary> public Type GetReflectionType(object instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return GetReflectionType(instance.GetType(), instance); } /// <summary> /// The GetReflection method is a lower level version of GetTypeDescriptor. /// If no custom type descriptor can be located for an object, GetReflectionType /// is called to perform normal reflection against the object. /// /// This method is prototyped as virtual, and by default returns the /// object type if no parent provider was passed. If a parent provider was passed, this /// method will invoke the parent provider's GetReflectionType method. /// </summary> public virtual Type GetReflectionType(Type objectType, object instance) { if (_parent != null) { return _parent.GetReflectionType(objectType, instance); } return objectType; } /// <summary> /// The GetRuntimeType method reverses GetReflectionType to convert a reflection type /// back into a runtime type. Historically the Type.UnderlyingSystemType property has /// been used to return the runtime type. This isn't exactly correct, but it needs /// to be preserved unless all type description providers are revised. /// </summary> public virtual Type GetRuntimeType(Type reflectionType) { if (_parent != null) { return _parent.GetRuntimeType(reflectionType); } if (reflectionType == null) { throw new ArgumentNullException(nameof(reflectionType)); } if (reflectionType.GetType().GetTypeInfo().Assembly == typeof(object).GetTypeInfo().Assembly) { return reflectionType; } return reflectionType.GetTypeInfo().UnderlyingSystemType; } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return base. /// </summary> public ICustomTypeDescriptor GetTypeDescriptor(Type objectType) { return GetTypeDescriptor(objectType, null); } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return base. /// </summary> public ICustomTypeDescriptor GetTypeDescriptor(object instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return GetTypeDescriptor(instance.GetType(), instance); } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return base. /// /// This method is prototyped as virtual, and by default returns a /// custom type descriptor that returns empty collections for all values /// if no parent provider was passed. If a parent provider was passed, /// this method will invoke the parent provider's GetTypeDescriptor /// method. /// </summary> public virtual ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { if (_parent != null) { return _parent.GetTypeDescriptor(objectType, instance); } if (_emptyDescriptor == null) { _emptyDescriptor = new EmptyCustomTypeDescriptor(); } return _emptyDescriptor; } /// <summary> /// This method returns true if the type is "supported" by the type descriptor /// and its chain of type description providers. /// </summary> public virtual bool IsSupportedType(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (_parent != null) { return _parent.IsSupportedType(type); } return true; } /// <summary> /// A simple empty descriptor that is used as a placeholder for times /// when the user does not provide their own. /// </summary> private sealed class EmptyCustomTypeDescriptor : CustomTypeDescriptor { } } }
/* * 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.Cache.Query { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cache.Query; /// <summary> /// SQL fields query. /// </summary> public class SqlFieldsQuery : IQueryBaseInternal { /// <summary> Default page size. </summary> public const int DefaultPageSize = 1024; /// <summary> /// Constructor. /// </summary> /// <param name="sql">SQL.</param> /// <param name="args">Arguments.</param> public SqlFieldsQuery(string sql, params object[] args) : this(sql, false, args) { // No-op. } /// <summary> /// Constructor, /// </summary> /// <param name="sql">SQL.</param> /// <param name="loc">Whether query should be executed locally.</param> /// <param name="args">Arguments.</param> public SqlFieldsQuery(string sql, bool loc, params object[] args) { Sql = sql; Local = loc; Arguments = args; PageSize = DefaultPageSize; } /// <summary> /// SQL. /// </summary> public string Sql { get; set; } /// <summary> /// Arguments. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] Arguments { get; set; } /// <summary> /// Local flag. When set query will be executed only on local node, so only local /// entries will be returned as query result. /// <para /> /// Defaults to <c>false</c>. /// </summary> public bool Local { get; set; } /// <summary> /// Optional page size. /// <para /> /// Defaults to <see cref="DefaultPageSize"/>. /// </summary> public int PageSize { get; set; } /// <summary> /// Gets or sets a value indicating whether distributed joins should be enabled for this query. /// <para /> /// When disabled, join results will only contain colocated data (joins work locally). /// When enabled, joins work as expected, no matter how the data is distributed. /// </summary> /// <value> /// <c>true</c> if enable distributed joins should be enabled; otherwise, <c>false</c>. /// </value> public bool EnableDistributedJoins { get; set; } /// <summary> /// Gets or sets a value indicating whether join order of tables should be enforced. /// <para /> /// When true, query optimizer will not reorder tables in join. /// <para /> /// It is not recommended to enable this property until you are sure that your indexes /// and the query itself are correct and tuned as much as possible but /// query optimizer still produces wrong join order. /// </summary> /// <value> /// <c>true</c> if join order should be enforced; otherwise, <c>false</c>. /// </value> public bool EnforceJoinOrder { get; set; } /// <summary> /// Gets or sets the query timeout. Query will be automatically cancelled if the execution timeout is exceeded. /// Default is <see cref="TimeSpan.Zero"/>, which means no timeout. /// </summary> public TimeSpan Timeout { get; set; } /// <summary> /// Gets or sets a value indicating whether this query contains only replicated tables. /// This is a hint for potentially more effective execution. /// </summary> [Obsolete("No longer used as of Apache Ignite 2.8.")] public bool ReplicatedOnly { get; set; } /// <summary> /// Gets or sets a value indicating whether this query operates on colocated data. /// <para /> /// Whenever Ignite executes a distributed query, it sends sub-queries to individual cluster members. /// If you know in advance that the elements of your query selection are colocated together on the same /// node and you group by colocated key (primary or affinity key), then Ignite can make significant /// performance and network optimizations by grouping data on remote nodes. /// </summary> public bool Colocated { get; set; } /// <summary> /// Gets or sets the default schema name for the query. /// <para /> /// If not set, current cache name is used, /// which means you can omit schema name for tables within the current cache. /// </summary> public string Schema { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="SqlFieldsQuery"/> is lazy. /// <para /> /// By default Ignite attempts to fetch the whole query result set to memory and send it to the client. /// For small and medium result sets this provides optimal performance and minimize duration of internal /// database locks, thus increasing concurrency. /// <para /> /// If result set is too big to fit in available memory this could lead to excessive GC pauses and even /// OutOfMemoryError. Use this flag as a hint for Ignite to fetch result set lazily, thus minimizing memory /// consumption at the cost of moderate performance hit. /// </summary> public bool Lazy { get; set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { var args = string.Join(", ", Arguments.Select(x => x == null ? "null" : x.ToString())); return string.Format("SqlFieldsQuery [Sql={0}, Arguments=[{1}], Local={2}, PageSize={3}, " + "EnableDistributedJoins={4}, EnforceJoinOrder={5}, Timeout={6}, ReplicatedOnly={7}" + ", Colocated={8}, Schema={9}, Lazy={10}]", Sql, args, Local, #pragma warning disable 618 PageSize, EnableDistributedJoins, EnforceJoinOrder, Timeout, ReplicatedOnly, #pragma warning restore 618 Colocated, Schema, Lazy); } /** <inheritdoc /> */ void IQueryBaseInternal.Write(BinaryWriter writer, bool keepBinary) { Write(writer); } /// <summary> /// Writes this query. /// </summary> internal void Write(BinaryWriter writer) { writer.WriteBoolean(Local); writer.WriteString(Sql); writer.WriteInt(PageSize); QueryBase.WriteQueryArgs(writer, Arguments); writer.WriteBoolean(EnableDistributedJoins); writer.WriteBoolean(EnforceJoinOrder); writer.WriteBoolean(Lazy); // Lazy flag. writer.WriteInt((int) Timeout.TotalMilliseconds); #pragma warning disable 618 writer.WriteBoolean(ReplicatedOnly); #pragma warning restore 618 writer.WriteBoolean(Colocated); writer.WriteString(Schema); // Schema } /** <inheritdoc /> */ CacheOp IQueryBaseInternal.OpId { get { return CacheOp.QrySqlFields; } } } }
//--------------------------------------------------------------------------- // // <copyright file="CacheHelper.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Static class that manages prefetching and normalization // // History: // 03/10/2004 : BrendanM Created // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.ComponentModel; using MS.Win32; // For methods that support prefetching, ClientAPI sends the UiaCoreApi // a cacherequest that lists the relatives of the element (TreeScope) // and properties/patterns to return. The API returns with a CacheResponse // with all this information "flattened out" - this class has the task // of inflating that response into a tree of AutomationElements. // // The response consists of two parts: // A 2-D array of property values: // There is one row for every element (usually just the target element // itself, but can also include rows for children and descendants if // TreeScope was used). // Each row then consists of: // - a value that is the hnode for the element (unless AutomationElementMode // is empty, in which case this slot is null). // - values for the requested properties // - values for the requetsed patterns // // The values in the 2-D array are Variant-based objects when we get them // back from the unmanaged API - we immediately convert them to the appropriate // CLR type before we use that array - this conversion is done in the CacheResponse // ctor in UiaCoreApis. This conversion, for example: // converts ints to appropriate enums // converts int[]s to Rects for BoundingRectangle // converts the inital object representing the hnode to a SafeHandle // converts objects representing hpatterns to SafeHandles. // // The second part of the response is a string describing the tree structure // - this is a lisp-like tree description, and it describes a traversal // of the tree - a '(' every time a node is entered, and a ')' every time // a node is left. // A simple tree consisting of a single node with two children would be // represented by the string "(()())". // The AutomationElement tree structure can be determined by parsing this // string. // // This string is modified slightly from the description above - if a node // in the tree also has a row of properties in the table - which is the // usual case - then the '(' is replaced with a 'P'. The rows in the table // are stored in "preorder traversal order", so they can easily be matched // up with successive 'P's from the tree description string. namespace MS.Internal.Automation { static class CacheHelper { //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal static AutomationElement BuildAutomationElementsFromResponse( UiaCoreApi.UiaCacheRequest cacheRequest, UiaCoreApi.UiaCacheResponse response) { if (response.TreeStructure == null) { Debug.Assert(response.RequestedData == null, "both RequestedData and TreeStructure should be null or non-null"); return null; } // FrozenCacheRequest should not be null one new AE code, but may // still be null on old code paths - eg. top level window events - where // prefetching is not yet enabled. if (cacheRequest == null) { cacheRequest = CacheRequest.DefaultUiaCacheRequest; } // ParseTreeDescription is the method that parses the returned data // and builds up the tree, setting properties on each node as it goes along... // index and propIndex keep track of where it is, and we check afterwards // that all are pointing to the end, to ensure that everything matched // up as expected. int index = 0; int propIndex = 0; bool askedForChildren = (cacheRequest.TreeScope & TreeScope.Children) != 0; bool askedForDescendants = (cacheRequest.TreeScope & TreeScope.Descendants) != 0; AutomationElement root = ParseTreeDescription(response.TreeStructure, response.RequestedData, ref index, ref propIndex, cacheRequest, askedForChildren, askedForDescendants); if (index != response.TreeStructure.Length) { Debug.Assert(false, "Internal error: got malformed tree description string (extra chars at end)"); return null; } if (response.RequestedData != null && propIndex != response.RequestedData.GetLength(0)) { Debug.Assert(false, "Internal error: mismatch between count of property buckets and nodes claiming them"); return null; } // Properties are wrapped (eg. pattern classes inserted in front of interface) as // they are being returned to the caller, in the AutomationElement accessors, not here. return root; } #endregion Internal Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // Parses the string as returned from ElementSearcher - see ElementSearcher.cs // for a description of the format string. Summary is that it is a lisp-like // set of parens indicating tree structure (eg. "(()())" indicates a node containing // two child nodes), but uses 'P' instead of an open paran to indicate that the // corresonding node has a property array that needs to be associated with it. // // index is the current position in the tree strucure string, // propIndex is the current position in the array of property arrays // (an array of properties returned for each element that matches the // condition specified in the Searcher condition.) private static AutomationElement ParseTreeDescription( string treeDescription, object[,] properties, ref int index, ref int propIndex, UiaCoreApi.UiaCacheRequest cacheRequest, bool askedForChildren, bool askedForDescendants ) { // Check that this is a 'begin node' tag (with or without properties)... if (string.IsNullOrEmpty(treeDescription)) return null; char c = treeDescription[index]; if (c != '(' && c != 'P') { return null; } bool havePropertiesForThisNode = c == 'P'; index++; SafeNodeHandle hnode = null; // If we have information for this node, and we want full remote // references back, then extract the hnode from the first slot of that // element's property row... if (havePropertiesForThisNode && cacheRequest.AutomationElementMode == AutomationElementMode.Full) { hnode = (SafeNodeHandle)properties[propIndex, 0]; } // Attach properties if present... object[,] cachedValues = null; int cachedValueIndex = 0; if (havePropertiesForThisNode) { cachedValues = properties; cachedValueIndex = propIndex; propIndex++; } AutomationElement node = new AutomationElement(hnode, cachedValues, cachedValueIndex, cacheRequest); if( askedForChildren || askedForDescendants ) { // If we did request children or descendants at this level, then set the // cached first child to null - it may get overwritten with // an actual value later; but the key thing is that it gets // set so we can distinguish the "asked, but doesn't have one" from // the "didn't ask" case. (Internally, AutomationElement uses // 'this' to indicate the later case, and throws an exception if // you ask for the children without having previously asked // for them in a CacheRequest.) node.SetCachedFirstChild(null); } // Add in children... AutomationElement prevChild = null; for (; ; ) { // Recursively parse the string... AutomationElement child = ParseTreeDescription( treeDescription, properties, ref index, ref propIndex, cacheRequest, askedForDescendants, askedForDescendants); if (child == null) break; // Then link child node into tree... child.SetCachedParent(node); if (prevChild == null) { node.SetCachedFirstChild(child); } else { prevChild.SetCachedNextSibling(child); } prevChild = child; } // Ensure that end node tag is present... if (treeDescription[index] != ')') { Debug.Assert(false, "Internal error: Got malformed tree description string, missing closing paren"); return null; } index++; return node; } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // Static class - no private fields #endregion Private Fields } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using Xunit; using Xunit.Abstractions; using static System.Runtime.InteropServices.MemoryMarshal; namespace System.Slices.Tests { public class UsageScenarioTests { private readonly ITestOutputHelper output; public UsageScenarioTests(ITestOutputHelper output) { this.output = output; } private struct MyByte { public MyByte(byte value) { Value = value; } public byte Value { get; private set; } } [Theory] [InlineData(new byte[] { })] [InlineData(new byte[] { 0 })] [InlineData(new byte[] { 0, 1 })] [InlineData(new byte[] { 0, 1, 2 })] [InlineData(new byte[] { 0, 1, 2, 3 })] [InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })] public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array) { Span<byte> span = new Span<byte>(array); Assert.Equal(array.Length, span.Length); Assert.NotSame(array, span.ToArray()); for (int i = 0; i < span.Length; i++) { Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); array[i] = unchecked((byte)(array[i] + 1)); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); var byteValue = unchecked((byte)(array[i] + 1)); Write(span.Slice(i), ref byteValue); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); var myByteValue = unchecked(new MyByte((byte)(array[i] + 1))); Write(span.Slice(i), ref myByteValue); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); } } [Theory] [InlineData(new byte[] { })] [InlineData(new byte[] { 0 })] [InlineData(new byte[] { 0, 1 })] [InlineData(new byte[] { 0, 1, 2 })] [InlineData(new byte[] { 0, 1, 2, 3 })] [InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })] public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array) { ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array); Assert.Equal(array.Length, span.Length); Assert.NotSame(array, span.ToArray()); for (int i = 0; i < span.Length; i++) { Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); array[i] = unchecked((byte)(array[i] + 1)); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); } } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)] // copy first half to first half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)] // copy second half to second half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)] // copy first half to first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy first byte of 1 element array to last position [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)] // copy first two bytes of 2 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6, 7 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy last two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 5, 6 }, 1, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 2 element array to the middle of other array [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 3, 4 }, 0, 2, new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] public void SpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount) { if (expected != null) { Span<byte> spanA = new Span<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); spanA.CopyTo(spanB); Assert.Equal(expected, b); Span<byte> spanExpected = new Span<byte>(expected); Span<byte> spanBAll = new Span<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { Span<byte> spanA = new Span<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); try { spanA.CopyTo(spanB); Assert.True(false); } catch (Exception) { Assert.True(true); } } } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)] // copy first half to first half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)] // copy second half to second half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)] // copy first half to first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy first byte of 1 element array to last position [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)] // copy first two bytes of 2 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6, 7 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy last two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 5, 6 }, 1, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 2 element array to the middle of other array [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 3, 4 }, 0, 2, new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] public void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount) { if (expected != null) { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); spanA.CopyTo(spanB); Assert.Equal(expected, b); ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected); ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); try { spanA.CopyTo(spanB); Assert.True(false); } catch (Exception) { Assert.True(true); } } ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(expected, a, aidx, acount, b, bidx, bcount); } public unsafe void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount) { IntPtr pa = Marshal.AllocHGlobal(a.Length); Span<byte> na = new Span<byte>(pa.ToPointer(), a.Length); a.CopyTo(na); IntPtr pb = Marshal.AllocHGlobal(b.Length); Span<byte> nb = new Span<byte>(pb.ToPointer(), b.Length); b.CopyTo(nb); ReadOnlySpan<byte> spanA = na.Slice(aidx, acount); Span<byte> spanB = nb.Slice(bidx, bcount); if (expected != null) { spanA.CopyTo(spanB); Assert.Equal(expected, b); ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected); ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { try { spanA.CopyTo(spanB); Assert.True(false); } catch (Exception) { Assert.True(true); } } Marshal.FreeHGlobal(pa); Marshal.FreeHGlobal(pb); } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy second half [InlineData( new byte[] { 4, 5, 6, 7, 7, 7 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy first byte of 1 element array [InlineData( new byte[] { 6, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 6 })] public void SpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b) { if (expected != null) { Span<byte> spanA = new Span<byte>(a, aidx, acount); spanA.CopyTo(b); Assert.Equal(expected, b); Span<byte> spanExpected = new Span<byte>(expected); Span<byte> spanBAll = new Span<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { Span<byte> spanA = new Span<byte>(a, aidx, acount); try { spanA.CopyTo(b); Assert.True(false); } catch (Exception) { Assert.True(true); } } } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy second half [InlineData( new byte[] { 4, 5, 6, 7, 7, 7 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy first byte of 1 element array [InlineData( new byte[] { 6, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 6 })] public void ROSpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b) { if (expected != null) { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); spanA.CopyTo(b); Assert.Equal(expected, b); ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected); ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); try { spanA.CopyTo(b); Assert.True(false); } catch (Exception) { Assert.True(true); } } } } }
namespace Notakey.SDK { using System; using Cryptos; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.IO; using System.Threading.Tasks; using System.Reactive.Linq; using System.Collections; public class NtkCypher { readonly NtkService api; NtkCryptoEntity owner; IBoundNotakeyApiV3 apiInt; INtkCypherStore store; RSA _pri; const string keyType = "rsa-sha256"; public NtkCypher(NtkService boundAPI, INtkCypherStore store, NtkCryptoEntity owner) { if (boundAPI.AccessToken == null) { throw new InvalidApiBoundState(nameof(boundAPI.AccessToken)); } if (boundAPI.BoundParams.HostEndpoint == null) { throw new InvalidApiBoundState(nameof(boundAPI.BoundParams.HostEndpoint)); } this.api = boundAPI; this.owner = owner ?? throw new ArgumentNullException(nameof(owner)); this.store = store ?? throw new ArgumentNullException(nameof(store)); ; } private IBoundNotakeyApiV3 GetApi() { // return InitializeApiAsync().GetAwaiter().GetResult(); if (apiInt == null) { apiInt = InitializeApiAsync().GetAwaiter().GetResult(); } return apiInt; } private async Task<IBoundNotakeyApiV3> InitializeApiAsync() { return await api.CreateBoundApi(api.AccessToken).FirstAsync(); } private async Task<UserPubkey> GetUserPubkey(NtkCryptoEntity user) { if (user.Pkey != null && String.IsNullOrEmpty(user.Pkey.Uuid)) { return await GetApi().GetPubkeyByUuid(user.Pkey.Uuid); } return await GetApi().GetUserPubkey(user.UserId); } public async Task<NtkCryptoEntity> RecoverEntity() { var pubkeyRsp = await GetUserPubkey(owner); if (String.IsNullOrEmpty(pubkeyRsp.Uuid)) { throw new Exception(string.Format("No key to recover for user")); } var keyPair = store.GetKey(pubkeyRsp.Uuid); if (keyPair == null || keyPair.Item1.Length == 0) { throw new Exception(string.Format("Key missing in {0} for owner user", typeof(INtkCypherStore))); } var binKey = GetBinKey(pubkeyRsp.Pubkey); if (StructuralComparisons.StructuralEqualityComparer.Equals(keyPair.Item1, binKey)) { throw new Exception(string.Format("Pubkey mismatch for key {0}", pubkeyRsp.Uuid)); } owner.Privkey = keyPair.Item1; owner.Pkey = new UserPubkey() { KeyType = pubkeyRsp.KeyType, Pubkey = pubkeyRsp.Pubkey, ExpiresIn = pubkeyRsp.ExpiresIn, Uuid = pubkeyRsp.Uuid }; RecoverPrivFromOwner(); return owner; } private string GetBase64Key(byte[] key) { return Convert.ToBase64String(key); } private byte[] GetBinKey(string key) { return Convert.FromBase64String(key); } public async Task<NtkCryptoEntity> BootstrapEntity(string keyToken) { var newKey = GenerateKey(); var pubKeyBas64 = GetBase64Key(newKey.PubKey); var uuidRsp = await GetApi().RegisterPubkey(pubKeyBas64, keyToken, keyType); store.StoreKey(uuidRsp.Uuid, newKey.PrivKey, newKey.PubKey, uuidRsp.ExpiresIn); owner.Privkey = newKey.PrivKey; owner.Pkey = new UserPubkey() { KeyType = keyType, Pubkey = pubKeyBas64, ExpiresIn = uuidRsp.ExpiresIn, Uuid = uuidRsp.Uuid }; RecoverPrivFromOwner(); return owner; } private void RecoverPrivFromOwner() { _pri = RecoverRSAFromParams(GetDeserializedKey(owner.Privkey)); } private RSA RecoverRSAFromParams(RSAParameters rp) { var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(rp); return rsa; } private KeyPair GenerateKey() { RSAParameters privKey, pubKey; using (RSA rsaKeypair = new RSACryptoServiceProvider(2048)) { privKey = rsaKeypair.ExportParameters(true); pubKey = rsaKeypair.ExportParameters(false); } //Console.WriteLine(privKey.ToString()+ privKey.); var privStream = new MemoryStream(); var pubStream = new MemoryStream(); KeyPair kp = new KeyPair(GetSerializedKey(pubKey), GetSerializedKey(privKey)); ; return kp; } private void AssertOwnerState() { if (_pri == null) throw new Exception(String.Format("Invalid key state, {0} or {1} required prior operation", nameof(BootstrapEntity), nameof(RecoverEntity))); if(owner.Pkey.ValidBefore <= DateTime.UtcNow){ throw new KeyExpiredException(); } } private byte[] GetSerializedKey(RSAParameters key) { var pubStream = new MemoryStream(); byte[] binKey = new byte[0]; try { var serializer = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); serializer.Serialize(pubStream, new RSAParametersSerializer(key)); pubStream.Position = 0; binKey = pubStream.ToArray(); } finally { pubStream.Close(); } return binKey; } /// <summary> /// Return latest registered pubkey for specified user ID or null /// </summary> /// <param name="userId">Unique user ID</param> /// <returns>UserPubkey object or null</returns> public async Task<UserPubkey> QueryUserPubkey(string userId) { var pk = await GetApi().GetUserPubkey(userId); if(pk != null){ store.StoreKey(pk.Uuid, new byte[0], GetBinKey(pk.Pubkey), pk.ExpiresIn); } return pk; } /// <summary> /// Return current identity public key state object, use for checking if key must be refreshed /// </summary> /// <param name="userId">Unique user ID</param> /// <returns>UserPubkey object or null</returns> public UserPubkey QueryOwner() { return owner.Pkey; } /// <summary> /// Prepare a base-64 encoded message string to entity without signature /// </summary> /// <param name="user">NtkCryptoEntity object containing UserId</param> /// <param name="payload">plain string that represent message</param> /// <returns>Base-64 encoded cypher message</returns> public async Task<string> SendTo(string pkeyUuid, string payload) { var cypherBytes = await SendTo(pkeyUuid, payload.ToBytes()); return cypherBytes.ToBase64(); } /// <summary> /// Prepare a raw cypher message string to entity without signature /// </summary> /// <param name="user">NtkCryptoEntity object containing UserId</param> /// <param name="payload">bytes that represent message</param> /// <returns>Raw cypher message</returns> public async Task<byte[]> SendTo(string pkeyUuid, byte[] payload) { var binKey = await GetEntityKey(pkeyUuid); return Encrypt(GetDeserializedKey(binKey), payload); } private async Task<byte[]> GetEntityKey(string pkeyUuid){ if(String.IsNullOrEmpty(pkeyUuid)){ throw new ArgumentException(nameof(pkeyUuid)); } byte[] binKey = new byte[0]; var keyPair = store.GetKey(pkeyUuid); if(keyPair.Item3 <= DateTimeOffset.UtcNow.ToUnixTimeSeconds()){ throw new KeyExpiredException(); } if(keyPair.Item2.Length > 0){ return keyPair.Item2; } var pubkeyRsp = await GetApi().GetPubkeyByUuid(pkeyUuid); if (String.IsNullOrEmpty(pubkeyRsp.Uuid)) { throw new Exception(string.Format("No valid key registered for user")); } if (!keyType.Equals(pubkeyRsp.KeyType)) { throw new Exception(string.Format("Invalid/unsupported key type")); } binKey = GetBinKey(pubkeyRsp.Pubkey); store.StoreKey(pubkeyRsp.Uuid, new byte[0], binKey, pubkeyRsp.ExpiresIn); return binKey; } /// <summary> /// Decrypt a payload without sender's signature validation. /// Message must be addressed to NtkCryptoEntity specified in NtkCypher constructor. /// </summary> /// <param name="payload">Raw bytes of message</param> /// <returns>Raw decyphered bytes</returns> #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task<byte[]> ReceiveMsg(byte[] payload) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { return Decrypt(payload); } /// <summary> /// Decrypt a payload specified as base-64 encoded string without sender's signature validation. /// Message must be addressed to NtkCryptoEntity specified in NtkCypher constructor. /// </summary> /// <param name="payload">Raw bytes of message</param> /// <returns>Raw decyphered bytes</returns> #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task<string> ReceiveMsg(string payload) { var decBytes = await ReceiveMsg(payload.FromBase64()); return System.Text.Encoding.UTF8.GetString(decBytes); } #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously /// <summary> /// Create a digital signature for a plaintext message using the private key. /// </summary> /// <param name="message">Any message to sign.</param> /// <returns>A digital signature.</returns> // public byte[] Sign(byte[] message) { return _pri.SignData(message, new HashAlgorithmName(_hash), RSASignaturePadding.Pkcs1); } /// <summary> /// Sign a string (e.g. JSON) and get a base-64 signature. /// </summary> /// <param name="message"></param> /// <returns></returns> // public string Sign(string message) { return _pri.SignData(message.ToBytes(), new HashAlgorithmName(_hash), RSASignaturePadding.Pkcs1).ToBase64(); } /// <summary> /// By using only the public key, verify that a signature was indeed created for a given message with the private key. /// </summary> /// <param name="message">Any message to verify. This is the same message that was passed into the Sign() method /// to create the digital signature.</param> /// <param name="signature">The signature returned from calling the Sign() method.</param> /// <returns></returns> // public bool Verify(byte[] message, byte[] signature) { return _pub.VerifyData(message, signature, new HashAlgorithmName(_hash), RSASignaturePadding.Pkcs1); } /// <summary> /// Verify that a base-64 signature matches the message it signed. /// </summary> /// <param name="message">A plain-text message.</param> /// <param name="signature">A base-64 signature.</param> /// <returns></returns> // public bool Verify(string message, string signature) { return _pub.VerifyData(message.ToBytes(), signature.FromBase64(), new HashAlgorithmName(_hash), RSASignaturePadding.Pkcs1); } /// <summary> /// This method will likely throw an exception if the message is longer than 200-ish bytes. /// It is only used to encrypt short messages, like one-time passwords. /// </summary> /// <param name="message"></param> /// <returns></returns> private byte[] EncryptAsymmetric(RSA user, byte[] message){ return user.Encrypt(message, RSAEncryptionPadding.Pkcs1); } /// <summary> /// This method will likely throw an exception if the message is longer than 200-ish bytes. /// It is only used to decrypt short messages, like one-time passwords. /// </summary> /// <param name="message"></param> /// <returns></returns> private byte[] DecryptAsymmetric(byte[] message) => _pri.Decrypt(message, RSAEncryptionPadding.Pkcs1); /// <summary> /// Encrypt a message using the public key. /// NOTE: The decrypting party must use this library's protocol to decrypt the message. /// The protocol is: /// (1) RSA-encrypt a random key of 32-bytes (256 bits). /// (2) Write the length of this key as Int32. /// (3) Write the encrypted key. /// (4) Write the symmetric-encrypted bytes of the message. /// To summarize this protocol, the cipher returned is a byte array containing the asymmetric-encrypted key plus the symmetric-encrypted message. /// </summary> /// <param name="message"></param> /// <returns></returns> private byte[] Encrypt(RSAParameters userParams, byte[] message) { AssertOwnerState(); // _pri.Encrypt() (backed by RSA 2048) can only encrypt a message that is 245 bytes or less; an inherent constraint of asymmetric cryptography. // Maybe longer bit spaces (e.g. 4096) can encrypt longer messages, but they all will be limited to under 1KB. // Your document will be longer. To get around this limitation, you asymmetric encrypt a short one-time password (random bytes) and use that to // symmetrically encrypt your message, since symmetric encryption has no message length limit. // So let's create a one-time key: var symmetricKey = Bytes.RandomBytesSecure(32); // 256-bit one-time key. var encryptedKey = EncryptAsymmetric(RecoverRSAFromParams(userParams), symmetricKey); using (var ms = new MemoryStream()) using (var bw = new BinaryWriter(ms)) { bw.Write(encryptedKey.Length); bw.Write(encryptedKey); bw.Write(Symmetric.Encrypt(message, symmetricKey)); return ms.ToArray(); } } /// <summary> /// Encrypt a string into a base-64 cipher. /// </summary> /// <param name="message">An string; e.g. JSON.</param> /// <returns>A base-64 encrypted string.</returns> private string Encrypt(RSAParameters userParams, string message) => Encrypt(userParams, message.ToBytes()).ToBase64(); /// <summary> /// Decrypt a message using the private key. /// </summary> /// <param name="cipher">The encrypted bytes of an array of bytes.</param> /// <returns></returns> private byte[] Decrypt(byte[] cipher) { AssertOwnerState(); using (var ms = new MemoryStream(cipher)) using (var br = new BinaryReader(ms)) { var encryptedKeyLength = br.ReadInt32(); var encryptedKey = br.ReadBytes(encryptedKeyLength); var symmetricKey = DecryptAsymmetric(encryptedKey); var encryptedMessage = ms.ReadAllBytes(); return Symmetric.Decrypt(encryptedMessage, symmetricKey); } } /// <summary> /// Decrypt a base-64 encrypted message string. /// </summary> /// <param name="cipher">The base-64 string that represents the encrypted message.</param> /// <returns></returns> private string Decrypt(string cipher) => Decrypt(cipher.FromBase64()).String(); private RSAParameters GetDeserializedKey(byte[] binaryKey) { var dummyStream = new MemoryStream(binaryKey); RSAParameters key ; try { var formater = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); RSAParametersSerializer primKey = (RSAParametersSerializer)formater.Deserialize(dummyStream); key = primKey.RSAParameters; } finally { dummyStream.Close(); } return key; } public void Encrypt(FileStream inStream, FileStream outStream) => throw new NotImplementedException(); public void Decrypt(FileStream inStream, FileStream outStream) => throw new NotImplementedException(); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class AutomationAccountOperationsExtensions { /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create or update automation /// account. /// </param> /// <returns> /// The response model for the create or update account operation. /// </returns> public static AutomationAccountCreateOrUpdateResponse CreateOrUpdate(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).CreateOrUpdateAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the create or update automation /// account. /// </param> /// <returns> /// The response model for the create or update account operation. /// </returns> public static Task<AutomationAccountCreateOrUpdateResponse> CreateOrUpdateAsync(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccountName'> /// Required. Automation account name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccountName) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).DeleteAsync(resourceGroupName, automationAccountName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccountName'> /// Required. Automation account name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccountName) { return operations.DeleteAsync(resourceGroupName, automationAccountName, CancellationToken.None); } /// <summary> /// Retrieve the account by account name. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the get account operation. /// </returns> public static AutomationAccountGetResponse Get(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).GetAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the account by account name. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the get account operation. /// </returns> public static Task<AutomationAccountGetResponse> GetAsync(this IAutomationAccountOperations operations, string resourceGroupName, string automationAccount) { return operations.GetAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve a list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static AutomationAccountListResponse List(this IAutomationAccountOperations operations, string resourceGroupName) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).ListAsync(resourceGroupName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Optional. The name of the resource group /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static Task<AutomationAccountListResponse> ListAsync(this IAutomationAccountOperations operations, string resourceGroupName) { return operations.ListAsync(resourceGroupName, CancellationToken.None); } /// <summary> /// Retrieve next list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static AutomationAccountListResponse ListNext(this IAutomationAccountOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of accounts. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list account operation. /// </returns> public static Task<AutomationAccountListResponse> ListNextAsync(this IAutomationAccountOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the patch automation account. /// </param> /// <returns> /// The response model for the create account operation. /// </returns> public static AutomationAccountPatchResponse Patch(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountPatchParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAutomationAccountOperations)s).PatchAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create an automation account. (see /// http://aka.ms/azureautomationsdk/automationaccountoperations for /// more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IAutomationAccountOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the patch automation account. /// </param> /// <returns> /// The response model for the create account operation. /// </returns> public static Task<AutomationAccountPatchResponse> PatchAsync(this IAutomationAccountOperations operations, string resourceGroupName, AutomationAccountPatchParameters parameters) { return operations.PatchAsync(resourceGroupName, parameters, CancellationToken.None); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Orleans.Runtime.Messaging; using Orleans.Runtime.Placement; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime { internal class Dispatcher { internal OrleansTaskScheduler Scheduler { get; private set; } internal ISiloMessageCenter Transport { get; private set; } private readonly Catalog catalog; private readonly Logger logger; private readonly ClusterConfiguration config; private readonly PlacementDirectorsManager placementDirectorsManager; private readonly double rejectionInjectionRate; private readonly bool errorInjection; private readonly double errorInjectionRate; private readonly SafeRandom random; public Dispatcher( OrleansTaskScheduler scheduler, ISiloMessageCenter transport, Catalog catalog, ClusterConfiguration config, PlacementDirectorsManager placementDirectorsManager) { Scheduler = scheduler; this.catalog = catalog; Transport = transport; this.config = config; this.placementDirectorsManager = placementDirectorsManager; logger = LogManager.GetLogger("Dispatcher", LoggerType.Runtime); rejectionInjectionRate = config.Globals.RejectionInjectionRate; double messageLossInjectionRate = config.Globals.MessageLossInjectionRate; errorInjection = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d; errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate; random = new SafeRandom(); } #region Receive path /// <summary> /// Receive a new message: /// - validate order constraints, queue (or possibly redirect) if out of order /// - validate transactions constraints /// - invoke handler if ready, otherwise enqueue for later invocation /// </summary> /// <param name="message"></param> public void ReceiveMessage(Message message) { MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message); // Don't process messages that have already timed out if (message.IsExpired) { logger.Warn(ErrorCode.Dispatcher_DroppingExpiredMessage, "Dropping an expired message: {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Expired"); message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Dispatch); return; } // check if its targeted at a new activation if (message.TargetGrain.IsSystemTarget) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ReceiveMessage on system target."); throw new InvalidOperationException("Dispatcher was called ReceiveMessage on system target for " + message); } if (errorInjection && ShouldInjectError(message)) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingRejection, "Injecting a rejection"); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ErrorInjection"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, null, "Injected rejection"); return; } try { Task ignore; ActivationData target = catalog.GetOrCreateActivation( message.TargetAddress, message.IsNewPlacement, message.NewGrainType, String.IsNullOrEmpty(message.GenericGrainType) ? null : message.GenericGrainType, message.RequestContextData, out ignore); if (ignore != null) { ignore.Ignore(); } if (message.Direction == Message.Directions.Response) { ReceiveResponse(message, target); } else // Request or OneWay { if (target.State == ActivationState.Valid) { catalog.ActivationCollector.TryRescheduleCollection(target); } // Silo is always capable to accept a new request. It's up to the activation to handle its internal state. // If activation is shutting down, it will queue and later forward this request. ReceiveRequest(message, target); } } catch (Exception ex) { try { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Non-existent activation"); var nea = ex as Catalog.NonExistentActivationException; if (nea == null) { var str = String.Format("Error creating activation for {0}. Message {1}", message.NewGrainType, message); logger.Error(ErrorCode.Dispatcher_ErrorCreatingActivation, str, ex); throw new OrleansException(str, ex); } if (nea.IsStatelessWorker) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate StatelessWorker NonExistentActivation for message {0}", message), ex); } else { logger.Info(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate NonExistentActivation for message {0}", message), ex); } ActivationAddress nonExistentActivation = nea.NonExistentActivation; if (message.Direction != Message.Directions.Response) { // Un-register the target activation so we don't keep getting spurious messages. // The time delay (one minute, as of this writing) is to handle the unlikely but possible race where // this request snuck ahead of another request, with new placement requested, for the same activation. // If the activation registration request from the new placement somehow sneaks ahead of this un-registration, // we want to make sure that we don't un-register the activation we just created. // We would add a counter here, except that there's already a counter for this in the Catalog. // Note that this has to run in a non-null scheduler context, so we always queue it to the catalog's context var origin = message.SendingSilo; Scheduler.QueueWorkItem(new ClosureWorkItem( // don't use message.TargetAddress, cause it may have been removed from the headers by this time! async () => { try { await Silo.CurrentSilo.LocalGrainDirectory.UnregisterAfterNonexistingActivation( nonExistentActivation, origin); } catch (Exception exc) { logger.Warn(ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct, String.Format("Failed to un-register NonExistentActivation {0}", nonExistentActivation), exc); } }, () => "LocalGrainDirectory.UnregisterAfterNonexistingActivation"), catalog.SchedulingContext); ProcessRequestToInvalidActivation(message, nonExistentActivation, null, "Non-existent activation"); } else { logger.Warn( ErrorCode.Dispatcher_NoTargetActivation, nonExistentActivation.Silo.IsClient ? "No target client {0} for response message: {1}. It's likely that the client recently disconnected." : "No target activation {0} for response message: {1}", nonExistentActivation, message); Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(nonExistentActivation); } } catch (Exception exc) { // Unable to create activation for this request - reject message RejectMessage(message, Message.RejectionTypes.Transient, exc); } } } public void RejectMessage( Message message, Message.RejectionTypes rejectType, Exception exc, string rejectInfo = null) { if (message.Direction == Message.Directions.Request) { var str = String.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString()); MessagingStatisticsGroup.OnRejectedMessage(message); Message rejection = message.CreateRejectionResponse(rejectType, str, exc as OrleansException); SendRejectionMessage(rejection); } else { logger.Warn(ErrorCode.Messaging_Dispatcher_DiscardRejection, "Discarding {0} rejection for message {1}. Exc = {2}", Enum.GetName(typeof(Message.Directions), message.Direction), message, exc == null ? "" : exc.Message); } } internal void SendRejectionMessage(Message rejection) { if (rejection.Result == Message.ResponseTypes.Rejection) { Transport.SendMessage(rejection); rejection.ReleaseBodyAndHeaderBuffers(); } else { throw new InvalidOperationException( "Attempt to invoke Dispatcher.SendRejectionMessage() for a message that isn't a rejection."); } } private void ReceiveResponse(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation, "Response received for invalid activation {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Ivalid"); return; } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); if (Transport.TryDeliverToProxy(message)) return; RuntimeClient.Current.ReceiveResponse(message); } } /// <summary> /// Check if we can locally accept this message. /// Redirects if it can't be accepted. /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void ReceiveRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation( message, targetActivation.Address, targetActivation.ForwardingAddress, "ReceiveRequest"); } else if (!ActivationMayAcceptRequest(targetActivation, message)) { // Check for deadlock before Enqueueing. if (config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget) { try { CheckDeadlock(message); } catch (DeadlockException exc) { // Record that this message is no longer flowing through the system MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Deadlock"); logger.Warn(ErrorCode.Dispatcher_DetectedDeadlock, "Detected Application Deadlock: {0}", exc.Message); // We want to send DeadlockException back as an application exception, rather than as a system rejection. SendResponse(message, Response.ExceptionResponse(exc)); return; } } EnqueueRequest(message, targetActivation); } else { HandleIncomingRequest(message, targetActivation); } } } /// <summary> /// Determine if the activation is able to currently accept the given message /// - always accept responses /// For other messages, require that: /// - activation is properly initialized /// - the message would not cause a reentrancy conflict /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming) { if (targetActivation.State != ActivationState.Valid) return false; if (!targetActivation.IsCurrentlyExecuting) return true; return CanInterleave(targetActivation, incoming); } /// <summary> /// Whether an incoming message can interleave /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> public bool CanInterleave(ActivationData targetActivation, Message incoming) { bool canInterleave = catalog.CanInterleave(targetActivation.ActivationId, incoming) || incoming.IsAlwaysInterleave || targetActivation.Running == null || (targetActivation.Running.IsReadOnly && incoming.IsReadOnly); return canInterleave; } /// <summary> /// Check if the current message will cause deadlock. /// Throw DeadlockException if yes. /// </summary> /// <param name="message">Message to analyze</param> private void CheckDeadlock(Message message) { var requestContext = message.RequestContextData; object obj; if (requestContext == null || !requestContext.TryGetValue(RequestContext.CALL_CHAIN_REQUEST_CONTEXT_HEADER, out obj) || obj == null) return; // first call in a chain var prevChain = ((IList)obj); ActivationId nextActivationId = message.TargetActivation; // check if the target activation already appears in the call chain. foreach (object invocationObj in prevChain) { var prevId = ((RequestInvocationHistory)invocationObj).ActivationId; if (!prevId.Equals(nextActivationId) || catalog.CanInterleave(nextActivationId, message)) continue; var newChain = new List<RequestInvocationHistory>(); newChain.AddRange(prevChain.Cast<RequestInvocationHistory>()); newChain.Add(new RequestInvocationHistory(message)); throw new DeadlockException(newChain); } } /// <summary> /// Handle an incoming message and queue/invoke appropriate handler /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> public void HandleIncomingRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest"); return; } // Now we can actually scheduler processing of this request targetActivation.RecordRunning(message); var context = new SchedulingContext(targetActivation); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); Scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, context, this), context); } } /// <summary> /// Enqueue message for local handling after transaction completes /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void EnqueueRequest(Message message, ActivationData targetActivation) { var overloadException = targetActivation.CheckOverloaded(logger); if (overloadException != null) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Overload2"); RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation); return; } switch (targetActivation.EnqueueMessage(message)) { case ActivationData.EnqueueMessageResult.Success: // Great, nothing to do break; case ActivationData.EnqueueMessageResult.ErrorInvalidActivation: ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest"); break; case ActivationData.EnqueueMessageResult.ErrorStuckActivation: // Avoid any new call to this activation catalog.DeactivateStuckActivation(targetActivation); ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest - blocked grain"); break; default: throw new ArgumentOutOfRangeException(); } // Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest. #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_EnqueueMessage, "EnqueueMessage for {0}: targetActivation={1}", message.TargetActivation, targetActivation.DumpStatus()); #endif } internal void ProcessRequestToInvalidActivation( Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(oldAddress); } // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. Scheduler.QueueWorkItem(new ClosureWorkItem( () => TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc)), catalog.SchedulingContext); } internal void ProcessRequestsToInvalidActivation( List<Message> messages, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(oldAddress); } logger.Info(ErrorCode.Messaging_Dispatcher_ForwardingRequests, String.Format("Forwarding {0} requests to old address {1} after {2}.", messages.Count, oldAddress, failedOperation)); // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. Scheduler.QueueWorkItem(new ClosureWorkItem( () => { foreach (var message in messages) { TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc); } } ), catalog.SchedulingContext); } internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { bool forwardingSucceded = true; try { logger.Info(ErrorCode.Messaging_Dispatcher_TryForward, String.Format("Trying to forward after {0}, ForwardCount = {1}. Message {2}.", failedOperation, message.ForwardCount, message)); // if this message is from a different cluster and hit a non-existing activation // in this cluster (which can happen due to stale cache or directory states) // we forward it back to the original silo it came from in the original cluster, // and target it to a fictional activation that is guaranteed to not exist. // This ensures that the GSI protocol creates a new instance there instead of here. if (forwardingAddress == null && message.TargetSilo != message.SendingSilo && !Silo.CurrentSilo.LocalGrainDirectory.IsSiloInCluster(message.SendingSilo)) { message.IsReturnedFromRemoteCluster = true; // marks message to force invalidation of stale directory entry forwardingAddress = ActivationAddress.NewActivationAddress(message.SendingSilo, message.TargetGrain); logger.Info(ErrorCode.Messaging_Dispatcher_ReturnToOriginCluster, String.Format("Forwarding back to origin cluster, to fictional activation {0}", message)); } MessagingProcessingStatisticsGroup.OnDispatcherMessageReRouted(message); if (oldAddress != null) { message.AddToCacheInvalidationHeader(oldAddress); } forwardingSucceded = InsideRuntimeClient.Current.TryForwardMessage(message, forwardingAddress); } catch (Exception exc2) { forwardingSucceded = false; exc = exc2; } finally { if (!forwardingSucceded) { var str = String.Format("Forwarding failed: tried to forward message {0} for {1} times after {2} to invalid activation. Rejecting now.", message, message.ForwardCount, failedOperation); logger.Warn(ErrorCode.Messaging_Dispatcher_TryForwardFailed, str, exc); RejectMessage(message, Message.RejectionTypes.Transient, exc, str); } } } #endregion #region Send path /// <summary> /// Send an outgoing message /// - may buffer for transaction completion / commit if it ends a transaction /// - choose target placement address, maintaining send order /// - add ordering info and maintain send order /// /// </summary> /// <param name="message"></param> /// <param name="sendingActivation"></param> public async Task AsyncSendMessage(Message message, ActivationData sendingActivation = null) { try { await AddressMessage(message); TransportMessage(message); } catch (Exception ex) { if (ShouldLogError(ex)) { logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed, String.Format("SelectTarget failed with {0}", ex.Message), ex); } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex); } } private bool ShouldLogError(Exception ex) { return !(ex.GetBaseException() is KeyNotFoundException) && !(ex.GetBaseException() is ClientNotAvailableException); } // this is a compatibility method for portions of the code base that don't use // async/await yet, which is almost everything. there's no liability to discarding the // Task returned by AsyncSendMessage() internal void SendMessage(Message message, ActivationData sendingActivation = null) { AsyncSendMessage(message, sendingActivation).Ignore(); } /// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private async Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) return; // placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference, // second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the // message. var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null; var placementResult = await this.placementDirectorsManager.SelectOrAddActivation( message.SendingAddress, message.TargetGrain, this.catalog, strategy); if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient) { logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, String.Format("AddressMessage could not find target for client pseudo-grain {0}", message)); throw new KeyNotFoundException(String.Format("Attempting to send a message {0} to an unregistered client pseudo-grain {1}", message, targetAddress.Grain)); } message.SetTargetPlacement(placementResult); if (placementResult.IsNewPlacement) { CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment(); } if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message); } internal void SendResponse(Message request, Response response) { // create the response var message = request.CreateResponseMessage(); message.BodyObject = response; if (message.TargetGrain.IsSystemTarget) { SendSystemTargetMessage(message); } else { TransportMessage(message); } } internal void SendSystemTargetMessage(Message message) { message.Category = message.TargetGrain.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; if (message.TargetSilo == null) { message.TargetSilo = Transport.MyAddress; } if (message.TargetActivation == null) { message.TargetActivation = ActivationId.GetSystemActivation(message.TargetGrain, message.TargetSilo); } TransportMessage(message); } /// <summary> /// Directly send a message to the transport without processing /// </summary> /// <param name="message"></param> public void TransportMessage(Message message) { if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_Send_AddressedMessage, "Addressed message {0}", message); Transport.SendMessage(message); } #endregion #region Execution /// <summary> /// Invoked when an activation has finished a transaction and may be ready for additional transactions /// </summary> /// <param name="activation">The activation that has just completed processing this message</param> /// <param name="message">The message that has just completed processing. /// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param> internal void OnActivationCompletedRequest(ActivationData activation, Message message) { lock (activation) { #if DEBUG // This is a hot code path, so using #if to remove diags from Release version if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting, "OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif activation.ResetRunning(message); // ensure inactive callbacks get run even with transactions disabled if (!activation.IsCurrentlyExecuting) activation.RunOnInactive(); // Run message pump to see if there is a new request arrived to be processed RunMessagePump(activation); } } internal void RunMessagePump(ActivationData activation) { // Note: this method must be called while holding lock (activation) #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_ActivationEndedTurn_Waiting, "RunMessagePump {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif // don't run any messages if activation is not ready or deactivating if (activation.State != ActivationState.Valid) return; bool runLoop; do { runLoop = false; var nextMessage = activation.PeekNextWaitingMessage(); if (nextMessage == null) continue; if (!ActivationMayAcceptRequest(activation, nextMessage)) continue; activation.DequeueNextWaitingMessage(); // we might be over-writing an already running read only request. HandleIncomingRequest(nextMessage, activation); runLoop = true; } while (runLoop); } private bool ShouldInjectError(Message message) { if (!errorInjection || message.Direction != Message.Directions.Request) return false; double r = random.NextDouble() * 100; if (!(r < errorInjectionRate)) return false; if (r < rejectionInjectionRate) { return true; } if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingMessageLoss, "Injecting a message loss"); // else do nothing and intentionally drop message on the floor to inject a message loss return true; } #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.ComponentModel.Design; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.CodeAnalysis.Versions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation; using Microsoft.VisualStudio.LanguageServices.Implementation.Interactive; using Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService; using Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.RuleSets; using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind; using Task = System.Threading.Tasks.Task; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Telemetry; namespace Microsoft.VisualStudio.LanguageServices.Setup { [Guid(Guids.RoslynPackageIdString)] [PackageRegistration(UseManagedResourcesOnly = true)] [ProvideMenuResource("Menus.ctmenu", version: 16)] internal class RoslynPackage : AbstractPackage { private LibraryManager _libraryManager; private uint _libraryManagerCookie; private VisualStudioWorkspace _workspace; private WorkspaceFailureOutputPane _outputPane; private IComponentModel _componentModel; private RuleSetEventHandler _ruleSetEventHandler; private IDisposable _solutionEventMonitor; protected override void Initialize() { base.Initialize(); FatalError.Handler = FailFast.OnFatalException; FatalError.NonFatalHandler = WatsonReporter.Report; // We also must set the FailFast handler for the compiler layer as well var compilerAssembly = typeof(Compilation).Assembly; var compilerFatalError = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true); var property = compilerFatalError.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public); var compilerFailFast = compilerAssembly.GetType(typeof(FailFast).FullName, throwOnError: true); var method = compilerFailFast.GetMethod(nameof(FailFast.OnFatalException), BindingFlags.Static | BindingFlags.NonPublic); property.SetValue(null, Delegate.CreateDelegate(property.PropertyType, method)); RegisterFindResultsLibraryManager(); var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel)); _workspace = componentModel.GetService<VisualStudioWorkspace>(); // Ensure the options persisters are loaded since we have to fetch options from the shell componentModel.GetExtensions<IOptionPersister>(); RoslynTelemetrySetup.Initialize(this); // set workspace output pane _outputPane = new WorkspaceFailureOutputPane(this, _workspace); InitializeColors(); // load some services that have to be loaded in UI thread LoadComponentsInUIContextOnceSolutionFullyLoaded(); _solutionEventMonitor = new SolutionEventMonitor(_workspace); } private void InitializeColors() { // Use VS color keys in order to support theming. CodeAnalysisColors.SystemCaptionTextColorKey = EnvironmentColors.SystemWindowTextColorKey; CodeAnalysisColors.SystemCaptionTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.CheckBoxTextBrushKey = EnvironmentColors.SystemWindowTextBrushKey; CodeAnalysisColors.RenameErrorTextBrushKey = VSCodeAnalysisColors.RenameErrorTextBrushKey; CodeAnalysisColors.RenameResolvableConflictTextBrushKey = VSCodeAnalysisColors.RenameResolvableConflictTextBrushKey; CodeAnalysisColors.BackgroundBrushKey = VsBrushes.CommandBarGradientBeginKey; CodeAnalysisColors.ButtonStyleKey = VsResourceKeys.ButtonStyleKey; CodeAnalysisColors.AccentBarColorKey = EnvironmentColors.FileTabInactiveDocumentBorderEdgeBrushKey; } protected override void LoadComponentsInUIContext() { // we need to load it as early as possible since we can have errors from // package from each language very early this.ComponentModel.GetService<VisualStudioDiagnosticListTable>(); this.ComponentModel.GetService<VisualStudioTodoListTable>(); this.ComponentModel.GetService<VisualStudioDiagnosticListTableCommandHandler>().Initialize(this); this.ComponentModel.GetService<HACK_ThemeColorFixer>(); this.ComponentModel.GetExtensions<IDefinitionsAndReferencesPresenter>(); this.ComponentModel.GetExtensions<INavigableItemsPresenter>(); this.ComponentModel.GetService<VisualStudioMetadataAsSourceFileSupportService>(); this.ComponentModel.GetService<VirtualMemoryNotificationListener>(); // The misc files workspace needs to be loaded on the UI thread. This way it will have // the appropriate task scheduler to report events on. this.ComponentModel.GetService<MiscellaneousFilesWorkspace>(); LoadAnalyzerNodeComponents(); Task.Run(() => LoadComponentsBackground()); } private void LoadComponentsBackground() { // Perf: Initialize the command handlers. var commandHandlerServiceFactory = this.ComponentModel.GetService<ICommandHandlerServiceFactory>(); commandHandlerServiceFactory.Initialize(ContentTypeNames.RoslynContentType); LoadInteractiveMenus(); this.ComponentModel.GetService<MiscellaneousTodoListTable>(); this.ComponentModel.GetService<MiscellaneousDiagnosticListTable>(); } private void LoadInteractiveMenus() { var menuCommandService = (OleMenuCommandService)GetService(typeof(IMenuCommandService)); var monitorSelectionService = (IVsMonitorSelection)this.GetService(typeof(SVsShellMonitorSelection)); new CSharpResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommand(); new VisualBasicResetInteractiveMenuCommand(menuCommandService, monitorSelectionService, ComponentModel) .InitializeResetInteractiveFromProjectCommand(); } internal IComponentModel ComponentModel { get { if (_componentModel == null) { _componentModel = (IComponentModel)GetService(typeof(SComponentModel)); } return _componentModel; } } protected override void Dispose(bool disposing) { UnregisterFindResultsLibraryManager(); DisposeVisualStudioServices(); UnregisterAnalyzerTracker(); UnregisterRuleSetEventHandler(); ReportSessionWideTelemetry(); if (_solutionEventMonitor != null) { _solutionEventMonitor.Dispose(); _solutionEventMonitor = null; } base.Dispose(disposing); } private void ReportSessionWideTelemetry() { PersistedVersionStampLogger.LogSummary(); LinkedFileDiffMergingLogger.ReportTelemetry(); } private void RegisterFindResultsLibraryManager() { var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2; if (objectManager != null) { _libraryManager = new LibraryManager(this); if (ErrorHandler.Failed(objectManager.RegisterSimpleLibrary(_libraryManager, out _libraryManagerCookie))) { _libraryManagerCookie = 0; } ((IServiceContainer)this).AddService(typeof(LibraryManager), _libraryManager, promote: true); } } private void UnregisterFindResultsLibraryManager() { if (_libraryManagerCookie != 0) { var objectManager = this.GetService(typeof(SVsObjectManager)) as IVsObjectManager2; if (objectManager != null) { objectManager.UnregisterLibrary(_libraryManagerCookie); _libraryManagerCookie = 0; } ((IServiceContainer)this).RemoveService(typeof(LibraryManager), promote: true); _libraryManager = null; } } private void DisposeVisualStudioServices() { if (_workspace != null) { var documentTrackingService = _workspace.Services.GetService<IDocumentTrackingService>() as VisualStudioDocumentTrackingService; documentTrackingService.Dispose(); _workspace.Services.GetService<VisualStudioMetadataReferenceManager>().DisconnectFromVisualStudioNativeServices(); } } private void LoadAnalyzerNodeComponents() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Initialize(this); _ruleSetEventHandler = this.ComponentModel.GetService<RuleSetEventHandler>(); if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Register(); } } private void UnregisterAnalyzerTracker() { this.ComponentModel.GetService<IAnalyzerNodeSetup>().Unregister(); } private void UnregisterRuleSetEventHandler() { if (_ruleSetEventHandler != null) { _ruleSetEventHandler.Unregister(); _ruleSetEventHandler = null; } } } }
/* Copyright 2008 The 'A Concurrent Hashtable' development team (http://www.codeplex.com/CH/People/ProjectPeople.aspx) This library is licensed under the GNU Library General Public License (LGPL). You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at http://www.codeplex.com/CH/license. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Runtime.Serialization; using System.Security; namespace Orvid.Concurrent.Collections { /// <summary> /// Represents a thread-safe collection of composite key-value pairs that can be accessed /// by multiple threads concurrently and has weak references to the values and parts of the key. /// </summary> /// <typeparam name="TWeakKey1">The type of the first part of the keys in this dictionary that will be weakly referenced. This must be a reference type.</typeparam> /// <typeparam name="TWeakKey2">The type of the second part of the keys in this dictionary that will be weakly referenced. This must be a reference type.</typeparam> /// <typeparam name="TStrongKey">The type of the part of the keys in this dictionary that can be a value type or a strongly referenced reference type.</typeparam> /// <typeparam name="TValue">The type of the values in this dictionary. This must be a reference type.</typeparam> /// <remarks> /// The keys consist of three parts. The first two parts are weakly referenced and can always be garbage collected. /// The third part is the strong part and it can be a value type or reference type that will never be garbage collected /// as long as the key-value pair is held by this dictionary and the dictionary itself is not garbage collected. /// /// Whenever any of the values or weak parts of the keys held by this dictionary are garbage collected the key-value pair /// holding the value or key part or parts will be removed from the dictionary. /// </remarks> #if !SILVERLIGHT [Serializable] #endif public class WeakDictionary<TWeakKey1, TWeakKey2, TStrongKey, TValue> : DictionaryBase<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue> #if !SILVERLIGHT , ISerializable #endif where TWeakKey1 : class where TWeakKey2 : class where TValue : class { sealed class InternalWeakDictionary : InternalWeakDictionaryWeakValueBase< Key<TWeakKey1, TWeakKey2, TStrongKey>, Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue, Stacktype<TWeakKey1, TWeakKey2, TStrongKey> > { public InternalWeakDictionary(int concurrencyLevel, int capacity, KeyComparer<TWeakKey1, TWeakKey2, TStrongKey> keyComparer) : base(concurrencyLevel, capacity, keyComparer) { _comparer = keyComparer; MaintenanceWorker.Register(this); } public InternalWeakDictionary(KeyComparer<TWeakKey1, TWeakKey2, TStrongKey> keyComparer) : base(keyComparer) { _comparer = keyComparer; MaintenanceWorker.Register(this); } public KeyComparer<TWeakKey1, TWeakKey2, TStrongKey> _comparer; protected override Key<TWeakKey1, TWeakKey2, TStrongKey> FromExternalKeyToSearchKey(Tuple<TWeakKey1, TWeakKey2, TStrongKey> externalKey) { return new SearchKey<TWeakKey1, TWeakKey2, TStrongKey>().Set(externalKey, _comparer); } protected override Key<TWeakKey1, TWeakKey2, TStrongKey> FromExternalKeyToStorageKey(Tuple<TWeakKey1, TWeakKey2, TStrongKey> externalKey) { return new StorageKey<TWeakKey1, TWeakKey2, TStrongKey>().Set(externalKey, _comparer); } protected override Key<TWeakKey1, TWeakKey2, TStrongKey> FromStackKeyToSearchKey(Stacktype<TWeakKey1, TWeakKey2, TStrongKey> externalKey) { return new SearchKey<TWeakKey1, TWeakKey2, TStrongKey>().Set(externalKey, _comparer); } protected override Key<TWeakKey1, TWeakKey2, TStrongKey> FromStackKeyToStorageKey(Stacktype<TWeakKey1, TWeakKey2, TStrongKey> externalKey) { return new StorageKey<TWeakKey1, TWeakKey2, TStrongKey>().Set(externalKey, _comparer); } protected override bool FromInternalKeyToExternalKey(Key<TWeakKey1, TWeakKey2, TStrongKey> internalKey, out Tuple<TWeakKey1, TWeakKey2, TStrongKey> externalKey) { return internalKey.Get(out externalKey); } protected override bool FromInternalKeyToStackKey(Key<TWeakKey1, TWeakKey2, TStrongKey> internalKey, out Stacktype<TWeakKey1, TWeakKey2, TStrongKey> externalKey) { return internalKey.Get(out externalKey); } } readonly InternalWeakDictionary _internalDictionary; protected override IDictionary<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue> InternalDictionary { get { return _internalDictionary; } } #if !SILVERLIGHT WeakDictionary(SerializationInfo serializationInfo, StreamingContext streamingContext) { var comparer = (KeyComparer<TWeakKey1, TWeakKey2, TStrongKey>)serializationInfo.GetValue("Comparer", typeof(KeyComparer<TWeakKey1, TWeakKey2, TStrongKey>)); var items = (List<KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>>)serializationInfo.GetValue("Items", typeof(List<KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>>)); _internalDictionary = new InternalWeakDictionary(comparer); _internalDictionary.InsertContents(items); } #region ISerializable Members [SecurityCritical] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Comparer", _internalDictionary._comparer); info.AddValue("Items", _internalDictionary.GetContents()); } #endregion #endif public WeakDictionary() : this(EqualityComparer<TWeakKey1>.Default, EqualityComparer<TWeakKey2>.Default, EqualityComparer<TStrongKey>.Default) {} public WeakDictionary(IEqualityComparer<TWeakKey1> weakKey1Comparer, IEqualityComparer<TWeakKey2> weakKey2Comparer, IEqualityComparer<TStrongKey> strongKeyComparer) : this(Enumerable.Empty<KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>>(), weakKey1Comparer, weakKey2Comparer, strongKeyComparer) {} public WeakDictionary(IEnumerable<KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>> collection) : this(collection, EqualityComparer<TWeakKey1>.Default, EqualityComparer<TWeakKey2>.Default, EqualityComparer<TStrongKey>.Default) {} public WeakDictionary(IEnumerable<KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>> collection, IEqualityComparer<TWeakKey1> weakKey1Comparer, IEqualityComparer<TWeakKey2> weakKey2Comparer, IEqualityComparer<TStrongKey> strongKeyComparer) { _internalDictionary = new InternalWeakDictionary( new KeyComparer<TWeakKey1, TWeakKey2, TStrongKey>(weakKey1Comparer, weakKey2Comparer, strongKeyComparer) ) ; _internalDictionary.InsertContents(collection); } public WeakDictionary(int concurrencyLevel, int capacity) : this(concurrencyLevel, capacity, EqualityComparer<TWeakKey1>.Default, EqualityComparer<TWeakKey2>.Default, EqualityComparer<TStrongKey>.Default) {} public WeakDictionary(int concurrencyLevel, IEnumerable<KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>> collection, IEqualityComparer<TWeakKey1> weakKey1Comparer, IEqualityComparer<TWeakKey2> weakKey2Comparer, IEqualityComparer<TStrongKey> strongKeyComparer) { var contentsList = collection.ToList(); _internalDictionary = new InternalWeakDictionary( concurrencyLevel, contentsList.Count, new KeyComparer<TWeakKey1, TWeakKey2, TStrongKey>(weakKey1Comparer, weakKey2Comparer, strongKeyComparer) ) ; _internalDictionary.InsertContents(contentsList); } public WeakDictionary(int concurrencyLevel, int capacity, IEqualityComparer<TWeakKey1> weakKey1Comparer, IEqualityComparer<TWeakKey2> weakKey2Comparer, IEqualityComparer<TStrongKey> strongKeyComparer) { _internalDictionary = new InternalWeakDictionary( concurrencyLevel, capacity, new KeyComparer<TWeakKey1, TWeakKey2, TStrongKey>(weakKey1Comparer, weakKey2Comparer, strongKeyComparer) ) ; } public bool ContainsKey(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey) { return _internalDictionary.ContainsKey(Stacktype.Create(weakKey1, weakKey2, strongKey)); } public bool TryGetValue(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, out TValue value) { return _internalDictionary.TryGetValue(Stacktype.Create(weakKey1, weakKey2, strongKey), out value); } public TValue this[TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey] { get { return _internalDictionary.GetItem(Stacktype.Create(weakKey1, weakKey2, strongKey)); } set { _internalDictionary.SetItem(Stacktype.Create(weakKey1, weakKey2, strongKey), value); } } public bool IsEmpty { get { return _internalDictionary.IsEmpty; } } public TValue AddOrUpdate(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, Func<TWeakKey1, TWeakKey2, TStrongKey, TValue> addValueFactory, Func<TWeakKey1, TWeakKey2, TStrongKey, TValue, TValue> updateValueFactory) { if (null == addValueFactory) throw new ArgumentNullException("addValueFactory"); if (null == updateValueFactory) throw new ArgumentNullException("updateValueFactory"); return _internalDictionary.AddOrUpdate( Stacktype.Create(weakKey1, weakKey2, strongKey), hr => addValueFactory(hr.Item1, hr.Item2, hr.Item3), (hr, v) => updateValueFactory(hr.Item1, hr.Item2, hr.Item3, v) ) ; } public TValue AddOrUpdate(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, TValue addValue, Func<TWeakKey1, TWeakKey2, TStrongKey, TValue, TValue> updateValueFactory) { if (null == updateValueFactory) throw new ArgumentNullException("updateValueFactory"); return _internalDictionary.AddOrUpdate( Stacktype.Create(weakKey1, weakKey2, strongKey), addValue, (hr, v) => updateValueFactory(hr.Item1, hr.Item2, hr.Item3, v) ) ; } public TValue GetOrAdd(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, TValue value) { return _internalDictionary.GetOrAdd(Stacktype.Create(weakKey1, weakKey2, strongKey), value); } public TValue GetOrAdd(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, Func<TWeakKey1, TWeakKey2, TStrongKey, TValue> valueFactory) { if (null == valueFactory) throw new ArgumentNullException("valueFactory"); return _internalDictionary.GetOrAdd(Stacktype.Create(weakKey1, weakKey2, strongKey), hr => valueFactory(hr.Item1, hr.Item2, hr.Item3)); } public KeyValuePair<Tuple<TWeakKey1, TWeakKey2, TStrongKey>, TValue>[] ToArray() { return _internalDictionary.ToArray(); } public bool TryAdd(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, TValue value) { return _internalDictionary.TryAdd(Stacktype.Create(weakKey1, weakKey2, strongKey), value); } public bool TryRemove(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, out TValue value) { return _internalDictionary.TryRemove(Stacktype.Create(weakKey1, weakKey2, strongKey), out value); } public bool TryUpdate(TWeakKey1 weakKey1, TWeakKey2 weakKey2, TStrongKey strongKey, TValue newValue, TValue comparisonValue) { return _internalDictionary.TryUpdate(Stacktype.Create(weakKey1, weakKey2, strongKey), newValue, comparisonValue ); } } }
// Code generated by a Template using System; using DNX.Helpers.Maths; using DNX.Helpers.Validation; using NUnit.Framework; using Shouldly; using Test.DNX.Helpers.Validation.TestsDataSource; namespace Test.DNX.Helpers.Validation { [TestFixture] public class GuardByteTests { [TestCaseSource(typeof(GuardByteTestsSource), "IsBetween_Default")] public bool Guard_IsBetween_Default(byte value, byte min, byte max, string messageText) { try { // Act Guard.IsBetween(() => value, min, max); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsBetween_BoundsType")] public bool Guard_IsBetween_BoundsType(byte value, byte min, byte max, IsBetweenBoundsType boundsType, string messageText) { try { // Act Guard.IsBetween(() => value, min, max, boundsType); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsBetween")] public bool Guard_IsBetween(byte value, byte min, byte max, bool allowEitherOrder, IsBetweenBoundsType boundsType, string messageText) { try { // Act Guard.IsBetween(() => value, min, max, allowEitherOrder, boundsType); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsGreaterThan")] public bool Guard_IsGreaterThan_Expr(byte value, byte min, string messageText) { try { // Act Guard.IsGreaterThan(() => value, min); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsGreaterThan")] public bool Guard_IsGreaterThan_Value(byte actualValue, byte min, string messageText) { try { // Act byte value = min; Guard.IsGreaterThan(() => value, actualValue, min); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsGreaterThanOrEqualTo")] public bool Guard_IsGreaterThanOrEqualTo_Expr(byte value, byte min, string messageText) { try { // Act Guard.IsGreaterThanOrEqualTo(() => value, min); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsGreaterThanOrEqualTo")] public bool Guard_IsGreaterThanOrEqualTo_Value(byte actualValue, byte min, string messageText) { try { // Act byte value = min; Guard.IsGreaterThanOrEqualTo(() => value, actualValue, min); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsLessThan")] public bool Guard_IsLessThan_Expr(byte value, byte max, string messageText) { try { // Act Guard.IsLessThan(() => value, max); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsLessThan")] public bool Guard_IsLessThan_Value(byte actualValue, byte max, string messageText) { try { // Act byte value = max; Guard.IsLessThan(() => value, actualValue, max); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsLessThanOrEqualTo")] public bool Guard_IsLessThanOrEqualTo_Expr(byte value, byte max, string messageText) { try { // Act Guard.IsLessThanOrEqualTo(() => value, max); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } [TestCaseSource(typeof(GuardByteTestsSource), "IsLessThanOrEqualTo")] public bool Guard_IsLessThanOrEqualTo_Value(byte actualValue, byte max, string messageText) { try { // Act byte value = max; Guard.IsLessThanOrEqualTo(() => value, actualValue, max); return true; } catch (ArgumentOutOfRangeException ex) { Assert.IsNotNull(messageText); Assert.IsNotEmpty(messageText); ex.Message.ShouldStartWith(messageText); return false; } catch (Exception ex) { // Assert Assert.Fail(ex.Message); return false; } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using RdKafka.Internal; namespace RdKafka { /// <summary> /// High-level Kafka Consumer, receives messages from a Kafka cluster. /// /// Requires Kafka >= 0.9.0.0. /// </summary> public class Consumer : Handle { public Consumer(Config config, string brokerList = null) { RebalanceDelegate = RebalanceCallback; CommitDelegate = CommitCallback; IntPtr cfgPtr = config.handle.Dup(); LibRdKafka.conf_set_rebalance_cb(cfgPtr, RebalanceDelegate); LibRdKafka.conf_set_offset_commit_cb(cfgPtr, CommitDelegate); if (config.DefaultTopicConfig != null) { LibRdKafka.conf_set_default_topic_conf(cfgPtr, config.DefaultTopicConfig.handle.Dup()); } Init(RdKafkaType.Consumer, cfgPtr, config.Logger); if (brokerList != null) { handle.AddBrokers(brokerList); } } /// <summary> /// Returns the current partition assignment as set by Assign. /// </summary> public List<TopicPartition> Assignment => handle.GetAssignment(); /// <summary> /// Returns the current partition subscription as set by Subscribe. /// </summary> public List<string> Subscription => handle.GetSubscription(); /// <summary> /// Update the subscription set to topics. /// /// Any previous subscription will be unassigned and unsubscribed first. /// /// The subscription set denotes the desired topics to consume and this /// set is provided to the partition assignor (one of the elected group /// members) for all clients which then uses the configured /// partition.assignment.strategy to assign the subscription sets's /// topics's partitions to the consumers, depending on their subscription. /// </summary> public void Subscribe(ICollection<string> topics) { handle.Subscribe(topics); } /// <summary> /// Unsubscribe from the current subscription set. /// </summary> public void Unsubscribe() { handle.Unsubscribe(); } /// <summary> /// Update the assignment set to \p partitions. /// /// The assignment set is the set of partitions actually being consumed /// by the KafkaConsumer. /// </summary> public void Assign(ICollection<TopicPartitionOffset> partitions) { handle.Assign(partitions); } /// <summary> /// Stop consumption and remove the current assignment. /// </summary> public void Unassign() { handle.Assign(null); } /// <summary> /// Manually consume message or get error, triggers events. /// /// Will invoke events for OnPartitionsAssigned/Revoked, /// OnOffsetCommit, etc. on the calling thread. /// /// Returns one of: /// - proper message (ErrorCode is NO_ERROR) /// - error event (ErrorCode is != NO_ERROR) /// - timeout due to no message or event within timeout (null) /// </summary> public MessageAndError? Consume(TimeSpan timeout) => handle.ConsumerPoll((IntPtr)timeout.TotalMilliseconds); /// <summary> /// Commit offsets for the current assignment. /// </summary> public Task Commit() { handle.Commit(); return Task.FromResult(false); } /// <summary> /// Commit offset for a single topic+partition based on message. /// </summary> public Task Commit(Message message) { var tpo = message.TopicPartitionOffset; Commit(new List<TopicPartitionOffset>() { new TopicPartitionOffset(tpo.Topic, tpo.Partition, tpo.Offset + 1) }); return Task.FromResult(false); } /// <summary> /// Commit explicit list of offsets. /// </summary> public Task Commit(ICollection<TopicPartitionOffset> offsets) { handle.Commit(offsets); return Task.FromResult(false); } /// <summary> /// Retrieve committed offsets for topics+partitions. /// </summary> public Task<List<TopicPartitionOffset>> Committed(ICollection<TopicPartition> partitions, TimeSpan timeout) { var result = handle.Committed(partitions, (IntPtr) timeout.TotalMilliseconds); return Task.FromResult(result); } /// <summary> /// Retrieve current positions (offsets) for topics+partitions. /// /// The offset field of each requested partition will be set to the offset /// of the last consumed message + 1, or RD_KAFKA_OFFSET_INVALID in case there was /// no previous message. /// </summary> public List<TopicPartitionOffset> Position(ICollection<TopicPartition> partitions) => handle.Position(partitions); /// <summary> /// Get last known low (oldest/beginning) and high (newest/end) offsets for partition. /// /// The low offset is updated periodically (if statistics.interval.ms is set) /// while the high offset is updated on each fetched message set from the broker. /// /// If there is no cached offset (either low or high, or both) then /// RD_KAFKA_OFFSET_INVALID will be returned for the respective offset. /// </summary> public Offsets GetWatermarkOffsets(TopicPartition topicPartition) => handle.GetWatermarkOffsets(topicPartition.Topic, topicPartition.Partition); // Rebalance callbacks public event EventHandler<List<TopicPartitionOffset>> OnPartitionsAssigned; public event EventHandler<List<TopicPartitionOffset>> OnPartitionsRevoked; // Explicitly keep reference to delegate so it stays alive LibRdKafka.RebalanceCallback RebalanceDelegate; void RebalanceCallback(IntPtr rk, ErrorCode err, /* rd_kafka_topic_partition_list_t * */ IntPtr partitions, IntPtr opaque) { var partitionList = SafeKafkaHandle.GetTopicPartitionOffsetList(partitions); if (err == ErrorCode._ASSIGN_PARTITIONS) { var handler = OnPartitionsAssigned; if (handler != null && handler.GetInvocationList().Length > 0) { handler(this, partitionList); } else { Assign(partitionList); } } if (err == ErrorCode._REVOKE_PARTITIONS) { var handler = OnPartitionsRevoked; if (handler != null && handler.GetInvocationList().Length > 0) { handler(this, partitionList); } else { Unassign(); } } } public struct OffsetCommitArgs { public ErrorCode Error { get; set; } public IList<TopicPartitionOffset> Offsets { get; set; } } public event EventHandler<OffsetCommitArgs> OnOffsetCommit; // Explicitly keep reference to delegate so it stays alive LibRdKafka.CommitCallback CommitDelegate; internal void CommitCallback(IntPtr rk, ErrorCode err, /* rd_kafka_topic_partition_list_t * */ IntPtr offsets, IntPtr opaque) { OnOffsetCommit?.Invoke(this, new OffsetCommitArgs() { Error = err, Offsets = SafeKafkaHandle.GetTopicPartitionOffsetList(offsets) }); } protected override void Dispose(bool disposing) { if (disposing) { handle.ConsumerClose(); } base.Dispose(disposing); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Lime.Protocol.Listeners; using Lime.Protocol.Network; using Lime.Protocol.Util; using Moq; using NUnit.Framework; using Shouldly; namespace Lime.Protocol.UnitTests.Listeners { [TestFixture] public class BufferedChannelListenerTests { private Mock<IEstablishedReceiverChannel> _channel; private BufferBlock<Message> _producedMessages; private BufferBlock<Notification> _producedNotifications; private BufferBlock<Command> _producedCommands; private BufferBlock<Message> _consumedMessages; private BufferBlock<Notification> _consumedNotifications; private BufferBlock<Command> _consumedCommands; private Func<Message, CancellationToken, Task<bool>> _messageConsumer; private Func<Notification, CancellationToken, Task<bool>> _notificationConsumer; private Func<Command, CancellationToken, Task<bool>> _commandConsumer; private CancellationToken _cancellationToken; private Message _completionMessage; private Notification _completionNotification; private Command _completionCommand; private List<BufferedChannelListener> _createdTargets; [SetUp] public void SetUp() { _channel = new Mock<IEstablishedReceiverChannel>(); _producedMessages = new BufferBlock<Message>(new DataflowBlockOptions() { BoundedCapacity = -1 }); _producedNotifications = new BufferBlock<Notification>(new DataflowBlockOptions() { BoundedCapacity = -1 }); _producedCommands = new BufferBlock<Command>(new DataflowBlockOptions() { BoundedCapacity = -1 }); _channel .Setup(m => m.ReceiveMessageAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken cancellationToken) => _producedMessages.ReceiveAsync(cancellationToken)); _channel .Setup(m => m.ReceiveNotificationAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken cancellationToken) => _producedNotifications.ReceiveAsync(cancellationToken)); _channel .Setup(m => m.ReceiveCommandAsync(It.IsAny<CancellationToken>())) .Returns((CancellationToken cancellationToken) => _producedCommands.ReceiveAsync(cancellationToken)); _consumedMessages = new BufferBlock<Message>(new DataflowBlockOptions() { BoundedCapacity = -1 }); _consumedNotifications = new BufferBlock<Notification>(new DataflowBlockOptions() { BoundedCapacity = -1 }); _consumedCommands = new BufferBlock<Command>(new DataflowBlockOptions() { BoundedCapacity = -1 }); _cancellationToken = TimeSpan.FromSeconds(15).ToCancellationToken(); _messageConsumer = (m, ct) => { if (ReferenceEquals(m, _completionMessage)) { _consumedMessages.Complete(); return TaskUtil.FalseCompletedTask; } _consumedMessages.SendAsync(m, _cancellationToken); return TaskUtil.TrueCompletedTask; }; _notificationConsumer = (n, ct) => { if (ReferenceEquals(n, _completionNotification)) { _consumedNotifications.Complete(); return TaskUtil.FalseCompletedTask; } _consumedNotifications.SendAsync(n, _cancellationToken); return TaskUtil.TrueCompletedTask; }; _commandConsumer = (c, ct) => { if (ReferenceEquals(c, _completionCommand)) { _consumedCommands.Complete(); return TaskUtil.FalseCompletedTask; } _consumedCommands.SendAsync(c, _cancellationToken); return TaskUtil.TrueCompletedTask; }; _completionMessage = Dummy.CreateMessage(Dummy.CreateTextContent()); _completionNotification = Dummy.CreateNotification(Event.Consumed); _completionCommand = Dummy.CreateCommand(); } [TearDown] public void TearDown() { _channel = null; _channel = null; _channel = null; _producedMessages = null; _producedNotifications = null; _producedCommands = null; _consumedMessages = null; _consumedNotifications = null; _consumedCommands = null; _cancellationToken = CancellationToken.None; if (_createdTargets != null) { foreach (var target in _createdTargets) { target.Dispose(); } } } protected BufferedChannelListener GetAndStartTarget() { if (_createdTargets == null) { _createdTargets = new List<BufferedChannelListener>(); } var target = new BufferedChannelListener(_messageConsumer, _notificationConsumer, _commandConsumer, -1); target.Start(_channel.Object); _createdTargets.Add(target); return target; } [Test] public async Task Start_MessageReceived_CallsConsumer() { // Arrange var message = Dummy.CreateMessage(Dummy.CreateTextContent()); var target = GetAndStartTarget(); // Act await _producedMessages.SendAsync(message); var actual = await _consumedMessages.ReceiveAsync(_cancellationToken); // Assert actual.ShouldBe(message); await _producedMessages.SendAsync(_completionMessage); (await target.MessageListenerTask.WithCancellation(_cancellationToken)).ShouldBe(_completionMessage); _channel.Verify(c => c.ReceiveMessageAsync(It.IsAny<CancellationToken>()), Times.Exactly(3)); } [Test] public async Task Start_MultipleMessagesReceived_CallsConsumer() { // Arrange var messages = new List<Message>(); var count = 100; for (int i = 0; i < count; i++) { messages.Add( Dummy.CreateMessage(Dummy.CreateTextContent())); } var target = GetAndStartTarget(); // Act foreach (var message in messages) { await _producedMessages.SendAsync(message); } // Assert await _producedMessages.SendAsync(_completionMessage); (await target.MessageListenerTask.WithCancellation(_cancellationToken)).ShouldBe(_completionMessage); _consumedMessages.Count.ShouldBe(count); _channel.Verify(c => c.ReceiveMessageAsync(It.IsAny<CancellationToken>()), Times.Exactly(count + 2)); } [Test] public async Task Start_ConsumerCompletedWhileProducingMessages_StopsConsuming() { // Arrange var messages = new List<Message>(); var count = 500; var halfCount = count/2; for (int i = 0; i < count; i++) { messages.Add( Dummy.CreateMessage(Dummy.CreateTextContent())); } int consumedCount = 0; _messageConsumer = (m, ct) => { Interlocked.Increment(ref consumedCount); if (consumedCount == halfCount) { return TaskUtil.FalseCompletedTask; } return TaskUtil.TrueCompletedTask; }; var target = GetAndStartTarget(); // Act foreach (var message in messages) { await _producedMessages.SendAsync(message); } // Assert var unconsumedMessage = await target.MessageListenerTask; unconsumedMessage.ShouldNotBeNull(); _producedMessages.TryReceiveAll(out var producedItems); producedItems?.ShouldNotContain(unconsumedMessage); _consumedMessages.TryReceiveAll(out var consumedItems); consumedItems?.ShouldNotContain(unconsumedMessage); consumedCount.ShouldBe(halfCount); _channel.Verify(c => c.ReceiveMessageAsync(It.IsAny<CancellationToken>()), Times.AtLeast(halfCount)); } [Test] public async Task Start_MessageChannelThrowsException_StopsListenerTaskAndThrows() { // Arrange var exception = Dummy.CreateException<ApplicationException>(); _channel .Setup(m => m.ReceiveMessageAsync(It.IsAny<CancellationToken>())) .ThrowsAsync(exception); var target = GetAndStartTarget(); // Act await target.MessageListenerTask.ShouldThrowAsync<ApplicationException>(); } [Test] public async Task Start_MessageConsumerThrowsException_StopsListenerTaskAndThrows() { // Arrange var message = Dummy.CreateMessage(Dummy.CreateTextContent()); var exception = Dummy.CreateException<ApplicationException>(); _messageConsumer = (m, ct) => { if (ReferenceEquals(message, m)) { throw exception; } throw new Exception("An unexpected message was received by the consumer"); }; var target = GetAndStartTarget(); // Act await _producedMessages.SendAsync(message); await target.MessageListenerTask.ShouldThrowAsync<ApplicationException>(); } [Test] public async Task Start_StoppedWhileProducingMessage_ReturnsNull() { // Arrange var target = GetAndStartTarget(); // Act target.Stop(); // Act (await target.MessageListenerTask).ShouldBeNull(); } [Test] public async Task Start_NotificationReceived_CallsConsumer() { // Arrange var notification = Dummy.CreateNotification(Event.Received); var target = GetAndStartTarget(); // Act await _producedNotifications.SendAsync(notification); var actual = await _consumedNotifications.ReceiveAsync(_cancellationToken); // Assert actual.ShouldBe(notification); await _producedNotifications.SendAsync(_completionNotification); (await target.NotificationListenerTask.WithCancellation(_cancellationToken)).ShouldBe(_completionNotification); _channel.Verify(c => c.ReceiveNotificationAsync(It.IsAny<CancellationToken>()), Times.Exactly(3)); } [Test] public async Task Start_MultipleNotificationsReceived_CallsConsumer() { // Arrange var notifications = new List<Notification>(); var count = 100; for (int i = 0; i < count; i++) { notifications.Add( Dummy.CreateNotification(Event.Received)); } var target = GetAndStartTarget(); // Act foreach (var notification in notifications) { await _producedNotifications.SendAsync(notification); } // Assert await _producedNotifications.SendAsync(_completionNotification); (await target.NotificationListenerTask.WithCancellation(_cancellationToken)).ShouldBe(_completionNotification); _consumedNotifications.Count.ShouldBe(count); _channel.Verify(c => c.ReceiveNotificationAsync(It.IsAny<CancellationToken>()), Times.Exactly(count + 2)); } [Test] public async Task Start_ConsumerCompletedWhileProducingNotifications_StopsConsuming() { // Arrange var notifications = new List<Notification>(); var count = 500; var halfCount = count / 2; for (int i = 0; i < count; i++) { notifications.Add( Dummy.CreateNotification(Event.Received)); } int consumedCount = 0; _notificationConsumer = (n, ct) => { Interlocked.Increment(ref consumedCount); if (consumedCount == halfCount) { return TaskUtil.FalseCompletedTask; } return TaskUtil.TrueCompletedTask; }; var target = GetAndStartTarget(); // Act foreach (var notification in notifications) { await _producedNotifications.SendAsync(notification); } // Assert var unconsumedNotification = await target.NotificationListenerTask; unconsumedNotification.ShouldNotBeNull(); _producedNotifications.TryReceiveAll(out var producedItems); producedItems?.ShouldNotContain(unconsumedNotification); _consumedNotifications.TryReceiveAll(out var consumedItems); consumedItems?.ShouldNotContain(unconsumedNotification); consumedCount.ShouldBe(halfCount); _channel.Verify(c => c.ReceiveNotificationAsync(It.IsAny<CancellationToken>()), Times.AtLeast(halfCount)); } [Test] public async Task Start_NotificationChannelThrowsException_StopsListenerTaskAndThrows() { // Arrange var exception = Dummy.CreateException<ApplicationException>(); _channel .Setup(m => m.ReceiveNotificationAsync(It.IsAny<CancellationToken>())) .ThrowsAsync(exception); var target = GetAndStartTarget(); // Act await target.NotificationListenerTask.ShouldThrowAsync<ApplicationException>(); } [Test] public async Task Start_NotificationConsumerThrowsException_StopsListenerTaskAndThrows() { // Arrange var notification = Dummy.CreateNotification(Event.Received); var exception = Dummy.CreateException<ApplicationException>(); _notificationConsumer = (m, ct) => { if (ReferenceEquals(notification, m)) { throw exception; } throw new Exception("An unexpected notification was received by the consumer"); }; var target = GetAndStartTarget(); // Act await _producedNotifications.SendAsync(notification); await target.NotificationListenerTask.ShouldThrowAsync<ApplicationException>(); } [Test] public async Task Start_StoppedWhileProducingNotification_ReturnsNull() { // Arrange var target = GetAndStartTarget(); // Act target.Stop(); // Act (await target.NotificationListenerTask).ShouldBeNull(); } [Test] public async Task Start_CommandReceived_CallsConsumer() { // Arrange var command = Dummy.CreateCommand(Dummy.CreateTextContent()); var target = GetAndStartTarget(); // Act await _producedCommands.SendAsync(command); var actual = await _consumedCommands.ReceiveAsync(_cancellationToken); // Assert actual.ShouldBe(command); await _producedCommands.SendAsync(_completionCommand); (await target.CommandListenerTask.WithCancellation(_cancellationToken)).ShouldBe(_completionCommand); _channel.Verify(c => c.ReceiveCommandAsync(It.IsAny<CancellationToken>()), Times.Exactly(3)); } [Test] public async Task Start_MultipleCommandsReceived_CallsConsumer() { // Arrange var commands = new List<Command>(); var count = 100; for (int i = 0; i < count; i++) { commands.Add( Dummy.CreateCommand()); } var target = GetAndStartTarget(); // Act foreach (var command in commands) { await _producedCommands.SendAsync(command); } // Assert await _producedCommands.SendAsync(_completionCommand); (await target.CommandListenerTask.WithCancellation(_cancellationToken)).ShouldBe(_completionCommand); _consumedCommands.Count.ShouldBe(count); _channel.Verify(c => c.ReceiveCommandAsync(It.IsAny<CancellationToken>()), Times.Exactly(count + 2)); } [Test] public async Task Start_ConsumerCompletedWhileProducingCommands_StopsConsuming() { // Arrange var commands = new List<Command>(); var count = 500; var halfCount = count / 2; for (int i = 0; i < count; i++) { commands.Add( Dummy.CreateCommand(Dummy.CreateTextContent())); } int consumedCount = 0; _commandConsumer = (c, ct) => { Interlocked.Increment(ref consumedCount); if (consumedCount == halfCount) { return TaskUtil.FalseCompletedTask; } return TaskUtil.TrueCompletedTask; }; var target = GetAndStartTarget(); // Act foreach (var command in commands) { await _producedCommands.SendAsync(command); } // Assert var unconsumedCommand = await target.CommandListenerTask; unconsumedCommand.ShouldNotBeNull(); _producedCommands.TryReceiveAll(out var producedItems); producedItems?.ShouldNotContain(unconsumedCommand); _consumedCommands.TryReceiveAll(out var consumedItems); consumedItems?.ShouldNotContain(unconsumedCommand); consumedCount.ShouldBe(halfCount); _channel.Verify(c => c.ReceiveCommandAsync(It.IsAny<CancellationToken>()), Times.AtLeast(halfCount)); } [Test] public async Task Start_CommandChannelThrowsException_StopsListenerTaskAndThrows() { // Arrange var exception = Dummy.CreateException<ApplicationException>(); _channel .Setup(m => m.ReceiveCommandAsync(It.IsAny<CancellationToken>())) .ThrowsAsync(exception); var target = GetAndStartTarget(); // Act await target.CommandListenerTask.ShouldThrowAsync<ApplicationException>(); } [Test] public async Task Start_CommandConsumerThrowsException_StopsListenerTaskAndThrows() { // Arrange var command = Dummy.CreateCommand(Dummy.CreateTextContent()); var exception = Dummy.CreateException<ApplicationException>(); _commandConsumer = (m, ct) => { if (ReferenceEquals(command, m)) { throw exception; } throw new Exception("An unexpected command was received by the consumer"); }; var target = GetAndStartTarget(); // Act await _producedCommands.SendAsync(command); await target.CommandListenerTask.ShouldThrowAsync<ApplicationException>(); } [Test] public async Task Start_StoppedWhileProducingCommand_ReturnsNull() { // Arrange var target = GetAndStartTarget(); // Act target.Stop(); // Act (await target.CommandListenerTask).ShouldBeNull(); } } }
using System; using Torshify.Core.Managers; namespace Torshify.Core.Native { internal class NativeArtistBrowse : NativeObject, IArtistBrowse { #region Fields private readonly IntPtr _artistToBrowse; private readonly ArtistBrowseType _browseType; private Spotify.ArtistBrowseCompleteCallback _browseCompleteCallback; private DelegateArray<ITrack> _tracks; private DelegateArray<ITrack> _topHitTracks; private DelegateArray<IAlbum> _albums; private DelegateArray<IArtist> _similarArtists; private DelegateArray<IImage> _portraits; #endregion Fields #region Constructors public NativeArtistBrowse(ISession session, IntPtr artistToBrowse, ArtistBrowseType browseType) : base(session, IntPtr.Zero) { _artistToBrowse = artistToBrowse; _browseType = browseType; } #endregion Constructors #region Events public event EventHandler Completed; #endregion Events #region Properties public bool IsComplete { get; private set; } public bool IsLoaded { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_is_loaded(Handle); } } } public Error Error { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_error(Handle); } } } public IArtist Artist { get { AssertHandle(); lock (Spotify.Mutex) { return ArtistManager.Get(Session, Spotify.sp_artistbrowse_artist(Handle)); } } } public IArray<IImage> Portraits { get { AssertHandle(); return _portraits; } } public IArray<ITrack> Tracks { get { AssertHandle(); return _tracks; } } public IArray<ITrack> TopHitTracks { get { AssertHandle(); return _topHitTracks; } } public IArray<IAlbum> Albums { get { AssertHandle(); return _albums; } } public IArray<IArtist> SimilarArtists { get { AssertHandle(); return _similarArtists; } } public string Biography { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_biography(Handle); } } } public TimeSpan BackendRequestDuration { get { AssertHandle(); lock (Spotify.Mutex) { return TimeSpan.FromMilliseconds(Spotify.sp_artistbrowse_backend_request_duration(Handle)); } } } #endregion Properties #region Public Methods public override void Initialize() { _browseCompleteCallback = OnBrowseCompleteCallback; _tracks = new DelegateArray<ITrack>(GetNumberOfTracks, GetTrackAtIndex); _topHitTracks = new DelegateArray<ITrack>(GetNumberOfTopHitTracks, GetTopHitTrackAtIndex); _albums = new DelegateArray<IAlbum>(GetNumberOfAlbums, GetAlbumAtIndex); _similarArtists = new DelegateArray<IArtist>(GetNumberOfSimilarArtists, GetSimilarArtistAtIndex); _portraits = new DelegateArray<IImage>(GetNumberOfPortraits, GetPortraitAtIndex); lock (Spotify.Mutex) { Handle = Spotify.sp_artistbrowse_create( Session.GetHandle(), _artistToBrowse, _browseType, _browseCompleteCallback, IntPtr.Zero); } } #endregion Public Methods #region Protected Methods protected override void Dispose(bool disposing) { // Dispose managed if (disposing) { } // Dispose unmanaged if (!IsInvalid) { try { lock (Spotify.Mutex) { Ensure(() => Spotify.sp_artistbrowse_release(Handle)); } GC.KeepAlive(_browseCompleteCallback); } catch { } } base.Dispose(disposing); } #endregion Protected Methods #region Private Methods private IImage GetPortraitAtIndex(int index) { AssertHandle(); lock (Spotify.Mutex) { IntPtr id = Spotify.sp_artistbrowse_portrait(Handle, index); string stringId = Spotify.ImageIdToString(id); return Session.GetImage(stringId); } } private int GetNumberOfPortraits() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_num_portraits(Handle); } } private IArtist GetSimilarArtistAtIndex(int index) { AssertHandle(); lock (Spotify.Mutex) { return ArtistManager.Get(Session, Spotify.sp_artistbrowse_similar_artist(Handle, index)); } } private int GetNumberOfSimilarArtists() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_num_similar_artists(Handle); } } private IAlbum GetAlbumAtIndex(int index) { AssertHandle(); lock (Spotify.Mutex) { return AlbumManager.Get(Session, Spotify.sp_artistbrowse_album(Handle, index)); } } private int GetNumberOfAlbums() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_num_albums(Handle); } } private ITrack GetTrackAtIndex(int index) { AssertHandle(); lock (Spotify.Mutex) { return TrackManager.Get(Session, Spotify.sp_artistbrowse_track(Handle, index)); } } private int GetNumberOfTracks() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_num_tracks(Handle); } } private ITrack GetTopHitTrackAtIndex(int index) { AssertHandle(); lock (Spotify.Mutex) { return TrackManager.Get(Session, Spotify.sp_artistbrowse_tophit_track(Handle, index)); } } private int GetNumberOfTopHitTracks() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_artistbrowse_num_tophit_tracks(Handle); } } private void OnBrowseCompleteCallback(IntPtr browseptr, IntPtr userdataptr) { if (browseptr != Handle) { return; } this.QueueThis(() => OnBrowseComplete(new UserDataEventArgs(EventArgs.Empty))); } private void OnBrowseComplete(EventArgs e) { IsComplete = true; Completed.RaiseEvent(this, e); } #endregion Private Methods } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #if SRM namespace System.Reflection.Metadata #else namespace Microsoft.CodeAnalysis.CodeGen #endif { #if SRM && FUTURE public #endif enum ILOpCode : ushort { Nop = 0x00, Break = 0x01, Ldarg_0 = 0x02, Ldarg_1 = 0x03, Ldarg_2 = 0x04, Ldarg_3 = 0x05, Ldloc_0 = 0x06, Ldloc_1 = 0x07, Ldloc_2 = 0x08, Ldloc_3 = 0x09, Stloc_0 = 0x0a, Stloc_1 = 0x0b, Stloc_2 = 0x0c, Stloc_3 = 0x0d, Ldarg_s = 0x0e, Ldarga_s = 0x0f, Starg_s = 0x10, Ldloc_s = 0x11, Ldloca_s = 0x12, Stloc_s = 0x13, Ldnull = 0x14, Ldc_i4_m1 = 0x15, Ldc_i4_0 = 0x16, Ldc_i4_1 = 0x17, Ldc_i4_2 = 0x18, Ldc_i4_3 = 0x19, Ldc_i4_4 = 0x1a, Ldc_i4_5 = 0x1b, Ldc_i4_6 = 0x1c, Ldc_i4_7 = 0x1d, Ldc_i4_8 = 0x1e, Ldc_i4_s = 0x1f, Ldc_i4 = 0x20, Ldc_i8 = 0x21, Ldc_r4 = 0x22, Ldc_r8 = 0x23, Dup = 0x25, Pop = 0x26, Jmp = 0x27, Call = 0x28, Calli = 0x29, Ret = 0x2a, Br_s = 0x2b, Brfalse_s = 0x2c, Brtrue_s = 0x2d, Beq_s = 0x2e, Bge_s = 0x2f, Bgt_s = 0x30, Ble_s = 0x31, Blt_s = 0x32, Bne_un_s = 0x33, Bge_un_s = 0x34, Bgt_un_s = 0x35, Ble_un_s = 0x36, Blt_un_s = 0x37, Br = 0x38, Brfalse = 0x39, Brtrue = 0x3a, Beq = 0x3b, Bge = 0x3c, Bgt = 0x3d, Ble = 0x3e, Blt = 0x3f, Bne_un = 0x40, Bge_un = 0x41, Bgt_un = 0x42, Ble_un = 0x43, Blt_un = 0x44, Switch = 0x45, Ldind_i1 = 0x46, Ldind_u1 = 0x47, Ldind_i2 = 0x48, Ldind_u2 = 0x49, Ldind_i4 = 0x4a, Ldind_u4 = 0x4b, Ldind_i8 = 0x4c, Ldind_i = 0x4d, Ldind_r4 = 0x4e, Ldind_r8 = 0x4f, Ldind_ref = 0x50, Stind_ref = 0x51, Stind_i1 = 0x52, Stind_i2 = 0x53, Stind_i4 = 0x54, Stind_i8 = 0x55, Stind_r4 = 0x56, Stind_r8 = 0x57, Add = 0x58, Sub = 0x59, Mul = 0x5a, Div = 0x5b, Div_un = 0x5c, Rem = 0x5d, Rem_un = 0x5e, And = 0x5f, Or = 0x60, Xor = 0x61, Shl = 0x62, Shr = 0x63, Shr_un = 0x64, Neg = 0x65, Not = 0x66, Conv_i1 = 0x67, Conv_i2 = 0x68, Conv_i4 = 0x69, Conv_i8 = 0x6a, Conv_r4 = 0x6b, Conv_r8 = 0x6c, Conv_u4 = 0x6d, Conv_u8 = 0x6e, Callvirt = 0x6f, Cpobj = 0x70, Ldobj = 0x71, Ldstr = 0x72, Newobj = 0x73, Castclass = 0x74, Isinst = 0x75, Conv_r_un = 0x76, Unbox = 0x79, Throw = 0x7a, Ldfld = 0x7b, Ldflda = 0x7c, Stfld = 0x7d, Ldsfld = 0x7e, Ldsflda = 0x7f, Stsfld = 0x80, Stobj = 0x81, Conv_ovf_i1_un = 0x82, Conv_ovf_i2_un = 0x83, Conv_ovf_i4_un = 0x84, Conv_ovf_i8_un = 0x85, Conv_ovf_u1_un = 0x86, Conv_ovf_u2_un = 0x87, Conv_ovf_u4_un = 0x88, Conv_ovf_u8_un = 0x89, Conv_ovf_i_un = 0x8a, Conv_ovf_u_un = 0x8b, Box = 0x8c, Newarr = 0x8d, Ldlen = 0x8e, Ldelema = 0x8f, Ldelem_i1 = 0x90, Ldelem_u1 = 0x91, Ldelem_i2 = 0x92, Ldelem_u2 = 0x93, Ldelem_i4 = 0x94, Ldelem_u4 = 0x95, Ldelem_i8 = 0x96, Ldelem_i = 0x97, Ldelem_r4 = 0x98, Ldelem_r8 = 0x99, Ldelem_ref = 0x9a, Stelem_i = 0x9b, Stelem_i1 = 0x9c, Stelem_i2 = 0x9d, Stelem_i4 = 0x9e, Stelem_i8 = 0x9f, Stelem_r4 = 0xa0, Stelem_r8 = 0xa1, Stelem_ref = 0xa2, Ldelem = 0xa3, Stelem = 0xa4, Unbox_any = 0xa5, Conv_ovf_i1 = 0xb3, Conv_ovf_u1 = 0xb4, Conv_ovf_i2 = 0xb5, Conv_ovf_u2 = 0xb6, Conv_ovf_i4 = 0xb7, Conv_ovf_u4 = 0xb8, Conv_ovf_i8 = 0xb9, Conv_ovf_u8 = 0xba, Refanyval = 0xc2, Ckfinite = 0xc3, Mkrefany = 0xc6, Ldtoken = 0xd0, Conv_u2 = 0xd1, Conv_u1 = 0xd2, Conv_i = 0xd3, Conv_ovf_i = 0xd4, Conv_ovf_u = 0xd5, Add_ovf = 0xd6, Add_ovf_un = 0xd7, Mul_ovf = 0xd8, Mul_ovf_un = 0xd9, Sub_ovf = 0xda, Sub_ovf_un = 0xdb, Endfinally = 0xdc, Leave = 0xdd, Leave_s = 0xde, Stind_i = 0xdf, Conv_u = 0xe0, Arglist = 0xfe00, Ceq = 0xfe01, Cgt = 0xfe02, Cgt_un = 0xfe03, Clt = 0xfe04, Clt_un = 0xfe05, Ldftn = 0xfe06, Ldvirtftn = 0xfe07, Ldarg = 0xfe09, Ldarga = 0xfe0a, Starg = 0xfe0b, Ldloc = 0xfe0c, Ldloca = 0xfe0d, Stloc = 0xfe0e, Localloc = 0xfe0f, Endfilter = 0xfe11, Unaligned = 0xfe12, Volatile = 0xfe13, Tail = 0xfe14, Initobj = 0xfe15, Constrained = 0xfe16, Cpblk = 0xfe17, Initblk = 0xfe18, Rethrow = 0xfe1a, Sizeof = 0xfe1c, Refanytype = 0xfe1d, Readonly = 0xfe1e, } }
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Threading.Tasks; namespace UnderGMX { class Program { static int gmxFileI = 0; static List<String> gmxFile = new List<String>(); static void gmxWrite(String str) { gmxFile.Add(str); } static void Main(string[] args) { String appDir = System.AppDomain.CurrentDomain.BaseDirectory; //Get application directory for future use. Console.WriteLine("Application Base Directory: "+appDir); String gmxBase = appDir + "UnderGMX.gmx\\"; Console.WriteLine("Writing GMX File..."); gmxFile.Add("<!--This Document is generated by UnderGMX, if you edit it by hand then you do so at your own risk!-->"); gmxFile.Add("<assets>"); // Entry point for GMX file assets. Console.WriteLine("GMX File -> Writing Config"); gmxWrite(" <Configs name=\"configs\">"); gmxWrite(" <Config>Configs\\Default</Config>"); gmxWrite(" </Configs>"); //Console.WriteLine("GMX File -> Writing datafiles (not implemented)"); //gmxWrite(" <datafiles name=\"datafiles\"/>"); Console.WriteLine("GMX File -> Writing Extensions (not implemented)"); gmxWrite(" <NewExtensions>"); gmxWrite(" </NewExtensions>"); // HERE WE GET ALL OF THE SPRITES, SCRIPTS, OBJECTS, ETC. INTO MEMORY AND WRITE THE GMX FILE CONTENT. gmxWrite(" <sounds name=\"sound\">"); String[] soundnames = Sounds.getSoundDataNames(appDir); int soundi = 0; while (soundi < soundnames.Length) { gmxWrite(" <sound>sound\\"+soundnames[soundi]+ "</sound>"); soundi++; } gmxWrite(" </sounds>"); gmxWrite(" <sprites name=\"sprites\">"); String[] spritenames = Sprites.getSpriteDataNames(appDir); int spritei = 0; while (spritei < spritenames.Length) { gmxWrite(" <sprite>sprites\\" + spritenames[spritei] + "</sprite>"); spritei++; } gmxWrite(" </sprites>"); gmxWrite(" <backgrounds name=\"background\">"); String[] bgnames = Backgrounds.getBackgroundDataNames(appDir); int bgi = 0; while (bgi < bgnames.Length) { gmxWrite(" <background>background\\" + bgnames[bgi] + "</background>"); bgi++; } gmxWrite(" </backgrounds>"); gmxWrite(" <paths name=\"paths\">"); String[] pathnames = Paths.getPathDataNames(appDir); int pathi = 0; while (pathi < pathnames.Length) { gmxWrite(" <path>paths\\" + pathnames[pathi] + "</path>"); pathi++; } gmxWrite(" </paths>"); gmxWrite(" <scripts name=\"scripts\">"); String[] scrnames = Scripts.getScriptDataNames(appDir); int scri = 0; while (scri < scrnames.Length) { gmxWrite(" <script>scripts\\" + scrnames[scri] + ".gml</script>"); scri++; } gmxWrite(" </scripts>"); gmxWrite(" <fonts name=\"fonts\">"); String[] fntnames = Fonts.getFontDataNames(appDir); int fnti = 0; while (fnti < fntnames.Length) { gmxWrite(" <font>fonts\\" + fntnames[fnti] + "</font>"); fnti++; } gmxWrite(" </fonts>"); /*gmxWrite(" <objects name=\"objects\">"); String[] objnames = Objects.getObjectDataNames(appDir); int obji = 0; while (obji < objnames.Length) { gmxWrite(" <object>objects\\" + objnames[obji] + "</object>"); obji++; } gmxWrite(" </objects>");*/ /*gmxWrite(" <rooms name=\"rooms\">"); String[] roomnames = Rooms.getRoomDataNames(appDir); int roomi = 0; while (roomi < roomnames.Length) { gmxWrite(" <room>rooms\\" + roomnames[roomi] + "</room>"); roomi++; } gmxWrite(" </rooms>");*/ // Here we complete the GMX file with the help files/tutorial states. gmxWrite(" <help>"); gmxWrite(" <rtf>help.rtf</rtf>"); gmxWrite(" </help>"); gmxWrite(" <TutorialState>"); gmxWrite(" <IsTutorial>0</IsTutorial>"); gmxWrite(" <TutorialName></TutorialName>"); gmxWrite(" <TutorialPage>0</TutorialPage>"); gmxWrite(" </TutorialState>"); //Close off GMX file. gmxWrite("</assets>"); var gmxFileArr = gmxFile.ToArray(); string list = ""; int i = 0; //while(i < gmxFileArr.Length) //{ // Console.WriteLine(gmxFileArr[i]); // list += gmxFileArr[i]; // i++; //} //Console.WriteLine(list); if (!Directory.Exists(appDir + "UnderGMX.gmx")) { Directory.CreateDirectory(appDir + "UnderGMX.gmx"); } else { //if(Directory.Exists(appDir+"gmx\\sprites")) Directory.Delete(appDir+"gmx\\sprites"); System.IO.DirectoryInfo di = new DirectoryInfo(appDir+"UnderGMX.gmx"); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } Directory.CreateDirectory(appDir + "UnderGMX.gmx"); } /*if ((!File.Exists(@appDir+"UnderGMX.project.gmx"))) { FileStream fs = File.Create(@appDir+"UnderGMX.project.gmx"); fs.Close(); } StreamWriter sw = new StreamWriter(appDir+"UnderGMX.project.gmx", true); while (i < gmxFileArr.Length) { sw.WriteLine(gmxFileArr[i]); i++; } sw.Close();*/ using (var dest = File.AppendText(Path.Combine(gmxBase, "help.rtf"))) { dest.Write(""); } using (var dest = File.AppendText(Path.Combine(gmxBase, "UnderGMX.project.gmx"))) { dest.Write(""); } while (i < gmxFileArr.Length) { using (var dest = File.AppendText(Path.Combine(gmxBase, "UnderGMX.project.gmx"))) { dest.WriteLine(gmxFileArr[i]); } i++; } if (!Directory.Exists(gmxBase + "Configs\\")) Directory.CreateDirectory(gmxBase + "Configs"); if (!Directory.Exists(gmxBase + "datafiles\\")) Directory.CreateDirectory(gmxBase + "datafiles"); if (!Directory.Exists(gmxBase + "extensions\\")) Directory.CreateDirectory(gmxBase + "extensions"); if (!Directory.Exists(gmxBase + "sound\\")) Directory.CreateDirectory(gmxBase + "sound"); if (!Directory.Exists(gmxBase + "sprites\\")) Directory.CreateDirectory(gmxBase + "sprites"); if (!Directory.Exists(gmxBase + "background\\")) Directory.CreateDirectory(gmxBase + "background"); if (!Directory.Exists(gmxBase + "paths\\")) Directory.CreateDirectory(gmxBase + "paths"); if (!Directory.Exists(gmxBase + "scripts\\")) Directory.CreateDirectory(gmxBase + "scripts"); if (!Directory.Exists(gmxBase + "fonts\\")) Directory.CreateDirectory(gmxBase + "fonts"); if (!Directory.Exists(gmxBase + "rooms\\")) Directory.CreateDirectory(gmxBase + "rooms"); string ConfigBase = gmxBase + "Configs\\"; string[] configasset = LoadAsset.loadAsset("Default.config.gmx"); i = 0; while (i < configasset.Length) { using (var dest = File.AppendText(Path.Combine(ConfigBase, "Default.project.gmx"))) { dest.WriteLine(configasset[i]); } i++; } CopyPaste.CopyDirectory(@"assets\Default",ConfigBase+"Default",true); Sprites.copySprites(appDir); Sprites.writeSprites(appDir,spritenames); Sounds.copySounds(appDir); Sounds.writeSounds(appDir,soundnames); Backgrounds.copyBackgrounds(appDir); Backgrounds.writeBackgrounds(appDir,bgnames); Scripts.writeScripts(appDir, scrnames); Console.WriteLine("GMX Project File Compiled successfully!"); Console.WriteLine("Press any key to exit."); //Finish off application. Console.ReadKey(); } } }
using UnityEngine; using System.Collections; public class EveryplayThumbnailPool : MonoBehaviour { public int thumbnailCount = 4; public int thumbnailWidth = 128; public bool pixelPerfect = false; public bool takeRandomShots = true; public TextureFormat textureFormat = TextureFormat.RGBA32; public bool dontDestroyOnLoad = true; public bool allowOneInstanceOnly = true; public Texture2D[] thumbnailTextures { get; private set; } public int availableThumbnailCount { get; private set; } public float aspectRatio { get; private set; } public Vector2 thumbnailScale { get; private set; } private bool npotSupported = false; private bool initialized = false; private int currentThumbnailTextureIndex; private float nextRandomShotTime; private int thumbnailHeight = 0; void Awake() { if (allowOneInstanceOnly && FindObjectsOfType(GetType()).Length > 1) { Destroy(gameObject); } else { if (dontDestroyOnLoad) { DontDestroyOnLoad(gameObject); } Everyplay.ReadyForRecording += OnReadyForRecording; } } void Start() { if (enabled) { Initialize(); } } private void OnReadyForRecording(bool ready) { if (ready) { Initialize(); } } private void Initialize() { if (!initialized && Everyplay.IsRecordingSupported()) { // Limit width between 32 and 2048 thumbnailWidth = Mathf.Clamp(thumbnailWidth, 32, 2048); // Thumbnails are always stored landscape in memory aspectRatio = (float) Mathf.Min(Screen.width, Screen.height) / (float) Mathf.Max(Screen.width, Screen.height); // Calculate height based on aspect ratio thumbnailHeight = (int) (thumbnailWidth * aspectRatio); // Check for npot support, always use pot textures for older Unitys versions and if npot support is not available npotSupported = false; #if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1) npotSupported = (SystemInfo.npotSupport != NPOTSupport.None); #endif int thumbnailPotWidth = Mathf.NextPowerOfTwo(thumbnailWidth); int thumbnailPotHeight = Mathf.NextPowerOfTwo(thumbnailHeight); // Create empty textures for requested amount of thumbnails thumbnailTextures = new Texture2D[thumbnailCount]; for (int i = 0; i < thumbnailCount; i++) { thumbnailTextures[i] = new Texture2D(npotSupported ? thumbnailWidth : thumbnailPotWidth, npotSupported ? thumbnailHeight : thumbnailPotHeight, textureFormat, false); // Always use clamp to assure texture completeness when npot support is restricted thumbnailTextures[i].wrapMode = TextureWrapMode.Clamp; } // Set thumbnail render target to the first texture currentThumbnailTextureIndex = 0; Everyplay.SetThumbnailTargetTexture(thumbnailTextures[currentThumbnailTextureIndex]); SetThumbnailTargetSize(); // Add thumbnail take listener Everyplay.ThumbnailTextureReady += OnThumbnailReady; Everyplay.RecordingStarted += OnRecordingStarted; initialized = true; } } private void OnRecordingStarted() { availableThumbnailCount = 0; currentThumbnailTextureIndex = 0; Everyplay.SetThumbnailTargetTexture(thumbnailTextures[currentThumbnailTextureIndex]); SetThumbnailTargetSize(); if (takeRandomShots) { Everyplay.TakeThumbnail(); nextRandomShotTime = Time.time + Random.Range(3.0f, 15.0f); } } void Update() { if (takeRandomShots && Everyplay.IsRecording() && !Everyplay.IsPaused()) { if (Time.time > nextRandomShotTime) { Everyplay.TakeThumbnail(); nextRandomShotTime = Time.time + Random.Range(3.0f, 15.0f); } } } private void OnThumbnailReady(Texture2D texture, bool portrait) { if (thumbnailTextures[currentThumbnailTextureIndex] == texture) { currentThumbnailTextureIndex++; if (currentThumbnailTextureIndex >= thumbnailTextures.Length) { currentThumbnailTextureIndex = 0; } if (availableThumbnailCount < thumbnailTextures.Length) { availableThumbnailCount++; } Everyplay.SetThumbnailTargetTexture(thumbnailTextures[currentThumbnailTextureIndex]); SetThumbnailTargetSize(); } } private void SetThumbnailTargetSize() { // Workaround issue that Unity might say that texture is size of x even it really is x to next power of two int thumbnailPotWidth = Mathf.NextPowerOfTwo(thumbnailWidth); int thumbnailPotHeight = Mathf.NextPowerOfTwo(thumbnailHeight); if (npotSupported) { #pragma warning disable 612, 618 Everyplay.SetThumbnailTargetTextureWidth(thumbnailWidth); Everyplay.SetThumbnailTargetTextureHeight(thumbnailHeight); #pragma warning restore 612, 618 thumbnailScale = new Vector2(1, 1); } else { if (pixelPerfect) { #pragma warning disable 612, 618 Everyplay.SetThumbnailTargetTextureWidth(thumbnailWidth); Everyplay.SetThumbnailTargetTextureHeight(thumbnailHeight); #pragma warning restore 612, 618 thumbnailScale = new Vector2((float) thumbnailWidth / (float) thumbnailPotWidth, (float) thumbnailHeight / (float) thumbnailPotHeight); } else { #pragma warning disable 612, 618 Everyplay.SetThumbnailTargetTextureWidth(thumbnailPotWidth); Everyplay.SetThumbnailTargetTextureHeight(thumbnailPotHeight); #pragma warning restore 612, 618 thumbnailScale = new Vector2(1, 1); } } } void OnDestroy() { Everyplay.ReadyForRecording -= OnReadyForRecording; if (initialized) { // Set Everyplay not to render to a texture anymore and remove event handlers Everyplay.SetThumbnailTargetTexture(null); Everyplay.RecordingStarted -= OnRecordingStarted; Everyplay.ThumbnailTextureReady -= OnThumbnailReady; // Destroy thumbnail textures foreach (Texture2D texture in thumbnailTextures) { if (texture != null) { Destroy(texture); } } thumbnailTextures = null; initialized = false; } } }
namespace NBug.Core.Submission.Tracker.Mantis { [System.SerializableAttribute(), System.Xml.Serialization.SoapTypeAttribute(Namespace = "http://futureware.biz/mantisconnect")] public class IssueData { private string idField; private ObjectRef view_stateField; private System.DateTime last_updatedField; private bool last_updatedFieldSpecified; private ObjectRef projectField; private string categoryField; private ObjectRef priorityField; private ObjectRef severityField; private ObjectRef statusField; private AccountData reporterField; private string summaryField; private string versionField; private string buildField; private string platformField; private string osField; private string os_buildField; private ObjectRef reproducibilityField; private System.DateTime date_submittedField; private bool date_submittedFieldSpecified; private string sponsorship_totalField; private AccountData handlerField; private ObjectRef projectionField; private ObjectRef etaField; private ObjectRef resolutionField; private string fixed_in_versionField; private string target_versionField; private string descriptionField; private string steps_to_reproduceField; private string additional_informationField; private AttachmentData[] attachmentsField; private RelationshipData[] relationshipsField; private IssueNoteData[] notesField; private CustomFieldValueForIssueData[] custom_fieldsField; private System.DateTime due_dateField; private bool due_dateFieldSpecified; private AccountData[] monitorsField; private bool stickyField; private bool stickyFieldSpecified; private ObjectRef[] tagsField; [System.Xml.Serialization.SoapElementAttribute(DataType = "integer")] public string id { get { return this.idField; } set { this.idField = value; } } public ObjectRef view_state { get { return this.view_stateField; } set { this.view_stateField = value; } } public System.DateTime last_updated { get { return this.last_updatedField; } set { this.last_updatedField = value; } } [System.Xml.Serialization.SoapIgnoreAttribute()] public bool last_updatedSpecified { get { return this.last_updatedFieldSpecified; } set { this.last_updatedFieldSpecified = value; } } public ObjectRef project { get { return this.projectField; } set { this.projectField = value; } } public string category { get { return this.categoryField; } set { this.categoryField = value; } } public ObjectRef priority { get { return this.priorityField; } set { this.priorityField = value; } } public ObjectRef severity { get { return this.severityField; } set { this.severityField = value; } } public ObjectRef status { get { return this.statusField; } set { this.statusField = value; } } public AccountData reporter { get { return this.reporterField; } set { this.reporterField = value; } } public string summary { get { return this.summaryField; } set { this.summaryField = value; } } public string version { get { return this.versionField; } set { this.versionField = value; } } public string build { get { return this.buildField; } set { this.buildField = value; } } public string platform { get { return this.platformField; } set { this.platformField = value; } } public string os { get { return this.osField; } set { this.osField = value; } } public string os_build { get { return this.os_buildField; } set { this.os_buildField = value; } } public ObjectRef reproducibility { get { return this.reproducibilityField; } set { this.reproducibilityField = value; } } public System.DateTime date_submitted { get { return this.date_submittedField; } set { this.date_submittedField = value; } } [System.Xml.Serialization.SoapIgnoreAttribute()] public bool date_submittedSpecified { get { return this.date_submittedFieldSpecified; } set { this.date_submittedFieldSpecified = value; } } [System.Xml.Serialization.SoapElementAttribute(DataType = "integer")] public string sponsorship_total { get { return this.sponsorship_totalField; } set { this.sponsorship_totalField = value; } } public AccountData handler { get { return this.handlerField; } set { this.handlerField = value; } } public ObjectRef projection { get { return this.projectionField; } set { this.projectionField = value; } } public ObjectRef eta { get { return this.etaField; } set { this.etaField = value; } } public ObjectRef resolution { get { return this.resolutionField; } set { this.resolutionField = value; } } public string fixed_in_version { get { return this.fixed_in_versionField; } set { this.fixed_in_versionField = value; } } public string target_version { get { return this.target_versionField; } set { this.target_versionField = value; } } public string description { get { return this.descriptionField; } set { this.descriptionField = value; } } public string steps_to_reproduce { get { return this.steps_to_reproduceField; } set { this.steps_to_reproduceField = value; } } public string additional_information { get { return this.additional_informationField; } set { this.additional_informationField = value; } } public AttachmentData[] attachments { get { return this.attachmentsField; } set { this.attachmentsField = value; } } public RelationshipData[] relationships { get { return this.relationshipsField; } set { this.relationshipsField = value; } } public IssueNoteData[] notes { get { return this.notesField; } set { this.notesField = value; } } public CustomFieldValueForIssueData[] custom_fields { get { return this.custom_fieldsField; } set { this.custom_fieldsField = value; } } public System.DateTime due_date { get { return this.due_dateField; } set { this.due_dateField = value; } } [System.Xml.Serialization.SoapIgnoreAttribute()] public bool due_dateSpecified { get { return this.due_dateFieldSpecified; } set { this.due_dateFieldSpecified = value; } } public AccountData[] monitors { get { return this.monitorsField; } set { this.monitorsField = value; } } public bool sticky { get { return this.stickyField; } set { this.stickyField = value; } } [System.Xml.Serialization.SoapIgnoreAttribute()] public bool stickySpecified { get { return this.stickyFieldSpecified; } set { this.stickyFieldSpecified = value; } } public ObjectRef[] tags { get { return this.tagsField; } set { this.tagsField = value; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Drawing; using System.Text; using System.Timers; using System.Windows.Forms; using SLNetworkComm; using libsecondlife; namespace SLeek { public partial class frmMain : Form { private SleekInstance instance; private SLNetCom netcom; private SecondLife client; private TabsConsole tabsConsole; private frmDebugLog debugLogForm; private System.Timers.Timer statusTimer; public frmMain(SleekInstance instance) { InitializeComponent(); this.instance = instance; client = this.instance.Client; netcom = this.instance.Netcom; netcom.NetcomSync = this; AddNetcomEvents(); client.Parcels.OnParcelProperties += new ParcelManager.ParcelPropertiesCallback(Parcels_OnParcelProperties); InitializeStatusTimer(); RefreshWindowTitle(); ApplyConfig(this.instance.Config.CurrentConfig, true); this.instance.Config.ConfigApplied += new EventHandler<ConfigAppliedEventArgs>(Config_ConfigApplied); } //Separate thread private void Parcels_OnParcelProperties(Parcel parcel, ParcelManager.ParcelResult result, int sequenceID, bool snapSelection) { StringBuilder sb = new StringBuilder(); sb.Append("Parcel: "); sb.Append(parcel.Name); if ((parcel.Flags & Parcel.ParcelFlags.AllowFly) != Parcel.ParcelFlags.AllowFly) sb.Append(" (no fly)"); if ((parcel.Flags & Parcel.ParcelFlags.CreateObjects) != Parcel.ParcelFlags.CreateObjects) sb.Append(" (no build)"); if ((parcel.Flags & Parcel.ParcelFlags.AllowOtherScripts) != Parcel.ParcelFlags.AllowOtherScripts) sb.Append(" (no scripts)"); if ((parcel.Flags & Parcel.ParcelFlags.RestrictPushObject) == Parcel.ParcelFlags.RestrictPushObject) sb.Append(" (no push)"); if ((parcel.Flags & Parcel.ParcelFlags.AllowDamage) == Parcel.ParcelFlags.AllowDamage) sb.Append(" (damage)"); BeginInvoke(new MethodInvoker(delegate() { tlblParcel.Text = sb.ToString(); })); } private void Config_ConfigApplied(object sender, ConfigAppliedEventArgs e) { ApplyConfig(e.AppliedConfig, false); } private void ApplyConfig(Config config, bool doingInit) { if (doingInit) this.WindowState = (FormWindowState)config.MainWindowState; if (config.InterfaceStyle == 0) //System toolStrip1.RenderMode = ToolStripRenderMode.System; else if (config.InterfaceStyle == 1) //Office 2003 toolStrip1.RenderMode = ToolStripRenderMode.ManagerRenderMode; } public void InitializeControls() { InitializeTabsConsole(); InitializeDebugLogForm(); } private void statusTimer_Elapsed(object sender, ElapsedEventArgs e) { RefreshWindowTitle(); RefreshStatusBar(); } private void AddNetcomEvents() { netcom.ClientLoginStatus += new EventHandler<ClientLoginEventArgs>(netcom_ClientLoginStatus); netcom.ClientLoggedOut += new EventHandler(netcom_ClientLoggedOut); netcom.ClientDisconnected += new EventHandler<ClientDisconnectEventArgs>(netcom_ClientDisconnected); netcom.InstantMessageReceived += new EventHandler<InstantMessageEventArgs>(netcom_InstantMessageReceived); } private void netcom_InstantMessageReceived(object sender, InstantMessageEventArgs e) { if (e.IM.Dialog == InstantMessageDialog.StartTyping || e.IM.Dialog == InstantMessageDialog.StopTyping) return; if (!this.Focused) FormFlash.Flash(this); } private void netcom_ClientLoginStatus(object sender, ClientLoginEventArgs e) { if (e.Status != LoginStatus.Success) return; tbtnStatus.Enabled = tbtnControl.Enabled = tbtnTeleport.Enabled = tbtnObjects.Enabled = true; statusTimer.Start(); RefreshWindowTitle(); } private void netcom_ClientLoggedOut(object sender, EventArgs e) { tbtnStatus.Enabled = tbtnControl.Enabled = tbtnTeleport.Enabled = tbtnObjects.Enabled = false; statusTimer.Stop(); RefreshStatusBar(); RefreshWindowTitle(); } private void netcom_ClientDisconnected(object sender, ClientDisconnectEventArgs e) { if (e.Type == NetworkManager.DisconnectType.ClientInitiated) return; tbtnStatus.Enabled = tbtnControl.Enabled = tbtnTeleport.Enabled = tbtnObjects.Enabled = false; statusTimer.Stop(); RefreshStatusBar(); RefreshWindowTitle(); (new frmDisconnected(instance, e)).ShowDialog(); } private void frmMain_FormClosing(object sender, FormClosingEventArgs e) { if (instance.IsFirstInstance && instance.OtherInstancesOpen) { if (MessageBox.Show("You are about to close the first instance of SLeek. This may cause any other open instances of SLeek to close. Are you sure you want to continue?", "SLeek", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { e.Cancel = true; return; } } debugLogForm.Dispose(); debugLogForm.Close(); debugLogForm = null; if (netcom.IsLoggedIn) netcom.Logout(); instance.Config.CurrentConfig.MainWindowState = (int)this.WindowState; } private void RefreshStatusBar() { if (netcom.IsLoggedIn) { tlblLoginName.Text = netcom.LoginOptions.FullName; tlblMoneyBalance.Text = "L$" + client.Self.Balance.ToString(); tlblHealth.Text = "Health: " + client.Self.Health.ToString(); tlblRegionInfo.Text = client.Network.CurrentSim.Name + " (" + Math.Floor(client.Self.SimPosition.X).ToString() + ", " + Math.Floor(client.Self.SimPosition.Y).ToString() + ", " + Math.Floor(client.Self.SimPosition.Z).ToString() + ")"; int totalPrims = 0; int totalAvatars = 0; foreach (Simulator sim in client.Network.Simulators) { totalPrims += sim.ObjectsPrimitives.Count; totalAvatars += sim.ObjectsAvatars.Count; } toolTip1.SetToolTip( statusStrip1, "Region: " + client.Network.CurrentSim.Name + "\n" + "X: " + client.Self.SimPosition.X.ToString() + "\n" + "Y: " + client.Self.SimPosition.Y.ToString() + "\n" + "Z: " + client.Self.SimPosition.Z.ToString() + "\n\n" + "Nearby prims: " + totalPrims.ToString() + "\n" + "Nearby avatars: " + totalAvatars.ToString()); } else { tlblLoginName.Text = "Offline"; tlblMoneyBalance.Text = "L$0"; tlblHealth.Text = "Health: 0"; tlblRegionInfo.Text = "No Region"; tlblParcel.Text = "No Parcel"; toolTip1.SetToolTip(statusStrip1, string.Empty); } } private void RefreshWindowTitle() { StringBuilder sb = new StringBuilder(); sb.Append("SLeek - "); if (netcom.IsLoggedIn) { sb.Append("[" + netcom.LoginOptions.FullName + "]"); if (instance.State.IsAway) { sb.Append(" - Away"); if (instance.State.IsBusy) sb.Append(", Busy"); } else if (instance.State.IsBusy) { sb.Append(" - Busy"); } if (instance.State.IsFollowing) { sb.Append(" - Following "); sb.Append(instance.State.FollowName); } } else { sb.Append("Logged Out"); } this.Text = sb.ToString(); sb = null; } private void InitializeStatusTimer() { statusTimer = new System.Timers.Timer(250); statusTimer.SynchronizingObject = this; statusTimer.Elapsed += new ElapsedEventHandler(statusTimer_Elapsed); } private void InitializeTabsConsole() { tabsConsole = new TabsConsole(instance); tabsConsole.Dock = DockStyle.Fill; toolStripContainer1.ContentPanel.Controls.Add(tabsConsole); } private void InitializeDebugLogForm() { debugLogForm = new frmDebugLog(instance); } private void tmnuAbout_Click(object sender, EventArgs e) { (new frmAbout()).ShowDialog(); } private void tmnuExit_Click(object sender, EventArgs e) { Close(); } private void frmMain_KeyUp(object sender, KeyEventArgs e) { if (e.Control && e.Alt && e.KeyCode == Keys.D) tbtnDebug.Visible = !tbtnDebug.Visible; } private void tbtnTeleport_Click(object sender, EventArgs e) { (new frmTeleport(instance)).ShowDialog(); } private void tmnuStatusAway_Click(object sender, EventArgs e) { instance.State.SetAway(tmnuStatusAway.Checked); } private void tmnuHelpReadme_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(Application.StartupPath + @"\Readme.txt"); } private void tmnuStatusBusy_Click(object sender, EventArgs e) { instance.State.SetBusy(tmnuStatusBusy.Checked); } private void tmnuControlFly_Click(object sender, EventArgs e) { instance.State.SetFlying(tmnuControlFly.Checked); } private void tmnuControlAlwaysRun_Click(object sender, EventArgs e) { instance.State.SetAlwaysRun(tmnuControlAlwaysRun.Checked); } private void tmnuDebugLog_Click(object sender, EventArgs e) { debugLogForm.Show(); } private void frmMain_Load(object sender, EventArgs e) { tabsConsole.SelectTab("Main"); } public TabsConsole TabConsole { get { return tabsConsole; } } private void tmnuNewWindow_Click(object sender, EventArgs e) { instance.Config.SaveCurrentConfig(); if (instance.IsFirstInstance) instance.OtherInstancesOpen = true; (new SleekInstance(false)).MainForm.Show(); } private void tmnuPrefs_Click(object sender, EventArgs e) { (new frmPreferences(instance)).ShowDialog(); } private void tmnuDonate_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(@"http://delta.slinked.net/donate/"); } private void tbtnObjects_Click(object sender, EventArgs e) { (new frmObjects(instance)).Show(); } } }
using System; using System.Diagnostics; namespace Lucene.Net.Search { /* * 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 ArrayUtil = Lucene.Net.Util.ArrayUtil; using ByteBlockPool = Lucene.Net.Util.ByteBlockPool; using BytesRef = Lucene.Net.Util.BytesRef; using BytesRefHash = Lucene.Net.Util.BytesRefHash; using IndexReader = Lucene.Net.Index.IndexReader; using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; using TermsEnum = Lucene.Net.Index.TermsEnum; using TermState = Lucene.Net.Index.TermState; /// <summary> /// A rewrite method that tries to pick the best /// constant-score rewrite method based on term and /// document counts from the query. If both the number of /// terms and documents is small enough, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE"/> is used. /// Otherwise, <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is /// used. /// </summary> // LUCENENET specific: made this class public. In Lucene there was a derived class // with the same name that was nested within MultiTermQuery, but in .NET it is // more intuitive if our classes are not nested. public class ConstantScoreAutoRewrite : TermCollectingRewrite<BooleanQuery> { /// <summary> /// Defaults derived from rough tests with a 20.0 million /// doc Wikipedia index. With more than 350 terms in the /// query, the filter method is fastest: /// </summary> public static int DEFAULT_TERM_COUNT_CUTOFF = 350; /// <summary> /// If the query will hit more than 1 in 1000 of the docs /// in the index (0.1%), the filter method is fastest: /// </summary> public static double DEFAULT_DOC_COUNT_PERCENT = 0.1; private int termCountCutoff = DEFAULT_TERM_COUNT_CUTOFF; private double docCountPercent = DEFAULT_DOC_COUNT_PERCENT; /// <summary> /// If the number of terms in this query is equal to or /// larger than this setting then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// </summary> public virtual int TermCountCutoff { set { termCountCutoff = value; } get { return termCountCutoff; } } /// <summary> /// If the number of documents to be visited in the /// postings exceeds this specified percentage of the /// <see cref="Index.IndexReader.MaxDoc"/> for the index, then /// <see cref="MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE"/> is used. /// Value may be 0.0 to 100.0. /// </summary> public virtual double DocCountPercent { set { docCountPercent = value; } get { return docCountPercent; } } protected override BooleanQuery GetTopLevelQuery() { return new BooleanQuery(true); } protected override void AddClause(BooleanQuery topLevel, Term term, int docFreq, float boost, TermContext states) //ignored { topLevel.Add(new TermQuery(term, states), Occur.SHOULD); } public override Query Rewrite(IndexReader reader, MultiTermQuery query) { // Get the enum and start visiting terms. If we // exhaust the enum before hitting either of the // cutoffs, we use ConstantBooleanQueryRewrite; else, // ConstantFilterRewrite: int docCountCutoff = (int)((docCountPercent / 100.0) * reader.MaxDoc); int termCountLimit = Math.Min(BooleanQuery.MaxClauseCount, termCountCutoff); CutOffTermCollector col = new CutOffTermCollector(docCountCutoff, termCountLimit); CollectTerms(reader, query, col); int size = col.pendingTerms.Count; if (col.hasCutOff) { return MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE.Rewrite(reader, query); } else { BooleanQuery bq = GetTopLevelQuery(); if (size > 0) { BytesRefHash pendingTerms = col.pendingTerms; int[] sort = pendingTerms.Sort(col.termsEnum.Comparer); for (int i = 0; i < size; i++) { int pos = sort[i]; // docFreq is not used for constant score here, we pass 1 // to explicitely set a fake value, so it's not calculated AddClause(bq, new Term(query.m_field, pendingTerms.Get(pos, new BytesRef())), 1, 1.0f, col.array.termState[pos]); } } // Strip scores Query result = new ConstantScoreQuery(bq); result.Boost = query.Boost; return result; } } internal sealed class CutOffTermCollector : TermCollector { private void InitializeInstanceFields() { pendingTerms = new BytesRefHash(new ByteBlockPool(new ByteBlockPool.DirectAllocator()), 16, array); } internal CutOffTermCollector(int docCountCutoff, int termCountLimit) { InitializeInstanceFields(); this.docCountCutoff = docCountCutoff; this.termCountLimit = termCountLimit; } public override void SetNextEnum(TermsEnum termsEnum) { this.termsEnum = termsEnum; } public override bool Collect(BytesRef bytes) { int pos = pendingTerms.Add(bytes); docVisitCount += termsEnum.DocFreq; if (pendingTerms.Count >= termCountLimit || docVisitCount >= docCountCutoff) { hasCutOff = true; return false; } TermState termState = termsEnum.GetTermState(); Debug.Assert(termState != null); if (pos < 0) { pos = (-pos) - 1; array.termState[pos].Register(termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } else { array.termState[pos] = new TermContext(m_topReaderContext, termState, m_readerContext.Ord, termsEnum.DocFreq, termsEnum.TotalTermFreq); } return true; } internal int docVisitCount = 0; internal bool hasCutOff = false; internal TermsEnum termsEnum; internal readonly int docCountCutoff, termCountLimit; internal readonly TermStateByteStart array = new TermStateByteStart(16); internal BytesRefHash pendingTerms; } public override int GetHashCode() { const int prime = 1279; return (int)(prime * termCountCutoff + BitConverter.DoubleToInt64Bits(docCountPercent)); } public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (this.GetType() != obj.GetType()) { return false; } ConstantScoreAutoRewrite other = (ConstantScoreAutoRewrite)obj; if (other.termCountCutoff != termCountCutoff) { return false; } if (BitConverter.DoubleToInt64Bits(other.docCountPercent) != BitConverter.DoubleToInt64Bits(docCountPercent)) { return false; } return true; } /// <summary> /// Special implementation of <see cref="BytesRefHash.BytesStartArray"/> that keeps parallel arrays for <see cref="TermContext"/> </summary> internal sealed class TermStateByteStart : BytesRefHash.DirectBytesStartArray { internal TermContext[] termState; public TermStateByteStart(int initSize) : base(initSize) { } public override int[] Init() { int[] ord = base.Init(); termState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Debug.Assert(termState.Length >= ord.Length); return ord; } public override int[] Grow() { int[] ord = base.Grow(); if (termState.Length < ord.Length) { TermContext[] tmpTermState = new TermContext[ArrayUtil.Oversize(ord.Length, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(termState, 0, tmpTermState, 0, termState.Length); termState = tmpTermState; } Debug.Assert(termState.Length >= ord.Length); return ord; } public override int[] Clear() { termState = null; return base.Clear(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraPrinting; using DevExpress.XtraPrinting.Preview; using DevExpress.XtraBars.Ribbon; using DevExpress.XtraBars.Ribbon.Gallery; using System.Drawing.Printing; using DevExpress.XtraEditors.Controls; using DevExpress.XtraBars; using DevExpress.XtraEditors; namespace DevExpress.MailClient.Win.Controls { public partial class PrintControl : RibbonApplicationUserControl { GalleryItem memoStyle, tableStyle; public PrintControl() { InitializeComponent(); splitContainer1.Panel1MinSize = layoutControlGroup1.MinSize.Width + 6; this.ddbOrientation.DropDownControl = CreateOrientationGallery(); this.ddbMargins.DropDownControl = CreateMarginsGallery(); this.ddbPaperSize.DropDownControl = CreatePageSizeGallery(); this.ddbCollate.DropDownControl = CreateCollateGallery(); this.ddbPrinter.DropDownControl = CreatePrintersGallery(); this.ddbDuplex.DropDownControl = CreateDuplexGallery(); this.ddbPrintStyle.DropDownControl = CreatePrintStyleGallery(); updatedZoom = true; zoomTextEdit.EditValue = 70; updatedZoom = false; } int GetZoomValue() { if(zoomTrackBarControl1.Value <= 40) return 10 + 90 * (zoomTrackBarControl1.Value - 0) / 40; else return 100 + 400 * (zoomTrackBarControl1.Value - 40) / 40; } int ZoomValueToValue(int zoomValue) { if(zoomValue < 100) return Math.Min(80, Math.Max(0, (zoomValue - 10) * 40 / 90)); return Math.Min(80, Math.Max(0, (zoomValue - 100) * 40 / 400 + 40)); } bool updatedZoom = false; private void zoomTrackBarControl1_EditValueChanged(object sender, EventArgs e) { if(updatedZoom) return; updatedZoom = true; try { zoomTextEdit.EditValue = GetZoomValue(); } finally { updatedZoom = false; } } public void InitPrintingSystem() { frmMain frm = BackstageView.Ribbon.FindForm() as frmMain; BarManager manager = frm == null || frm.Ribbon == null? null: frm.Ribbon.Manager; ((GalleryDropDown)this.ddbOrientation.DropDownControl).Manager = manager; ((GalleryDropDown)this.ddbMargins.DropDownControl).Manager = manager; ((GalleryDropDown)this.ddbPaperSize.DropDownControl).Manager = manager; ((GalleryDropDown)this.ddbCollate.DropDownControl).Manager = manager; ((GalleryDropDown)this.ddbPrinter.DropDownControl).Manager = manager; ((GalleryDropDown)this.ddbDuplex.DropDownControl).Manager = manager; ((GalleryDropDown)this.ddbPrintStyle.DropDownControl).Manager = manager; lciPrintStyle.Visibility = frm.CurrentRichEdit == null ? DevExpress.XtraLayout.Utils.LayoutVisibility.Never : DevExpress.XtraLayout.Utils.LayoutVisibility.Always; CreateDocument(); } void CreateDocument() { PrintingSystem ps = new PrintingSystem(); if(true.Equals(printControl1.Tag)) ps.StartPrint -= new PrintDocumentEventHandler(OnStartPrint); printControl1.PrintingSystem = ps; ps.StartPrint += new PrintDocumentEventHandler(OnStartPrint); printControl1.Tag = true; CreateLink(ps); this.pageButtonEdit.EditValue = 1; UpdatePagesInfo(); } void CreateLink(PrintingSystem ps) { frmMain frm = BackstageView.Ribbon.FindForm() as frmMain; bool showMemo = memoStyle.Checked && frm.CurrentRichEdit != null; if(showMemo) { Link link = new Link(ps); link.RtfReportHeader = frm.CurrentRichEdit.RtfText; link.PaperKind = GetPaperKind(); link.Landscape = GetLandscape(); link.Margins = GetMargins(); link.CreateDocument(); } else { PrintableComponentLink link = new PrintableComponentLink(ps); link.Component = frm.CurrentPrintableComponent; link.PaperKind = GetPaperKind(); link.Landscape = GetLandscape(); link.Margins = GetMargins(); link.CreateDocument(); } } void OnStartPrint(object sender, PrintDocumentEventArgs e) { e.PrintDocument.PrinterSettings.Copies = (short)this.copySpinEdit.Value; GetMargins(); e.PrintDocument.PrinterSettings.Collate = (bool)this.ddbCollate.Tag; e.PrintDocument.PrinterSettings.Duplex = ((bool)this.ddbDuplex.Tag)? Duplex.Horizontal: Duplex.Simplex; } private void zoomTextEdit_EditValueChanged(object sender, EventArgs e) { try { int zoomValue = Int32.Parse((string)zoomTextEdit.EditValue.ToString()); this.zoomTrackBarControl1.Value = ZoomValueToValue(zoomValue); this.printControl1.Zoom = 0.01f * (int)zoomValue; } catch(Exception) { } } GalleryDropDown CreateListBoxGallery() { GalleryDropDown res = new GalleryDropDown(); res.Gallery.FixedImageSize = false; res.Gallery.ShowItemText = true; res.Gallery.ColumnCount = 1; res.Gallery.CheckDrawMode = CheckDrawMode.OnlyImage; res.Gallery.ShowGroupCaption = false; res.Gallery.AutoSize = GallerySizeMode.Vertical; res.Gallery.SizeMode = GallerySizeMode.None; res.Gallery.ShowScrollBar = ShowScrollBar.Hide; res.Gallery.ItemCheckMode = ItemCheckMode.SingleRadio; res.Gallery.Appearance.ItemCaptionAppearance.Normal.Options.UseTextOptions = true; res.Gallery.Appearance.ItemCaptionAppearance.Normal.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; res.Gallery.Appearance.ItemCaptionAppearance.Normal.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; res.Gallery.Appearance.ItemCaptionAppearance.Hovered.Options.UseTextOptions = true; res.Gallery.Appearance.ItemCaptionAppearance.Hovered.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; res.Gallery.Appearance.ItemCaptionAppearance.Hovered.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; res.Gallery.Appearance.ItemCaptionAppearance.Pressed.Options.UseTextOptions = true; res.Gallery.Appearance.ItemCaptionAppearance.Pressed.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; res.Gallery.Appearance.ItemCaptionAppearance.Pressed.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; res.Gallery.ItemImageLocation = DevExpress.Utils.Locations.Left; res.Gallery.Appearance.ItemDescriptionAppearance.Normal.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; res.Gallery.Appearance.ItemDescriptionAppearance.Normal.Options.UseTextOptions = true; res.Gallery.Appearance.ItemDescriptionAppearance.Hovered.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; res.Gallery.Appearance.ItemDescriptionAppearance.Hovered.Options.UseTextOptions = true; res.Gallery.Appearance.ItemDescriptionAppearance.Pressed.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near; res.Gallery.Appearance.ItemDescriptionAppearance.Pressed.Options.UseTextOptions = true; res.Gallery.Groups.Add(new GalleryItemGroup()); res.Gallery.StretchItems = true; return res; } GalleryDropDown CreateOrientationGallery() { GalleryDropDown res = CreateListBoxGallery(); GalleryItem portraitItem = new GalleryItem(); portraitItem.Image = Properties.Resources.PageOrientationPortrait; portraitItem.Caption = Properties.Resources.PortraitOrientation; GalleryItem landscapeItem = new GalleryItem(); landscapeItem.Image = Properties.Resources.PageOrientationLandscape; landscapeItem.Caption = Properties.Resources.LandscapeOrientation; res.Gallery.Groups[0].Items.Add(portraitItem); res.Gallery.Groups[0].Items.Add(landscapeItem); res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnOrientationGalleryItemCheckedChanged); portraitItem.Checked = true; return res; } GalleryDropDown CreateMarginsGallery() { GalleryDropDown res = CreateListBoxGallery(); GalleryItem normal = new GalleryItem(); normal.Image = Properties.Resources.PageMarginsNormal; normal.Caption = Properties.Resources.MarginsNormal; normal.Description = Properties.Resources.MarginsNormalDescription; normal.Tag = new Padding(25, 25, 25, 25); GalleryItem narrow = new GalleryItem(); narrow.Image = Properties.Resources.PageMarginsNarrow; narrow.Caption = Properties.Resources.MarginsNarrow; narrow.Description = Properties.Resources.MarginsNarrowDescription; narrow.Tag = new Padding(12, 12, 12, 12); GalleryItem moderate = new GalleryItem(); moderate.Image = Properties.Resources.PageMarginsModerate; moderate.Caption = Properties.Resources.MarginsModerate; moderate.Description = Properties.Resources.MarginsModerateDescription; moderate.Tag = new Padding(19, 25, 19, 25); GalleryItem wide = new GalleryItem(); wide.Image = Properties.Resources.PageMarginsWide; wide.Caption = Properties.Resources.MarginsWide; wide.Description = Properties.Resources.MarginsWideDescription; wide.Tag = new Padding(50, 25, 50, 25); res.Gallery.Groups[0].Items.Add(normal); res.Gallery.Groups[0].Items.Add(narrow); res.Gallery.Groups[0].Items.Add(moderate); res.Gallery.Groups[0].Items.Add(wide); res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnMarginsGalleryItemCheckedChanged); normal.Checked = true; return res; } GalleryDropDown CreatePageSizeGallery() { GalleryDropDown res = CreateListBoxGallery(); GalleryItem letter = new GalleryItem(); letter.Image = Properties.Resources.PaperKind_Letter; letter.Caption = Properties.Resources.PaperKindLetter; letter.Description = Properties.Resources.PaperKindLetterDescription; letter.Tag = PaperKind.Letter; GalleryItem tabloid = new GalleryItem(); tabloid.Image = Properties.Resources.PaperKind_Tabloid; tabloid.Caption = Properties.Resources.PaperKindTabloid; tabloid.Description = Properties.Resources.PaperKindTabloidDescription; tabloid.Tag = PaperKind.Tabloid; GalleryItem legal = new GalleryItem(); legal.Image = Properties.Resources.PaperKind_Legal; legal.Caption = Properties.Resources.PaperKindLegal; legal.Description = Properties.Resources.PaperKindLegalDescription; legal.Tag = PaperKind.Legal; GalleryItem executive = new GalleryItem(); executive.Image = Properties.Resources.PaperKind_Executive; executive.Caption = Properties.Resources.PaperKindExecutive; executive.Description = Properties.Resources.PaperKindExecutiveDescription; executive.Tag = PaperKind.Executive; GalleryItem a3 = new GalleryItem(); a3.Image = Properties.Resources.PaperKind_A3; a3.Caption = Properties.Resources.PaperKindA3; a3.Description = Properties.Resources.PaperKindA3Description; a3.Tag = PaperKind.A3; GalleryItem a4 = new GalleryItem(); a4.Image = Properties.Resources.PaperKind_A4; a4.Caption = Properties.Resources.PaperKindA4; a4.Description = Properties.Resources.PaperKindA4Description; a4.Tag = PaperKind.A4; GalleryItem a5 = new GalleryItem(); a5.Image = Properties.Resources.PaperKind_A5; a5.Caption = Properties.Resources.PaperKindA5; a5.Description = Properties.Resources.PaperKindA5Description; a5.Tag = PaperKind.A5; GalleryItem a6 = new GalleryItem(); a6.Image = Properties.Resources.PaperKind_A6; a6.Caption = Properties.Resources.PaperKindA6; a6.Description = Properties.Resources.PaperKindA6Description; a6.Tag = PaperKind.A6; res.Gallery.Groups[0].Items.Add(letter); res.Gallery.Groups[0].Items.Add(tabloid); res.Gallery.Groups[0].Items.Add(legal); res.Gallery.Groups[0].Items.Add(executive); res.Gallery.Groups[0].Items.Add(a3); res.Gallery.Groups[0].Items.Add(a4); res.Gallery.Groups[0].Items.Add(a5); res.Gallery.Groups[0].Items.Add(a6); res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnPaperSizeGalleryItemCheckedChanged); a4.Checked = true; return res; } GalleryDropDown CreateCollateGallery() { GalleryDropDown res = CreateListBoxGallery(); GalleryItem collated = new GalleryItem(); collated.Image = Properties.Resources.MultiplePagesLarge; collated.Caption = Properties.Resources.Collated; collated.Description = Properties.Resources.CollatedDescription; collated.Tag = true; GalleryItem uncollated = new GalleryItem(); uncollated.Image = Properties.Resources.MultiplePagesLarge; uncollated.Caption = Properties.Resources.Uncollated; uncollated.Description = Properties.Resources.UncollatedDescription; uncollated.Tag = false; res.Gallery.Groups[0].Items.Add(collated); res.Gallery.Groups[0].Items.Add(uncollated); res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnCollateGalleryItemCheckedChanged); collated.Checked = true; return res; } GalleryDropDown CreateDuplexGallery() { GalleryDropDown res = CreateListBoxGallery(); GalleryItem oneSided = new GalleryItem(); oneSided.Image = Properties.Resources.MultiplePagesLarge; oneSided.Caption = Properties.Resources.OneSide; oneSided.Description = Properties.Resources.OneSideDescription; oneSided.Tag = false; GalleryItem twoSided = new GalleryItem(); twoSided.Image = Properties.Resources.MultiplePagesLarge; twoSided.Caption = Properties.Resources.TwoSide; twoSided.Description = Properties.Resources.TwoSideDescription; twoSided.Tag = false; res.Gallery.Groups[0].Items.Add(oneSided); res.Gallery.Groups[0].Items.Add(twoSided); res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnDuplexGalleryItemCheckedChanged); oneSided.Checked = true; return res; } GalleryDropDown CreatePrintStyleGallery() { GalleryDropDown res = CreateListBoxGallery(); res.Gallery.ItemCheckMode = ItemCheckMode.SingleRadio; memoStyle = new GalleryItem(); memoStyle.Image = Properties.Resources.MemoStyle; memoStyle.Caption = Properties.Resources.MemoStyleString; tableStyle = new GalleryItem(); tableStyle.Image = Properties.Resources.TableStyle; tableStyle.Caption = Properties.Resources.TableStyleString; res.Gallery.Groups[0].Items.Add(memoStyle); res.Gallery.Groups[0].Items.Add(tableStyle); res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnPrintStyleGalleryItemCheckedChanged); memoStyle.Checked = true; return res; } void OnPrintStyleGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { this.ddbPrintStyle.Text = e.Item.Caption; this.ddbPrintStyle.Image = e.Item.Image; if(printControl1.PrintingSystem != null) CreateDocument(); } void OnDuplexGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { this.ddbDuplex.Text = e.Item.Caption; this.ddbDuplex.Image = e.Item.Image; this.ddbDuplex.Tag = e.Item.Tag; } GalleryDropDown CreatePrintersGallery() { GalleryDropDown res = CreateListBoxGallery(); PrinterSettings ps = new PrinterSettings(); GalleryItem defaultPrinter = null; try { foreach(string str in PrinterSettings.InstalledPrinters) { GalleryItem item = new GalleryItem(); item.Image = Properties.Resources.PrintDirectLarge; item.Caption = str; res.Gallery.Groups[0].Items.Add(item); ps.PrinterName = str; if(ps.IsDefaultPrinter) defaultPrinter = item; } } catch { } res.Gallery.ItemCheckedChanged += new GalleryItemEventHandler(OnPrinterGalleryItemCheckedChanged); if(defaultPrinter != null) defaultPrinter.Checked = true; return res; } void OnMarginsGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { this.ddbMargins.Image = e.Item.Image; this.ddbMargins.Text = e.Item.Caption; this.ddbMargins.Tag = e.Item.Tag; if(this.printControl1.PrintingSystem != null) { Margins margins = GetMargins(); this.printControl1.PrintingSystem.PageSettings.LeftMargin = margins.Left; this.printControl1.PrintingSystem.PageSettings.RightMargin = margins.Right; this.printControl1.PrintingSystem.PageSettings.TopMargin = margins.Top; this.printControl1.PrintingSystem.PageSettings.BottomMargin = margins.Bottom; } UpdatePageButtonsEnabledState(); } Margins GetMargins() { Padding p = (Padding)this.ddbMargins.Tag; return new Margins((int)(p.Left * 3.9), (int)(p.Right * 3.9), (int)(p.Top * 3.9), (int)(p.Bottom * 3.9)); } void OnPrinterGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { this.ddbPrinter.Text = e.Item.Caption; this.ddbPrinter.Image = e.Item.Image; } void OnCollateGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { this.ddbCollate.Image = e.Item.Image; this.ddbCollate.Text = e.Item.Caption; this.ddbCollate.Tag = e.Item.Tag; } void OnPaperSizeGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { this.ddbPaperSize.Image = e.Item.Image; this.ddbPaperSize.Text = e.Item.Caption; this.ddbPaperSize.Tag = e.Item.Tag; if(this.printControl1.PrintingSystem != null) this.printControl1.PrintingSystem.PageSettings.PaperKind = GetPaperKind(); UpdatePageButtonsEnabledState(); } PaperKind GetPaperKind() { return (PaperKind)this.ddbPaperSize.Tag; } void OnOrientationGalleryItemCheckedChanged(object sender, GalleryItemEventArgs e) { ddbOrientation.Text = e.Item.Caption; ddbOrientation.Image = e.Item.Image; if(printControl1.PrintingSystem != null) this.printControl1.PrintingSystem.PageSettings.Landscape = GetLandscape(); UpdatePageButtonsEnabledState(); } bool GetLandscape() { if(ddbOrientation.DropDownControl != null) return ((GalleryDropDown)ddbOrientation.DropDownControl).Gallery.Groups[0].Items[1].Checked; return false; } private void printButton_Click(object sender, EventArgs e) { ((PrintingSystem)this.printControl1.PrintingSystem).Print(this.ddbPrinter.Text); } private void pageButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { int pageIndex = (int)this.pageButtonEdit.EditValue; if(e.Button.Kind == ButtonPredefines.Left) { if(pageIndex > 1) pageIndex--; } else if(e.Button.Kind == ButtonPredefines.Right) { if(pageIndex < this.printControl1.PrintingSystem.Pages.Count) pageIndex ++; } this.pageButtonEdit.EditValue = pageIndex; } private void pageButtonEdit_EditValueChanging(object sender, ChangingEventArgs e) { try { int pageIndex = Int32.Parse(e.NewValue.ToString()); if(pageIndex < 1) pageIndex = 1; else if(pageIndex > this.printControl1.PrintingSystem.Pages.Count) pageIndex = this.printControl1.PrintingSystem.Pages.Count; e.NewValue = pageIndex; } catch(Exception) { e.NewValue = 1; } } void UpdatePagesInfo() { if(printControl1.PrintingSystem != null) { this.pageButtonEdit.Properties.DisplayFormat.FormatString = Properties.Resources.PageInfo + printControl1.PrintingSystem.Pages.Count; this.printButton.Enabled = printControl1.PrintingSystem.Pages.Count > 0; this.pageButtonEdit.Enabled = printControl1.PrintingSystem.Pages.Count > 0; } } void UpdatePageButtonsEnabledState(int pageIndex) { if(printControl1.PrintingSystem == null) return; this.pageButtonEdit.Properties.Buttons[0].Enabled = pageIndex != 1; this.pageButtonEdit.Properties.Buttons[1].Enabled = pageIndex != printControl1.PrintingSystem.Pages.Count; UpdatePagesInfo(); } void UpdatePageButtonsEnabledState() { UpdatePageButtonsEnabledState(this.printControl1.SelectedPageIndex + 1); } private void pageButtonEdit_EditValueChanged(object sender, EventArgs e) { int pageIndex = Convert.ToInt32(this.pageButtonEdit.EditValue); this.printControl1.SelectedPageIndex = pageIndex - 1; UpdatePageButtonsEnabledState(pageIndex); } private void printControl1_SelectedPageChanged(object sender, EventArgs e) { this.pageButtonEdit.EditValue = this.printControl1.SelectedPageIndex + 1; } } }
// 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 gax = Google.Api.Gax; using gcdcv = Google.Cloud.Dialogflow.Cx.V3; using sys = System; namespace Google.Cloud.Dialogflow.Cx.V3 { /// <summary>Resource name for the <c>TestCase</c> resource.</summary> public sealed partial class TestCaseName : gax::IResourceName, sys::IEquatable<TestCaseName> { /// <summary>The possible contents of <see cref="TestCaseName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>. /// </summary> ProjectLocationAgentTestCase = 1, } private static gax::PathTemplate s_projectLocationAgentTestCase = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}"); /// <summary>Creates a <see cref="TestCaseName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TestCaseName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static TestCaseName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TestCaseName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TestCaseName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TestCaseName"/> constructed from the provided ids.</returns> public static TestCaseName FromProjectLocationAgentTestCase(string projectId, string locationId, string agentId, string testCaseId) => new TestCaseName(ResourceNameType.ProjectLocationAgentTestCase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TestCaseName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TestCaseName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>. /// </returns> public static string Format(string projectId, string locationId, string agentId, string testCaseId) => FormatProjectLocationAgentTestCase(projectId, locationId, agentId, testCaseId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TestCaseName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TestCaseName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c>. /// </returns> public static string FormatProjectLocationAgentTestCase(string projectId, string locationId, string agentId, string testCaseId) => s_projectLocationAgentTestCase.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId))); /// <summary>Parses the given resource name string into a new <see cref="TestCaseName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TestCaseName"/> if successful.</returns> public static TestCaseName Parse(string testCaseName) => Parse(testCaseName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TestCaseName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TestCaseName"/> if successful.</returns> public static TestCaseName Parse(string testCaseName, bool allowUnparsed) => TryParse(testCaseName, allowUnparsed, out TestCaseName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TestCaseName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TestCaseName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string testCaseName, out TestCaseName result) => TryParse(testCaseName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TestCaseName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="testCaseName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TestCaseName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string testCaseName, bool allowUnparsed, out TestCaseName result) { gax::GaxPreconditions.CheckNotNull(testCaseName, nameof(testCaseName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentTestCase.TryParseName(testCaseName, out resourceName)) { result = FromProjectLocationAgentTestCase(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(testCaseName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TestCaseName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null, string testCaseId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; LocationId = locationId; ProjectId = projectId; TestCaseId = testCaseId; } /// <summary> /// Constructs a new instance of a <see cref="TestCaseName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> public TestCaseName(string projectId, string locationId, string agentId, string testCaseId) : this(ResourceNameType.ProjectLocationAgentTestCase, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>TestCase</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TestCaseId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAgentTestCase: return s_projectLocationAgentTestCase.Expand(ProjectId, LocationId, AgentId, TestCaseId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TestCaseName); /// <inheritdoc/> public bool Equals(TestCaseName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TestCaseName a, TestCaseName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TestCaseName a, TestCaseName b) => !(a == b); } /// <summary>Resource name for the <c>TestCaseResult</c> resource.</summary> public sealed partial class TestCaseResultName : gax::IResourceName, sys::IEquatable<TestCaseResultName> { /// <summary>The possible contents of <see cref="TestCaseResultName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>. /// </summary> ProjectLocationAgentTestCaseResult = 1, } private static gax::PathTemplate s_projectLocationAgentTestCaseResult = new gax::PathTemplate("projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}"); /// <summary>Creates a <see cref="TestCaseResultName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TestCaseResultName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TestCaseResultName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TestCaseResultName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TestCaseResultName"/> with the pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TestCaseResultName"/> constructed from the provided ids.</returns> public static TestCaseResultName FromProjectLocationAgentTestCaseResult(string projectId, string locationId, string agentId, string testCaseId, string resultId) => new TestCaseResultName(ResourceNameType.ProjectLocationAgentTestCaseResult, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)), resultId: gax::GaxPreconditions.CheckNotNullOrEmpty(resultId, nameof(resultId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TestCaseResultName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TestCaseResultName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>. /// </returns> public static string Format(string projectId, string locationId, string agentId, string testCaseId, string resultId) => FormatProjectLocationAgentTestCaseResult(projectId, locationId, agentId, testCaseId, resultId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TestCaseResultName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TestCaseResultName"/> with pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c>. /// </returns> public static string FormatProjectLocationAgentTestCaseResult(string projectId, string locationId, string agentId, string testCaseId, string resultId) => s_projectLocationAgentTestCaseResult.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)), gax::GaxPreconditions.CheckNotNullOrEmpty(resultId, nameof(resultId))); /// <summary> /// Parses the given resource name string into a new <see cref="TestCaseResultName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TestCaseResultName"/> if successful.</returns> public static TestCaseResultName Parse(string testCaseResultName) => Parse(testCaseResultName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TestCaseResultName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TestCaseResultName"/> if successful.</returns> public static TestCaseResultName Parse(string testCaseResultName, bool allowUnparsed) => TryParse(testCaseResultName, allowUnparsed, out TestCaseResultName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TestCaseResultName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TestCaseResultName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string testCaseResultName, out TestCaseResultName result) => TryParse(testCaseResultName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TestCaseResultName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="testCaseResultName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TestCaseResultName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string testCaseResultName, bool allowUnparsed, out TestCaseResultName result) { gax::GaxPreconditions.CheckNotNull(testCaseResultName, nameof(testCaseResultName)); gax::TemplatedResourceName resourceName; if (s_projectLocationAgentTestCaseResult.TryParseName(testCaseResultName, out resourceName)) { result = FromProjectLocationAgentTestCaseResult(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(testCaseResultName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TestCaseResultName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string agentId = null, string locationId = null, string projectId = null, string resultId = null, string testCaseId = null) { Type = type; UnparsedResource = unparsedResourceName; AgentId = agentId; LocationId = locationId; ProjectId = projectId; ResultId = resultId; TestCaseId = testCaseId; } /// <summary> /// Constructs a new instance of a <see cref="TestCaseResultName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/agents/{agent}/testCases/{test_case}/results/{result}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="agentId">The <c>Agent</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="testCaseId">The <c>TestCase</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="resultId">The <c>Result</c> ID. Must not be <c>null</c> or empty.</param> public TestCaseResultName(string projectId, string locationId, string agentId, string testCaseId, string resultId) : this(ResourceNameType.ProjectLocationAgentTestCaseResult, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), agentId: gax::GaxPreconditions.CheckNotNullOrEmpty(agentId, nameof(agentId)), testCaseId: gax::GaxPreconditions.CheckNotNullOrEmpty(testCaseId, nameof(testCaseId)), resultId: gax::GaxPreconditions.CheckNotNullOrEmpty(resultId, nameof(resultId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Agent</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AgentId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Result</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ResultId { get; } /// <summary> /// The <c>TestCase</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TestCaseId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationAgentTestCaseResult: return s_projectLocationAgentTestCaseResult.Expand(ProjectId, LocationId, AgentId, TestCaseId, ResultId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TestCaseResultName); /// <inheritdoc/> public bool Equals(TestCaseResultName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TestCaseResultName a, TestCaseResultName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TestCaseResultName a, TestCaseResultName b) => !(a == b); } public partial class TestCase { /// <summary> /// <see cref="gcdcv::TestCaseName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TestCaseName TestCaseName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class TestCaseResult { /// <summary> /// <see cref="gcdcv::TestCaseResultName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TestCaseResultName TestCaseResultName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseResultName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property. /// </summary> public EnvironmentName EnvironmentAsEnvironmentName { get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true); set => Environment = value?.ToString() ?? ""; } } public partial class TestConfig { /// <summary><see cref="FlowName"/>-typed view over the <see cref="Flow"/> resource name property.</summary> public FlowName FlowAsFlowName { get => string.IsNullOrEmpty(Flow) ? null : FlowName.Parse(Flow, allowUnparsed: true); set => Flow = value?.ToString() ?? ""; } } public partial class CalculateCoverageRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Agent"/> resource name property.</summary> public AgentName AgentAsAgentName { get => string.IsNullOrEmpty(Agent) ? null : AgentName.Parse(Agent, allowUnparsed: true); set => Agent = value?.ToString() ?? ""; } } public partial class CalculateCoverageResponse { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Agent"/> resource name property.</summary> public AgentName AgentAsAgentName { get => string.IsNullOrEmpty(Agent) ? null : AgentName.Parse(Agent, allowUnparsed: true); set => Agent = value?.ToString() ?? ""; } } public partial class ListTestCasesRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class BatchDeleteTestCasesRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="TestCaseName"/>-typed view over the <see cref="Names"/> resource name property. /// </summary> public gax::ResourceNameList<TestCaseName> TestCaseNames { get => new gax::ResourceNameList<TestCaseName>(Names, s => string.IsNullOrEmpty(s) ? null : TestCaseName.Parse(s, allowUnparsed: true)); } } public partial class CreateTestCaseRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetTestCaseRequest { /// <summary> /// <see cref="gcdcv::TestCaseName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TestCaseName TestCaseName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class RunTestCaseRequest { /// <summary> /// <see cref="gcdcv::TestCaseName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TestCaseName TestCaseName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property. /// </summary> public EnvironmentName EnvironmentAsEnvironmentName { get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true); set => Environment = value?.ToString() ?? ""; } } public partial class BatchRunTestCasesRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } /// <summary> /// <see cref="EnvironmentName"/>-typed view over the <see cref="Environment"/> resource name property. /// </summary> public EnvironmentName EnvironmentAsEnvironmentName { get => string.IsNullOrEmpty(Environment) ? null : EnvironmentName.Parse(Environment, allowUnparsed: true); set => Environment = value?.ToString() ?? ""; } /// <summary> /// <see cref="TestCaseName"/>-typed view over the <see cref="TestCases"/> resource name property. /// </summary> public gax::ResourceNameList<TestCaseName> TestCasesAsTestCaseNames { get => new gax::ResourceNameList<TestCaseName>(TestCases, s => string.IsNullOrEmpty(s) ? null : TestCaseName.Parse(s, allowUnparsed: true)); } } public partial class TestError { /// <summary> /// <see cref="TestCaseName"/>-typed view over the <see cref="TestCase"/> resource name property. /// </summary> public TestCaseName TestCaseAsTestCaseName { get => string.IsNullOrEmpty(TestCase) ? null : TestCaseName.Parse(TestCase, allowUnparsed: true); set => TestCase = value?.ToString() ?? ""; } } public partial class ImportTestCasesRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ImportTestCasesResponse { /// <summary> /// <see cref="TestCaseName"/>-typed view over the <see cref="Names"/> resource name property. /// </summary> public gax::ResourceNameList<TestCaseName> TestCaseNames { get => new gax::ResourceNameList<TestCaseName>(Names, s => string.IsNullOrEmpty(s) ? null : TestCaseName.Parse(s, allowUnparsed: true)); } } public partial class ExportTestCasesRequest { /// <summary><see cref="AgentName"/>-typed view over the <see cref="Parent"/> resource name property.</summary> public AgentName ParentAsAgentName { get => string.IsNullOrEmpty(Parent) ? null : AgentName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class ListTestCaseResultsRequest { /// <summary> /// <see cref="TestCaseName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public TestCaseName ParentAsTestCaseName { get => string.IsNullOrEmpty(Parent) ? null : TestCaseName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetTestCaseResultRequest { /// <summary> /// <see cref="gcdcv::TestCaseResultName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdcv::TestCaseResultName TestCaseResultName { get => string.IsNullOrEmpty(Name) ? null : gcdcv::TestCaseResultName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }