context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.ComponentModel.Design; using System.IO; using System.Linq; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Notification; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.VisualStudio.CodeAnalysis; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.LanguageServices.SolutionExplorer; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Roslyn.Utilities; using VSLangProj140; namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer { [Export] internal class AnalyzersCommandHandler : IAnalyzersCommandHandler, IVsUpdateSolutionEvents { private readonly AnalyzerItemsTracker _tracker; private readonly AnalyzerReferenceManager _analyzerReferenceManager; private readonly IServiceProvider _serviceProvider; private ContextMenuController _analyzerFolderContextMenuController; private ContextMenuController _analyzerContextMenuController; private ContextMenuController _diagnosticContextMenuController; // Analyzers folder context menu items private MenuCommand _addMenuItem; private MenuCommand _openRuleSetMenuItem; // Analyzer context menu items private MenuCommand _removeMenuItem; // Diagnostic context menu items private MenuCommand _setSeverityDefaultMenuItem; private MenuCommand _setSeverityErrorMenuItem; private MenuCommand _setSeverityWarningMenuItem; private MenuCommand _setSeverityInfoMenuItem; private MenuCommand _setSeverityHiddenMenuItem; private MenuCommand _setSeverityNoneMenuItem; private MenuCommand _openHelpLinkMenuItem; // Other menu items private MenuCommand _projectAddMenuItem; private MenuCommand _projectContextAddMenuItem; private MenuCommand _referencesContextAddMenuItem; private MenuCommand _setActiveRuleSetMenuItem; private Workspace _workspace; private bool _allowProjectSystemOperations = true; [ImportingConstructor] public AnalyzersCommandHandler( AnalyzerItemsTracker tracker, AnalyzerReferenceManager analyzerReferenceManager, [Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider) { _tracker = tracker; _analyzerReferenceManager = analyzerReferenceManager; _serviceProvider = serviceProvider; } /// <summary> /// Hook up the context menu handlers. /// </summary> public void Initialize(IMenuCommandService menuCommandService) { if (menuCommandService != null) { // Analyzers folder context menu items _addMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.AddAnalyzer, AddAnalyzerHandler); _openRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenRuleSet, OpenRuleSetHandler); // Analyzer context menu items _removeMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.RemoveAnalyzer, RemoveAnalyzerHandler); // Diagnostic context menu items _setSeverityDefaultMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityDefault, SetSeverityHandler); _setSeverityErrorMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityError, SetSeverityHandler); _setSeverityWarningMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityWarning, SetSeverityHandler); _setSeverityInfoMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityInfo, SetSeverityHandler); _setSeverityHiddenMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityHidden, SetSeverityHandler); _setSeverityNoneMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetSeverityNone, SetSeverityHandler); _openHelpLinkMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.OpenDiagnosticHelpLink, OpenDiagnosticHelpLinkHandler); // Other menu items _projectAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectAddAnalyzer, AddAnalyzerHandler); _projectContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ProjectContextAddAnalyzer, AddAnalyzerHandler); _referencesContextAddMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.ReferencesContextAddAnalyzer, AddAnalyzerHandler); _setActiveRuleSetMenuItem = AddCommandHandler(menuCommandService, ID.RoslynCommands.SetActiveRuleSet, SetActiveRuleSetHandler); UpdateOtherMenuItemsVisibility(); if (_tracker != null) { _tracker.SelectedHierarchyItemChanged += SelectedHierarchyItemChangedHandler; } var buildManager = (IVsSolutionBuildManager)_serviceProvider.GetService(typeof(SVsSolutionBuildManager)); uint cookie; buildManager.AdviseUpdateSolutionEvents(this, out cookie); } } public IContextMenuController AnalyzerFolderContextMenuController { get { if (_analyzerFolderContextMenuController == null) { _analyzerFolderContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerFolderContextMenu, ShouldShowAnalyzerFolderContextMenu, UpdateAnalyzerFolderContextMenu); } return _analyzerFolderContextMenuController; } } private bool ShouldShowAnalyzerFolderContextMenu(IEnumerable<object> items) { return items.Count() == 1; } private void UpdateAnalyzerFolderContextMenu() { _addMenuItem.Visible = SelectedProjectSupportsAnalyzers(); _addMenuItem.Enabled = _allowProjectSystemOperations; } public IContextMenuController AnalyzerContextMenuController { get { if (_analyzerContextMenuController == null) { _analyzerContextMenuController = new ContextMenuController( ID.RoslynCommands.AnalyzerContextMenu, ShouldShowAnalyzerContextMenu, UpdateAnalyzerContextMenu); } return _analyzerContextMenuController; } } private bool ShouldShowAnalyzerContextMenu(IEnumerable<object> items) { return items.All(item => item is AnalyzerItem); } private void UpdateAnalyzerContextMenu() { _removeMenuItem.Enabled = _allowProjectSystemOperations; } public IContextMenuController DiagnosticContextMenuController { get { if (_diagnosticContextMenuController == null) { _diagnosticContextMenuController = new ContextMenuController( ID.RoslynCommands.DiagnosticContextMenu, ShouldShowDiagnosticContextMenu, UpdateDiagnosticContextMenu); } return _diagnosticContextMenuController; } } private bool ShouldShowDiagnosticContextMenu(IEnumerable<object> items) { return items.All(item => item is DiagnosticItem); } private void UpdateDiagnosticContextMenu() { UpdateSeverityMenuItemsChecked(); UpdateSeverityMenuItemsEnabled(); UpdateOpenHelpLinkMenuItemVisibility(); } private MenuCommand AddCommandHandler(IMenuCommandService menuCommandService, int roslynCommand, EventHandler handler) { var commandID = new CommandID(Guids.RoslynGroupId, roslynCommand); var menuCommand = new MenuCommand(handler, commandID); menuCommandService.AddCommand(menuCommand); return menuCommand; } private void SelectedHierarchyItemChangedHandler(object sender, EventArgs e) { UpdateOtherMenuItemsVisibility(); } private void UpdateOtherMenuItemsVisibility() { bool selectedProjectSupportsAnalyzers = SelectedProjectSupportsAnalyzers(); _projectAddMenuItem.Visible = selectedProjectSupportsAnalyzers; _projectContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedItemId == VSConstants.VSITEMID_ROOT; _referencesContextAddMenuItem.Visible = selectedProjectSupportsAnalyzers; string itemName; _setActiveRuleSetMenuItem.Visible = selectedProjectSupportsAnalyzers && _tracker.SelectedHierarchy.TryGetItemName(_tracker.SelectedItemId, out itemName) && Path.GetExtension(itemName).Equals(".ruleset", StringComparison.OrdinalIgnoreCase); } private void UpdateOtherMenuItemsEnabled() { _projectAddMenuItem.Enabled = _allowProjectSystemOperations; _projectContextAddMenuItem.Enabled = _allowProjectSystemOperations; _referencesContextAddMenuItem.Enabled = _allowProjectSystemOperations; _removeMenuItem.Enabled = _allowProjectSystemOperations; } private void UpdateOpenHelpLinkMenuItemVisibility() { _openHelpLinkMenuItem.Visible = _tracker.SelectedDiagnosticItems.Length == 1 && _tracker.SelectedDiagnosticItems[0].GetHelpLink() != null; } private void UpdateSeverityMenuItemsChecked() { _setSeverityDefaultMenuItem.Checked = false; _setSeverityErrorMenuItem.Checked = false; _setSeverityWarningMenuItem.Checked = false; _setSeverityInfoMenuItem.Checked = false; _setSeverityHiddenMenuItem.Checked = false; _setSeverityNoneMenuItem.Checked = false; var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } HashSet<ReportDiagnostic> selectedItemSeverities = new HashSet<ReportDiagnostic>(); var groups = _tracker.SelectedDiagnosticItems.GroupBy(item => item.AnalyzerItem.AnalyzersFolder.ProjectId); foreach (var group in groups) { var project = (AbstractProject)workspace.GetHostProject(group.Key); IRuleSetFile ruleSet = project.RuleSetFile; if (ruleSet != null) { var specificOptions = ruleSet.GetSpecificDiagnosticOptions(); foreach (var diagnosticItem in group) { ReportDiagnostic ruleSetSeverity; if (specificOptions.TryGetValue(diagnosticItem.Descriptor.Id, out ruleSetSeverity)) { selectedItemSeverities.Add(ruleSetSeverity); } else { // The rule has no setting. selectedItemSeverities.Add(ReportDiagnostic.Default); } } } } if (selectedItemSeverities.Count != 1) { return; } switch (selectedItemSeverities.Single()) { case ReportDiagnostic.Default: _setSeverityDefaultMenuItem.Checked = true; break; case ReportDiagnostic.Error: _setSeverityErrorMenuItem.Checked = true; break; case ReportDiagnostic.Warn: _setSeverityWarningMenuItem.Checked = true; break; case ReportDiagnostic.Info: _setSeverityInfoMenuItem.Checked = true; break; case ReportDiagnostic.Hidden: _setSeverityHiddenMenuItem.Checked = true; break; case ReportDiagnostic.Suppress: _setSeverityNoneMenuItem.Checked = true; break; default: break; } } private bool AnyDiagnosticsWithSeverity(ReportDiagnostic severity) { return _tracker.SelectedDiagnosticItems.Any(item => item.EffectiveSeverity == severity); } private void UpdateSeverityMenuItemsEnabled() { bool configurable = !_tracker.SelectedDiagnosticItems.Any(item => item.Descriptor.CustomTags.Contains(WellKnownDiagnosticTags.NotConfigurable)); _setSeverityDefaultMenuItem.Enabled = configurable; _setSeverityErrorMenuItem.Enabled = configurable; _setSeverityWarningMenuItem.Enabled = configurable; _setSeverityInfoMenuItem.Enabled = configurable; _setSeverityHiddenMenuItem.Enabled = configurable; _setSeverityNoneMenuItem.Enabled = configurable; } private bool SelectedProjectSupportsAnalyzers() { EnvDTE.Project project; return _tracker != null && _tracker.SelectedHierarchy != null && _tracker.SelectedHierarchy.TryGetProject(out project) && project.Object is VSProject3; } /// <summary> /// Handler for "Add Analyzer..." context menu on Analyzers folder node. /// </summary> internal void AddAnalyzerHandler(object sender, EventArgs args) { if (_analyzerReferenceManager != null) { _analyzerReferenceManager.ShowDialog(); } } /// <summary> /// Handler for "Remove" context menu on individual Analyzer items. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> internal void RemoveAnalyzerHandler(object sender, EventArgs args) { foreach (var item in _tracker.SelectedAnalyzerItems) { item.Remove(); } } internal void OpenRuleSetHandler(object sender, EventArgs args) { if (_tracker.SelectedFolder != null && _serviceProvider != null) { var workspace = _tracker.SelectedFolder.Workspace as VisualStudioWorkspaceImpl; var projectId = _tracker.SelectedFolder.ProjectId; if (workspace != null) { var project = (AbstractProject)workspace.GetHostProject(projectId); if (project == null) { SendUnableToOpenRuleSetNotification(workspace, string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CouldNotFindProject, projectId)); return; } if (project.RuleSetFile == null) { SendUnableToOpenRuleSetNotification(workspace, SolutionExplorerShim.AnalyzersCommandHandler_NoRuleSetFile); return; } try { EnvDTE.DTE dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(project.RuleSetFile.FilePath); } catch (Exception e) { SendUnableToOpenRuleSetNotification(workspace, e.Message); } } } } private void SetSeverityHandler(object sender, EventArgs args) { var selectedItem = (MenuCommand)sender; ReportDiagnostic? selectedAction = MapSelectedItemToReportDiagnostic(selectedItem); if (!selectedAction.HasValue) { return; } var workspace = TryGetWorkspace() as VisualStudioWorkspaceImpl; if (workspace == null) { return; } foreach (var selectedDiagnostic in _tracker.SelectedDiagnosticItems) { var projectId = selectedDiagnostic.AnalyzerItem.AnalyzersFolder.ProjectId; var project = (AbstractProject)workspace.GetHostProject(projectId); if (project == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CouldNotFindProject, projectId)); continue; } var pathToRuleSet = project.RuleSetFile?.FilePath; if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, SolutionExplorerShim.AnalyzersCommandHandler_NoRuleSetFile); continue; } try { EnvDTE.Project envDteProject; project.Hierarchy.TryGetProject(out envDteProject); if (SdkUiUtilities.IsBuiltInRuleSet(pathToRuleSet, _serviceProvider)) { pathToRuleSet = CreateCopyOfRuleSetForProject(pathToRuleSet, envDteProject); if (pathToRuleSet == null) { SendUnableToUpdateRuleSetNotification(workspace, string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CouldNotCreateRuleSetFile, envDteProject.Name)); continue; } var fileInfo = new FileInfo(pathToRuleSet); fileInfo.IsReadOnly = false; } var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var waitIndicator = componentModel.GetService<IWaitIndicator>(); waitIndicator.Wait( title: SolutionExplorerShim.AnalyzersCommandHandler_RuleSet, message: string.Format(SolutionExplorerShim.AnalyzersCommandHandler_CheckingOutRuleSet, Path.GetFileName(pathToRuleSet)), allowCancel: false, action: c => { if (envDteProject.DTE.SourceControl.IsItemUnderSCC(pathToRuleSet)) { envDteProject.DTE.SourceControl.CheckOutItem(pathToRuleSet); } }); selectedDiagnostic.SetSeverity(selectedAction.Value, pathToRuleSet); } catch (Exception e) { SendUnableToUpdateRuleSetNotification(workspace, e.Message); } } } private void OpenDiagnosticHelpLinkHandler(object sender, EventArgs e) { if (_tracker.SelectedDiagnosticItems.Length != 1) { return; } var uri = _tracker.SelectedDiagnosticItems[0].GetHelpLink(); if (uri != null) { BrowserHelper.StartBrowser(uri); } } private void SetActiveRuleSetHandler(object sender, EventArgs e) { EnvDTE.Project project; string ruleSetFileFullPath; if (_tracker.SelectedHierarchy.TryGetProject(out project) && _tracker.SelectedHierarchy.TryGetCanonicalName(_tracker.SelectedItemId, out ruleSetFileFullPath)) { string projectDirectoryFullPath = Path.GetDirectoryName(project.FullName); string ruleSetFileRelativePath = FilePathUtilities.GetRelativePath(projectDirectoryFullPath, ruleSetFileFullPath); UpdateProjectConfigurationsToUseRuleSetFile(project, ruleSetFileRelativePath); } } private string CreateCopyOfRuleSetForProject(string pathToRuleSet, EnvDTE.Project envDteProject) { string fileName = GetNewRuleSetFileNameForProject(envDteProject); string projectDirectory = Path.GetDirectoryName(envDteProject.FullName); string fullFilePath = Path.Combine(projectDirectory, fileName); File.Copy(pathToRuleSet, fullFilePath); UpdateProjectConfigurationsToUseRuleSetFile(envDteProject, fileName); envDteProject.ProjectItems.AddFromFile(fullFilePath); return fullFilePath; } private void UpdateProjectConfigurationsToUseRuleSetFile(EnvDTE.Project envDteProject, string fileName) { foreach (EnvDTE.Configuration config in envDteProject.ConfigurationManager) { EnvDTE.Properties properties = config.Properties; try { EnvDTE.Property codeAnalysisRuleSetFileProperty = properties?.Item("CodeAnalysisRuleSet"); if (codeAnalysisRuleSetFileProperty != null) { codeAnalysisRuleSetFileProperty.Value = fileName; } } catch (ArgumentException) { // Unfortunately the properties collection sometimes throws an ArgumentException // instead of returning null if the current configuration doesn't support CodeAnalysisRuleSet. // Ignore it and move on. } } } private string GetNewRuleSetFileNameForProject(EnvDTE.Project envDteProject) { string projectName = envDteProject.Name; HashSet<string> projectItemNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (ProjectItem item in envDteProject.ProjectItems) { projectItemNames.Add(item.Name); } string ruleSetName = projectName + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } for (int i = 1; i < int.MaxValue; i++) { ruleSetName = projectName + i + ".ruleset"; if (!projectItemNames.Contains(ruleSetName)) { return ruleSetName; } } return null; } private static ReportDiagnostic? MapSelectedItemToReportDiagnostic(MenuCommand selectedItem) { ReportDiagnostic? selectedAction = null; if (selectedItem.CommandID.Guid == Guids.RoslynGroupId) { switch (selectedItem.CommandID.ID) { case ID.RoslynCommands.SetSeverityDefault: selectedAction = ReportDiagnostic.Default; break; case ID.RoslynCommands.SetSeverityError: selectedAction = ReportDiagnostic.Error; break; case ID.RoslynCommands.SetSeverityWarning: selectedAction = ReportDiagnostic.Warn; break; case ID.RoslynCommands.SetSeverityInfo: selectedAction = ReportDiagnostic.Info; break; case ID.RoslynCommands.SetSeverityHidden: selectedAction = ReportDiagnostic.Hidden; break; case ID.RoslynCommands.SetSeverityNone: selectedAction = ReportDiagnostic.Suppress; break; default: selectedAction = null; break; } } return selectedAction; } private void SendUnableToOpenRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.AnalyzersCommandHandler_RuleSetFileCouldNotBeOpened, message); } private void SendUnableToUpdateRuleSetNotification(Workspace workspace, string message) { SendErrorNotification( workspace, SolutionExplorerShim.AnalyzersCommandHandler_RuleSetFileCouldNotBeUpdated, message); } private void SendErrorNotification(Workspace workspace, string title, string message) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification(message, title, NotificationSeverity.Error); } int IVsUpdateSolutionEvents.UpdateSolution_Begin(ref int pfCancelUpdate) { _allowProjectSystemOperations = false; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_StartUpdate(ref int pfCancelUpdate) { return VSConstants.S_OK; } int IVsUpdateSolutionEvents.UpdateSolution_Cancel() { _allowProjectSystemOperations = true; UpdateOtherMenuItemsEnabled(); return VSConstants.S_OK; } int IVsUpdateSolutionEvents.OnActiveProjectCfgChange(IVsHierarchy pIVsHierarchy) { return VSConstants.S_OK; } private Workspace TryGetWorkspace() { if (_workspace == null) { var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var provider = componentModel.DefaultExportProvider.GetExportedValueOrDefault<ISolutionExplorerWorkspaceProvider>(); if (provider != null) { _workspace = provider.GetWorkspace(); } } return _workspace; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace ProgrammingAssignment3 { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SoundEffectInstance soundnstance; SoundEffect sound; const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 600; Random rand = new Random(); Vector2 centerLocation = new Vector2( WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2); // STUDENTS: declare variables for 3 rock sprites Texture2D rockSprite0, rockSprite1, rockSprite2; // STUDENTS: declare variables for 3 rocks Rock rock0, rock1, rock2; // delay support const int TOTAL_DELAY_MILLISECONDS = 1000; int elapsedDelayMilliseconds = 0; // random velocity support const float BASE_SPEED = 0.15f; Vector2 upLeft = new Vector2(-BASE_SPEED, -BASE_SPEED); Vector2 upRight = new Vector2(BASE_SPEED, -BASE_SPEED); Vector2 downRight = new Vector2(BASE_SPEED, BASE_SPEED); Vector2 downLeft = new Vector2(-BASE_SPEED, BASE_SPEED); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // change resolution graphics.PreferredBackBufferWidth = WINDOW_WIDTH; graphics.PreferredBackBufferHeight = WINDOW_HEIGHT; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // STUDENTS: Load content for 3 sprites rockSprite0 = Content.Load<Texture2D>("greenrock"); rockSprite1 = Content.Load<Texture2D>("whiterock"); rockSprite2 = Content.Load<Texture2D>("magentarock"); // STUDENTS: Create a new random rock by calling the GetRandomRock method rock0 = GetRandomRock(); sound = Content.Load<SoundEffect>("Bomb"); soundnstance = sound.CreateInstance(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); // STUDENTS: update rocks if(rock0!=null)rock0.Update(gameTime); if (rock1 != null) rock1.Update(gameTime); if (rock2 != null) rock2.Update(gameTime); // update timer elapsedDelayMilliseconds += gameTime.ElapsedGameTime.Milliseconds; if (elapsedDelayMilliseconds >= TOTAL_DELAY_MILLISECONDS) { // STUDENTS: timer expired, so spawn new rock if fewer than 3 rocks in window if (rock0 == null) rock0 = GetRandomRock(); if (rock1 == null) rock1 = GetRandomRock(); if (rock2 == null) rock2 = GetRandomRock(); // restart timer elapsedDelayMilliseconds = 0; } if (gameTime.TotalGameTime.Milliseconds > 30000) { this.Exit(); } // STUDENTS: Check each rock to see if it's outside the window. If so // spawn a new random rock for it by calling the GetRandomRock method // Caution: Only check the property if the variable isn't null if (rock0 != null && rock0.OutsideWindow) { //sound.Play(); rock0 = GetRandomRock(); soundnstance.Play(); } if (rock1 != null && rock1.OutsideWindow) { soundnstance.Play(); rock1 = GetRandomRock(); } if (rock2 != null && rock2.OutsideWindow) { soundnstance.Play(); rock2 = GetRandomRock(); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); // STUDENTS: draw rocks spriteBatch.Begin(); if (rock0 != null) rock0.Draw(spriteBatch); if (rock1 != null) rock1.Draw(spriteBatch); if (rock2 != null) rock2.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } /// <summary> /// Gets a rock with a random sprite and velocity /// </summary> /// <returns>the rock</returns> private Rock GetRandomRock() { // STUDENTS: Uncomment and complete the code below to randomly pick a rock sprite by calling the GetRandomSprite method Texture2D sprite = GetRandomSprite(); // STUDENTS: Uncomment and complete the code below to randomly pick a velocity by calling the GetRandomVelocity method Vector2 velocity = GetRandomVelocity(); // return a new rock, centered in the window, with the random sprite and velocity return new Rock(sprite, centerLocation, velocity, WINDOW_WIDTH, WINDOW_HEIGHT); } /// <summary> /// Gets a random sprite /// </summary> /// <returns>the sprite</returns> private Texture2D GetRandomSprite() { // STUDENTS: Uncommment and modify the code below as appropriate to return // a random sprite int spriteNumber = rand.Next(3); ; if (spriteNumber == 0) { return rockSprite0; } else if (spriteNumber == 1) { return rockSprite1; } else { return rockSprite2; } } /// <summary> /// Gets a random velocity /// </summary> /// <returns>the velocity</returns> private Vector2 GetRandomVelocity() { // STUDENTS: Uncommment and modify the code below as appropriate to return // a random velocity int velocityNumber =rand.Next(4) ; if (velocityNumber == 0) { return upLeft; } else if (velocityNumber == 1) { return upRight; } else if (velocityNumber == 2) { return downRight; } else { return downLeft; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; namespace Compute.Tests { public class VMScaleSetVMOperationalTests : VMScaleSetVMTestsBase { private string rgName, vmssName, storageAccountName, instanceId; private ImageReference imageRef; private VirtualMachineScaleSet inputVMScaleSet; private void InitializeCommon(MockContext context) { EnsureClientsInitialized(context); imageRef = GetPlatformVMImage(useWindowsImage: true); rgName = TestUtilities.GenerateName(TestPrefix) + 1; vmssName = TestUtilities.GenerateName("vmss"); storageAccountName = TestUtilities.GenerateName(TestPrefix); } /// <summary> /// Covers following Operations: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Get VMScaleSetVM Model View /// Get VMScaleSetVM Instance View /// List VMScaleSetVMs Model View /// List VMScaleSetVMs Instance View /// Start VMScaleSetVM /// Stop VMScaleSetVM /// Restart VMScaleSetVM /// Deallocate VMScaleSetVM /// Delete VMScaleSetVM /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations() { using (MockContext context = MockContext.Start(this.GetType())) { TestVMScaleSetVMOperationsInternal(context); } } /// <summary> /// Covers following Operations for a VMSS VM with managed disks: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Get VMScaleSetVM Model View /// Get VMScaleSetVM Instance View /// List VMScaleSetVMs Model View /// List VMScaleSetVMs Instance View /// Start VMScaleSetVM /// Reimage VMScaleSetVM /// ReimageAll VMScaleSetVM /// Stop VMScaleSetVM /// Restart VMScaleSetVM /// Deallocate VMScaleSetVM /// Delete VMScaleSetVM /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations_ManagedDisks() { using (MockContext context = MockContext.Start(this.GetType())) { TestVMScaleSetVMOperationsInternal(context, true); } } private void TestVMScaleSetVMOperationsInternal(MockContext context, bool hasManagedDisks = false) { InitializeCommon(context); instanceId = "0"; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, createWithManagedDisks: hasManagedDisks); var getResponse = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmScaleSet.Name, instanceId); var imageReference = getResponse.StorageProfile.ImageReference; Assert.NotNull(imageReference?.ExactVersion); Assert.Equal(imageReference.Version, imageReference.ExactVersion); VirtualMachineScaleSetVM vmScaleSetVMModel = GenerateVMScaleSetVMModel(vmScaleSet, instanceId, hasManagedDisks); ValidateVMScaleSetVM(vmScaleSetVMModel, vmScaleSet.Sku.Name, getResponse, hasManagedDisks); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName, vmScaleSet.Name, instanceId); Assert.True(getInstanceViewResponse != null, "VMScaleSetVM not returned."); ValidateVMScaleSetVMInstanceView(getInstanceViewResponse, hasManagedDisks); var query = new Microsoft.Rest.Azure.OData.ODataQuery<VirtualMachineScaleSetVM>(); query.SetFilter(vm => vm.LatestModelApplied == true); var listResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query); Assert.False(listResponse == null, "VMScaleSetVMs not returned"); Assert.True(listResponse.Count() == inputVMScaleSet.Sku.Capacity); query.Filter = null; query.Expand = "instanceView"; listResponse = m_CrpClient.VirtualMachineScaleSetVMs.List(rgName, vmssName, query, "instanceView"); Assert.False(listResponse == null, "VMScaleSetVMs not returned"); Assert.True(listResponse.Count() == inputVMScaleSet.Sku.Capacity); m_CrpClient.VirtualMachineScaleSetVMs.Start(rgName, vmScaleSet.Name, instanceId); m_CrpClient.VirtualMachineScaleSetVMs.Reimage(rgName, vmScaleSet.Name, instanceId, tempDisk: null); if (hasManagedDisks) { m_CrpClient.VirtualMachineScaleSetVMs.ReimageAll(rgName, vmScaleSet.Name, instanceId); } m_CrpClient.VirtualMachineScaleSetVMs.Restart(rgName, vmScaleSet.Name, instanceId); m_CrpClient.VirtualMachineScaleSetVMs.PowerOff(rgName, vmScaleSet.Name, instanceId); m_CrpClient.VirtualMachineScaleSetVMs.Deallocate(rgName, vmScaleSet.Name, instanceId); m_CrpClient.VirtualMachineScaleSetVMs.Delete(rgName, vmScaleSet.Name, instanceId); passed = true; } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } Assert.True(passed); } /// <summary> /// Covers following Operations for a VMSS VM with managed disks: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Start VMScaleSetVM /// RunCommand VMScaleSetVM /// Delete VMScaleSetVM /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations_RunCommand() { using (MockContext context = MockContext.Start(this.GetType())) { InitializeCommon(context); instanceId = "0"; bool passed = false; try { var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, createWithManagedDisks: true); m_CrpClient.VirtualMachineScaleSetVMs.Start(rgName, vmScaleSet.Name, instanceId); RunCommandResult result = m_CrpClient.VirtualMachineScaleSetVMs.RunCommand(rgName, vmScaleSet.Name, instanceId, new RunCommandInput() { CommandId = "ipconfig" }); Assert.NotNull(result); Assert.NotNull(result.Value); Assert.True(result.Value.Count > 0); passed = true; } finally { // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } Assert.True(passed); } } /// <summary> /// Covers following Operations for a VMSS VM with managed disks: /// Create RG /// Create Storage Account /// Create Network Resources /// Create VMScaleSet /// Get VMScaleSetVM Model View /// Create DataDisk /// Update VirtualMachineScaleVM to Attach Disk /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations_Put() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); bool passed = false; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "westus2"); InitializeCommon(context); instanceId = "0"; var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking( rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, createWithManagedDisks: true, machineSizeType: VirtualMachineSizeTypes.StandardA1V2); VirtualMachineScaleSetVM vmssVM = m_CrpClient.VirtualMachineScaleSetVMs.Get(rgName, vmScaleSet.Name, instanceId); VirtualMachineScaleSetVM vmScaleSetVMModel = GenerateVMScaleSetVMModel(vmScaleSet, instanceId, hasManagedDisks: true); ValidateVMScaleSetVM(vmScaleSetVMModel, vmScaleSet.Sku.Name, vmssVM, hasManagedDisks: true); AttachDataDiskToVMScaleSetVM(vmssVM, vmScaleSetVMModel, 2); VirtualMachineScaleSetVM vmssVMReturned = m_CrpClient.VirtualMachineScaleSetVMs.Update(rgName, vmScaleSet.Name, vmssVM.InstanceId, vmssVM); ValidateVMScaleSetVM(vmScaleSetVMModel, vmScaleSet.Sku.Name, vmssVMReturned, hasManagedDisks: true); passed = true; } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.Delete(rgName); } Assert.True(passed); } } /// <summary> /// Covers following operations: /// Create RG /// Create VM Scale Set /// Redeploy one instance of VM Scale Set /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations_Redeploy() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); instanceId = "0"; bool passed = false; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "EastUS2"); InitializeCommon(context); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, createWithManagedDisks: true); m_CrpClient.VirtualMachineScaleSetVMs.Redeploy(rgName, vmScaleSet.Name, instanceId); passed = true; } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Covers following operations: /// Create RG /// Create VM Scale Set /// Perform maintenance on one instance of VM Scale Set /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations_PerformMaintenance() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); instanceId = "0"; VirtualMachineScaleSet vmScaleSet = null; bool passed = false; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "EastUS2"); InitializeCommon(context); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, createWithManagedDisks: true); m_CrpClient.VirtualMachineScaleSetVMs.PerformMaintenance(rgName, vmScaleSet.Name, instanceId); passed = true; } catch (CloudException cex) { passed = true; string expectedMessage = $"Operation 'performMaintenance' is not allowed on VM '{vmScaleSet.Name}_0' " + "since the Subscription of this VM is not eligible."; Assert.Equal(expectedMessage, cex.Message); } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } /// <summary> /// Covers following operations: /// Create RG /// Create VM Scale Set with managed boot diagnostics enabled /// RetrieveBootDiagnosticsData for a VM instance /// Delete RG /// </summary> [Fact] public void TestVMScaleSetVMOperations_ManagedBootDiagnostics() { using (MockContext context = MockContext.Start(this.GetType())) { string originalTestLocation = Environment.GetEnvironmentVariable("AZURE_VM_TEST_LOCATION"); instanceId = "0"; bool passed = false; try { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", "eastus2euap"); InitializeCommon(context); var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); VirtualMachineScaleSet vmScaleSet = CreateVMScaleSet_NoAsyncTracking(rgName, vmssName, storageAccountOutput, imageRef, out inputVMScaleSet, createWithManagedDisks: true, faultDomainCount: 1, bootDiagnosticsProfile: GetManagedDiagnosticsProfile()); var getInstanceViewResponse = m_CrpClient.VirtualMachineScaleSetVMs.GetInstanceView(rgName, vmScaleSet.Name, instanceId); ValidateBootDiagnosticsInstanceView(getInstanceViewResponse.BootDiagnostics, hasError: false, enabledWithManagedBootDiagnostics: true); RetrieveBootDiagnosticsDataResult bootDiagnosticsData = m_CrpClient.VirtualMachineScaleSetVMs.RetrieveBootDiagnosticsData(rgName, vmScaleSet.Name, instanceId); ValidateBootDiagnosticsData(bootDiagnosticsData); passed = true; } finally { Environment.SetEnvironmentVariable("AZURE_VM_TEST_LOCATION", originalTestLocation); // Cleanup the created resources. But don't wait since it takes too long, and it's not the purpose // of the test to cover deletion. CSM does persistent retrying over all RG resources. m_ResourcesClient.ResourceGroups.DeleteIfExists(rgName); } Assert.True(passed); } } private Disk CreateDataDisk(string diskName) { var disk = new Disk { Location = m_location, DiskSizeGB = 10, }; disk.Sku = new DiskSku() { Name = StorageAccountTypes.StandardLRS }; disk.CreationData = new CreationData() { CreateOption = DiskCreateOption.Empty }; return m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); } private DataDisk CreateModelDataDisk(Disk disk) { var modelDisk = new DataDisk { DiskSizeGB = disk.DiskSizeGB, CreateOption = DiskCreateOptionTypes.Attach }; return modelDisk; } private void AttachDataDiskToVMScaleSetVM(VirtualMachineScaleSetVM vmssVM, VirtualMachineScaleSetVM vmModel, int lun) { if(vmssVM.StorageProfile.DataDisks == null) vmssVM.StorageProfile.DataDisks = new List<DataDisk>(); if (vmModel.StorageProfile.DataDisks == null) vmModel.StorageProfile.DataDisks = new List<DataDisk>(); var diskName = TestPrefix + "dataDisk" + lun; var disk = CreateDataDisk(diskName); var dd = new DataDisk { CreateOption = DiskCreateOptionTypes.Attach, Lun = lun, Name = diskName, ManagedDisk = new ManagedDiskParameters() { Id = disk.Id, StorageAccountType = disk.Sku.Name } }; vmssVM.StorageProfile.DataDisks.Add(dd); // Add the data disk to the model for validation later vmModel.StorageProfile.DataDisks.Add(CreateModelDataDisk(disk)); } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.Model; using Orleans.CodeGenerator.Utilities; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Orleans.CodeGenerator.Generators { /// <summary> /// Generates IGrainMethodInvoker implementations for grains. /// </summary> internal class GrainMethodInvokerGenerator { private readonly CodeGeneratorOptions options; private readonly WellKnownTypes wellKnownTypes; /// <summary> /// The next id used for generated code disambiguation purposes. /// </summary> private int nextId; public GrainMethodInvokerGenerator(CodeGeneratorOptions options, WellKnownTypes wellKnownTypes) { this.options = options; this.wellKnownTypes = wellKnownTypes; } /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> internal static string GetGeneratedClassName(INamedTypeSymbol type) => CodeGenerator.ToolName + type.GetSuitableClassName() + "MethodInvoker"; /// <summary> /// Generates the class for the provided grain types. /// </summary> internal TypeDeclarationSyntax GenerateClass(GrainInterfaceDescription description) { var generatedTypeName = description.InvokerTypeName; var grainType = description.Type; var baseTypes = new List<BaseTypeSyntax> { SimpleBaseType(wellKnownTypes.IGrainMethodInvoker.ToTypeSyntax()) }; var genericTypes = grainType.GetHierarchyTypeParameters() .Select(_ => TypeParameter(_.ToString())) .ToArray(); // Create the special method invoker marker attribute. var interfaceId = description.InterfaceId; var interfaceIdArgument = interfaceId.ToHexLiteral(); var grainTypeArgument = TypeOfExpression(grainType.WithoutTypeParameters().ToTypeSyntax()); var attributes = new List<AttributeSyntax> { GeneratedCodeAttributeGenerator.GetGeneratedCodeAttributeSyntax(wellKnownTypes), Attribute(wellKnownTypes.MethodInvokerAttribute.ToNameSyntax()) .AddArgumentListArguments( AttributeArgument(grainTypeArgument), AttributeArgument(interfaceIdArgument)), Attribute(wellKnownTypes.ExcludeFromCodeCoverageAttribute.ToNameSyntax()) }; var genericInvokerFields = GenerateGenericInvokerFields(wellKnownTypes, description.Methods); var members = new List<MemberDeclarationSyntax>(genericInvokerFields.Values.Select(x => x.Declaration)) { GenerateInvokeMethod(wellKnownTypes, grainType, genericInvokerFields), GrainInterfaceCommon.GenerateInterfaceIdProperty(wellKnownTypes, description), GrainInterfaceCommon.GenerateInterfaceVersionProperty(wellKnownTypes, description) }; // If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker. if (grainType.HasInterface(wellKnownTypes.IGrainExtension)) { baseTypes.Add(SimpleBaseType(wellKnownTypes.IGrainExtensionMethodInvoker.ToTypeSyntax())); members.Add(GenerateExtensionInvokeMethod(wellKnownTypes, grainType, genericInvokerFields)); } var classDeclaration = ClassDeclaration(generatedTypeName) .AddModifiers(Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes(baseTypes.ToArray()) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(members.ToArray()) .AddAttributeLists(AttributeList().AddAttributes(attributes.ToArray())); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } if (this.options.DebuggerStepThrough) { var debuggerStepThroughAttribute = Attribute(this.wellKnownTypes.DebuggerStepThroughAttribute.ToNameSyntax()); classDeclaration = classDeclaration.AddAttributeLists(AttributeList().AddAttributes(debuggerStepThroughAttribute)); } return classDeclaration; } /// <summary> /// Generates syntax for the IGrainMethodInvoker.Invoke method. /// </summary> private MethodDeclarationSyntax GenerateInvokeMethod( WellKnownTypes wellKnownTypes, INamedTypeSymbol grainType, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { // Get the method with the correct type. var invokeMethod = wellKnownTypes.IGrainMethodInvoker.Method("Invoke", wellKnownTypes.IAddressable, wellKnownTypes.InvokeMethodRequest); return GenerateInvokeMethod(wellKnownTypes, grainType, invokeMethod, genericInvokerFields); } /// <summary> /// Generates syntax for the IGrainExtensionMethodInvoker.Invoke method. /// </summary> private MethodDeclarationSyntax GenerateExtensionInvokeMethod( WellKnownTypes wellKnownTypes, INamedTypeSymbol grainType, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { // Get the method with the correct type. var invokeMethod = wellKnownTypes.IGrainExtensionMethodInvoker.Method("Invoke", wellKnownTypes.IGrainExtension, wellKnownTypes.InvokeMethodRequest); return GenerateInvokeMethod(wellKnownTypes, grainType, invokeMethod, genericInvokerFields); } /// <summary> /// Generates syntax for an invoke method. /// </summary> private MethodDeclarationSyntax GenerateInvokeMethod( WellKnownTypes wellKnownTypes, INamedTypeSymbol grainType, IMethodSymbol invokeMethod, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { var parameters = invokeMethod.Parameters; var grainArgument = parameters[0].Name.ToIdentifierName(); var requestArgument = parameters[1].Name.ToIdentifierName(); var interfaceIdProperty = wellKnownTypes.InvokeMethodRequest.Property("InterfaceId"); var methodIdProperty = wellKnownTypes.InvokeMethodRequest.Property("MethodId"); var argumentsProperty = wellKnownTypes.InvokeMethodRequest.Property("Arguments"); // Store the relevant values from the request in local variables. var interfaceIdDeclaration = LocalDeclarationStatement( VariableDeclaration(wellKnownTypes.Int32.ToTypeSyntax()) .AddVariables( VariableDeclarator("interfaceId") .WithInitializer(EqualsValueClause(requestArgument.Member(interfaceIdProperty.Name))))); var interfaceIdVariable = IdentifierName("interfaceId"); var methodIdDeclaration = LocalDeclarationStatement( VariableDeclaration(wellKnownTypes.Int32.ToTypeSyntax()) .AddVariables( VariableDeclarator("methodId") .WithInitializer(EqualsValueClause(requestArgument.Member(methodIdProperty.Name))))); var methodIdVariable = IdentifierName("methodId"); var argumentsDeclaration = LocalDeclarationStatement( VariableDeclaration(IdentifierName("var")) .AddVariables( VariableDeclarator("arguments") .WithInitializer(EqualsValueClause(requestArgument.Member(argumentsProperty.Name))))); var argumentsVariable = IdentifierName("arguments"); var methodDeclaration = invokeMethod.GetDeclarationSyntax() .AddModifiers(Token(SyntaxKind.AsyncKeyword)) .AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration); var callThrowMethodNotImplemented = InvocationExpression(IdentifierName("ThrowMethodNotImplemented")) .WithArgumentList(ArgumentList(SeparatedList(new[] { Argument(interfaceIdVariable), Argument(methodIdVariable) }))); // This method is used directly after its declaration to create blocks for each interface id, comprising // primarily of a nested switch statement for each of the methods in the given interface. BlockSyntax ComposeInterfaceBlock(INamedTypeSymbol interfaceType, SwitchStatementSyntax methodSwitch) { var typedGrainDeclaration = LocalDeclarationStatement( VariableDeclaration(IdentifierName("var")) .AddVariables( VariableDeclarator("casted") .WithInitializer(EqualsValueClause(ParenthesizedExpression(CastExpression(interfaceType.ToTypeSyntax(), grainArgument)))))); return Block(typedGrainDeclaration, methodSwitch.AddSections(SwitchSection() .AddLabels(DefaultSwitchLabel()) .AddStatements( ExpressionStatement(callThrowMethodNotImplemented), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression))))); } var interfaceCases = GrainInterfaceCommon.GenerateGrainInterfaceAndMethodSwitch( wellKnownTypes, grainType, methodIdVariable, methodType => GenerateInvokeForMethod(wellKnownTypes, IdentifierName("casted"), methodType, argumentsVariable, genericInvokerFields), ComposeInterfaceBlock); var throwInterfaceNotImplemented = GrainInterfaceCommon.GenerateMethodNotImplementedFunction(wellKnownTypes); var throwMethodNotImplemented = GrainInterfaceCommon.GenerateInterfaceNotImplementedFunction(wellKnownTypes); // Generate the default case, which will call the above local function to throw . var callThrowInterfaceNotImplemented = InvocationExpression(IdentifierName("ThrowInterfaceNotImplemented")) .WithArgumentList(ArgumentList(SingletonSeparatedList(Argument(interfaceIdVariable)))); var defaultCase = SwitchSection() .AddLabels(DefaultSwitchLabel()) .AddStatements( ExpressionStatement(callThrowInterfaceNotImplemented), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression))); var interfaceIdSwitch = SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); return methodDeclaration.AddBodyStatements(interfaceIdSwitch, throwInterfaceNotImplemented, throwMethodNotImplemented); } /// <summary> /// Generates syntax to invoke a method on a grain. /// </summary> private StatementSyntax[] GenerateInvokeForMethod( WellKnownTypes wellKnownTypes, ExpressionSyntax castGrain, IMethodSymbol method, ExpressionSyntax arguments, Dictionary<IMethodSymbol, GenericInvokerField> genericInvokerFields) { // Construct expressions to retrieve each of the method's parameters. var parameters = new List<ExpressionSyntax>(); var methodParameters = method.Parameters.ToList(); for (var i = 0; i < methodParameters.Count; i++) { var parameter = methodParameters[i]; var parameterType = parameter.Type.ToTypeSyntax(); var indexArg = Argument(LiteralExpression(SyntaxKind.NumericLiteralExpression, Literal(i))); var arg = CastExpression( parameterType, ElementAccessExpression(arguments).AddArgumentListArguments(indexArg)); parameters.Add(arg); } // If the method is a generic method definition, use the generic method invoker field to invoke the method. if (method.IsGenericMethod) { var invokerFieldName = genericInvokerFields[method].FieldName; var invokerCall = InvocationExpression( IdentifierName(invokerFieldName) .Member(wellKnownTypes.IGrainMethodInvoker.Method("Invoke").Name)) .AddArgumentListArguments(Argument(castGrain), Argument(arguments)); return new StatementSyntax[] { ReturnStatement(AwaitExpression(invokerCall)) }; } // Invoke the method. var grainMethodCall = InvocationExpression(castGrain.Member(method.Name)) .AddArgumentListArguments(parameters.Select(Argument).ToArray()); // For void methods, invoke the method and return null. if (method.ReturnsVoid) { return new StatementSyntax[] { ExpressionStatement(grainMethodCall), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } // For methods which return an awaitable type which has no result type, await the method and return null. if (method.ReturnType.Method("GetAwaiter").ReturnType.Method("GetResult").ReturnsVoid) { return new StatementSyntax[] { ExpressionStatement(AwaitExpression(grainMethodCall)), ReturnStatement(LiteralExpression(SyntaxKind.NullLiteralExpression)) }; } return new StatementSyntax[] { ReturnStatement(AwaitExpression(grainMethodCall)) }; } /// <summary> /// Generates GenericMethodInvoker fields for the generic methods in <paramref name="methodDescriptions"/>. /// </summary> private Dictionary<IMethodSymbol, GenericInvokerField> GenerateGenericInvokerFields(WellKnownTypes wellKnownTypes, List<GrainMethodDescription> methodDescriptions) { if (!(wellKnownTypes.GenericMethodInvoker is WellKnownTypes.Some genericMethodInvoker)) return new Dictionary<IMethodSymbol, GenericInvokerField>(); var result = new Dictionary<IMethodSymbol, GenericInvokerField>(methodDescriptions.Count); foreach (var description in methodDescriptions) { var method = description.Method; if (!method.IsGenericMethod) continue; result[method] = GenerateGenericInvokerField(method, genericMethodInvoker.Value); } return result; } /// <summary> /// Generates a GenericMethodInvoker field for the provided generic method. /// </summary> private GenericInvokerField GenerateGenericInvokerField(IMethodSymbol method, INamedTypeSymbol genericMethodInvoker) { var fieldName = $"GenericInvoker_{method.Name}_{Interlocked.Increment(ref nextId):X}"; var fieldInfoVariable = VariableDeclarator(fieldName) .WithInitializer( EqualsValueClause( ObjectCreationExpression(genericMethodInvoker.ToTypeSyntax()) .AddArgumentListArguments( Argument(TypeOfExpression(method.ContainingType.ToTypeSyntax())), Argument(method.Name.ToLiteralExpression()), Argument( LiteralExpression( SyntaxKind.NumericLiteralExpression, Literal(method.TypeArguments.Length)))))); var declaration = FieldDeclaration( VariableDeclaration(genericMethodInvoker.ToTypeSyntax()).AddVariables(fieldInfoVariable)) .AddModifiers( Token(SyntaxKind.PrivateKeyword), Token(SyntaxKind.StaticKeyword), Token(SyntaxKind.ReadOnlyKeyword)); return new GenericInvokerField(fieldName, declaration); } private readonly struct GenericInvokerField { public GenericInvokerField(string fieldName, MemberDeclarationSyntax declaration) { this.FieldName = fieldName; this.Declaration = declaration; } public string FieldName { get; } public MemberDeclarationSyntax Declaration { get; } } } }
// A Tile in the game that makes up the 2D map grid. // DO NOT MODIFY THIS FILE // Never try to directly create an instance of this class, or modify its member variables. // Instead, you should only be reading its variables and calling its functions. using System; using System.Collections.Generic; using System.Linq; using System.Text; // <<-- Creer-Merge: usings -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional using(s) here // <<-- /Creer-Merge: usings -->> namespace Joueur.cs.Games.Necrowar { /// <summary> /// A Tile in the game that makes up the 2D map grid. /// </summary> public class Tile : Necrowar.GameObject { #region Properties /// <summary> /// The amount of corpses on this tile. /// </summary> public int Corpses { get; protected set; } /// <summary> /// Whether or not the tile is a castle tile. /// </summary> public bool IsCastle { get; protected set; } /// <summary> /// Whether or not the tile is considered to be a gold mine or not. /// </summary> public bool IsGoldMine { get; protected set; } /// <summary> /// Whether or not the tile is considered grass or not (Workers can walk on grass). /// </summary> public bool IsGrass { get; protected set; } /// <summary> /// Whether or not the tile is considered to be the island gold mine or not. /// </summary> public bool IsIslandGoldMine { get; protected set; } /// <summary> /// Whether or not the tile is considered a path or not (Units can walk on paths). /// </summary> public bool IsPath { get; protected set; } /// <summary> /// Whether or not the tile is considered a river or not. /// </summary> public bool IsRiver { get; protected set; } /// <summary> /// Whether or not the tile is considered a tower or not. /// </summary> public bool IsTower { get; protected set; } /// <summary> /// Whether or not the tile is the unit spawn. /// </summary> public bool IsUnitSpawn { get; protected set; } /// <summary> /// Whether or not the tile can be moved on by workers. /// </summary> public bool IsWall { get; protected set; } /// <summary> /// Whether or not the tile is the worker spawn. /// </summary> public bool IsWorkerSpawn { get; protected set; } /// <summary> /// The amount of Ghouls on this tile. /// </summary> public int NumGhouls { get; protected set; } /// <summary> /// The amount of Hounds on this tile. /// </summary> public int NumHounds { get; protected set; } /// <summary> /// The amount of Zombies on this tile. /// </summary> public int NumZombies { get; protected set; } /// <summary> /// Which player owns this tile, only applies to grass tiles for workers, NULL otherwise. /// </summary> public Necrowar.Player Owner { get; protected set; } /// <summary> /// The Tile to the 'East' of this one (x+1, y). Null if out of bounds of the map. /// </summary> public Necrowar.Tile TileEast { get; protected set; } /// <summary> /// The Tile to the 'North' of this one (x, y-1). Null if out of bounds of the map. /// </summary> public Necrowar.Tile TileNorth { get; protected set; } /// <summary> /// The Tile to the 'South' of this one (x, y+1). Null if out of bounds of the map. /// </summary> public Necrowar.Tile TileSouth { get; protected set; } /// <summary> /// The Tile to the 'West' of this one (x-1, y). Null if out of bounds of the map. /// </summary> public Necrowar.Tile TileWest { get; protected set; } /// <summary> /// The Tower on this Tile if present, otherwise null. /// </summary> public Necrowar.Tower Tower { get; protected set; } /// <summary> /// The Unit on this Tile if present, otherwise null. /// </summary> public Necrowar.Unit Unit { get; protected set; } /// <summary> /// The x (horizontal) position of this Tile. /// </summary> public int X { get; protected set; } /// <summary> /// The y (vertical) position of this Tile. /// </summary> public int Y { get; protected set; } // <<-- Creer-Merge: properties -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional properties(s) here. None of them will be tracked or updated by the server. // <<-- /Creer-Merge: properties -->> #endregion #region Methods /// <summary> /// Creates a new instance of Tile. Used during game initialization, do not call directly. /// </summary> protected Tile() : base() { } /// <summary> /// Resurrect the corpses on this tile into Zombies. /// </summary> /// <param name="num">Number of zombies to resurrect.</param> /// <returns>True if successful res, false otherwise.</returns> public bool Res(int num) { return this.RunOnServer<bool>("res", new Dictionary<string, object> { {"num", num} }); } /// <summary> /// Spawns a fighting unit on the correct tile. /// </summary> /// <param name="title">The title of the desired unit type.</param> /// <returns>True if successfully spawned, false otherwise.</returns> public bool SpawnUnit(string title) { return this.RunOnServer<bool>("spawnUnit", new Dictionary<string, object> { {"title", title} }); } /// <summary> /// Spawns a worker on the correct tile. /// </summary> /// <returns>True if successfully spawned, false otherwise.</returns> public bool SpawnWorker() { return this.RunOnServer<bool>("spawnWorker", new Dictionary<string, object> { }); } /// <summary> /// Gets the neighbors of this Tile /// </summary> /// <returns>The neighboring (adjacent) Tiles to this tile</returns> public List<Tile> GetNeighbors() { var list = new List<Tile>(); if (this.TileNorth != null) { list.Add(this.TileNorth); } if (this.TileEast != null) { list.Add(this.TileEast); } if (this.TileSouth != null) { list.Add(this.TileSouth); } if (this.TileWest != null) { list.Add(this.TileWest); } return list; } /// <summary> /// Checks if a Tile is pathable to units /// </summary> /// <returns>True if pathable, false otherwise</returns> public bool IsPathable() { // <<-- Creer-Merge: is_pathable_builtin -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. return false; // DEVELOPER ADD LOGIC HERE // <<-- /Creer-Merge: is_pathable_builtin -->> } /// <summary> /// Checks if this Tile has a specific neighboring Tile /// </summary> /// <param name="tile">Tile to check against</param> /// <returns>true if the tile is a neighbor of this Tile, false otherwise</returns> public bool HasNeighbor(Tile tile) { if (tile == null) { return false; } return this.TileNorth == tile || this.TileEast == tile || this.TileSouth == tile || this.TileWest == tile; } // <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. // you can add additional method(s) here. // <<-- /Creer-Merge: methods -->> #endregion } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnObrasSociale class. /// </summary> [Serializable] public partial class PnObrasSocialeCollection : ActiveList<PnObrasSociale, PnObrasSocialeCollection> { public PnObrasSocialeCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnObrasSocialeCollection</returns> public PnObrasSocialeCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnObrasSociale o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_obras_sociales table. /// </summary> [Serializable] public partial class PnObrasSociale : ActiveRecord<PnObrasSociale>, IActiveRecord { #region .ctors and Default Settings public PnObrasSociale() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnObrasSociale(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnObrasSociale(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnObrasSociale(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_obras_sociales", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCodOs = new TableSchema.TableColumn(schema); colvarCodOs.ColumnName = "cod_os"; colvarCodOs.DataType = DbType.Int32; colvarCodOs.MaxLength = 0; colvarCodOs.AutoIncrement = false; colvarCodOs.IsNullable = false; colvarCodOs.IsPrimaryKey = true; colvarCodOs.IsForeignKey = false; colvarCodOs.IsReadOnly = false; colvarCodOs.DefaultSetting = @""; colvarCodOs.ForeignKeyTableName = ""; schema.Columns.Add(colvarCodOs); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiStringFixedLength; colvarNombre.MaxLength = 500; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_obras_sociales",schema); } } #endregion #region Props [XmlAttribute("CodOs")] [Bindable(true)] public int CodOs { get { return GetColumnValue<int>(Columns.CodOs); } set { SetColumnValue(Columns.CodOs, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varCodOs,string varNombre) { PnObrasSociale item = new PnObrasSociale(); item.CodOs = varCodOs; item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varCodOs,string varNombre) { PnObrasSociale item = new PnObrasSociale(); item.CodOs = varCodOs; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn CodOsColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string CodOs = @"cod_os"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.Reinforcement.CS { partial class ColumnFramReinMakerForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; /// otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.rebarTypesGroupBox = new System.Windows.Forms.GroupBox(); this.centerTransverseRebarTypeComboBox = new System.Windows.Forms.ComboBox(); this.endTransverseRebarTypeComboBox = new System.Windows.Forms.ComboBox(); this.verticalRebarTypeComboBox = new System.Windows.Forms.ComboBox(); this.centerTransverseRebarLabel = new System.Windows.Forms.Label(); this.endTranseverseRebarLabel = new System.Windows.Forms.Label(); this.verticalRebarTypeLabel = new System.Windows.Forms.Label(); this.rebarSpacingGroupBox = new System.Windows.Forms.GroupBox(); this.centerRebarUnitLabel = new System.Windows.Forms.Label(); this.endRebarUnitLabel = new System.Windows.Forms.Label(); this.centerSpacingTextBox = new System.Windows.Forms.TextBox(); this.endSpacingTextBox = new System.Windows.Forms.TextBox(); this.centerSpacingLabel = new System.Windows.Forms.Label(); this.endSpacingLabel = new System.Windows.Forms.Label(); this.rebarQuantityLabel = new System.Windows.Forms.Label(); this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.hookTypeGroupBox = new System.Windows.Forms.GroupBox(); this.transverseRebarHookComboBox = new System.Windows.Forms.ComboBox(); this.transverseRebarHookLabel = new System.Windows.Forms.Label(); this.rebarQuantityNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.rebarTypesGroupBox.SuspendLayout(); this.rebarSpacingGroupBox.SuspendLayout(); this.hookTypeGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.rebarQuantityNumericUpDown)).BeginInit(); this.SuspendLayout(); // // rebarTypesGroupBox // this.rebarTypesGroupBox.Controls.Add(this.centerTransverseRebarTypeComboBox); this.rebarTypesGroupBox.Controls.Add(this.endTransverseRebarTypeComboBox); this.rebarTypesGroupBox.Controls.Add(this.verticalRebarTypeComboBox); this.rebarTypesGroupBox.Controls.Add(this.centerTransverseRebarLabel); this.rebarTypesGroupBox.Controls.Add(this.endTranseverseRebarLabel); this.rebarTypesGroupBox.Controls.Add(this.verticalRebarTypeLabel); this.rebarTypesGroupBox.Location = new System.Drawing.Point(10, 12); this.rebarTypesGroupBox.Name = "rebarTypesGroupBox"; this.rebarTypesGroupBox.Size = new System.Drawing.Size(307, 122); this.rebarTypesGroupBox.TabIndex = 0; this.rebarTypesGroupBox.TabStop = false; this.rebarTypesGroupBox.Text = "Bar Type"; // // centerTransverseRebarTypeComboBox // this.centerTransverseRebarTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.centerTransverseRebarTypeComboBox.FormattingEnabled = true; this.centerTransverseRebarTypeComboBox.Location = new System.Drawing.Point(130, 89); this.centerTransverseRebarTypeComboBox.Name = "centerTransverseRebarTypeComboBox"; this.centerTransverseRebarTypeComboBox.Size = new System.Drawing.Size(171, 21); this.centerTransverseRebarTypeComboBox.TabIndex = 6; // // endTransverseRebarTypeComboBox // this.endTransverseRebarTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.endTransverseRebarTypeComboBox.FormattingEnabled = true; this.endTransverseRebarTypeComboBox.Location = new System.Drawing.Point(130, 55); this.endTransverseRebarTypeComboBox.Name = "endTransverseRebarTypeComboBox"; this.endTransverseRebarTypeComboBox.Size = new System.Drawing.Size(171, 21); this.endTransverseRebarTypeComboBox.TabIndex = 5; // // verticalRebarTypeComboBox // this.verticalRebarTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.verticalRebarTypeComboBox.FormattingEnabled = true; this.verticalRebarTypeComboBox.Location = new System.Drawing.Point(130, 21); this.verticalRebarTypeComboBox.Name = "verticalRebarTypeComboBox"; this.verticalRebarTypeComboBox.Size = new System.Drawing.Size(171, 21); this.verticalRebarTypeComboBox.TabIndex = 4; // // centerTransverseRebarLabel // this.centerTransverseRebarLabel.AutoSize = true; this.centerTransverseRebarLabel.Location = new System.Drawing.Point(8, 92); this.centerTransverseRebarLabel.Name = "centerTransverseRebarLabel"; this.centerTransverseRebarLabel.Size = new System.Drawing.Size(116, 13); this.centerTransverseRebarLabel.TabIndex = 3; this.centerTransverseRebarLabel.Text = "Center Transverse Bar:"; // // endTranseverseRebarLabel // this.endTranseverseRebarLabel.AutoSize = true; this.endTranseverseRebarLabel.Location = new System.Drawing.Point(8, 58); this.endTranseverseRebarLabel.Name = "endTranseverseRebarLabel"; this.endTranseverseRebarLabel.Size = new System.Drawing.Size(107, 13); this.endTranseverseRebarLabel.TabIndex = 2; this.endTranseverseRebarLabel.Text = "End Transverse Bar:"; // // verticalRebarTypeLabel // this.verticalRebarTypeLabel.AutoSize = true; this.verticalRebarTypeLabel.Location = new System.Drawing.Point(8, 24); this.verticalRebarTypeLabel.Name = "verticalRebarTypeLabel"; this.verticalRebarTypeLabel.Size = new System.Drawing.Size(64, 13); this.verticalRebarTypeLabel.TabIndex = 1; this.verticalRebarTypeLabel.Text = "Vertical Bar:"; // // rebarSpacingGroupBox // this.rebarSpacingGroupBox.Controls.Add(this.centerRebarUnitLabel); this.rebarSpacingGroupBox.Controls.Add(this.endRebarUnitLabel); this.rebarSpacingGroupBox.Controls.Add(this.centerSpacingTextBox); this.rebarSpacingGroupBox.Controls.Add(this.endSpacingTextBox); this.rebarSpacingGroupBox.Controls.Add(this.centerSpacingLabel); this.rebarSpacingGroupBox.Controls.Add(this.endSpacingLabel); this.rebarSpacingGroupBox.Location = new System.Drawing.Point(10, 222); this.rebarSpacingGroupBox.Name = "rebarSpacingGroupBox"; this.rebarSpacingGroupBox.Size = new System.Drawing.Size(307, 81); this.rebarSpacingGroupBox.TabIndex = 12; this.rebarSpacingGroupBox.TabStop = false; this.rebarSpacingGroupBox.Text = "Bar Spacing"; // // centerRebarUnitLabel // this.centerRebarUnitLabel.AutoSize = true; this.centerRebarUnitLabel.Location = new System.Drawing.Point(273, 52); this.centerRebarUnitLabel.Name = "centerRebarUnitLabel"; this.centerRebarUnitLabel.Size = new System.Drawing.Size(28, 13); this.centerRebarUnitLabel.TabIndex = 22; this.centerRebarUnitLabel.Text = "Feet"; // // endRebarUnitLabel // this.endRebarUnitLabel.AutoSize = true; this.endRebarUnitLabel.Location = new System.Drawing.Point(273, 22); this.endRebarUnitLabel.Name = "endRebarUnitLabel"; this.endRebarUnitLabel.Size = new System.Drawing.Size(28, 13); this.endRebarUnitLabel.TabIndex = 21; this.endRebarUnitLabel.Text = "Feet"; // // centerSpacingTextBox // this.centerSpacingTextBox.Location = new System.Drawing.Point(130, 49); this.centerSpacingTextBox.Name = "centerSpacingTextBox"; this.centerSpacingTextBox.Size = new System.Drawing.Size(140, 20); this.centerSpacingTextBox.TabIndex = 16; // // endSpacingTextBox // this.endSpacingTextBox.Location = new System.Drawing.Point(130, 19); this.endSpacingTextBox.Name = "endSpacingTextBox"; this.endSpacingTextBox.Size = new System.Drawing.Size(140, 20); this.endSpacingTextBox.TabIndex = 15; // // centerSpacingLabel // this.centerSpacingLabel.AutoSize = true; this.centerSpacingLabel.Location = new System.Drawing.Point(8, 52); this.centerSpacingLabel.Name = "centerSpacingLabel"; this.centerSpacingLabel.Size = new System.Drawing.Size(97, 13); this.centerSpacingLabel.TabIndex = 14; this.centerSpacingLabel.Text = "Transverse Center:"; // // endSpacingLabel // this.endSpacingLabel.AutoSize = true; this.endSpacingLabel.Location = new System.Drawing.Point(8, 22); this.endSpacingLabel.Name = "endSpacingLabel"; this.endSpacingLabel.Size = new System.Drawing.Size(85, 13); this.endSpacingLabel.TabIndex = 13; this.endSpacingLabel.Text = "Transverse End:"; // // rebarQuantityLabel // this.rebarQuantityLabel.AutoSize = true; this.rebarQuantityLabel.Location = new System.Drawing.Point(18, 322); this.rebarQuantityLabel.Name = "rebarQuantityLabel"; this.rebarQuantityLabel.Size = new System.Drawing.Size(118, 13); this.rebarQuantityLabel.TabIndex = 17; this.rebarQuantityLabel.Text = "Quantity of Vertical Bar:"; // // okButton // this.okButton.Location = new System.Drawing.Point(131, 359); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(90, 25); this.okButton.TabIndex = 19; this.okButton.Text = "&OK"; this.okButton.UseVisualStyleBackColor = true; this.okButton.Click += new System.EventHandler(this.okButton_Click); // // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(227, 359); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(90, 25); this.cancelButton.TabIndex = 20; this.cancelButton.Text = "&Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // hookTypeGroupBox // this.hookTypeGroupBox.Controls.Add(this.transverseRebarHookComboBox); this.hookTypeGroupBox.Controls.Add(this.transverseRebarHookLabel); this.hookTypeGroupBox.Location = new System.Drawing.Point(10, 150); this.hookTypeGroupBox.Name = "hookTypeGroupBox"; this.hookTypeGroupBox.Size = new System.Drawing.Size(307, 55); this.hookTypeGroupBox.TabIndex = 7; this.hookTypeGroupBox.TabStop = false; this.hookTypeGroupBox.Text = "Hook Type"; // // transverseRebarHookComboBox // this.transverseRebarHookComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.transverseRebarHookComboBox.FormattingEnabled = true; this.transverseRebarHookComboBox.Location = new System.Drawing.Point(130, 20); this.transverseRebarHookComboBox.Name = "transverseRebarHookComboBox"; this.transverseRebarHookComboBox.Size = new System.Drawing.Size(171, 21); this.transverseRebarHookComboBox.TabIndex = 11; // // transverseRebarHookLabel // this.transverseRebarHookLabel.AutoSize = true; this.transverseRebarHookLabel.Location = new System.Drawing.Point(8, 23); this.transverseRebarHookLabel.Name = "transverseRebarHookLabel"; this.transverseRebarHookLabel.Size = new System.Drawing.Size(82, 13); this.transverseRebarHookLabel.TabIndex = 9; this.transverseRebarHookLabel.Text = "Transverse Bar:"; // // rebarQuantityNumericUpDown // this.rebarQuantityNumericUpDown.Location = new System.Drawing.Point(140, 320); this.rebarQuantityNumericUpDown.Minimum = new decimal(new int[] { 4, 0, 0, 0}); this.rebarQuantityNumericUpDown.Name = "rebarQuantityNumericUpDown"; this.rebarQuantityNumericUpDown.Size = new System.Drawing.Size(171, 20); this.rebarQuantityNumericUpDown.TabIndex = 18; this.rebarQuantityNumericUpDown.Value = new decimal(new int[] { 4, 0, 0, 0}); // // ColumnFramReinMakerForm // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; this.ClientSize = new System.Drawing.Size(329, 393); this.Controls.Add(this.rebarQuantityNumericUpDown); this.Controls.Add(this.hookTypeGroupBox); this.Controls.Add(this.cancelButton); this.Controls.Add(this.okButton); this.Controls.Add(this.rebarSpacingGroupBox); this.Controls.Add(this.rebarTypesGroupBox); this.Controls.Add(this.rebarQuantityLabel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ColumnFramReinMakerForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Column Reinforcement"; this.rebarTypesGroupBox.ResumeLayout(false); this.rebarTypesGroupBox.PerformLayout(); this.rebarSpacingGroupBox.ResumeLayout(false); this.rebarSpacingGroupBox.PerformLayout(); this.hookTypeGroupBox.ResumeLayout(false); this.hookTypeGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.rebarQuantityNumericUpDown)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox rebarTypesGroupBox; private System.Windows.Forms.GroupBox rebarSpacingGroupBox; private System.Windows.Forms.Label centerTransverseRebarLabel; private System.Windows.Forms.Label endTranseverseRebarLabel; private System.Windows.Forms.Label verticalRebarTypeLabel; private System.Windows.Forms.ComboBox verticalRebarTypeComboBox; private System.Windows.Forms.ComboBox centerTransverseRebarTypeComboBox; private System.Windows.Forms.ComboBox endTransverseRebarTypeComboBox; private System.Windows.Forms.Label centerSpacingLabel; private System.Windows.Forms.Label endSpacingLabel; private System.Windows.Forms.TextBox centerSpacingTextBox; private System.Windows.Forms.TextBox endSpacingTextBox; private System.Windows.Forms.Label rebarQuantityLabel; private System.Windows.Forms.Button okButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.GroupBox hookTypeGroupBox; private System.Windows.Forms.ComboBox transverseRebarHookComboBox; private System.Windows.Forms.Label transverseRebarHookLabel; private System.Windows.Forms.Label centerRebarUnitLabel; private System.Windows.Forms.Label endRebarUnitLabel; private System.Windows.Forms.NumericUpDown rebarQuantityNumericUpDown; } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Linq; using System.Text; #pragma warning disable 0618 namespace NLog.UnitTests.Contexts { using System; using System.Collections.Generic; using System.Threading; using Xunit; public class NestedDiagnosticsContextTests { [Fact] public void NDCTest1() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { NestedDiagnosticsContext.Clear(); Assert.Equal(string.Empty, NestedDiagnosticsContext.TopMessage); Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop()); AssertContents(NestedDiagnosticsContext.GetAllMessages()); using (NestedDiagnosticsContext.Push("foo")) { Assert.Equal("foo", NestedDiagnosticsContext.TopMessage); AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo"); using (NestedDiagnosticsContext.Push("bar")) { AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo"); Assert.Equal("bar", NestedDiagnosticsContext.TopMessage); NestedDiagnosticsContext.Push("baz"); AssertContents(NestedDiagnosticsContext.GetAllMessages(), "baz", "bar", "foo"); Assert.Equal("baz", NestedDiagnosticsContext.TopMessage); Assert.Equal("baz", NestedDiagnosticsContext.Pop()); AssertContents(NestedDiagnosticsContext.GetAllMessages(), "bar", "foo"); Assert.Equal("bar", NestedDiagnosticsContext.TopMessage); } AssertContents(NestedDiagnosticsContext.GetAllMessages(), "foo"); Assert.Equal("foo", NestedDiagnosticsContext.TopMessage); } AssertContents(NestedDiagnosticsContext.GetAllMessages()); Assert.Equal(string.Empty, NestedDiagnosticsContext.Pop()); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void NDCTest2() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { NDC.Clear(); Assert.Equal(string.Empty, NDC.TopMessage); Assert.Equal(string.Empty, NDC.Pop()); AssertContents(NDC.GetAllMessages()); using (NDC.Push("foo")) { Assert.Equal("foo", NDC.TopMessage); AssertContents(NDC.GetAllMessages(), "foo"); using (NDC.Push("bar")) { AssertContents(NDC.GetAllMessages(), "bar", "foo"); Assert.Equal("bar", NDC.TopMessage); NDC.Push("baz"); AssertContents(NDC.GetAllMessages(), "baz", "bar", "foo"); Assert.Equal("baz", NDC.TopMessage); Assert.Equal("baz", NDC.Pop()); AssertContents(NDC.GetAllMessages(), "bar", "foo"); Assert.Equal("bar", NDC.TopMessage); } AssertContents(NDC.GetAllMessages(), "foo"); Assert.Equal("foo", NDC.TopMessage); } AssertContents(NDC.GetAllMessages()); Assert.Equal(string.Empty, NDC.Pop()); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } [Fact] public void NDCTest2_object() { List<Exception> exceptions = new List<Exception>(); ManualResetEvent mre = new ManualResetEvent(false); int counter = 100; int remaining = counter; for (int i = 0; i < counter; ++i) { ThreadPool.QueueUserWorkItem( s => { try { NDC.Clear(); Assert.Equal(null, NDC.TopObject); Assert.Equal(null, NDC.PopObject()); AssertContents(NDC.GetAllMessages()); using (NDC.Push("foo")) { Assert.Equal("foo", NDC.TopObject); AssertContents(NDC.GetAllObjects(), "foo"); using (NDC.Push("bar")) { AssertContents(NDC.GetAllObjects(), "bar", "foo"); Assert.Equal("bar", NDC.TopObject); NDC.Push("baz"); AssertContents(NDC.GetAllObjects(), "baz", "bar", "foo"); Assert.Equal("baz", NDC.TopObject); Assert.Equal("baz", NDC.PopObject()); AssertContents(NDC.GetAllObjects(), "bar", "foo"); Assert.Equal("bar", NDC.TopObject); } AssertContents(NDC.GetAllObjects(), "foo"); Assert.Equal("foo", NDC.TopObject); } AssertContents(NDC.GetAllMessages()); Assert.Equal(null, NDC.PopObject()); } catch (Exception ex) { lock (exceptions) { exceptions.Add(ex); } } finally { if (Interlocked.Decrement(ref remaining) == 0) { mre.Set(); } } }); } mre.WaitOne(); StringBuilder exceptionsMessage = new StringBuilder(); foreach (var ex in exceptions) { if (exceptionsMessage.Length > 0) { exceptionsMessage.Append("\r\n"); } exceptionsMessage.Append(ex.ToString()); } Assert.True(exceptions.Count == 0, exceptionsMessage.ToString()); } private static void AssertContents(object[] actual, params string[] expected) { Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } private static void AssertContents(string[] actual, params string[] expected) { Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; ++i) { Assert.Equal(expected[i], actual[i]); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Text; using Microsoft.PowerShell.Commands; namespace System.Management.Automation { using Language; /// <summary> /// The parameter binder for native commands. /// </summary> internal class NativeCommandParameterBinder : ParameterBinderBase { #region ctor /// <summary> /// Constructs a NativeCommandParameterBinder. /// </summary> /// <param name="command"> /// The NativeCommand to bind to. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="command"/>.Context is null /// </exception> internal NativeCommandParameterBinder( NativeCommand command) : base(command.MyInvocation, command.Context, command) { _nativeCommand = command; } #endregion ctor #region internal members #region Parameter binding /// <summary> /// Binds a parameter for a native command (application). /// </summary> /// <param name="name"> /// The name of the parameter to bind the value to. For applications /// this just becomes another parameter... /// </param> /// <param name="value"> /// The value to bind to the parameter. It should be assumed by /// derived classes that the proper type coercion has already taken /// place and that any prerequisite metadata has been satisfied. /// </param> /// <param name="parameterMetadata"></param> internal override void BindParameter(string name, object value, CompiledCommandParameter parameterMetadata) { Diagnostics.Assert(false, "Unreachable code"); throw new NotSupportedException(); } internal override object GetDefaultParameterValue(string name) { return null; } internal void BindParameters(Collection<CommandParameterInternal> parameters) { bool sawVerbatimArgumentMarker = false; bool first = true; foreach (CommandParameterInternal parameter in parameters) { if (!first) { _arguments.Append(' '); } first = false; if (parameter.ParameterNameSpecified) { Diagnostics.Assert(!parameter.ParameterText.Contains(' '), "Parameters cannot have whitespace"); PossiblyGlobArg(parameter.ParameterText, parameter, StringConstantType.BareWord); if (parameter.SpaceAfterParameter) { _arguments.Append(' '); } } if (parameter.ArgumentSpecified) { // If this is the verbatim argument marker, we don't pass it on to the native command. // We do need to remember it though - we'll expand environment variables in subsequent args. object argValue = parameter.ArgumentValue; if (string.Equals("--%", argValue as string, StringComparison.OrdinalIgnoreCase)) { sawVerbatimArgumentMarker = true; continue; } if (argValue != AutomationNull.Value && argValue != UnboundParameter.Value) { // ArrayLiteralAst is used to reconstruct the correct argument, e.g. // windbg -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect // The parser produced an array of strings but marked the parameter so we // can properly reconstruct the correct command line. StringConstantType stringConstantType = StringConstantType.BareWord; ArrayLiteralAst arrayLiteralAst = null; switch (parameter?.ArgumentAst) { case StringConstantExpressionAst sce: stringConstantType = sce.StringConstantType; break; case ExpandableStringExpressionAst ese: stringConstantType = ese.StringConstantType; break; case ArrayLiteralAst ala: arrayLiteralAst = ala; break; } // Prior to PSNativePSPathResolution experimental feature, a single quote worked the same as a double quote // so if the feature is not enabled, we treat any quotes as double quotes. When this feature is no longer // experimental, this code here needs to be removed. if (!ExperimentalFeature.IsEnabled("PSNativePSPathResolution") && stringConstantType == StringConstantType.SingleQuoted) { stringConstantType = StringConstantType.DoubleQuoted; } AppendOneNativeArgument(Context, parameter, argValue, arrayLiteralAst, sawVerbatimArgumentMarker, stringConstantType); } } } } #endregion Parameter binding /// <summary> /// Gets the command arguments in string form. /// </summary> internal string Arguments { get { return _arguments.ToString(); } } private readonly StringBuilder _arguments = new StringBuilder(); internal string[] ArgumentList { get { return _argumentList.ToArray(); } } /// <summary> /// Add an argument to the ArgumentList. /// We may need to construct the argument out of the parameter text and the argument /// in the case that we have a parameter that appears as "-switch:value". /// </summary> /// <param name="parameter">The parameter associated with the operation.</param> /// <param name="argument">The value used with parameter.</param> internal void AddToArgumentList(CommandParameterInternal parameter, string argument) { if (parameter.ParameterNameSpecified && parameter.ParameterText.EndsWith(":")) { if (argument != parameter.ParameterText) { _argumentList.Add(parameter.ParameterText + argument); } } else { _argumentList.Add(argument); } } private readonly List<string> _argumentList = new List<string>(); /// <summary> /// Gets a value indicating whether to use an ArgumentList or string for arguments when invoking a native executable. /// </summary> internal NativeArgumentPassingStyle ArgumentPassingStyle { get { if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSNativeCommandArgumentPassingFeatureName)) { try { // This will default to the new behavior if it is set to anything other than Legacy var preference = LanguagePrimitives.ConvertTo<NativeArgumentPassingStyle>( Context.GetVariableValue(SpecialVariables.NativeArgumentPassingVarPath, NativeArgumentPassingStyle.Standard)); return preference; } catch { // The value is not convertable send back Legacy return NativeArgumentPassingStyle.Legacy; } } return NativeArgumentPassingStyle.Legacy; } } #endregion internal members #region private members /// <summary> /// Stringize a non-IEnum argument to a native command, adding quotes /// and trailing spaces as appropriate. An array gets added as multiple arguments /// each of which will be stringized. /// </summary> /// <param name="context">Execution context instance.</param> /// <param name="parameter">The parameter associated with the operation.</param> /// <param name="obj">The object to append.</param> /// <param name="argArrayAst">If the argument was an array literal, the Ast, otherwise null.</param> /// <param name="sawVerbatimArgumentMarker">True if the argument occurs after --%.</param> /// <param name="stringConstantType">Bare, SingleQuoted, or DoubleQuoted.</param> private void AppendOneNativeArgument(ExecutionContext context, CommandParameterInternal parameter, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, StringConstantType stringConstantType) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); Diagnostics.Assert((argArrayAst == null) || (obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count), "array argument and ArrayLiteralAst differ in number of elements"); int currentElement = -1; string separator = string.Empty; do { string arg; object currentObj; if (list == null) { arg = PSObject.ToStringParser(context, obj); currentObj = obj; } else { if (!ParserOps.MoveNext(context, null, list)) { break; } currentObj = ParserOps.Current(null, list); arg = PSObject.ToStringParser(context, currentObj); currentElement += 1; if (currentElement != 0) { separator = GetEnumerableArgSeparator(argArrayAst, currentElement); } } if (!string.IsNullOrEmpty(arg)) { // Only add the separator to the argument string rather than adding a separator to the ArgumentList. _arguments.Append(separator); if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); // we need to split the argument on spaces _argumentList.AddRange(arg.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } else { // We need to add quotes if the argument has unquoted spaces. The // quotes could appear anywhere inside the string, not just at the start, // e.g. // $a = 'a"b c"d' // echoargs $a 'a"b c"d' a"b c"d // // The above should see 3 identical arguments in argv (the command line will // actually have quotes in different places, but the Win32 command line=>argv parser // erases those differences. // // We need to check quotes that the win32 argument parser checks which is currently // just the normal double quotes, no other special quotes. Also note that mismatched // quotes are supported if (NeedQuotes(arg)) { _arguments.Append('"'); if (stringConstantType == StringConstantType.DoubleQuoted) { _arguments.Append(ResolvePath(arg, Context)); AddToArgumentList(parameter, ResolvePath(arg, Context)); } else { _arguments.Append(arg); AddToArgumentList(parameter, arg); } // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); } _arguments.Append('"'); } else { if (argArrayAst != null && ArgumentPassingStyle == NativeArgumentPassingStyle.Standard) { // We have a literal array, so take the extent, break it on spaces and add them to the argument list. foreach (string element in argArrayAst.Extent.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries)) { PossiblyGlobArg(element, parameter, stringConstantType); } break; } else { PossiblyGlobArg(arg, parameter, stringConstantType); } } } } else if (ArgumentPassingStyle == NativeArgumentPassingStyle.Standard && currentObj != null) { // add empty strings to arglist, but not nulls AddToArgumentList(parameter, arg); } } while (list != null); } /// <summary> /// On Windows, just append <paramref name="arg"/>. /// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>. /// </summary> /// <param name="arg">The argument that possibly needs expansion.</param> /// <param name="parameter">The parameter associated with the operation.</param> /// <param name="stringConstantType">Bare, SingleQuoted, or DoubleQuoted.</param> private void PossiblyGlobArg(string arg, CommandParameterInternal parameter, StringConstantType stringConstantType) { var argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against // the file system just like bash, etc. if (stringConstantType == StringConstantType.BareWord) { if (WildcardPattern.ContainsWildcardCharacters(arg)) { // See if the current working directory is a filesystem provider location // We won't do the expansion if it isn't since native commands can only access the file system. var cwdinfo = Context.EngineSessionState.CurrentLocation; // If it's a filesystem location then expand the wildcards if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { // On UNIX, paths starting with ~ or absolute paths are not normalized bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/'); // See if there are any matching paths otherwise just add the pattern as the argument Collection<PSObject> paths = null; try { paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); } catch { // Fallthrough will append the pattern unchanged. } // Expand paths, but only from the file system. if (paths?.Count > 0 && paths.All(static p => p.BaseObject is FileSystemInfo)) { var sep = string.Empty; foreach (var path in paths) { _arguments.Append(sep); sep = " "; var expandedPath = (path.BaseObject as FileSystemInfo).FullName; if (normalizePath) { expandedPath = Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); } // If the path contains spaces, then add quotes around it. if (NeedQuotes(expandedPath)) { _arguments.Append('"'); _arguments.Append(expandedPath); _arguments.Append('"'); AddToArgumentList(parameter, expandedPath); } else { _arguments.Append(expandedPath); AddToArgumentList(parameter, expandedPath); } argExpanded = true; } } } } else { // Even if there are no wildcards, we still need to possibly // expand ~ into the filesystem provider home directory path ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); string home = fileSystemProvider.Home; if (string.Equals(arg, "~")) { _arguments.Append(home); AddToArgumentList(parameter, home); argExpanded = true; } else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) { string replacementString = string.Concat(home, arg.AsSpan(1)); _arguments.Append(replacementString); AddToArgumentList(parameter, replacementString); argExpanded = true; } } } #endif // UNIX if (stringConstantType != StringConstantType.SingleQuoted) { arg = ResolvePath(arg, Context); } if (!argExpanded) { _arguments.Append(arg); AddToArgumentList(parameter, arg); } } /// <summary> /// Check if string is prefixed by psdrive, if so, expand it if filesystem path. /// </summary> /// <param name="path">The potential PSPath to resolve.</param> /// <param name="context">The current ExecutionContext.</param> /// <returns>Resolved PSPath if applicable otherwise the original path</returns> internal static string ResolvePath(string path, ExecutionContext context) { if (ExperimentalFeature.IsEnabled("PSNativePSPathResolution")) { #if !UNIX // on Windows, we need to expand ~ to point to user's home path if (string.Equals(path, "~", StringComparison.Ordinal) || path.StartsWith(TildeDirectorySeparator, StringComparison.Ordinal) || path.StartsWith(TildeAltDirectorySeparator, StringComparison.Ordinal)) { try { ProviderInfo fileSystemProvider = context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); return new StringBuilder(fileSystemProvider.Home) .Append(path.AsSpan(1)) .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) .ToString(); } catch { return path; } } // check if the driveName is an actual disk drive on Windows, if so, no expansion if (path.Length >= 2 && path[1] == ':') { foreach (var drive in DriveInfo.GetDrives()) { if (drive.Name.StartsWith(new string(path[0], 1), StringComparison.OrdinalIgnoreCase)) { return path; } } } #endif if (path.Contains(':')) { LocationGlobber globber = new LocationGlobber(context.SessionState); try { ProviderInfo providerInfo; // replace the argument with resolved path if it's a filesystem path string pspath = globber.GetProviderPath(path, out providerInfo); if (string.Equals(providerInfo.Name, FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { path = pspath; } } catch { // if it's not a provider path, do nothing } } } return path; } /// <summary> /// Check to see if the string contains spaces and therefore must be quoted. /// </summary> /// <param name="stringToCheck">The string to check for spaces.</param> internal static bool NeedQuotes(string stringToCheck) { bool needQuotes = false, followingBackslash = false; int quoteCount = 0; for (int i = 0; i < stringToCheck.Length; i++) { if (stringToCheck[i] == '"' && !followingBackslash) { quoteCount += 1; } else if (char.IsWhiteSpace(stringToCheck[i]) && (quoteCount % 2 == 0)) { needQuotes = true; } followingBackslash = stringToCheck[i] == '\\'; } return needQuotes; } private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, int index) { if (arrayLiteralAst == null) return " "; // index points to the *next* element, so we're looking for space between // it and the previous element. var next = arrayLiteralAst.Elements[index]; var prev = arrayLiteralAst.Elements[index - 1]; var arrayExtent = arrayLiteralAst.Extent; var afterPrev = prev.Extent.EndOffset; var beforeNext = next.Extent.StartOffset - 1; if (afterPrev == beforeNext) return ","; var arrayText = arrayExtent.Text; afterPrev -= arrayExtent.StartOffset; beforeNext -= arrayExtent.StartOffset; if (arrayText[afterPrev] == ',') return ", "; if (arrayText[beforeNext] == ',') return " ,"; return " , "; } /// <summary> /// The native command to bind to. /// </summary> private readonly NativeCommand _nativeCommand; private static readonly string TildeDirectorySeparator = $"~{Path.DirectorySeparatorChar}"; private static readonly string TildeAltDirectorySeparator = $"~{Path.AltDirectorySeparatorChar}"; #endregion private members } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Text.Tests { public class DecoderConvert2Decoder : Decoder { private Decoder _decoder = null; public DecoderConvert2Decoder() { _decoder = Encoding.UTF8.GetDecoder(); } public override int GetCharCount(byte[] bytes, int index, int count) { return _decoder.GetCharCount(bytes, index, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return _decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } public override void Reset() { _decoder.Reset(); } } // Convert(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32,System.Int32,System.Boolean,System.Int32@,System.Int32@,System.Boolean@) public class DecoderConvert2 { private const int c_SIZE_OF_ARRAY = 127; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); // PosTest1: Call Convert to convert a arbitrary byte array to character array by using ASCII decoder [Fact] public void PosTest1() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = _generator.GetByte(-55); } int bytesUsed; int charsUsed; bool completed; decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, true, out bytesUsed, out charsUsed, out completed); decoder.Reset(); decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, false, out bytesUsed, out charsUsed, out completed); decoder.Reset(); } // PosTest2: Call Convert to convert a arbitrary byte array to character array by using Unicode decoder" [Fact] public void PosTest2() { Decoder decoder = Encoding.Unicode.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY * 2]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = _generator.GetByte(-55); } int bytesUsed; int charsUsed; bool completed; decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, true, out bytesUsed, out charsUsed, out completed); decoder.Reset(); decoder.Convert(bytes, 0, bytes.Length, chars, 0, chars.Length, false, out bytesUsed, out charsUsed, out completed); decoder.Reset(); } // PosTest3: Call Convert to convert a ASCII byte array to character array by using ASCII decoder [Fact] public void PosTest3() { Decoder decoder = Encoding.UTF8.GetDecoder(); char[] chars = new char[c_SIZE_OF_ARRAY]; byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] expected = new char[c_SIZE_OF_ARRAY]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } for (int i = 0; i < expected.Length; ++i) { expected[i] = (char)('\0' + i); } VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "003.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "003.2"); decoder.Reset(); } // PosTest4: Call Convert to convert a ASCII byte array with user implemented decoder [Fact] public void PosTest4() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; char[] expected = new char[bytes.Length]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } for (int i = 0; i < expected.Length; ++i) { expected[i] = (char)('\0' + i); } Decoder decoder = new DecoderConvert2Decoder(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "004.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "004.2"); decoder.Reset(); } // PosTest5: Call Convert to convert partial of a ASCII byte array with ASCII decoder [Fact] public void PosTest5() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.UTF8.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } VerificationHelper(decoder, bytes, 0, 1, chars, 0, 1, false, 1, 1, true, "005.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, 1, chars, 0, 1, true, 1, 1, true, "005.2"); decoder.Reset(); // Verify maxBytes is large than character count VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length - 1, false, bytes.Length - 1, chars.Length - 1, false, "005.3"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length - 1, true, bytes.Length - 1, chars.Length - 1, false, "005.4"); decoder.Reset(); } // PosTest6: Call Convert to convert a ASCII character array with Unicode encoder [Fact] public void PosTest6() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length / 2, true, "006.1"); decoder.Reset(); // There will be 1 byte left unconverted after previous statement, and set flush = false should left this 1 byte in the buffer. VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length / 2 + 1, true, "006.2"); decoder.Reset(); } // PosTest7: Call Convert to convert partial of a ASCII character array with Unicode encoder [Fact] public void PosTest7() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, false, 2, 1, true, "007.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, true, 2, 1, true, "007.2"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, false, 2, 1, false, "007.3"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, true, 2, 1, false, "007.4"); decoder.Reset(); } // PosTest8: Call Convert to convert a unicode character array with Unicode encoder [Fact] public void PosTest8() { char[] expected = "\u8FD9\u4E2A\u4E00\u4E2A\u6D4B\u8BD5".ToCharArray(); byte[] bytes = new byte[] { 217, 143, 42, 78, 0, 78, 42, 78, 75, 109, 213, 139 }; char[] chars = new char[expected.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, false, bytes.Length, chars.Length, true, expected, "008.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, chars.Length, true, bytes.Length, chars.Length, true, expected, "008.2"); decoder.Reset(); } // PosTest9: Call Convert to convert partial of a unicode character array with Unicode encoder [Fact] public void PosTest9() { char[] expected = "\u8FD9".ToCharArray(); char[] chars = new char[expected.Length]; byte[] bytes = new byte[] { 217, 143, 42, 78, 0, 78, 42, 78, 75, 109, 213, 139 }; Decoder decoder = Encoding.Unicode.GetDecoder(); VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, false, 2, 1, true, expected, "009.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, 2, chars, 0, 1, true, 2, 1, true, expected, "009.2"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, false, 2, 1, false, expected, "009.3"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, bytes.Length, chars, 0, 1, true, 2, 1, false, expected, "009.4"); decoder.Reset(); } // PosTest10: Call Convert with ASCII decoder and convert nothing [Fact] public void PosTest10() { byte[] bytes = new byte[c_SIZE_OF_ARRAY]; char[] chars = new char[bytes.Length]; Decoder decoder = Encoding.Unicode.GetDecoder(); for (int i = 0; i < bytes.Length; ++i) { bytes[i] = (byte)i; } VerificationHelper(decoder, bytes, 0, 0, chars, 0, 0, false, 0, 0, true, "010.1"); decoder.Reset(); VerificationHelper(decoder, bytes, 0, 0, chars, 0, chars.Length, true, 0, 0, true, "010.2"); decoder.Reset(); } // NegTest1: ArgumentNullException should be thrown when chars or bytes is a null reference [Fact] public void NegTest1() { Decoder decoder = Encoding.UTF8.GetDecoder(); byte[] b = new byte[c_SIZE_OF_ARRAY]; char[] c = new char[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, c, 0, 0, true, typeof(ArgumentNullException), "101.1"); VerificationHelper<ArgumentNullException>(decoder, b, 0, 0, null, 0, 0, true, typeof(ArgumentNullException), "101.2"); VerificationHelper<ArgumentNullException>(decoder, null, 0, 0, c, 0, 0, false, typeof(ArgumentNullException), "101.3"); VerificationHelper<ArgumentNullException>(decoder, b, 0, 0, null, 0, 0, false, typeof(ArgumentNullException), "101.4"); } // NegTest2: ArgumentOutOfRangeException should be thrown when charIndex, charCount, byteIndex, or byteCount is less than zero. [Fact] public void NegTest2() { Decoder decoder = Encoding.UTF8.GetDecoder(); byte[] b = new byte[c_SIZE_OF_ARRAY]; char[] c = new char[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, b, -1, 0, c, 0, 0, true, typeof(ArgumentOutOfRangeException), "102.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, -1, 0, true, typeof(ArgumentOutOfRangeException), "102.2"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, -1, 0, c, 0, 0, false, typeof(ArgumentOutOfRangeException), "102.3"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, -1, 0, false, typeof(ArgumentOutOfRangeException), "102.4"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, -1, c, 0, 0, true, typeof(ArgumentOutOfRangeException), "102.5"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, 0, -1, true, typeof(ArgumentOutOfRangeException), "102.6"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, -1, c, 0, 0, false, typeof(ArgumentOutOfRangeException), "102.7"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 0, c, 0, -1, false, typeof(ArgumentOutOfRangeException), "102.8"); } // NegTest3: ArgumentException should be thrown when The output buffer is too small to contain any of the converted input [Fact] public void NegTest3() { Decoder decoder = Encoding.Unicode.GetDecoder(); byte[] bytes = new byte[c_SIZE_OF_ARRAY]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = _generator.GetByte(-55); } char[] chars = new char[0]; VerificationHelper<ArgumentException>(decoder, bytes, 0, c_SIZE_OF_ARRAY, chars, 0, 0, true, typeof(ArgumentException), "103.1"); } // NegTest4: ArgumentOutOfRangeException should be thrown when The length of chars - charIndex is less than charCount. [Fact] public void NegTest4() { Decoder decoder = Encoding.UTF8.GetDecoder(); byte[] b = new byte[c_SIZE_OF_ARRAY]; char[] c = new char[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, 1, c, 1, c.Length, true, typeof(ArgumentOutOfRangeException), "104.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 1, c, c.Length, 1, true, typeof(ArgumentOutOfRangeException), "104.2"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, 1, c, 1, c.Length, false, typeof(ArgumentOutOfRangeException), "104.3"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 0, 1, c, c.Length, 1, true, typeof(ArgumentOutOfRangeException), "104.4"); } // NegTest5: ArgumentOutOfRangeException should be thrown when The length of bytes - byteIndex is less than byteCount [Fact] public void NegTest5() { Decoder decoder = Encoding.UTF8.GetDecoder(); byte[] b = new byte[c_SIZE_OF_ARRAY]; char[] c = new char[c_SIZE_OF_ARRAY]; VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, b.Length, c, 1, 0, true, typeof(ArgumentOutOfRangeException), "105.1"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, b.Length, 1, c, 0, 1, true, typeof(ArgumentOutOfRangeException), "105.2"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, 1, b.Length, c, 1, 0, false, typeof(ArgumentOutOfRangeException), "105.3"); VerificationHelper<ArgumentOutOfRangeException>(decoder, b, b.Length, 1, c, 0, 1, true, typeof(ArgumentOutOfRangeException), "105.4"); } private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, int desiredBytesUsed, int desiredCharsUsed, bool desiredCompleted, string errorno) { int bytesUsed; int charsUsed; bool completed; decoder.Convert(bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); Assert.Equal(desiredBytesUsed, bytesUsed); Assert.Equal(desiredCharsUsed, charsUsed); Assert.Equal(desiredCompleted, completed); } private void VerificationHelper(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, int desiredBytesUsed, int desiredCharsUsed, bool desiredCompleted, char[] desiredChars, string errorno) { VerificationHelper(decoder, bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, desiredBytesUsed, desiredCharsUsed, desiredCompleted, errorno + ".1"); Assert.Equal(desiredChars.Length, chars.Length); for (int i = 0; i < chars.Length; ++i) { Assert.Equal(desiredChars[i], chars[i]); } } private void VerificationHelper<T>(Decoder decoder, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, Type expected, string errorno) where T : Exception { string str = null; int bytesUsed; int charsUsed; bool completed; str = new string(chars); Assert.Throws<T>(() => { decoder.Convert(bytes, byteIndex, byteCount, chars, charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); }); } } }
//--------------------------------------------------------------------- // <copyright file="TypeSystem.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Utility functions for processing Expression trees // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services.Client { using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; /// <summary>Utility functions for processing Expression trees</summary> internal static class TypeSystem { /// <summary> Method map for methods in URI query options</summary> private static readonly Dictionary<MethodInfo, string> expressionMethodMap; /// <summary> VB Method map for methods in URI query options</summary> private static readonly Dictionary<string, string> expressionVBMethodMap; /// <summary> Properties that should be represented as methods</summary> private static readonly Dictionary<PropertyInfo, MethodInfo> propertiesAsMethodsMap; /// <summary> VB Assembly name</summary> #if !ASTORIA_LIGHT private const string VisualBasicAssemblyFullName = "Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken; #else private const string VisualBasicAssemblyFullName = "Microsoft.VisualBasic, Version=2.0.5.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftSilverlightPublicKeyToken; #endif /// <summary> /// Initializes method map /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Cleaner code")] static TypeSystem() { // string functions #if !ASTORIA_LIGHT const int ExpectedCount = 24; #else const int ExpectedCount = 22; #endif expressionMethodMap = new Dictionary<MethodInfo, string>(ExpectedCount, EqualityComparer<MethodInfo>.Default); expressionMethodMap.Add(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }), @"substringof"); expressionMethodMap.Add(typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) }), @"endswith"); expressionMethodMap.Add(typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) }), @"startswith"); expressionMethodMap.Add(typeof(string).GetMethod("IndexOf", new Type[] { typeof(string) }), @"indexof"); expressionMethodMap.Add(typeof(string).GetMethod("Replace", new Type[] { typeof(string), typeof(string) }), @"replace"); expressionMethodMap.Add(typeof(string).GetMethod("Substring", new Type[] { typeof(int) }), @"substring"); expressionMethodMap.Add(typeof(string).GetMethod("Substring", new Type[] { typeof(int), typeof(int) }), @"substring"); expressionMethodMap.Add(typeof(string).GetMethod("ToLower", Type.EmptyTypes), @"tolower"); expressionMethodMap.Add(typeof(string).GetMethod("ToUpper", Type.EmptyTypes), @"toupper"); expressionMethodMap.Add(typeof(string).GetMethod("Trim", Type.EmptyTypes), @"trim"); expressionMethodMap.Add(typeof(string).GetMethod("Concat", new Type[] { typeof(string), typeof(string) }, null), @"concat"); expressionMethodMap.Add(typeof(string).GetProperty("Length", typeof(int)).GetGetMethod(), @"length"); // datetime methods expressionMethodMap.Add(typeof(DateTime).GetProperty("Day", typeof(int)).GetGetMethod(), @"day"); expressionMethodMap.Add(typeof(DateTime).GetProperty("Hour", typeof(int)).GetGetMethod(), @"hour"); expressionMethodMap.Add(typeof(DateTime).GetProperty("Month", typeof(int)).GetGetMethod(), @"month"); expressionMethodMap.Add(typeof(DateTime).GetProperty("Minute", typeof(int)).GetGetMethod(), @"minute"); expressionMethodMap.Add(typeof(DateTime).GetProperty("Second", typeof(int)).GetGetMethod(), @"second"); expressionMethodMap.Add(typeof(DateTime).GetProperty("Year", typeof(int)).GetGetMethod(), @"year"); // math methods expressionMethodMap.Add(typeof(Math).GetMethod("Round", new Type[] { typeof(double) }), @"round"); expressionMethodMap.Add(typeof(Math).GetMethod("Round", new Type[] { typeof(decimal) }), @"round"); expressionMethodMap.Add(typeof(Math).GetMethod("Floor", new Type[] { typeof(double) }), @"floor"); #if !ASTORIA_LIGHT // Math.Floor(Decimal) not available expressionMethodMap.Add(typeof(Math).GetMethod("Floor", new Type[] { typeof(decimal) }), @"floor"); #endif expressionMethodMap.Add(typeof(Math).GetMethod("Ceiling", new Type[] { typeof(double) }), @"ceiling"); #if !ASTORIA_LIGHT // Math.Ceiling(Decimal) not available expressionMethodMap.Add(typeof(Math).GetMethod("Ceiling", new Type[] { typeof(decimal) }), @"ceiling"); #endif Debug.Assert(expressionMethodMap.Count == ExpectedCount, "expressionMethodMap.Count == ExpectedCount"); // vb methods // lookup these by type name + method name expressionVBMethodMap = new Dictionary<string, string>(EqualityComparer<string>.Default); expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.Trim", @"trim"); expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.Len", @"length"); expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.Mid", @"substring"); expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.UCase", @"toupper"); expressionVBMethodMap.Add("Microsoft.VisualBasic.Strings.LCase", @"tolower"); expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Year", @"year"); expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Month", @"month"); expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Day", @"day"); expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Hour", @"hour"); expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Minute", @"minute"); expressionVBMethodMap.Add("Microsoft.VisualBasic.DateAndTime.Second", @"second"); Debug.Assert(expressionVBMethodMap.Count == 11, "expressionVBMethodMap.Count == 11"); propertiesAsMethodsMap = new Dictionary<PropertyInfo, MethodInfo>(EqualityComparer<PropertyInfo>.Default); propertiesAsMethodsMap.Add( typeof(string).GetProperty("Length", typeof(int)), typeof(string).GetProperty("Length", typeof(int)).GetGetMethod()); propertiesAsMethodsMap.Add( typeof(DateTime).GetProperty("Day", typeof(int)), typeof(DateTime).GetProperty("Day", typeof(int)).GetGetMethod()); propertiesAsMethodsMap.Add( typeof(DateTime).GetProperty("Hour", typeof(int)), typeof(DateTime).GetProperty("Hour", typeof(int)).GetGetMethod()); propertiesAsMethodsMap.Add( typeof(DateTime).GetProperty("Minute", typeof(int)), typeof(DateTime).GetProperty("Minute", typeof(int)).GetGetMethod()); propertiesAsMethodsMap.Add( typeof(DateTime).GetProperty("Second", typeof(int)), typeof(DateTime).GetProperty("Second", typeof(int)).GetGetMethod()); propertiesAsMethodsMap.Add( typeof(DateTime).GetProperty("Month", typeof(int)), typeof(DateTime).GetProperty("Month", typeof(int)).GetGetMethod()); propertiesAsMethodsMap.Add( typeof(DateTime).GetProperty("Year", typeof(int)), typeof(DateTime).GetProperty("Year", typeof(int)).GetGetMethod()); Debug.Assert(propertiesAsMethodsMap.Count == 7, "propertiesAsMethodsMap.Count == 7"); } /// <summary> /// Sees if method has URI equivalent /// </summary> /// <param name="mi">The method info</param> /// <param name="methodName">uri method name</param> /// <returns>true/ false</returns> internal static bool TryGetQueryOptionMethod(MethodInfo mi, out string methodName) { return (expressionMethodMap.TryGetValue(mi, out methodName) || (mi.DeclaringType.Assembly.FullName == VisualBasicAssemblyFullName && expressionVBMethodMap.TryGetValue(mi.DeclaringType.FullName + "." + mi.Name, out methodName))); } /// <summary> /// Sees if property can be represented as method for translation to URI /// </summary> /// <param name="pi">The property info</param> /// <param name="mi">get method for property</param> /// <returns>true/ false</returns> internal static bool TryGetPropertyAsMethod(PropertyInfo pi, out MethodInfo mi) { return propertiesAsMethodsMap.TryGetValue(pi, out mi); } /// <summary> /// Gets the elementtype for a sequence /// </summary> /// <param name="seqType">The sequence type</param> /// <returns>The element type</returns> internal static Type GetElementType(Type seqType) { Type ienum = FindIEnumerable(seqType); if (ienum == null) { return seqType; } return ienum.GetGenericArguments()[0]; } /// <summary> /// Determines whether a property is private /// </summary> /// <param name="pi">The PropertyInfo structure for the property</param> /// <returns>true/ false if property is private</returns> internal static bool IsPrivate(PropertyInfo pi) { MethodInfo mi = pi.GetGetMethod() ?? pi.GetSetMethod(); if (mi != null) { return mi.IsPrivate; } return true; } /// <summary> /// Finds type that implements IEnumerable so can get elemtent type /// </summary> /// <param name="seqType">The Type to check</param> /// <returns>returns the type which implements IEnumerable</returns> internal static Type FindIEnumerable(Type seqType) { if (seqType == null || seqType == typeof(string)) { return null; } if (seqType.IsArray) { return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType()); } if (seqType.IsGenericType) { foreach (Type arg in seqType.GetGenericArguments()) { Type ienum = typeof(IEnumerable<>).MakeGenericType(arg); if (ienum.IsAssignableFrom(seqType)) { return ienum; } } } Type[] ifaces = seqType.GetInterfaces(); if (ifaces != null && ifaces.Length > 0) { foreach (Type iface in ifaces) { Type ienum = FindIEnumerable(iface); if (ienum != null) { return ienum; } } } if (seqType.BaseType != null && seqType.BaseType != typeof(object)) { return FindIEnumerable(seqType.BaseType); } return null; } } }
using System; using System.Diagnostics; using System.Text; using u32 = System.UInt32; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2004 April 13 ** ** 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 routines used to translate between UTF-8, ** UTF-16, UTF-16BE, and UTF-16LE. ** ** Notes on UTF-8: ** ** Byte-0 Byte-1 Byte-2 Byte-3 Value ** 0xxxxxxx 00000000 00000000 0xxxxxxx ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** ** ** Notes on UTF-16: (with wwww+1==uuuuu) ** ** Word-0 Word-1 Value ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx ** ** ** BOM or Byte Order Mark: ** 0xff 0xfe little-endian utf-16 follows ** 0xfe 0xff big-endian utf-16 follows ** ************************************************************************* ** 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: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <assert.h> //#include "vdbeInt.h" #if !SQLITE_AMALGAMATION /* ** The following constant value is used by the SQLITE_BIGENDIAN and ** SQLITE_LITTLEENDIAN macros. */ //const int sqlite3one = 1; #endif //* SQLITE_AMALGAMATION */ /* ** This lookup table is used to help decode the first byte of ** a multi-byte UTF8 character. */ static byte[] sqlite3Utf8Trans1 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; //#define WRITE_UTF8(zOut, c) { \ // if( c<0x00080 ){ \ // *zOut++ = (u8)(c&0xFF); \ // } \ // else if( c<0x00800 ){ \ // *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // } \ // else if( c<0x10000 ){ \ // *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ // *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // }else{ \ // *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ // *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ // *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ // *zOut++ = 0x80 + (u8)(c & 0x3F); \ // } \ //} //#define WRITE_UTF16LE(zOut, c) { \ // if( c<=0xFFFF ){ \ // *zOut++ = (u8)(c&0x00FF); \ // *zOut++ = (u8)((c>>8)&0x00FF); \ // }else{ \ // *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ // *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ // *zOut++ = (u8)(c&0x00FF); \ // *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ // } \ //} //#define WRITE_UTF16BE(zOut, c) { \ // if( c<=0xFFFF ){ \ // *zOut++ = (u8)((c>>8)&0x00FF); \ // *zOut++ = (u8)(c&0x00FF); \ // }else{ \ // *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \ // *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \ // *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \ // *zOut++ = (u8)(c&0x00FF); \ // } \ //} //#define READ_UTF16LE(zIn, TERM, c){ \ // c = (*zIn++); \ // c += ((*zIn++)<<8); \ // if( c>=0xD800 && c<0xE000 && TERM ){ \ // int c2 = (*zIn++); \ // c2 += ((*zIn++)<<8); \ // c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ // } \ //} //#define READ_UTF16BE(zIn, TERM, c){ \ // c = ((*zIn++)<<8); \ // c += (*zIn++); \ // if( c>=0xD800 && c<0xE000 && TERM ){ \ // int c2 = ((*zIn++)<<8); \ // c2 += (*zIn++); \ // c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \ // } \ //} /* ** Translate a single UTF-8 character. Return the unicode value. ** ** During translation, assume that the byte that zTerm points ** is a 0x00. ** ** Write a pointer to the next unread byte back into pzNext. ** ** Notes On Invalid UTF-8: ** ** * This routine never allows a 7-bit character (0x00 through 0x7f) to ** be encoded as a multi-byte character. Any multi-byte character that ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd. ** ** * This routine never allows a UTF16 surrogate value to be encoded. ** If a multi-byte character attempts to encode a value between ** 0xd800 and 0xe000 then it is rendered as 0xfffd. ** ** * Bytes in the range of 0x80 through 0xbf which occur as the first ** byte of a character are interpreted as single-byte characters ** and rendered as themselves even though they are technically ** invalid characters. ** ** * This routine accepts an infinite number of different UTF8 encodings ** for unicode values 0x80 and greater. It do not change over-length ** encodings to 0xfffd as some systems recommend. */ //#define READ_UTF8(zIn, zTerm, c) \ // c = *(zIn++); \ // if( c>=0xc0 ){ \ // c = sqlite3Utf8Trans1[c-0xc0]; \ // while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ // c = (c<<6) + (0x3f & *(zIn++)); \ // } \ // if( c<0x80 \ // || (c&0xFFFFF800)==0xD800 \ // || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ // } static u32 sqlite3Utf8Read( string zIn, /* First byte of UTF-8 character */ ref string pzNext /* Write first byte past UTF-8 char here */ ) { //unsigned int c; /* Same as READ_UTF8() above but without the zTerm parameter. ** For this routine, we assume the UTF8 string is always zero-terminated. */ if ( String.IsNullOrEmpty( zIn ) ) return 0; //c = *( zIn++ ); //if ( c >= 0xc0 ) //{ // c = sqlite3Utf8Trans1[c - 0xc0]; // while ( ( *zIn & 0xc0 ) == 0x80 ) // { // c = ( c << 6 ) + ( 0x3f & *( zIn++ ) ); // } // if ( c < 0x80 // || ( c & 0xFFFFF800 ) == 0xD800 // || ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; } //} //*pzNext = zIn; int zIndex = 0; u32 c = zIn[zIndex++]; if ( c >= 0xc0 ) { //if ( c > 0xff ) c = 0; //else { //c = sqlite3Utf8Trans1[c - 0xc0]; while ( zIndex != zIn.Length && ( zIn[zIndex] & 0xc0 ) == 0x80 ) { c = (u32)( ( c << 6 ) + ( 0x3f & zIn[zIndex++] ) ); } if ( c < 0x80 || ( c & 0xFFFFF800 ) == 0xD800 || ( c & 0xFFFFFFFE ) == 0xFFFE ) { c = 0xFFFD; } } } pzNext = zIn.Substring( zIndex ); return c; } /* ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate(). */ /* #define TRANSLATE_TRACE 1 */ #if NO_SQLITE_OMIT_UTF16 //#if !SQLITE_OMIT_UTF16 /* ** This routine transforms the internal text encoding used by pMem to ** desiredEnc. It is an error if the string is already of the desired ** encoding, or if pMem does not contain a string value. */ static int sqlite3VdbeMemTranslate(Mem pMem, int desiredEnc){ int len; /* Maximum length of output string in bytes */ Debugger.Break (); // TODO - //unsigned char *zOut; /* Output buffer */ //unsigned char *zIn; /* Input iterator */ //unsigned char *zTerm; /* End of input */ //unsigned char *z; /* Output iterator */ //unsigned int c; Debug.Assert( pMem.db==null || sqlite3_mutex_held(pMem.db.mutex) ); Debug.Assert( (pMem.flags&MEM_Str )!=0); Debug.Assert( pMem.enc!=desiredEnc ); Debug.Assert( pMem.enc!=0 ); Debug.Assert( pMem.n>=0 ); #if TRANSLATE_TRACE && SQLITE_DEBUG { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "INPUT: %s\n", zBuf); } #endif /* If the translation is between UTF-16 little and big endian, then ** all that is required is to swap the byte order. This case is handled ** differently from the others. */ Debugger.Break (); // TODO - //if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ // u8 temp; // int rc; // rc = sqlite3VdbeMemMakeWriteable(pMem); // if( rc!=SQLITE_OK ){ // Debug.Assert( rc==SQLITE_NOMEM ); // return SQLITE_NOMEM; // } // zIn = (u8*)pMem.z; // zTerm = &zIn[pMem->n&~1]; // while( zIn<zTerm ){ // temp = *zIn; // *zIn = *(zIn+1); // zIn++; // *zIn++ = temp; // } // pMem->enc = desiredEnc; // goto translate_out; //} /* Set len to the maximum number of bytes required in the output buffer. */ if( desiredEnc==SQLITE_UTF8 ){ /* When converting from UTF-16, the maximum growth results from ** translating a 2-byte character to a 4-byte UTF-8 character. ** A single byte is required for the output string ** nul-terminator. */ pMem->n &= ~1; len = pMem.n * 2 + 1; }else{ /* When converting from UTF-8 to UTF-16 the maximum growth is caused ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 ** character. Two bytes are required in the output buffer for the ** nul-terminator. */ len = pMem.n * 2 + 2; } /* Set zIn to point at the start of the input buffer and zTerm to point 1 ** byte past the end. ** ** Variable zOut is set to point at the output buffer, space obtained ** from sqlite3Malloc(). */ Debugger.Break (); // TODO - //zIn = (u8*)pMem.z; //zTerm = &zIn[pMem->n]; //zOut = sqlite3DbMallocRaw(pMem->db, len); //if( !zOut ){ // return SQLITE_NOMEM; //} //z = zOut; //if( pMem->enc==SQLITE_UTF8 ){ // if( desiredEnc==SQLITE_UTF16LE ){ // /* UTF-8 -> UTF-16 Little-endian */ // while( zIn<zTerm ){ ///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */ //READ_UTF8(zIn, zTerm, c); // WRITE_UTF16LE(z, c); // } // }else{ // Debug.Assert( desiredEnc==SQLITE_UTF16BE ); // /* UTF-8 -> UTF-16 Big-endian */ // while( zIn<zTerm ){ ///* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */ //READ_UTF8(zIn, zTerm, c); // WRITE_UTF16BE(z, c); // } // } // pMem->n = (int)(z - zOut); // *z++ = 0; //}else{ // Debug.Assert( desiredEnc==SQLITE_UTF8 ); // if( pMem->enc==SQLITE_UTF16LE ){ // /* UTF-16 Little-endian -> UTF-8 */ // while( zIn<zTerm ){ // READ_UTF16LE(zIn, zIn<zTerm, c); // WRITE_UTF8(z, c); // } // }else{ // /* UTF-16 Big-endian -> UTF-8 */ // while( zIn<zTerm ){ // READ_UTF16BE(zIn, zIn<zTerm, c); // WRITE_UTF8(z, c); // } // } // pMem->n = (int)(z - zOut); //} //*z = 0; //Debug.Assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); //sqlite3VdbeMemRelease(pMem); //pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem); //pMem->enc = desiredEnc; //pMem->flags |= (MEM_Term|MEM_Dyn); //pMem.z = (char*)zOut; //pMem.zMalloc = pMem.z; translate_out: #if TRANSLATE_TRACE && SQLITE_DEBUG { char zBuf[100]; sqlite3VdbeMemPrettyPrint(pMem, zBuf); fprintf(stderr, "OUTPUT: %s\n", zBuf); } #endif return SQLITE_OK; } /* ** This routine checks for a byte-order mark at the beginning of the ** UTF-16 string stored in pMem. If one is present, it is removed and ** the encoding of the Mem adjusted. This routine does not do any ** byte-swapping, it just sets Mem.enc appropriately. ** ** The allocation (static, dynamic etc.) and encoding of the Mem may be ** changed by this function. */ static int sqlite3VdbeMemHandleBom(Mem pMem){ int rc = SQLITE_OK; int bom = 0; byte[] b01 = new byte[2]; Encoding.Unicode.GetBytes( pMem.z, 0, 1,b01,0 ); assert( pMem->n>=0 ); if( pMem->n>1 ){ // u8 b1 = *(u8 *)pMem.z; // u8 b2 = *(((u8 *)pMem.z) + 1); if( b01[0]==0xFE && b01[1]==0xFF ){// if( b1==0xFE && b2==0xFF ){ bom = SQLITE_UTF16BE; } if( b01[0]==0xFF && b01[1]==0xFE ){ // if( b1==0xFF && b2==0xFE ){ bom = SQLITE_UTF16LE; } } if( bom!=0 ){ rc = sqlite3VdbeMemMakeWriteable(pMem); if( rc==SQLITE_OK ){ pMem.n -= 2; Debugger.Break (); // TODO - //memmove(pMem.z, pMem.z[2], pMem.n); //pMem.z[pMem.n] = '\0'; //pMem.z[pMem.n+1] = '\0'; pMem.flags |= MEM_Term; pMem.enc = bom; } } return rc; } #endif // * SQLITE_OMIT_UTF16 */ /* ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero, ** return the number of unicode characters in pZ up to (but not including) ** the first 0x00 byte. If nByte is not less than zero, return the ** number of unicode characters in the first nByte of pZ (or up to ** the first 0x00, whichever comes first). */ static int sqlite3Utf8CharLen( string zIn, int nByte ) { //int r = 0; //string z = zIn; if ( zIn.Length == 0 ) return 0; int zInLength = zIn.Length; int zTerm = ( nByte >= 0 && nByte <= zInLength ) ? nByte : zInLength; //Debug.Assert( z<=zTerm ); //for ( int i = 0 ; i < zTerm ; i++ ) //while( *z!=0 && z<zTerm ){ //{ // SQLITE_SKIP_UTF8( ref z);// SQLITE_SKIP_UTF8(z); // r++; //} //return r; if ( zTerm == zInLength ) return zInLength - ( zIn[zTerm - 1] == 0 ? 1 : 0 ); else return nByte; } /* This test function is not currently used by the automated test-suite. ** Hence it is only available in debug builds. */ #if SQLITE_TEST && SQLITE_DEBUG /* ** Translate UTF-8 to UTF-8. ** ** This has the effect of making sure that the string is well-formed ** UTF-8. Miscoded characters are removed. ** ** The translation is done in-place and aborted if the output ** overruns the input. */ static int sqlite3Utf8To8(byte[] zIn){ //byte[] zOut = zIn; //byte[] zStart = zIn; //u32 c; // while( zIn[0] && zOut<=zIn ){ // c = sqlite3Utf8Read(zIn, (const u8**)&zIn); // if( c!=0xfffd ){ // WRITE_UTF8(zOut, c); // } //} //zOut = 0; //return (int)(zOut - zStart); try { string z1 = Encoding.UTF8.GetString( zIn, 0, zIn.Length ); byte[] zOut = Encoding.UTF8.GetBytes( z1 ); //if ( zOut.Length != zIn.Length ) // return 0; //else { Array.Copy( zOut, 0, zIn, 0,zIn.Length ); return zIn.Length;} } catch ( EncoderFallbackException e ) { return 0; } } #endif #if NO_SQLITE_OMIT_UTF16 //#if !SQLITE_OMIT_UTF16 /* ** Convert a UTF-16 string in the native encoding into a UTF-8 string. ** Memory to hold the UTF-8 string is obtained from sqlite3Malloc and must ** be freed by the calling function. ** ** NULL is returned if there is an allocation error. */ static string sqlite3Utf16to8(sqlite3 db, string z, int nByte, u8 enc){ Debugger.Break (); // TODO - Mem m = Pool.Allocate_Mem(); // memset(&m, 0, sizeof(m)); // m.db = db; // sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC); // sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8); // if( db.mallocFailed !=0{ // sqlite3VdbeMemRelease(&m); // m.z = 0; // } // Debug.Assert( (m.flags & MEM_Term)!=0 || db.mallocFailed !=0); // Debug.Assert( (m.flags & MEM_Str)!=0 || db.mallocFailed !=0); assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed ); assert( m.z || db->mallocFailed ); return m.z; } /* ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter ** enc. A pointer to the new string is returned, and the value of *pnOut ** is set to the length of the returned string in bytes. The call should ** arrange to call sqlite3DbFree() on the returned pointer when it is ** no longer required. ** ** If a malloc failure occurs, NULL is returned and the db.mallocFailed ** flag set. */ #if SQLITE_ENABLE_STAT2 char *sqlite3Utf8to16(sqlite3 db, u8 enc, char *z, int n, int *pnOut){ Mem m; memset(&m, 0, sizeof(m)); m.db = db; sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC); if( sqlite3VdbeMemTranslate(&m, enc) ){ assert( db->mallocFailed ); return 0; } assert( m.z==m.zMalloc ); *pnOut = m.n; return m.z; } #endif /* ** zIn is a UTF-16 encoded unicode string at least nChar characters long. ** Return the number of bytes in the first nChar unicode characters ** in pZ. nChar must be non-negative. */ int sqlite3Utf16ByteLen(const void *zIn, int nChar){ int c; unsigned char const *z = zIn; int n = 0; if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){ while( n<nChar ){ READ_UTF16BE(z, 1, c); n++; } }else{ while( n<nChar ){ READ_UTF16LE(z, 1, c); n++; } } return (int)(z-(unsigned char const *)zIn); } #if SQLITE_TEST /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ /* ** This routine is called from the TCL test function "translate_selftest". ** It checks that the primitives for serializing and deserializing ** characters in each encoding are inverses of each other. */ void sqlite3UtfSelfTest(void){ unsigned int i, t; unsigned char zBuf[20]; unsigned char *z; int n; unsigned int c; for(i=0; i<0x00110000; i++){ z = zBuf; WRITE_UTF8(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; c = sqlite3Utf8Read(z, (const u8**)&z); t = i; if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD; if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD; assert( c==t ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16LE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16LE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } for(i=0; i<0x00110000; i++){ if( i>=0xD800 && i<0xE000 ) continue; z = zBuf; WRITE_UTF16BE(z, i); n = (int)(z-zBuf); assert( n>0 && n<=4 ); z[0] = 0; z = zBuf; READ_UTF16BE(z, 1, c); assert( c==i ); assert( (z-zBuf)==n ); } } #endif // * SQLITE_TEST */ #endif // * SQLITE_OMIT_UTF16 */ } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Globalization; using System.IO; using System.Net.Mime; using System.Runtime; using System.Runtime.Diagnostics; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.Text; using System.Xml; class TextMessageEncoderFactory : MessageEncoderFactory { TextMessageEncoder messageEncoder; internal static ContentEncoding[] Soap11Content = GetContentEncodingMap(MessageVersion.Soap11WSAddressing10); internal static ContentEncoding[] Soap12Content = GetContentEncodingMap(MessageVersion.Soap12WSAddressing10); internal static ContentEncoding[] SoapNoneContent = GetContentEncodingMap(MessageVersion.None); internal const string Soap11MediaType = "text/xml"; internal const string Soap12MediaType = "application/soap+xml"; const string XmlMediaType = "application/xml"; public TextMessageEncoderFactory(MessageVersion version, Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas) { messageEncoder = new TextMessageEncoder(version, writeEncoding, maxReadPoolSize, maxWritePoolSize, quotas); } public override MessageEncoder Encoder { get { return messageEncoder; } } public override MessageVersion MessageVersion { get { return messageEncoder.MessageVersion; } } public int MaxWritePoolSize { get { return messageEncoder.MaxWritePoolSize; } } public int MaxReadPoolSize { get { return messageEncoder.MaxReadPoolSize; } } public static Encoding[] GetSupportedEncodings() { Encoding[] supported = TextEncoderDefaults.SupportedEncodings; Encoding[] enc = new Encoding[supported.Length]; Array.Copy(supported, enc, supported.Length); return enc; } public XmlDictionaryReaderQuotas ReaderQuotas { get { return messageEncoder.ReaderQuotas; } } internal static string GetMediaType(MessageVersion version) { string mediaType = null; if (version.Envelope == EnvelopeVersion.Soap12) { mediaType = TextMessageEncoderFactory.Soap12MediaType; } else if (version.Envelope == EnvelopeVersion.Soap11) { mediaType = TextMessageEncoderFactory.Soap11MediaType; } else if (version.Envelope == EnvelopeVersion.None) { mediaType = TextMessageEncoderFactory.XmlMediaType; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.EnvelopeVersionNotSupported, version.Envelope))); } return mediaType; } internal static string GetContentType(string mediaType, Encoding encoding) { return String.Format(CultureInfo.InvariantCulture, "{0}; charset={1}", mediaType, TextEncoderDefaults.EncodingToCharSet(encoding)); } static ContentEncoding[] GetContentEncodingMap(MessageVersion version) { Encoding[] readEncodings = TextMessageEncoderFactory.GetSupportedEncodings(); string media = GetMediaType(version); ContentEncoding[] map = new ContentEncoding[readEncodings.Length]; for (int i = 0; i < readEncodings.Length; i++) { ContentEncoding contentEncoding = new ContentEncoding(); contentEncoding.contentType = GetContentType(media, readEncodings[i]); contentEncoding.encoding = readEncodings[i]; map[i] = contentEncoding; } return map; } internal static Encoding GetEncodingFromContentType(string contentType, ContentEncoding[] contentMap) { if (contentType == null) { return null; } // Check for known/expected content types for (int i = 0; i < contentMap.Length; i++) { if (contentMap[i].contentType == contentType) { return contentMap[i].encoding; } } // then some heuristic matches (since System.Mime.ContentType is a performance hit) // start by looking for a parameter. // If none exists, we don't have an encoding int semiColonIndex = contentType.IndexOf(';'); if (semiColonIndex == -1) { return null; } // optimize for charset being the first parameter int charsetValueIndex = -1; // for Indigo scenarios, we'll have "; charset=", so check for the c if ((contentType.Length > semiColonIndex + 11) // need room for parameter + charset + '=' && contentType[semiColonIndex + 2] == 'c' && string.Compare("charset=", 0, contentType, semiColonIndex + 2, 8, StringComparison.OrdinalIgnoreCase) == 0) { charsetValueIndex = semiColonIndex + 10; } else { // look for charset= somewhere else in the message int paramIndex = contentType.IndexOf("charset=", semiColonIndex + 1, StringComparison.OrdinalIgnoreCase); if (paramIndex != -1) { // validate there's only whitespace or semi-colons beforehand for (int i = paramIndex - 1; i >= semiColonIndex; i--) { if (contentType[i] == ';') { charsetValueIndex = paramIndex + 8; break; } if (contentType[i] == '\n') { if (i == semiColonIndex || contentType[i - 1] != '\r') { break; } i--; continue; } if (contentType[i] != ' ' && contentType[i] != '\t') { break; } } } } string charSet; Encoding enc; // we have a possible charset value. If it's easy to parse, do so if (charsetValueIndex != -1) { // get the next semicolon semiColonIndex = contentType.IndexOf(';', charsetValueIndex); if (semiColonIndex == -1) { charSet = contentType.Substring(charsetValueIndex); } else { charSet = contentType.Substring(charsetValueIndex, semiColonIndex - charsetValueIndex); } // and some minimal quote stripping if (charSet.Length > 2 && charSet[0] == '"' && charSet[charSet.Length - 1] == '"') { charSet = charSet.Substring(1, charSet.Length - 2); } Fx.Assert(charSet == (new ContentType(contentType)).CharSet, "CharSet parsing failed to correctly parse the ContentType header."); if (TryGetEncodingFromCharSet(charSet, out enc)) { return enc; } } // our quick heuristics failed. fall back to System.Net try { ContentType parsedContentType = new ContentType(contentType); charSet = parsedContentType.CharSet; } catch (FormatException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.EncoderBadContentType), e)); } if (TryGetEncodingFromCharSet(charSet, out enc)) return enc; throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.EncoderUnrecognizedCharSet, charSet))); } internal static bool TryGetEncodingFromCharSet(string charSet, out Encoding encoding) { encoding = null; if (charSet == null || charSet.Length == 0) return true; return TextEncoderDefaults.TryGetEncoding(charSet, out encoding); } internal class ContentEncoding { internal string contentType; internal Encoding encoding; } class TextMessageEncoder : MessageEncoder, ITraceSourceStringProvider { int maxReadPoolSize; int maxWritePoolSize; // Double-checked locking pattern requires volatile for read/write synchronization volatile SynchronizedPool<XmlDictionaryWriter> streamedWriterPool; volatile SynchronizedPool<XmlDictionaryReader> streamedReaderPool; volatile SynchronizedPool<UTF8BufferedMessageData> bufferedReaderPool; volatile SynchronizedPool<TextBufferedMessageWriter> bufferedWriterPool; volatile SynchronizedPool<RecycledMessageState> recycledStatePool; object thisLock; string contentType; string mediaType; Encoding writeEncoding; MessageVersion version; bool optimizeWriteForUTF8; const int maxPooledXmlReadersPerMessage = 2; XmlDictionaryReaderQuotas readerQuotas; XmlDictionaryReaderQuotas bufferedReadReaderQuotas; OnXmlDictionaryReaderClose onStreamedReaderClose; ContentEncoding[] contentEncodingMap; public TextMessageEncoder(MessageVersion version, Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas) { if (version == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version"); if (writeEncoding == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding"); TextEncoderDefaults.ValidateEncoding(writeEncoding); this.writeEncoding = writeEncoding; optimizeWriteForUTF8 = IsUTF8Encoding(writeEncoding); thisLock = new object(); this.version = version; this.maxReadPoolSize = maxReadPoolSize; this.maxWritePoolSize = maxWritePoolSize; this.readerQuotas = new XmlDictionaryReaderQuotas(); quotas.CopyTo(this.readerQuotas); this.bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(this.readerQuotas); this.onStreamedReaderClose = new OnXmlDictionaryReaderClose(ReturnStreamedReader); this.mediaType = TextMessageEncoderFactory.GetMediaType(version); this.contentType = TextMessageEncoderFactory.GetContentType(mediaType, writeEncoding); if (version.Envelope == EnvelopeVersion.Soap12) { contentEncodingMap = TextMessageEncoderFactory.Soap12Content; } else if (version.Envelope == EnvelopeVersion.Soap11) { contentEncodingMap = TextMessageEncoderFactory.Soap11Content; } else if (version.Envelope == EnvelopeVersion.None) { contentEncodingMap = TextMessageEncoderFactory.SoapNoneContent; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.GetString(SR.EnvelopeVersionNotSupported, version.Envelope))); } } static bool IsUTF8Encoding(Encoding encoding) { return encoding.WebName == "utf-8"; } public override string ContentType { get { return contentType; } } public int MaxWritePoolSize { get { return maxWritePoolSize; } } public int MaxReadPoolSize { get { return maxReadPoolSize; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return readerQuotas; } } public override string MediaType { get { return mediaType; } } public override MessageVersion MessageVersion { get { return version; } } object ThisLock { get { return thisLock; } } internal override bool IsCharSetSupported(string charSet) { Encoding tmp; return TextEncoderDefaults.TryGetEncoding(charSet, out tmp); } public override bool IsContentTypeSupported(string contentType) { if (contentType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType"); } if (base.IsContentTypeSupported(contentType)) { return true; } // we support a few extra content types for "none" if (MessageVersion == MessageVersion.None) { const string rss1MediaType = "text/xml"; const string rss2MediaType = "application/rss+xml"; const string atomMediaType = "application/atom+xml"; const string htmlMediaType = "text/html"; if (IsContentTypeSupported(contentType, rss1MediaType, rss1MediaType)) { return true; } if (IsContentTypeSupported(contentType, rss2MediaType, rss2MediaType)) { return true; } if (IsContentTypeSupported(contentType, htmlMediaType, atomMediaType)) { return true; } if (IsContentTypeSupported(contentType, atomMediaType, atomMediaType)) { return true; } // application/xml checked by base method } return false; } public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType) { if (bufferManager == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bufferManager")); if (TD.TextMessageDecodingStartIsEnabled()) { TD.TextMessageDecodingStart(); } Message message; UTF8BufferedMessageData messageData = TakeBufferedReader(); messageData.Encoding = GetEncodingFromContentType(contentType, this.contentEncodingMap); messageData.Open(buffer, bufferManager); RecycledMessageState messageState = messageData.TakeMessageState(); if (messageState == null) messageState = new RecycledMessageState(); message = new BufferedMessage(messageData, messageState); message.Properties.Encoder = this; if (TD.MessageReadByEncoderIsEnabled() && buffer != null) { TD.MessageReadByEncoder( EventTraceActivityHelper.TryExtractActivity(message, true), buffer.Count, this); } if (MessageLogger.LogMessagesAtTransportLevel) MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive); return message; } public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType) { if (stream == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream")); if (TD.TextMessageDecodingStartIsEnabled()) { TD.TextMessageDecodingStart(); } XmlReader reader = TakeStreamedReader(stream, GetEncodingFromContentType(contentType, this.contentEncodingMap)); Message message = Message.CreateMessage(reader, maxSizeOfHeaders, version); message.Properties.Encoder = this; if (TD.StreamedMessageReadByEncoderIsEnabled()) { TD.StreamedMessageReadByEncoder(EventTraceActivityHelper.TryExtractActivity(message, true)); } if (MessageLogger.LogMessagesAtTransportLevel) MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive); return message; } public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message")); if (bufferManager == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("bufferManager"), message); if (maxMessageSize < 0) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize, SR.GetString(SR.ValueMustBeNonNegative)), message); if (messageOffset < 0 || messageOffset > maxMessageSize) throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset, SR.GetString(SR.ValueMustBeInRange, 0, maxMessageSize)), message); ThrowIfMismatchedMessageVersion(message); EventTraceActivity eventTraceActivity = null; if (TD.TextMessageEncodingStartIsEnabled()) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.TextMessageEncodingStart(eventTraceActivity); } message.Properties.Encoder = this; TextBufferedMessageWriter messageWriter = TakeBufferedWriter(); ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize); ReturnMessageWriter(messageWriter); if (TD.MessageWrittenByEncoderIsEnabled() && messageData != null) { TD.MessageWrittenByEncoder( eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message), messageData.Count, this); } if (MessageLogger.LogMessagesAtTransportLevel) { XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(messageData.Array, messageData.Offset, messageData.Count, null, XmlDictionaryReaderQuotas.Max, null); MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend); } return messageData; } public override void WriteMessage(Message message, Stream stream) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message")); if (stream == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message); ThrowIfMismatchedMessageVersion(message); EventTraceActivity eventTraceActivity = null; if (TD.TextMessageEncodingStartIsEnabled()) { eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.TextMessageEncodingStart(eventTraceActivity); } message.Properties.Encoder = this; XmlDictionaryWriter xmlWriter = TakeStreamedWriter(stream); if (optimizeWriteForUTF8) { message.WriteMessage(xmlWriter); } else { xmlWriter.WriteStartDocument(); message.WriteMessage(xmlWriter); xmlWriter.WriteEndDocument(); } xmlWriter.Flush(); ReturnStreamedWriter(xmlWriter); if (TD.StreamedMessageWrittenByEncoderIsEnabled()) { TD.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message)); } if (MessageLogger.LogMessagesAtTransportLevel) MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend); } public override IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state) { if (message == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message")); if (stream == null) throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message); ThrowIfMismatchedMessageVersion(message); message.Properties.Encoder = this; return new WriteMessageAsyncResult(message, stream, this, callback, state); } public override void EndWriteMessage(IAsyncResult result) { WriteMessageAsyncResult.End(result); } class WriteMessageAsyncResult : AsyncResult { static AsyncCompletion onWriteMessage = new AsyncCompletion(OnWriteMessage); Message message; TextMessageEncoder textEncoder; XmlDictionaryWriter xmlWriter; EventTraceActivity eventTraceActivity; public WriteMessageAsyncResult(Message message, Stream stream, TextMessageEncoder textEncoder, AsyncCallback callback, object state) : base(callback, state) { this.message = message; this.textEncoder = textEncoder; this.xmlWriter = textEncoder.TakeStreamedWriter(stream); this.eventTraceActivity = null; if (TD.TextMessageEncodingStartIsEnabled()) { this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message); TD.TextMessageEncodingStart(this.eventTraceActivity); } if (!textEncoder.optimizeWriteForUTF8) { xmlWriter.WriteStartDocument(); } IAsyncResult result = message.BeginWriteMessage(this.xmlWriter, PrepareAsyncCompletion(onWriteMessage), this); if (SyncContinue(result)) { this.Complete(true); } } static bool OnWriteMessage(IAsyncResult result) { WriteMessageAsyncResult thisPtr = (WriteMessageAsyncResult)result.AsyncState; return thisPtr.HandleWriteMessage(result); } bool HandleWriteMessage(IAsyncResult result) { message.EndWriteMessage(result); if (!textEncoder.optimizeWriteForUTF8) { this.xmlWriter.WriteEndDocument(); } xmlWriter.Flush(); // blocking call textEncoder.ReturnStreamedWriter(this.xmlWriter); if (TD.MessageWrittenAsynchronouslyByEncoderIsEnabled()) { TD.MessageWrittenAsynchronouslyByEncoder( this.eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message)); } if (MessageLogger.LogMessagesAtTransportLevel) MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend); return true; } public static void End(IAsyncResult result) { AsyncResult.End<WriteMessageAsyncResult>(result); } } XmlDictionaryWriter TakeStreamedWriter(Stream stream) { if (streamedWriterPool == null) { lock (ThisLock) { if (streamedWriterPool == null) { streamedWriterPool = new SynchronizedPool<XmlDictionaryWriter>(maxWritePoolSize); } } } XmlDictionaryWriter xmlWriter = streamedWriterPool.Take(); if (xmlWriter == null) { xmlWriter = XmlDictionaryWriter.CreateTextWriter(stream, this.writeEncoding, false); if (TD.WritePoolMissIsEnabled()) { TD.WritePoolMiss(xmlWriter.GetType().Name); } } else { ((IXmlTextWriterInitializer)xmlWriter).SetOutput(stream, this.writeEncoding, false); } return xmlWriter; } void ReturnStreamedWriter(XmlWriter xmlWriter) { xmlWriter.Close(); streamedWriterPool.Return((XmlDictionaryWriter)xmlWriter); } TextBufferedMessageWriter TakeBufferedWriter() { if (bufferedWriterPool == null) { lock (ThisLock) { if (bufferedWriterPool == null) { bufferedWriterPool = new SynchronizedPool<TextBufferedMessageWriter>(maxWritePoolSize); } } } TextBufferedMessageWriter messageWriter = bufferedWriterPool.Take(); if (messageWriter == null) { messageWriter = new TextBufferedMessageWriter(this); if (TD.WritePoolMissIsEnabled()) { TD.WritePoolMiss(messageWriter.GetType().Name); } } return messageWriter; } void ReturnMessageWriter(TextBufferedMessageWriter messageWriter) { bufferedWriterPool.Return(messageWriter); } XmlReader TakeStreamedReader(Stream stream, Encoding enc) { if (streamedReaderPool == null) { lock (ThisLock) { if (streamedReaderPool == null) { streamedReaderPool = new SynchronizedPool<XmlDictionaryReader>(maxReadPoolSize); } } } XmlDictionaryReader xmlReader = streamedReaderPool.Take(); if (xmlReader == null) { xmlReader = XmlDictionaryReader.CreateTextReader(stream, enc, this.readerQuotas, null); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(xmlReader.GetType().Name); } } else { ((IXmlTextReaderInitializer)xmlReader).SetInput(stream, enc, this.readerQuotas, onStreamedReaderClose); } return xmlReader; } void ReturnStreamedReader(XmlDictionaryReader xmlReader) { streamedReaderPool.Return(xmlReader); } XmlDictionaryWriter CreateWriter(Stream stream) { return XmlDictionaryWriter.CreateTextWriter(stream, writeEncoding, false); } UTF8BufferedMessageData TakeBufferedReader() { if (bufferedReaderPool == null) { lock (ThisLock) { if (bufferedReaderPool == null) { bufferedReaderPool = new SynchronizedPool<UTF8BufferedMessageData>(maxReadPoolSize); } } } UTF8BufferedMessageData messageData = bufferedReaderPool.Take(); if (messageData == null) { messageData = new UTF8BufferedMessageData(this, maxPooledXmlReadersPerMessage); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(messageData.GetType().Name); } } return messageData; } void ReturnBufferedData(UTF8BufferedMessageData messageData) { bufferedReaderPool.Return(messageData); } SynchronizedPool<RecycledMessageState> RecycledStatePool { get { if (recycledStatePool == null) { lock (ThisLock) { if (recycledStatePool == null) { recycledStatePool = new SynchronizedPool<RecycledMessageState>(maxReadPoolSize); } } } return recycledStatePool; } } string ITraceSourceStringProvider.GetSourceString() { return base.GetTraceSourceString(); } static readonly byte[] xmlDeclarationStartText = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l' }; static readonly byte[] version10Text = { (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"' }; static readonly byte[] encodingText = { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=' }; class UTF8BufferedMessageData : BufferedMessageData { TextMessageEncoder messageEncoder; Pool<XmlDictionaryReader> readerPool; OnXmlDictionaryReaderClose onClose; Encoding encoding; const int additionalNodeSpace = 1024; public UTF8BufferedMessageData(TextMessageEncoder messageEncoder, int maxReaderPoolSize) : base(messageEncoder.RecycledStatePool) { this.messageEncoder = messageEncoder; readerPool = new Pool<XmlDictionaryReader>(maxReaderPoolSize); onClose = new OnXmlDictionaryReaderClose(OnXmlReaderClosed); } internal Encoding Encoding { set { this.encoding = value; } } public override MessageEncoder MessageEncoder { get { return messageEncoder; } } public override XmlDictionaryReaderQuotas Quotas { get { return messageEncoder.bufferedReadReaderQuotas; } } protected override void OnClosed() { messageEncoder.ReturnBufferedData(this); } protected override XmlDictionaryReader TakeXmlReader() { ArraySegment<byte> buffer = this.Buffer; XmlDictionaryReader xmlReader = readerPool.Take(); if (xmlReader == null) { xmlReader = XmlDictionaryReader.CreateTextReader(buffer.Array, buffer.Offset, buffer.Count, this.encoding, this.Quotas, onClose); if (TD.ReadPoolMissIsEnabled()) { TD.ReadPoolMiss(xmlReader.GetType().Name); } } else { ((IXmlTextReaderInitializer)xmlReader).SetInput(buffer.Array, buffer.Offset, buffer.Count, this.encoding, this.Quotas, onClose); } return xmlReader; } protected override void ReturnXmlReader(XmlDictionaryReader xmlReader) { if (xmlReader != null) { readerPool.Return(xmlReader); } } } class TextBufferedMessageWriter : BufferedMessageWriter { TextMessageEncoder messageEncoder; XmlDictionaryWriter writer; public TextBufferedMessageWriter(TextMessageEncoder messageEncoder) { this.messageEncoder = messageEncoder; } protected override void OnWriteStartMessage(XmlDictionaryWriter writer) { if (!messageEncoder.optimizeWriteForUTF8) writer.WriteStartDocument(); } protected override void OnWriteEndMessage(XmlDictionaryWriter writer) { if (!messageEncoder.optimizeWriteForUTF8) writer.WriteEndDocument(); } protected override XmlDictionaryWriter TakeXmlWriter(Stream stream) { if (messageEncoder.optimizeWriteForUTF8) { XmlDictionaryWriter returnedWriter = writer; if (returnedWriter == null) { returnedWriter = XmlDictionaryWriter.CreateTextWriter(stream, messageEncoder.writeEncoding, false); } else { writer = null; ((IXmlTextWriterInitializer)returnedWriter).SetOutput(stream, messageEncoder.writeEncoding, false); } return returnedWriter; } else { return messageEncoder.CreateWriter(stream); } } protected override void ReturnXmlWriter(XmlDictionaryWriter writer) { writer.Close(); if (messageEncoder.optimizeWriteForUTF8) { if (this.writer == null) this.writer = writer; } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Security; using System.Threading; using System.Threading.Tasks; namespace EnumerableTests { internal class EnumerableUtils { private int _totalFailCount = 0; private int _totalCount = 0; public bool Passed { get { return _totalFailCount == 0; } } public void PrintTestStatus(String testName, String methodName, int failCount) { _totalCount++; if (failCount != 0) { _totalFailCount++; Console.WriteLine("---- Inner Test FAILED: {0} ({1}) ----", methodName, testName); } } // test setup and tear-down public void CreateTestDirs() { String currentDir = Directory.GetCurrentDirectory(); testDir = Path.Combine(currentDir, "FSEnumeratorTest", Path.GetRandomFileName()); if (Directory.Exists(testDir)) Directory.Delete(testDir, true); Directory.CreateDirectory(testDir); String subDir_a = Path.Combine(testDir, "lev1_a"); String subDir_b = Path.Combine(testDir, "lev1_b"); String subDir_c = Path.Combine(testDir, "lev1_c"); Directory.CreateDirectory(subDir_a); Directory.CreateDirectory(subDir_b); Directory.CreateDirectory(subDir_c); String subDir_d = Path.Combine(subDir_a, "lev2_d"); String subDir_e = Path.Combine(subDir_a, "lev2_e"); String subDir_f = Path.Combine(subDir_b, "lev2_f"); deepDir = subDir_b; Directory.CreateDirectory(subDir_d); Directory.CreateDirectory(subDir_e); Directory.CreateDirectory(subDir_f); String file1 = Path.Combine(testDir, "file1"); String file2 = Path.Combine(subDir_b, "file2"); String file3 = Path.Combine(subDir_f, "file3"); deepFile = file2; File.WriteAllText(file1, "this is file 1" + Environment.NewLine + "Line 2 in file 1" + Environment.NewLine + "Line 3 in file 1" + Environment.NewLine + "Line 4 in file 1"); File.WriteAllText(file2, "this is file 2"); File.WriteAllText(file3, "this is file 3"); expected_Dirs_Deep = new HashSet<String>(); expected_Dirs_Deep.Add(subDir_a); expected_Dirs_Deep.Add(subDir_b); expected_Dirs_Deep.Add(subDir_c); expected_Dirs_Deep.Add(subDir_d); expected_Dirs_Deep.Add(subDir_e); expected_Dirs_Deep.Add(subDir_f); expected_Dirs_Shallow = new HashSet<String>(); expected_Dirs_Shallow.Add(subDir_a); expected_Dirs_Shallow.Add(subDir_b); expected_Dirs_Shallow.Add(subDir_c); expected_Files_Deep = new HashSet<String>(); expected_Files_Deep.Add(file1); expected_Files_Deep.Add(file2); expected_Files_Deep.Add(file3); expected_Files_Shallow = new HashSet<String>(); expected_Files_Shallow.Add(file1); expected_Dirs_Subdir = new HashSet<String>(); expected_Dirs_Subdir.Add(subDir_d); expected_Dirs_Subdir.Add(subDir_e); expected_Dirs_Lev2SearchPattern = new HashSet<String>(); expected_Dirs_Lev2SearchPattern.Add(subDir_d); expected_Dirs_Lev2SearchPattern.Add(subDir_e); expected_Dirs_Lev2SearchPattern.Add(subDir_f); expected_Dirs_ExactSearchPattern = new HashSet<String>(); expected_Dirs_ExactSearchPattern.Add(subDir_f); FSIEntry entry_a = new FSIEntry("lev1_a", subDir_a, null, "lev1_a"); FSIEntry entry_b = new FSIEntry("lev1_b", subDir_b, null, "lev1_b"); FSIEntry entry_c = new FSIEntry("lev1_c", subDir_c, null, "lev1_c"); FSIEntry entry_d = new FSIEntry("lev2_d", subDir_d, null, "lev2_d"); FSIEntry entry_e = new FSIEntry("lev2_e", subDir_e, null, "lev2_e"); FSIEntry entry_f = new FSIEntry("lev2_f", subDir_f, null, "lev2_f"); FSIEntry entry_1 = new FSIEntry("file1", file1, testDir, "file1"); FSIEntry entry_2 = new FSIEntry("file2", file2, subDir_b, "file2"); FSIEntry entry_3 = new FSIEntry("file3", file3, subDir_f, "file3"); expected_Dirs_Deep_FSI = new HashSet<FSIEntry>(); expected_Dirs_Deep_FSI.Add(entry_a); expected_Dirs_Deep_FSI.Add(entry_b); expected_Dirs_Deep_FSI.Add(entry_c); expected_Dirs_Deep_FSI.Add(entry_d); expected_Dirs_Deep_FSI.Add(entry_e); expected_Dirs_Deep_FSI.Add(entry_f); expected_Dirs_Shallow_FSI = new HashSet<FSIEntry>(); expected_Dirs_Shallow_FSI.Add(entry_a); expected_Dirs_Shallow_FSI.Add(entry_b); expected_Dirs_Shallow_FSI.Add(entry_c); expected_Files_Deep_FSI = new HashSet<FSIEntry>(); expected_Files_Deep_FSI.Add(entry_1); expected_Files_Deep_FSI.Add(entry_2); expected_Files_Deep_FSI.Add(entry_3); expected_Files_Shallow_FSI = new HashSet<FSIEntry>(); expected_Files_Shallow_FSI.Add(entry_1); expected_Dirs_Subdir_FSI = new HashSet<FSIEntry>(); expected_Dirs_Subdir_FSI.Add(entry_d); expected_Dirs_Subdir_FSI.Add(entry_e); } public static string GetUnusedDrive() { return IOServices.GetNonExistentDrive(); } public void DeleteTestDirs() { bool deleted = false; int attemptsRemaining = 5; while (!deleted && attemptsRemaining > 0) { try { if (Directory.Exists(testDir)) Directory.Delete(testDir, true); deleted = true; break; } catch (IOException) { if (-attemptsRemaining == 0) throw; else Task.Delay(200).Wait(); } } } public void ChangeFSAdd() { String subDir_a = Path.Combine(testDir, "lev1_a"); String subDir_b = Path.Combine(testDir, "lev1_b"); String subDir_c = Path.Combine(testDir, "lev1_c"); String subDir_d = Path.Combine(subDir_a, "lev2_d"); String subDir_e = Path.Combine(subDir_a, "lev2_e"); String subDir_f = Path.Combine(subDir_b, "lev2_f"); String file1 = Path.Combine(testDir, "file1"); String file2 = Path.Combine(subDir_b, "file2"); String file3 = Path.Combine(subDir_f, "file3"); String newDir = Path.Combine(subDir_b, "newDir"); String newFile = Path.Combine(subDir_c, "newFile"); Directory.CreateDirectory(newDir); File.WriteAllText(newFile, "new file"); expected_Dirs_Changed = new HashSet<String>(); expected_Dirs_Changed.Add(subDir_a); expected_Dirs_Changed.Add(subDir_b); expected_Dirs_Changed.Add(subDir_c); expected_Dirs_Changed.Add(subDir_d); expected_Dirs_Changed.Add(subDir_e); expected_Dirs_Changed.Add(subDir_f); expected_Dirs_Changed.Add(newDir); expected_Files_Changed = new HashSet<String>(); expected_Files_Changed.Add(file1); expected_Files_Changed.Add(file2); expected_Files_Changed.Add(newFile); expected_Files_Changed.Add(file3); } public void ChangeFSDelete() { String subDir_a = Path.Combine(testDir, "lev1_a"); String subDir_b = Path.Combine(testDir, "lev1_b"); String subDir_c = Path.Combine(testDir, "lev1_c"); String subDir_f = Path.Combine(subDir_b, "lev2_f"); String file1 = Path.Combine(testDir, "file1"); String file2 = Path.Combine(subDir_b, "file2"); String file3 = Path.Combine(subDir_f, "file3"); Directory.Delete(subDir_a, true); // also deletes d and e File.Delete(file1); File.Delete(file3); expected_Dirs_Changed = new HashSet<String>(); expected_Dirs_Changed.Add(subDir_a); // enumerated before delete expected_Dirs_Changed.Add(subDir_b); expected_Dirs_Changed.Add(subDir_c); expected_Dirs_Changed.Add(subDir_f); expected_Files_Changed = new HashSet<String>(); expected_Files_Changed.Add(file1); // enumerated before delete expected_Files_Changed.Add(file2); } public String testDir; public String deepDir; public String deepFile; public HashSet<String> expected_Dirs_Deep; public HashSet<String> expected_Dirs_Shallow; public HashSet<String> expected_Dirs_Subdir; public HashSet<String> expected_Dirs_Lev2SearchPattern; public HashSet<String> expected_Files_Deep; public HashSet<String> expected_Files_Shallow; public HashSet<String> expected_Dirs_ExactSearchPattern; public HashSet<String> expected_Dirs_Changed; public HashSet<String> expected_Files_Changed; public HashSet<FSIEntry> expected_Dirs_Deep_FSI; public HashSet<FSIEntry> expected_Dirs_Shallow_FSI; public HashSet<FSIEntry> expected_Dirs_Subdir_FSI; public HashSet<FSIEntry> expected_Files_Deep_FSI; public HashSet<FSIEntry> expected_Files_Shallow_FSI; public delegate IEnumerable<String> ReadFastDelegate1(String path); public delegate IEnumerable<String> ReadFastDelegate2(String path, Encoding encoding); public delegate void WriteFastDelegate1(String path, IEnumerable<String> contents); public delegate void WriteFastDelegate2(String path, IEnumerable<String> contents, Encoding encoding); public delegate void AppendFastDelegate1(String path, IEnumerable<String> contents); public delegate void AppendFastDelegate2(String path, IEnumerable<String> contents, Encoding encoding); public delegate String[] GetFSEs0(String path); public delegate String[] GetFSEs1(String path, String pattern); public delegate String[] GetFSEs2(String path, String pattern, SearchOption option); public delegate IEnumerable<String> GetFSEsFast0(String path); public delegate IEnumerable<String> GetFSEsFast1(String path, String pattern); public delegate IEnumerable<String> GetFSEsFast2(String path, String pattern, SearchOption option); } public sealed class FSIEntry { public FSIEntry(String Name, String FullName, String DirectoryName, String ToString) { this.Name = Name; this.FullName = FullName; this.DirectoryName = DirectoryName; this.ToStr = ToString; } public String Name; public String FullName; public String DirectoryName; public String ToStr; public override bool Equals(Object o) { FSIEntry other = o as FSIEntry; if (other == null) return false; return this.Name == other.Name && this.FullName == other.FullName && this.DirectoryName == other.DirectoryName && this.ToStr == other.ToStr; } public override int GetHashCode() { int hc = Name.GetHashCode() + FullName.GetHashCode() + ToStr.GetHashCode(); if (DirectoryName != null) { hc += DirectoryName.GetHashCode(); } return hc; } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet * The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangGreekModel.cpp * and adjusted to language specific support. */ namespace UtfUnknown.Core.Models.SingleByte.Greek; internal class Iso_8859_7_GreekModel : GreekModel { // Generated by BuildLangModel.py // On: 2016-05-25 15:21:50.073117 // Character Mapping Table: // ILL: illegal character. // CTR: control character specific to the charset. // RET: carriage/return. // SYM: symbol (punctuation) that does not belong to word. // NUM: 0 - 9. // // Other characters are ordered by probabilities // (0 is the most common character in the language). // // Orders are generic to a language.So the codepoint with order X in // CHARSET1 maps to the same character as the codepoint with the same // order X in CHARSET2 for the same language. // As such, it is possible to get missing order.For instance the // ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 // even though they are both used for French.Same for the euro sign. //Character Mapping Table: private static readonly byte[] CHAR_TO_ORDER_MAP = { CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, RET, CTR, CTR, RET, CTR, CTR, /* 0X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 1X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* 2X */ NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, SYM, SYM, SYM, SYM, SYM, SYM, /* 3X */ SYM, 32, 46, 41, 40, 30, 52, 48, 42, 33, 56, 49, 39, 44, 36, 34, /* 4X */ 47, 59, 35, 38, 37, 43, 54, 50, 58, 53, 57, SYM, SYM, SYM, SYM, SYM, /* 5X */ SYM, 32, 46, 41, 40, 30, 52, 48, 42, 33, 56, 49, 39, 44, 36, 34, /* 6X */ 47, 59, 35, 38, 37, 43, 54, 50, 58, 53, 57, SYM, SYM, SYM, SYM, CTR, /* 7X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 8X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 9X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, ILL, SYM, /* AX */ SYM, SYM, SYM, SYM, SYM, SYM, 17, SYM, 19, 22, 15, SYM, 16, SYM, 24, 28, /* BX */ 55, 0, 25, 18, 20, 5, 29, 10, 26, 3, 8, 14, 13, 4, 31, 1, /* CX */ 11, 6, ILL, 7, 2, 12, 27, 23, 45, 21, 51, 60, 17, 19, 22, 15, /* DX */ 61, 0, 25, 18, 20, 5, 29, 10, 26, 3, 8, 14, 13, 4, 31, 1, /* EX */ 11, 6, 9, 7, 2, 12, 27, 23, 45, 21, 51, 60, 16, 24, 28, ILL /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ public Iso_8859_7_GreekModel() : base( CHAR_TO_ORDER_MAP, CodepageName.ISO_8859_7) { } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Collections.ObjectModel { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime; [Serializable] [System.Runtime.InteropServices.ComVisible(false)] [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class Collection<T>: IList<T>, IList, IReadOnlyList<T> { IList<T> items; [NonSerialized] private Object _syncRoot; public Collection() { items = new List<T>(); } public Collection(IList<T> list) { if (list == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list); } items = list; } public int Count { get { return items.Count; } } protected IList<T> Items { get { return items; } } public T this[int index] { get { return items[index]; } set { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } SetItem(index, value); } } public void Add(T item) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } int index = items.Count; InsertItem(index, item); } public void Clear() { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ClearItems(); } public void CopyTo(T[] array, int index) { items.CopyTo(array, index); } public bool Contains(T item) { return items.Contains(item); } public IEnumerator<T> GetEnumerator() { return items.GetEnumerator(); } public int IndexOf(T item) { return items.IndexOf(item); } public void Insert(int index, T item) { if (items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index > items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } InsertItem(index, item); } public bool Remove(T item) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } int index = items.IndexOf(item); if (index < 0) return false; RemoveItem(index); return true; } public void RemoveAt(int index) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if (index < 0 || index >= items.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(); } RemoveItem(index); } protected virtual void ClearItems() { items.Clear(); } protected virtual void InsertItem(int index, T item) { items.Insert(index, item); } protected virtual void RemoveItem(int index) { items.RemoveAt(index); } protected virtual void SetItem(int index, T item) { items[index] = item; } bool ICollection<T>.IsReadOnly { get { return items.IsReadOnly; } } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)items).GetEnumerator(); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if( _syncRoot == null) { ICollection c = items as ICollection; if( c != null) { _syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } } return _syncRoot; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if( array.GetLowerBound(0) != 0 ) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 ) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } T[] tArray = array as T[]; if (tArray != null) { items.CopyTo(tArray , index); } else { // // Catch the obvious case assignment will fail. // We can found all possible problems by doing the check though. // For example, if the element type of the Array is derived from T, // we can't figure out if we can successfully copy the element beforehand. // Type targetType = array.GetType().GetElementType(); Type sourceType = typeof(T); if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } // // We can't cast array of value type to object[], so we don't support // widening of primitive types here. // object[] objects = array as object[]; if( objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } int count = items.Count; try { for (int i = 0; i < count; i++) { objects[index++] = items[i]; } } catch(ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } object IList.this[int index] { get { return items[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { this[index] = (T)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } } bool IList.IsReadOnly { get { return items.IsReadOnly; } } bool IList.IsFixedSize { get { // There is no IList<T>.IsFixedSize, so we must assume that only // readonly collections are fixed size, if our internal item // collection does not implement IList. Note that Array implements // IList, and therefore T[] and U[] will be fixed-size. IList list = items as IList; if(list != null) { return list.IsFixedSize; } return items.IsReadOnly; } } int IList.Add(object value) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { Add((T)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } return this.Count - 1; } bool IList.Contains(object value) { if(IsCompatibleObject(value)) { return Contains((T) value); } return false; } int IList.IndexOf(object value) { if(IsCompatibleObject(value)) { return IndexOf((T)value); } return -1; } void IList.Insert(int index, object value) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { Insert(index, (T)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } void IList.Remove(object value) { if( items.IsReadOnly) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } if(IsCompatibleObject(value)) { Remove((T) value); } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } } }
#region File Description //----------------------------------------------------------------------------- // ScreenManager.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Diagnostics; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace Pickture { /// <summary> /// The screen manager is a component which manages one or more GameScreen /// instances. It maintains a stack of screens, calls their Update and Draw /// methods at the appropriate times, and automatically routes input to the /// topmost active screen. /// </summary> public class ScreenManager : DrawableGameComponent { #region Fields List<GameScreen> screens = new List<GameScreen>(); List<GameScreen> screensToUpdate = new List<GameScreen>(); InputState input = new InputState(); SpriteBatch spriteBatch; SpriteFont font; Texture2D blankTexture; bool isInitialized; bool traceEnabled; #endregion #region Properties /// <summary> /// A default SpriteBatch shared by all the screens. This saves /// each screen having to bother creating their own local instance. /// </summary> public SpriteBatch SpriteBatch { get { return spriteBatch; } } /// <summary> /// A default font shared by all the screens. This saves /// each screen having to bother loading their own local copy. /// </summary> public SpriteFont Font { get { return font; } } /// <summary> /// If true, the manager prints out a list of all the screens /// each time it is updated. This can be useful for making sure /// everything is being added and removed at the right times. /// </summary> public bool TraceEnabled { get { return traceEnabled; } set { traceEnabled = value; } } #endregion #region Initialization /// <summary> /// Constructs a new screen manager component. /// </summary> public ScreenManager(Game game) : base(game) { } /// <summary> /// Initializes the screen manager component. /// </summary> public override void Initialize() { base.Initialize(); isInitialized = true; } /// <summary> /// Load your graphics content. /// </summary> protected override void LoadContent() { // Load content belonging to the screen manager. ContentManager content = Game.Content; spriteBatch = new SpriteBatch(GraphicsDevice); font = content.Load<SpriteFont>("UiFont"); blankTexture = content.Load<Texture2D>("blank"); // Tell each of the screens to load their content. foreach (GameScreen screen in screens) { screen.LoadContent(); } } /// <summary> /// Unload your graphics content. /// </summary> protected override void UnloadContent() { // Tell each of the screens to unload their content. foreach (GameScreen screen in screens) { screen.UnloadContent(); } } #endregion #region Update and Draw /// <summary> /// Allows each screen to run logic. /// </summary> public override void Update(GameTime gameTime) { // Read the keyboard and gamepad. input.Update(); // Make a copy of the master screen list, to avoid confusion if // the process of updating one screen adds or removes others. screensToUpdate.Clear(); foreach (GameScreen screen in screens) screensToUpdate.Add(screen); bool otherScreenHasFocus = !Game.IsActive; bool coveredByOtherScreen = false; // Loop as long as there are screens waiting to be updated. while (screensToUpdate.Count > 0) { // Pop the topmost screen off the waiting list. GameScreen screen = screensToUpdate[screensToUpdate.Count - 1]; screensToUpdate.RemoveAt(screensToUpdate.Count - 1); // Update the screen. screen.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); if (screen.ScreenState == ScreenState.TransitionOn || screen.ScreenState == ScreenState.Active) { // If this is the first active screen we came across, // give it a chance to handle input. if (!otherScreenHasFocus) { screen.HandleInput(input); otherScreenHasFocus = true; } // If this is an active non-popup, inform any subsequent // screens that they are covered by it. if (!screen.IsPopup) coveredByOtherScreen = true; } } // Print debug trace? if (traceEnabled) TraceScreens(); } /// <summary> /// Prints a list of all the screens, for debugging. /// </summary> void TraceScreens() { List<string> screenNames = new List<string>(); foreach (GameScreen screen in screens) screenNames.Add(screen.GetType().Name); Trace.WriteLine(string.Join(", ", screenNames.ToArray())); } /// <summary> /// Tells each screen to draw itself. /// </summary> public override void Draw(GameTime gameTime) { foreach (GameScreen screen in screens) { if (screen.ScreenState == ScreenState.Hidden) continue; screen.Draw(gameTime); } } #endregion #region Public Methods /// <summary> /// Adds a new screen to the screen manager. /// </summary> public void AddScreen(GameScreen screen) { screen.ScreenManager = this; screen.IsExiting = false; // If we have a graphics device, tell the screen to load content. if (isInitialized) { screen.LoadContent(); } screens.Add(screen); } /// <summary> /// Removes a screen from the screen manager. You should normally /// use GameScreen.ExitScreen instead of calling this directly, so /// the screen can gradually transition off rather than just being /// instantly removed. /// </summary> public void RemoveScreen(GameScreen screen) { // If we have a graphics device, tell the screen to unload content. if (isInitialized) { screen.UnloadContent(); } screens.Remove(screen); screensToUpdate.Remove(screen); } /// <summary> /// Expose an array holding all the screens. We return a copy rather /// than the real master list, because screens should only ever be added /// or removed using the AddScreen and RemoveScreen methods. /// </summary> public GameScreen[] GetScreens() { return screens.ToArray(); } /// <summary> /// Helper draws a translucent black fullscreen sprite, used for fading /// screens in and out, and for darkening the background behind popups. /// </summary> public void FadeBackBufferToBlack(int alpha) { Viewport viewport = GraphicsDevice.Viewport; spriteBatch.Begin(); spriteBatch.Draw(blankTexture, new Rectangle(0, 0, viewport.Width, viewport.Height), new Color(0, 0, 0, (byte)alpha)); spriteBatch.End(); } #endregion } }
#if UNITY_EDITOR || !(UNITY_WEBPLAYER || UNITY_WEBGL) #region License /* * Logger.cs * * The MIT License * * Copyright (c) 2013-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Diagnostics; using System.IO; namespace WebSocketSharp { /// <summary> /// Provides a set of methods and properties for logging. /// </summary> /// <remarks> /// <para> /// If you output a log with lower than the value of the <see cref="Logger.Level"/> property, /// it cannot be outputted. /// </para> /// <para> /// The default output action writes a log to the standard output stream and the log file /// if the <see cref="Logger.File"/> property has a valid path to it. /// </para> /// <para> /// If you would like to use the custom output action, you should set /// the <see cref="Logger.Output"/> property to any <c>Action&lt;LogData, string&gt;</c> /// delegate. /// </para> /// </remarks> public class Logger { #region Private Fields private volatile string _file; private volatile LogLevel _level; private Action<LogData, string> _output; private object _sync; #endregion #region Public Constructors /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class. /// </summary> /// <remarks> /// This constructor initializes the current logging level with <see cref="LogLevel.Error"/>. /// </remarks> public Logger () : this (LogLevel.Error, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class with /// the specified logging <paramref name="level"/>. /// </summary> /// <param name="level"> /// One of the <see cref="LogLevel"/> enum values. /// </param> public Logger (LogLevel level) : this (level, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="Logger"/> class with /// the specified logging <paramref name="level"/>, path to the log <paramref name="file"/>, /// and <paramref name="output"/> action. /// </summary> /// <param name="level"> /// One of the <see cref="LogLevel"/> enum values. /// </param> /// <param name="file"> /// A <see cref="string"/> that represents the path to the log file. /// </param> /// <param name="output"> /// An <c>Action&lt;LogData, string&gt;</c> delegate that references the method(s) used to /// output a log. A <see cref="string"/> parameter passed to this delegate is /// <paramref name="file"/>. /// </param> public Logger (LogLevel level, string file, Action<LogData, string> output) { _level = level; _file = file; _output = output ?? defaultOutput; _sync = new object (); } #endregion #region Public Properties /// <summary> /// Gets or sets the current path to the log file. /// </summary> /// <value> /// A <see cref="string"/> that represents the current path to the log file if any. /// </value> public string File { get { return _file; } set { lock (_sync) { _file = value; Warn ( String.Format ("The current path to the log file has been changed to {0}.", _file)); } } } /// <summary> /// Gets or sets the current logging level. /// </summary> /// <remarks> /// A log with lower than the value of this property cannot be outputted. /// </remarks> /// <value> /// One of the <see cref="LogLevel"/> enum values, specifies the current logging level. /// </value> public LogLevel Level { get { return _level; } set { lock (_sync) { _level = value; Warn (String.Format ("The current logging level has been changed to {0}.", _level)); } } } /// <summary> /// Gets or sets the current output action used to output a log. /// </summary> /// <value> /// <para> /// An <c>Action&lt;LogData, string&gt;</c> delegate that references the method(s) used to /// output a log. A <see cref="string"/> parameter passed to this delegate is the value of /// the <see cref="Logger.File"/> property. /// </para> /// <para> /// If the value to set is <see langword="null"/>, the current output action is changed to /// the default output action. /// </para> /// </value> public Action<LogData, string> Output { get { return _output; } set { lock (_sync) { _output = value ?? defaultOutput; Warn ("The current output action has been changed."); } } } #endregion #region Private Methods private static void defaultOutput (LogData data, string path) { var log = data.ToString (); Console.WriteLine (log); if (path != null && path.Length > 0) writeToFile (log, path); } private void output (string message, LogLevel level) { lock (_sync) { if (_level > level) return; LogData data = null; try { data = new LogData (level, new StackFrame (2, true), message); _output (data, _file); } catch (Exception ex) { data = new LogData (LogLevel.Fatal, new StackFrame (0, true), ex.Message); Console.WriteLine (data.ToString ()); } } } private static void writeToFile (string value, string path) { using (var writer = new StreamWriter (path, true)) using (var syncWriter = TextWriter.Synchronized (writer)) syncWriter.WriteLine (value); } #endregion #region Public Methods /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Debug"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Debug"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Debug (string message) { if (_level > LogLevel.Debug) return; output (message, LogLevel.Debug); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Error"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Error"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Error (string message) { if (_level > LogLevel.Error) return; output (message, LogLevel.Error); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Fatal"/>. /// </summary> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Fatal (string message) { output (message, LogLevel.Fatal); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Info"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Info"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Info (string message) { if (_level > LogLevel.Info) return; output (message, LogLevel.Info); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Trace"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Trace"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Trace (string message) { if (_level > LogLevel.Trace) return; output (message, LogLevel.Trace); } /// <summary> /// Outputs <paramref name="message"/> as a log with <see cref="LogLevel.Warn"/>. /// </summary> /// <remarks> /// If the current logging level is higher than <see cref="LogLevel.Warn"/>, /// this method doesn't output <paramref name="message"/> as a log. /// </remarks> /// <param name="message"> /// A <see cref="string"/> that represents the message to output as a log. /// </param> public void Warn (string message) { if (_level > LogLevel.Warn) return; output (message, LogLevel.Warn); } #endregion } } #endif
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function initializeRoadEditor() { echo( " - Initializing Road and Path Editor" ); exec( "./roadEditor.cs" ); exec( "./RoadEditorGui.gui" ); exec( "./RoadEditorToolbar.gui"); exec( "./roadEditorGui.cs" ); // Add ourselves to EditorGui, where all the other tools reside RoadEditorGui.setVisible( false ); RoadEditorToolbar.setVisible( false ); RoadEditorOptionsWindow.setVisible( false ); RoadEditorTreeWindow.setVisible( false ); EditorGui.add( RoadEditorGui ); EditorGui.add( RoadEditorToolbar ); EditorGui.add( RoadEditorOptionsWindow ); EditorGui.add( RoadEditorTreeWindow ); new ScriptObject( RoadEditorPlugin ) { superClass = "EditorPlugin"; editorGui = RoadEditorGui; }; %map = new ActionMap(); %map.bindCmd( keyboard, "backspace", "RoadEditorGui.onDeleteKey();", "" ); %map.bindCmd( keyboard, "1", "RoadEditorGui.prepSelectionMode();", "" ); %map.bindCmd( keyboard, "2", "ToolsPaletteArray->RoadEditorMoveMode.performClick();", "" ); %map.bindCmd( keyboard, "4", "ToolsPaletteArray->RoadEditorScaleMode.performClick();", "" ); %map.bindCmd( keyboard, "5", "ToolsPaletteArray->RoadEditorAddRoadMode.performClick();", "" ); %map.bindCmd( keyboard, "=", "ToolsPaletteArray->RoadEditorInsertPointMode.performClick();", "" ); %map.bindCmd( keyboard, "numpadadd", "ToolsPaletteArray->RoadEditorInsertPointMode.performClick();", "" ); %map.bindCmd( keyboard, "-", "ToolsPaletteArray->RoadEditorRemovePointMode.performClick();", "" ); %map.bindCmd( keyboard, "numpadminus", "ToolsPaletteArray->RoadEditorRemovePointMode.performClick();", "" ); %map.bindCmd( keyboard, "z", "RoadEditorShowSplineBtn.performClick();", "" ); %map.bindCmd( keyboard, "x", "RoadEditorWireframeBtn.performClick();", "" ); %map.bindCmd( keyboard, "v", "RoadEditorShowRoadBtn.performClick();", "" ); RoadEditorPlugin.map = %map; RoadEditorPlugin.initSettings(); } function destroyRoadEditor() { } function RoadEditorPlugin::onWorldEditorStartup( %this ) { // Add ourselves to the window menu. %accel = EditorGui.addToEditorsMenu( "Road and Path Editor", "", RoadEditorPlugin ); // Add ourselves to the ToolsToolbar %tooltip = "Road Editor (" @ %accel @ ")"; EditorGui.addToToolsToolbar( "RoadEditorPlugin", "RoadEditorPalette", expandFilename("tools/worldEditor/images/toolbar/road-path-editor"), %tooltip ); //connect editor windows GuiWindowCtrl::attach( RoadEditorOptionsWindow, RoadEditorTreeWindow); // Add ourselves to the Editor Settings window exec( "./RoadEditorSettingsTab.gui" ); ESettingsWindow.addTabPage( ERoadEditorSettingsPage ); } function RoadEditorPlugin::onActivated( %this ) { %this.readSettings(); ToolsPaletteArray->RoadEditorAddRoadMode.performClick(); EditorGui.bringToFront( RoadEditorGui ); RoadEditorGui.setVisible( true ); RoadEditorGui.makeFirstResponder( true ); RoadEditorToolbar.setVisible( true ); RoadEditorOptionsWindow.setVisible( true ); RoadEditorTreeWindow.setVisible( true ); RoadTreeView.open(ServerDecalRoadSet,true); %this.map.push(); // Set the status bar here until all tool have been hooked up EditorGuiStatusBar.setInfo("Road editor."); EditorGuiStatusBar.setSelection(""); Parent::onActivated(%this); } function RoadEditorPlugin::onDeactivated( %this ) { %this.writeSettings(); RoadEditorGui.setVisible( false ); RoadEditorToolbar.setVisible( false ); RoadEditorOptionsWindow.setVisible( false ); RoadEditorTreeWindow.setVisible( false ); %this.map.pop(); Parent::onDeactivated(%this); } function RoadEditorPlugin::onEditMenuSelect( %this, %editMenu ) { %hasSelection = false; if( isObject( RoadEditorGui.road ) ) %hasSelection = true; %editMenu.enableItem( 3, false ); // Cut %editMenu.enableItem( 4, false ); // Copy %editMenu.enableItem( 5, false ); // Paste %editMenu.enableItem( 6, %hasSelection ); // Delete %editMenu.enableItem( 8, false ); // Deselect } function RoadEditorPlugin::handleDelete( %this ) { RoadEditorGui.onDeleteKey(); } function RoadEditorPlugin::handleEscape( %this ) { return RoadEditorGui.onEscapePressed(); } function RoadEditorPlugin::isDirty( %this ) { return RoadEditorGui.isDirty; } function RoadEditorPlugin::onSaveMission( %this, %missionFile ) { if( RoadEditorGui.isDirty ) { getRootScene().save( %missionFile ); RoadEditorGui.isDirty = false; } } function RoadEditorPlugin::setEditorFunction( %this ) { %terrainExists = parseMissionGroup( "TerrainBlock" ); if( %terrainExists == false ) MessageBoxYesNoCancel("No Terrain","Would you like to create a New Terrain?", "Canvas.pushDialog(CreateNewTerrainGui);"); return %terrainExists; } //----------------------------------------------------------------------------- // Settings //----------------------------------------------------------------------------- function RoadEditorPlugin::initSettings( %this ) { EditorSettings.beginGroup( "RoadEditor", true ); EditorSettings.setDefaultValue( "DefaultWidth", "10" ); EditorSettings.setDefaultValue( "HoverSplineColor", "255 0 0 255" ); EditorSettings.setDefaultValue( "SelectedSplineColor", "0 255 0 255" ); EditorSettings.setDefaultValue( "HoverNodeColor", "255 255 255 255" ); //<-- Not currently used EditorSettings.setDefaultValue( "MaterialName", "DefaultDecalRoadMaterial" ); EditorSettings.endGroup(); } function RoadEditorPlugin::readSettings( %this ) { EditorSettings.beginGroup( "RoadEditor", true ); RoadEditorGui.DefaultWidth = EditorSettings.value("DefaultWidth"); RoadEditorGui.HoverSplineColor = EditorSettings.value("HoverSplineColor"); RoadEditorGui.SelectedSplineColor = EditorSettings.value("SelectedSplineColor"); RoadEditorGui.HoverNodeColor = EditorSettings.value("HoverNodeColor"); RoadEditorGui.materialName = EditorSettings.value("MaterialName"); EditorSettings.endGroup(); } function RoadEditorPlugin::writeSettings( %this ) { EditorSettings.beginGroup( "RoadEditor", true ); EditorSettings.setValue( "DefaultWidth", RoadEditorGui.DefaultWidth ); EditorSettings.setValue( "HoverSplineColor", RoadEditorGui.HoverSplineColor ); EditorSettings.setValue( "SelectedSplineColor", RoadEditorGui.SelectedSplineColor ); EditorSettings.setValue( "HoverNodeColor", RoadEditorGui.HoverNodeColor ); EditorSettings.setValue( "MaterialName", RoadEditorGui.materialName ); EditorSettings.endGroup(); }
#region Foreign-License // .Net40 Kludge #endregion #if !CLR4 using System.Runtime.InteropServices; using System.Security; using System.Collections; namespace System.Runtime.CompilerServices { /* * Description: Compiler support for runtime-generated "object fields." * * Lets DLR and other language compilers expose the ability to attach arbitrary "properties" to instanced managed objects at runtime. * * We expose this support as a dictionary whose keys are the instanced objects and the values are the "properties." * * Unlike a regular dictionary, ConditionalWeakTables will not keep keys alive. * * * Lifetimes of keys and values: * * Inserting a key and value into the dictonary will not prevent the key from dying, even if the key is strongly reachable * from the value. * * Prior to ConditionalWeakTable, the CLR did not expose the functionality needed to implement this guarantee. * * Once the key dies, the dictionary automatically removes the key/value entry. * * * Relationship between ConditionalWeakTable and Dictionary: * * ConditionalWeakTable mirrors the form and functionality of the IDictionary interface for the sake of api consistency. * * Unlike Dictionary, ConditionalWeakTable is fully thread-safe and requires no additional locking to be done by callers. * * ConditionalWeakTable defines equality as Object.ReferenceEquals(). ConditionalWeakTable does not invoke GetHashCode() overrides. * * It is not intended to be a general purpose collection and it does not formally implement IDictionary or * expose the full public surface area. * * * Thread safety guarantees: * * ConditionalWeakTable is fully thread-safe and requires no additional locking to be done by callers. * * * OOM guarantees: * * Will not corrupt unmanaged handle table on OOM. No guarantees about managed weak table consistency. Native handles reclamation * may be delayed until appdomain shutdown. */ /// <summary> /// ConditionalWeakTable /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TValue">The type of the value.</typeparam> [ComVisible(false)] #if !COREINTERNAL public #endif sealed class ConditionalWeakTable<TKey, TValue> where TKey : class where TValue : class { private int[] _buckets; // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty) private Entry[] _entries; private int _freeList; // -1 = empty, else index of first unused Entry private const int _initialCapacity = 5; private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. private object _lock; // this could be a ReaderWriterLock but CoreCLR does not support RWLocks. /// <summary> /// /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public delegate TValue CreateValueCallback(TKey key); [StructLayout(LayoutKind.Sequential)] private struct Entry { // Holds key and value using a weak reference for the key and a strong reference // for the value that is traversed only if the key is reachable without going through the value. public DependentHandle depHnd; public int hashCode; // Cached copy of key's hashcode public int next; // Index of next entry, -1 if last } /// <summary> /// Initializes a new instance of the <see cref="ConditionalWeakTable&lt;TKey, TValue&gt;"/> class. /// </summary> [SecuritySafeCritical] public ConditionalWeakTable() { _buckets = new int[0]; _entries = new Entry[0]; _freeList = -1; _lock = new object(); // Resize at once (so won't need "if initialized" checks all over) Resize(); } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="ConditionalWeakTable&lt;TKey, TValue&gt;"/> is reclaimed by garbage collection. /// </summary> [SecuritySafeCritical] ~ConditionalWeakTable() { // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, don't bother. // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.) if (!Environment.HasShutdownStarted && (_lock != null)) lock (_lock) if (!_invalid) { Entry[] entries = _entries; // Make sure anyone sneaking into the table post-resurrection gets booted before they can damage the native handle table. _invalid = true; _entries = null; _buckets = null; for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++) entries[entriesIndex].depHnd.Free(); } } /// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [SecuritySafeCritical] public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException("key"); lock (_lock) { VerifyIntegrity(); _invalid = true; if (FindEntry(key) != -1) { _invalid = false; throw new ArgumentException("Argument_AddingDuplicate", "key"); } CreateEntry(key, value); _invalid = false; } } [SecurityCritical] private void CreateEntry(TKey key, TValue value) { if (_freeList == -1) Resize(); int hashCode = RuntimeHelpers.GetHashCode(key) & 0x7fffffff; int bucket = hashCode % _buckets.Length; int newEntry = _freeList; _freeList = _entries[newEntry].next; _entries[newEntry].hashCode = hashCode; _entries[newEntry].depHnd = new DependentHandle(key, value); _entries[newEntry].next = _buckets[bucket]; _buckets[bucket] = newEntry; } [SecurityCritical] private int FindEntry(TKey key) { int hashCode = RuntimeHelpers.GetHashCode(key) & 0x7fffffff; for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) if ((_entries[entriesIndex].hashCode == hashCode) && (_entries[entriesIndex].depHnd.GetPrimary() == key)) return entriesIndex; return -1; } // Kludge: CompilerServicesExtensions dependency internal int FindEntryForLazyValueHelper<TLazyKey>(TLazyKey key, bool isValueCreated) { Lazy<TLazyKey> lazy; for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { var depHnd = _entries[entriesIndex].depHnd; if (depHnd.IsAllocated && ((lazy = (Lazy<TLazyKey>)depHnd.GetPrimary()) != null) && (lazy.IsValueCreated || isValueCreated) && lazy.Value.Equals(key)) return entriesIndex; } return -1; } /// <summary> /// Gets the or create value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public TValue GetOrCreateValue(TKey key) { return GetValue(key, (TKey k) => Activator.CreateInstance<TValue>()); } /// <summary> /// Gets the value. /// </summary> /// <param name="key">The key.</param> /// <param name="createValueCallback">The create value callback.</param> /// <returns></returns> [SecuritySafeCritical] public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { TValue local; if (createValueCallback == null) throw new ArgumentNullException("createValueCallback"); if (TryGetValue(key, out local)) return local; // If we got here, the key is not currently in table. Invoke the callback (outside the lock) to generate the new value for the key. var newValue = createValueCallback(key); lock (_lock) { VerifyIntegrity(); _invalid = true; // Now that we've retaken the lock, must recheck in case we lost a ---- to add the key. if (TryGetValueWorker(key, out local)) { _invalid = false; return local; } // Verified in-lock that we won the ---- to add the key. Add it now. CreateEntry(key, newValue); _invalid = false; return newValue; } } /// <summary> /// Removes the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> [SecuritySafeCritical] public bool Remove(TKey key) { if (key == null) throw new ArgumentException("key"); lock (_lock) { VerifyIntegrity(); _invalid = true; int hashCode = RuntimeHelpers.GetHashCode(key) & 0x7fffffff; int bucket = hashCode % _buckets.Length; int last = -1; for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { if ((_entries[entriesIndex].hashCode == hashCode) && (_entries[entriesIndex].depHnd.GetPrimary() == key)) { if (last == -1) _buckets[bucket] = _entries[entriesIndex].next; else _entries[last].next = _entries[entriesIndex].next; _entries[entriesIndex].depHnd.Free(); _entries[entriesIndex].next = _freeList; _freeList = entriesIndex; _invalid = false; return true; } last = entriesIndex; } _invalid = false; return false; } } [SecurityCritical] private void Resize() { // Start by assuming we won't resize. int newSize = _buckets.Length; // If any expired keys exist, we won't resize. bool hasExpiredEntries = false; int entriesIndex; for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) if (_entries[entriesIndex].depHnd.IsAllocated && (_entries[entriesIndex].depHnd.GetPrimary() == null)) { hasExpiredEntries = true; break; } if (!hasExpiredEntries) newSize = HashHelpers.GetPrime((_buckets.Length == 0) ? 6 : (_buckets.Length * 2)); // Reallocate both buckets and entries and rebuild the bucket and freelists from scratch. // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket. int newFreeList = -1; int[] newBuckets = new int[newSize]; for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++) newBuckets[bucketIndex] = -1; var newEntries = new Entry[newSize]; // Migrate existing entries to the new table. for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { var depHnd = _entries[entriesIndex].depHnd; if (depHnd.IsAllocated && (depHnd.GetPrimary() != null)) { // Entry is used and has not expired. Link it into the appropriate bucket list. int index = _entries[entriesIndex].hashCode % newSize; newEntries[entriesIndex].depHnd = depHnd; newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode; newEntries[entriesIndex].next = newBuckets[index]; newBuckets[index] = entriesIndex; } else { // Entry has either expired or was on the freelist to begin with. Either way insert it on the new freelist. _entries[entriesIndex].depHnd.Free(); newEntries[entriesIndex].depHnd = new DependentHandle(); newEntries[entriesIndex].next = newFreeList; newFreeList = entriesIndex; } } // Add remaining entries to freelist. while (entriesIndex != newEntries.Length) { newEntries[entriesIndex].depHnd = new DependentHandle(); newEntries[entriesIndex].next = newFreeList; newFreeList = entriesIndex; entriesIndex++; } _buckets = newBuckets; _entries = newEntries; _freeList = newFreeList; } /// <summary> /// Tries the get value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <returns></returns> [SecuritySafeCritical] public bool TryGetValue(TKey key, out TValue value) { if (key == null) throw new ArgumentException("key"); lock (_lock) { VerifyIntegrity(); return TryGetValueWorker(key, out value); } } [SecurityCritical] private bool TryGetValueWorker(TKey key, out TValue value) { int index = FindEntry(key); if (index != -1) { object primary = null; object secondary = null; _entries[index].depHnd.GetPrimaryAndSecondary(out primary, out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again to ensure it didn't expire // (otherwise, we open a ---- where TryGetValue misreports an expired key as a live key with a null value.) if (primary != null) { value = (TValue)secondary; return true; } } value = default(TValue); return false; } // Kludge: CompilerServicesExtensions dependency /// <summary> /// Tries the get value worker for lazy value helper. /// </summary> /// <typeparam name="TLazyKey">The type of the lazy key.</typeparam> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="isValueCreated">if set to <c>true</c> [is value created].</param> /// <returns></returns> [SecurityCritical] public bool TryGetValueWorkerForLazyValueHelper<TLazyKey>(TLazyKey key, out TValue value, bool isValueCreated) { int index = FindEntryForLazyValueHelper(key, isValueCreated); if (index != -1) { object primary = null; object secondary = null; _entries[index].depHnd.GetPrimaryAndSecondary(out primary, out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again to ensure it didn't expire // (otherwise, we open a ---- where TryGetValue misreports an expired key as a live key with a null value.) if (primary != null) { value = (TValue)secondary; return true; } } value = default(TValue); return false; } private void VerifyIntegrity() { if (_invalid) throw new InvalidOperationException(EnvironmentEx2.GetResourceString("CollectionCorrupted")); } } } #endif
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Test.Utilities.Parallel; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { [ParallelFixture] public class FromKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInEmptyStatement() { VerifyAbsence(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InEmptySpace() { VerifyKeyword(AddInsideMethod( @"var v = $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIdentifier() { VerifyKeyword(AddInsideMethod( @"var v = a$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NestedInQueryExpression() { VerifyKeyword(AddInsideMethod( @"var q = from x in $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterFrom() { VerifyKeyword(AddInsideMethod( @"var v = from x in y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPreviousClause() { VerifyKeyword(AddInsideMethod( @"var v = from x in y where x > y $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPreviousContinuationClause() { VerifyKeyword(AddInsideMethod( @"var v = from x in y group x by y into g $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterFrom1() { VerifyAbsence(AddInsideMethod( @"var v = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterFrom2() { VerifyAbsence(AddInsideMethod( @"var v = from a in y from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void BetweenClauses() { VerifyKeyword(AddInsideMethod( @"var v = from x in y $$ from z in w")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void ContinueInSelect() { VerifyKeyword(AddInsideMethod( @"var v = from x in y select $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void BetweenTokens() { VerifyKeyword(AddInsideMethod( @"var v =$$;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInDeclaration() { VerifyAbsence(AddInsideMethod( @"int $$")); } [WorkItem(538264)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInEnumMemberInitializer1() { VerifyAbsence( @"enum E { a = $$ }"); } [WorkItem(538264)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInConstMemberInitializer1() { VerifyAbsence( @"class E { const int a = $$ }"); } [WorkItem(538264)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InMemberInitializer1() { VerifyKeyword( @"class E { int a = $$ }"); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInTypeOf() { VerifyAbsence(AddInsideMethod( @"typeof($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInDefault() { VerifyAbsence(AddInsideMethod( @"default($$")); } [WorkItem(538804)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInSizeOf() { VerifyAbsence(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219)] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInObjectInitializerMemberContext() { VerifyAbsence(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterOutInArgument() { var experimentalFeatures = new System.Collections.Generic.Dictionary<string, string>(); // no experimental features to enable VerifyAbsence(@" class C { void M(out int x) { x = 42; } void N() { M(out var $$", options: Options.Regular.WithFeatures(experimentalFeatures), scriptOptions: Options.Script.WithFeatures(experimentalFeatures)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Debugging Macros for use in the Base Class Libraries ** ** ============================================================*/ namespace System { using System.IO; using System.Text; using System.Diagnostics; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; internal enum LogLevel { Trace = 0, Status = 20, Warning = 40, Error = 50, Panic = 100, } internal struct SwitchStructure { internal String name; internal int value; internal SwitchStructure(String n, int v) { name = n; value = v; } } // Only statics, does not need to be marked with the serializable attribute internal static class BCLDebug { internal static volatile bool m_registryChecked = false; internal static volatile bool m_loggingNotEnabled = false; internal static bool m_perfWarnings; internal static bool m_correctnessWarnings; internal static bool m_safeHandleStackTraces; #if _DEBUG internal static volatile bool m_domainUnloadAdded; #endif private static readonly SwitchStructure[] switches = { new SwitchStructure("NLS", 0x00000001), new SwitchStructure("SER", 0x00000002), new SwitchStructure("DYNIL",0x00000004), new SwitchStructure("REMOTE",0x00000008), new SwitchStructure("BINARY",0x00000010), //Binary Formatter new SwitchStructure("SOAP",0x00000020), // Soap Formatter new SwitchStructure("REMOTINGCHANNELS",0x00000040), new SwitchStructure("CACHE",0x00000080), new SwitchStructure("RESMGRFILEFORMAT", 0x00000100), // .resources files new SwitchStructure("PERF", 0x00000200), new SwitchStructure("CORRECTNESS", 0x00000400), new SwitchStructure("MEMORYFAILPOINT", 0x00000800), new SwitchStructure("DATETIME", 0x00001000), // System.DateTime managed tracing new SwitchStructure("INTEROP", 0x00002000), // Interop tracing }; private static readonly LogLevel[] levelConversions = { LogLevel.Panic, LogLevel.Error, LogLevel.Error, LogLevel.Warning, LogLevel.Warning, LogLevel.Status, LogLevel.Status, LogLevel.Trace, LogLevel.Trace, LogLevel.Trace, LogLevel.Trace }; #if _DEBUG internal static void WaitForFinalizers(Object sender, EventArgs e) { if (!m_registryChecked) { CheckRegistry(); } if (m_correctnessWarnings) { GC.GetTotalMemory(true); GC.WaitForPendingFinalizers(); } } #endif [Conditional("_DEBUG")] static public void Assert(bool condition) { #if _DEBUG Assert(condition, "Assert failed."); #endif } [Conditional("_DEBUG")] static public void Assert(bool condition, String message) { #if _DEBUG // Speed up debug builds marginally by avoiding the garbage from // concatinating "BCL Assert: " and the message. if (!condition) System.Diagnostics.Assert.Check(condition, "BCL Assert", message); #endif } [Conditional("_LOGGING")] static public void Log(String message) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) { CheckRegistry(); } System.Diagnostics.Log.Trace(message); System.Diagnostics.Log.Trace(Environment.NewLine); } [Conditional("_LOGGING")] static public void Log(String switchName, String message) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) { CheckRegistry(); } try { LogSwitch ls; ls = LogSwitch.GetSwitch(switchName); if (ls != null) { System.Diagnostics.Log.Trace(ls, message); System.Diagnostics.Log.Trace(ls, Environment.NewLine); } } catch { System.Diagnostics.Log.Trace("Exception thrown in logging." + Environment.NewLine); System.Diagnostics.Log.Trace("Switch was: " + ((switchName == null) ? "<null>" : switchName) + Environment.NewLine); System.Diagnostics.Log.Trace("Message was: " + ((message == null) ? "<null>" : message) + Environment.NewLine); } } // // This code gets called during security startup, so we can't go through Marshal to get the values. This is // just a small helper in native code instead of that. // [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces); private static void CheckRegistry() { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (m_registryChecked) { return; } m_registryChecked = true; bool loggingEnabled; bool logToConsole; int logLevel; int facilityValue; facilityValue = GetRegistryLoggingValues(out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings, out m_safeHandleStackTraces); // Note we can get into some recursive situations where we call // ourseves recursively through the .cctor. That's why we have the // check for levelConversions == null. if (!loggingEnabled) { m_loggingNotEnabled = true; } if (loggingEnabled && levelConversions != null) { try { //The values returned for the logging levels in the registry don't map nicely onto the //values which we support internally (which are an approximation of the ones that //the System.Diagnostics namespace uses) so we have a quick map. Assert(logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10"); logLevel = (int)levelConversions[logLevel]; if (facilityValue > 0) { for (int i = 0; i < switches.Length; i++) { if ((switches[i].value & facilityValue) != 0) { LogSwitch L = new LogSwitch(switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch); L.MinimumLevel = (LoggingLevels)logLevel; } } System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel; System.Diagnostics.Log.IsConsoleEnabled = logToConsole; } } catch { //Silently eat any exceptions. } } } internal static bool CheckEnabled(String switchName) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return false; if (!m_registryChecked) CheckRegistry(); LogSwitch logSwitch = LogSwitch.GetSwitch(switchName); if (logSwitch == null) { return false; } return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace); } private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) { logSwitch = null; return false; } logSwitch = LogSwitch.GetSwitch(switchName); if (logSwitch == null) { return false; } return ((int)logSwitch.MinimumLevel <= (int)level); } [Conditional("_LOGGING")] public static void Log(String switchName, LogLevel level, params Object[] messages) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; //Add code to check if logging is enabled in the registry. LogSwitch logSwitch; if (!m_registryChecked) { CheckRegistry(); } if (!CheckEnabled(switchName, level, out logSwitch)) { return; } StringBuilder sb = StringBuilderCache.Acquire(); for (int i = 0; i < messages.Length; i++) { String s; try { if (messages[i] == null) { s = "<null>"; } else { s = messages[i].ToString(); } } catch { s = "<unable to convert>"; } sb.Append(s); } System.Diagnostics.Log.LogMessage((LoggingLevels)((int)level), logSwitch, StringBuilderCache.GetStringAndRelease(sb)); } [Conditional("_LOGGING")] public static void Trace(String switchName, String format, params Object[] messages) { if (m_loggingNotEnabled) { return; } LogSwitch logSwitch; if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) { return; } StringBuilder sb = StringBuilderCache.Acquire(); sb.AppendFormat(format, messages); sb.Append(Environment.NewLine); System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, StringBuilderCache.GetStringAndRelease(sb)); } // For perf-related asserts. On a debug build, set the registry key // BCLPerfWarnings to non-zero. [Conditional("_DEBUG")] internal static void Perf(bool expr, String msg) { if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) CheckRegistry(); if (!m_perfWarnings) return; if (!expr) { Log("PERF", "BCL Perf Warning: " + msg); } System.Diagnostics.Assert.Check(expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg); } // For correctness-related asserts. On a debug build, set the registry key // BCLCorrectnessWarnings to non-zero. [Conditional("_DEBUG")] #if _DEBUG #endif internal static void Correctness(bool expr, String msg) { #if _DEBUG if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize()) return; if (!m_registryChecked) CheckRegistry(); if (!m_correctnessWarnings) return; if (!m_domainUnloadAdded) { m_domainUnloadAdded = true; AppDomain.CurrentDomain.DomainUnload += new EventHandler(WaitForFinalizers); } if (!expr) { Log("CORRECTNESS", "BCL Correctness Warning: " + msg); } System.Diagnostics.Assert.Check(expr, "BCL Correctness Warning: Your program may not work because...", msg); #endif } // Whether SafeHandles include a stack trace showing where they // were allocated. Only useful in checked & debug builds. internal static bool SafeHandleStackTracesEnabled { get { #if _DEBUG if (!m_registryChecked) CheckRegistry(); return m_safeHandleStackTraces; #else return false; #endif } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; using System.Threading.Tasks; using Newtonsoft.Json; using ServiceStack.WebHost.Endpoints; using QuantConnect.CodingServices; using QuantConnect.CodingServices.Models; using QuantConnect.CodingServices.Services.ProjectModelRepository; using NRefactoryTestApp.ViewModels; namespace NRefactoryTestApp.Views { /// <summary> /// Interaction logic for ProjectView.xaml /// </summary> public partial class ProjectView : UserControl { public ProjectView() { InitializeComponent(); //TaskScheduler.FromCurrentSynchronizationContext SelectedFileContent.PreviewMouseUp += SelectedFileContentOnPreviewMouseUp; } private void SelectedFileContentOnPreviewMouseUp(object sender, MouseButtonEventArgs mouseButtonEventArgs) { UpdateLineAndColumnOfCursorPositionInViewModel(false); } private void SelectedFileContent_KeyDown(object sender, KeyEventArgs e) { bool ctrl = Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl); if (ctrl & e.Key == Key.Space) { e.Handled = true; //MessageBox.Show("Get Intellisense info..."); // TEMPORARY... //bool ctrlSpace = CtrlSpaceCheckBox.IsChecked == true; //AnalyzeProject(ctrlSpace); AnalyzeProject2(true); } } private bool IsNonprintableCharacter(Key key) { return ( // includes pgup, pgdown, up, down, left, right, home, end (key >= Key.PageUp && key <= Key.Down) ); } /// <summary> /// try to convert the content index to a line and column /// </summary> /// <param name="fileVm"></param> /// <param name="caretIndex"></param> private void ResolveLineAndColumnPositionInFileFromCaretIndex(ProjectFileViewModel fileVm) { int caretIndex = fileVm.CaretIndex; var contentParts = fileVm.Content.Split(new[] { "\r\n" }, StringSplitOptions.None); int newStart = 0; bool done = false; for (int line = 0; line < contentParts.Length && !done; line++) { string lineContent = contentParts[line]; int start = newStart; int end = newStart + lineContent.Length; if (caretIndex >= start && caretIndex <= end) { fileVm.CaretLine = line + 1; fileVm.CaretColumn = caretIndex - start + 1; done = true; } newStart = end + 2; } fileVm.CaretLocation = string.Format("line {0}, col {1}", fileVm.CaretLine, fileVm.CaretColumn); } private bool UpdateLineAndColumnOfCursorPositionInViewModel(bool bypassContentSynchronizationWithViewModel) { ProjectViewModel proj = DataContext as ProjectViewModel; if (proj == null) return false; ProjectFileViewModel projFile = proj.SelectedProjectItem as ProjectFileViewModel; if (projFile == null) return false; // Update the caret index. I'd like to just data-bind the thing, but it's not a dependency property, // and this seems to be the simplest way to do it. projFile.CaretIndex = SelectedFileContent.CaretIndex; if (bypassContentSynchronizationWithViewModel) { // Update file content projFile.Content = SelectedFileContent.Text; } ResolveLineAndColumnPositionInFileFromCaretIndex(projFile); return true; } private void SelectedFileContent_KeyUp(object sender, System.Windows.Input.KeyEventArgs e) { // if input was not a control character, update the text if (!UpdateLineAndColumnOfCursorPositionInViewModel(IsNonprintableCharacter(e.Key))) return; // Run code completion when a period is entered if (e.Key == Key.Decimal || e.Key == Key.OemPeriod) { AnalyzeProject2(false); } return; /* if (_fileToParse == projFile) { // reset time _timeAtWhichToParse = DateTime.Now + temporalParseBuffer; } else if (_fileToParse == null) { // set file and time to parse _fileToParse = projFile; _timeAtWhichToParse = DateTime.Now + temporalParseBuffer; Task.Factory.StartNew(() => { while (_timeAtWhichToParse > DateTime.Now) { // If file has changed by now, just bail out. // For the purposes of this prototype, it's not important to deal with this. if (_fileToParse != projFile) return; Thread.Sleep(_timeAtWhichToParse - DateTime.Now); } // at this point, the timeAtWhichToParse should have passed // Check just one more time... if (_fileToParse != projFile) return; ParseFile(); }); } */ } private readonly TimeSpan temporalParseBuffer = TimeSpan.FromMilliseconds(2000); private ProjectFileViewModel _fileToParse; private DateTime _timeAtWhichToParse; private void ParseFile() { if (Dispatcher != null && !Dispatcher.CheckAccess()) { Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)ParseFile); return; } ProjectFileViewModel fileToParse = _fileToParse; #region Do Parsing and other stuff... //Logger.AppendLine("this is where we will parse file {0}...", fileToParse.Name); //ParseFile(fileToParse); #endregion // if the preconditions for this method invocation still hold true, then clear the file to parse ref to indicate that we've parse the file. if (fileToParse == _fileToParse && DateTime.Now > _timeAtWhichToParse) _fileToParse = null; } //private void ParseFile(ProjectFileViewModel fileViewModelToParse) //{ // var fileDto = ProjectMVVMConverters.FromViewModelToModel(fileViewModelToParse); // MockWebServiceUtility.ParseFile(fileDto, response => // { // if (response.Parse == null) // return; // var errors = response.Parse.Errors; // //response.Parse.Errors // if (errors != null) // { // Logger.AppendLine("{0} error(s) detected.", errors.Length); // if (errors.Length > 0) // foreach (var err in errors) // Logger.AppendLine("{0}: In file {1} ({2}, {3}): {4}", err.Type, err.FileName, err.Line, err.Column, err.Message); // } // }); //} //private static FileOperationResponse DoAutoComplete(FileOperationRequest request) //{ // return AutocompleteServiceUtil.DoAutoComplete(request); //} private void AnalyzeProject2(bool ctrlSpace) { //ctrlSpace = true; var sw = Stopwatch.StartNew(); var projectVm = (ProjectViewModel)DataContext; var fileVm = projectVm.SelectedProjectItem as ProjectFileViewModel; if (fileVm == null) { Logger.AppendLine("A file must be selected"); return; } fileVm.CaretIndex = SelectedFileContent.CaretIndex; // Synchronize the view's content with the viewmodel (since by default this is only done AFTER the textbox loses focus) fileVm.Content = SelectedFileContent.Text; // update file content in local data store if not already done var projectModelRepo = EndpointHost.AppHost.TryResolve<IProjectModelRepository>(); projectModelRepo.SaveFileContent(478, fileVm.ProjectId, fileVm.Id, fileVm.Content); var fileRequest = new FileOperationRequest() { UserId = 478, //projectVm..UserId, ProjectId = projectVm.ProjectId, FileId = fileVm.Id, CompleteCode = new FileCodeCompletionRequest() { AutoComplete = true, Offset = fileVm.CaretIndex, LineNumber = fileVm.CaretLine, ColumnNumber = fileVm.CaretColumn, CtrlSpace = ctrlSpace }, Parse = new FileParseRequest() }; var fileResponse = AutocompleteServiceUtil.DoAutoComplete(fileRequest); #if false var projectDto = ProjectMVVMConverters.FromViewModelToModel(projectVm); var projectModel = ProjectModelConverters.FromDtoToModel(projectDto); var analysisRequest = new ProjectAnalysisRequest() { ProjectModel = projectModel, CodeCompletionParameters = new ProjectAnalysisCodeCompletionParameters() { CtrlSpace = ctrlSpace, FileId = fileVm.Id, Offset = fileVm.CaretIndex //Line = request.CompleteCode.LineNumber, //Column = request.CompleteCode.ColumnNumber, //CtrlSpace = true // always true for now } }; ProjectAnalysisResult analysisResult = NRefactoryUtils.RunFullProjectAnalysis(analysisRequest); //StatelessProjectResponse response = MockWebServiceUtility.Server_HandleStatelessCodeCompletionRequest(request); FileOperationResponse response = new FileOperationResponse(); // Convert analysis result model to file operation response DTO if (analysisResult.CompletionOptions != null) { response.CodeCompletion = new FileCodeCompletionResponse(); response.CodeCompletion.CompletionOptions = analysisResult.CompletionOptions .Select(ProjectModelConverters.FromICompletionDataToFileCodeCompletionResult).ToArray(); for (int i = 0, len = response.CodeCompletion.CompletionOptions.Length; i < len; i++) response.CodeCompletion.CompletionOptions[i].Id = i; response.CodeCompletion.CompletionWord = analysisResult.CompletionWord; if (analysisResult.BestMatchToCompletionWord != null) response.CodeCompletion.BestMatchToCompletionWord = response.CodeCompletion.CompletionOptions.FirstOrDefault(x => x.CompletionText == analysisResult.BestMatchToCompletionWord.CompletionText); } var allErrors = new List<FileParseResult>(); foreach (var fileModel in analysisRequest.ProjectModel.GetFileDescendants()) { allErrors.AddRange(fileModel.Parser.ErrorsAndWarnings .Select(x => new FileParseResult() { FileId = fileModel.Id, FileName = fileModel.Name, Line = x.Region.BeginLine, Column = x.Region.BeginColumn, Type = x.ErrorType, Message = x.Message }).ToArray()); } response.ParseResults = allErrors.ToArray(); #endif //var jsonResponse = JsonConvert.SerializeObject(fileResponse, Formatting.Indented); //Logger.AppendLine(jsonResponse); // Summarize results... Logger.AppendLine("========================================================="); Logger.AppendLine("Project analysis completed in {0} ms", sw.ElapsedMilliseconds); if (fileResponse.CodeCompletion == null) { Logger.AppendLine("No Completion Results."); Logger.SetCodeCompletionOptions(null, null); } else { var codeCompletion = fileResponse.CodeCompletion; Logger.SetCodeCompletionOptions(codeCompletion.CompletionOptions, codeCompletion.BestMatchToCompletionWord); Logger.AppendLine("Completion Results..."); Logger.AppendLine(" Input: Line:{0} Col:{1} Offset:{2}", codeCompletion.Line, codeCompletion.Column, codeCompletion.Offset); Logger.AppendLine(" Context: \"{0}\" <cursor> \"{1}\"", codeCompletion.TextBeforeCursor, codeCompletion.TextAfterCursor); Logger.AppendLine(" {0} code completion option(s) generated.", codeCompletion.CompletionOptions.Length); // Try to find closest matching completion result if (string.IsNullOrWhiteSpace(codeCompletion.CompletionWord)) { Logger.AppendLine(" No code completion word detected."); } else { if (codeCompletion.BestMatchToCompletionWord != null) { Logger.AppendLine(" Detected code completion word, \"{0}\", most closely matches completion option \"{1}\".", codeCompletion.CompletionWord, codeCompletion.BestMatchToCompletionWord.CompletionText); } else { Logger.AppendLine(" Detected code completion word: {0}", codeCompletion.CompletionWord); } } } if (fileResponse.ParseResults != null) { Logger.AppendLine("{0} error(s) detected.", fileResponse.ParseResults.Length); if (fileResponse.ParseResults.Length > 0) foreach (var err in fileResponse.ParseResults) Logger.AppendLine("{0}: In file {1} ({2}, {3}): {4}", err.Type, err.FileName, err.Line, err.Column, err.Message); } } private void AnalyzeProject(bool ctrlSpace) { ctrlSpace = true; var sw = Stopwatch.StartNew(); var projectVm = (ProjectViewModel)DataContext; var fileVm = projectVm.SelectedProjectItem as ProjectFileViewModel; if (fileVm == null) { Logger.AppendLine("A file must be selected"); return; } fileVm.CaretIndex = SelectedFileContent.CaretIndex; // Synchronize the view's content with the viewmodel (since by default this is only done AFTER the textbox loses focus) fileVm.Content = SelectedFileContent.Text; var projectDto = ProjectMVVMConverters.FromViewModelToModel(projectVm); var request = new StatelessProjectRequest() { Project = projectDto, CodeCompletionParameters = new StatelessProjectCodeCompletionParameters() { CtrlSpace = ctrlSpace, FileId = fileVm.Id, Offset = fileVm.CaretIndex } }; StatelessProjectResponse response = MockWebServiceUtility.Server_HandleStatelessCodeCompletionRequest(request); var jsonResponse = JsonConvert.SerializeObject(response, Formatting.Indented); //Logger.AppendLine(jsonResponse); // Summarize results... Logger.AppendLine("Project analysis completed in {0} ms", sw.ElapsedMilliseconds); if (response.CompletionOptions != null) { // Order results by completion text response.CompletionOptions = response.CompletionOptions.OrderBy(x => x.CompletionText).ToArray(); Logger.AppendLine("{0} code completion option(s) generated.", response.CompletionOptions.Length); // Try to find closest matching completion result if (string.IsNullOrWhiteSpace(response.CompletionWord)) { Logger.AppendLine("No code completion word detected."); } else { //response. .CompletionOptionMostCloselyMatchingCompletionWord = response.CompletionOptions // .FirstOrDefault(x => x.CompletionText.CompareTo(response.CompletionWord) >= 0); //response.CompletionOptionMostCloselyMatchingCompletionWord = response.CompletionOptions.FirstOrDefault(x => x.CompletionText.StartsWith(response.CompletionWord, StringComparison.InvariantCultureIgnoreCase)); if (response.BestMatchToCompletionWord != null) { Logger.AppendLine("Detected code completion word, \"{0}\", most closely matches completion option \"{1}\".", response.CompletionWord, response.BestMatchToCompletionWord.CompletionText); } else { Logger.AppendLine("Detected code completion word: {0}", response.CompletionWord); } } } Logger.SetCodeCompletionOptions(response.CompletionOptions, response.BestMatchToCompletionWord); // response.CompletionWord); if (response.Errors != null) { Logger.AppendLine("{0} error(s) detected.", response.Errors.Length); if (response.Errors.Length > 0) foreach (var err in response.Errors) Logger.AppendLine("{0}: In file {1} ({2}, {3}): {4}", err.Type, err.FileName, err.Line, err.Column, err.Message); } } //private void AppendToProjectLog(string format, params object[] args) //{ // var str = string.Format(format, args); // ProjectLogTextBox.AppendText(str); // if (!str.EndsWith("\r\n")) // ProjectLogTextBox.AppendText("\r\n"); //} } public class ProjectDataTemplateSelector : DataTemplateSelector { //public NamedItemBrowserDataTemplateSelector() //{ //} public DataTemplate FileDataTemplate { get; set; } public DataTemplate DirectoryDataTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item is ProjectFileViewModel) return FileDataTemplate; else if (item is ProjectDirectoryViewModel) return DirectoryDataTemplate; return base.SelectTemplate(item, container); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/housekeeping/housekeeping_time.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Operations.Housekeeping { /// <summary>Holder for reflection information generated from operations/housekeeping/housekeeping_time.proto</summary> public static partial class HousekeepingTimeReflection { #region Descriptor /// <summary>File descriptor for operations/housekeeping/housekeeping_time.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static HousekeepingTimeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci9vcGVyYXRpb25zL2hvdXNla2VlcGluZy9ob3VzZWtlZXBpbmdfdGltZS5w", "cm90bxIjaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ob3VzZWtlZXBpbmcaHmdv", "b2dsZS9wcm90b2J1Zi9kdXJhdGlvbi5wcm90bxo5b3BlcmF0aW9ucy9ob3Vz", "ZWtlZXBpbmcvaG91c2VrZWVwaW5nX3RpbWVfaW5kaWNhdG9yLnByb3RvIrAB", "ChBIb3VzZWtlZXBpbmdUaW1lElEKCWVudGl0eV9pZBgBIAEoCzI+LmhvbG1z", "LnR5cGVzLm9wZXJhdGlvbnMuaG91c2VrZWVwaW5nLkhvdXNla2VlcGluZ1Rp", "bWVJbmRpY2F0b3ISDAoEbmFtZRgCIAEoCRI7Chh0aW1lX3Bhc3RfbG9jYWxf", "bWlkbmlnaHQYAyABKAsyGS5nb29nbGUucHJvdG9idWYuRHVyYXRpb25CP1oX", "b3BlcmF0aW9ucy9ob3VzZWtlZXBpbmeqAiNIT0xNUy5UeXBlcy5PcGVyYXRp", "b25zLkhvdXNla2VlcGluZ2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.Housekeeping.HousekeepingTime), global::HOLMS.Types.Operations.Housekeeping.HousekeepingTime.Parser, new[]{ "EntityId", "Name", "TimePastLocalMidnight" }, null, null, null) })); } #endregion } #region Messages public sealed partial class HousekeepingTime : pb::IMessage<HousekeepingTime> { private static readonly pb::MessageParser<HousekeepingTime> _parser = new pb::MessageParser<HousekeepingTime>(() => new HousekeepingTime()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<HousekeepingTime> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingTime() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingTime(HousekeepingTime other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; name_ = other.name_; TimePastLocalMidnight = other.timePastLocalMidnight_ != null ? other.TimePastLocalMidnight.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public HousekeepingTime Clone() { return new HousekeepingTime(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 2; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "time_past_local_midnight" field.</summary> public const int TimePastLocalMidnightFieldNumber = 3; private global::Google.Protobuf.WellKnownTypes.Duration timePastLocalMidnight_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration TimePastLocalMidnight { get { return timePastLocalMidnight_; } set { timePastLocalMidnight_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as HousekeepingTime); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(HousekeepingTime other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (Name != other.Name) return false; if (!object.Equals(TimePastLocalMidnight, other.TimePastLocalMidnight)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (timePastLocalMidnight_ != null) hash ^= TimePastLocalMidnight.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (Name.Length != 0) { output.WriteRawTag(18); output.WriteString(Name); } if (timePastLocalMidnight_ != null) { output.WriteRawTag(26); output.WriteMessage(TimePastLocalMidnight); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (timePastLocalMidnight_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(TimePastLocalMidnight); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(HousekeepingTime other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.Name.Length != 0) { Name = other.Name; } if (other.timePastLocalMidnight_ != null) { if (timePastLocalMidnight_ == null) { timePastLocalMidnight_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } TimePastLocalMidnight.MergeFrom(other.TimePastLocalMidnight); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Operations.Housekeeping.HousekeepingTimeIndicator(); } input.ReadMessage(entityId_); break; } case 18: { Name = input.ReadString(); break; } case 26: { if (timePastLocalMidnight_ == null) { timePastLocalMidnight_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(timePastLocalMidnight_); break; } } } } } #endregion } #endregion Designer generated code
// 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.Security.Cryptography; namespace Internal.Cryptography { internal sealed class AppleCCCryptor : BasicSymmetricCipher { private readonly bool _encrypting; private SafeAppleCryptorHandle _cryptor; public AppleCCCryptor( Interop.AppleCrypto.PAL_SymmetricAlgorithm algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, byte[] iv, bool encrypting) : base(cipherMode.GetCipherIv(iv), blockSizeInBytes) { _encrypting = encrypting; OpenCryptor(algorithm, cipherMode, key); } protected override void Dispose(bool disposing) { if (disposing) { _cryptor?.Dispose(); _cryptor = null; } base.Dispose(disposing); } public override int Transform(byte[] input, int inputOffset, int count, byte[] output, int outputOffset) { Debug.Assert(input != null, "Expected valid input, got null"); Debug.Assert(inputOffset >= 0, $"Expected non-negative inputOffset, got {inputOffset}"); Debug.Assert(count > 0, $"Expected positive count, got {count}"); Debug.Assert((count % BlockSizeInBytes) == 0, $"Expected count aligned to block size {BlockSizeInBytes}, got {count}"); Debug.Assert(input.Length - inputOffset >= count, $"Expected valid input length/offset/count triplet, got {input.Length}/{inputOffset}/{count}"); Debug.Assert(output != null, "Expected valid output, got null"); Debug.Assert(outputOffset >= 0, $"Expected non-negative outputOffset, got {outputOffset}"); Debug.Assert(output.Length - outputOffset >= count, $"Expected valid output length/offset/count triplet, got {output.Length}/{outputOffset}/{count}"); return CipherUpdate(input, inputOffset, count, output, outputOffset); } public override byte[] TransformFinal(byte[] input, int inputOffset, int count) { Debug.Assert(input != null, "Expected valid input, got null"); Debug.Assert(inputOffset >= 0, $"Expected non-negative inputOffset, got {inputOffset}"); Debug.Assert(count > 0, $"Expected positive count, got {count}"); Debug.Assert((count % BlockSizeInBytes) == 0, $"Expected count aligned to block size {BlockSizeInBytes}, got {count}"); Debug.Assert(input.Length - inputOffset >= count, $"Expected valid input length/offset/count triplet, got {input.Length}/{inputOffset}/{count}"); byte[] output = ProcessFinalBlock(input, inputOffset, count); Reset(); return output; } private unsafe byte[] ProcessFinalBlock(byte[] input, int inputOffset, int count) { if (count == 0) { return Array.Empty<byte>(); } byte[] output = new byte[count]; int outputBytes = CipherUpdate(input, inputOffset, count, output, 0); int ret; int errorCode; fixed (byte* outputStart = output) { byte* outputCurrent = outputStart + outputBytes; int bytesWritten; ret = Interop.AppleCrypto.CryptorFinal( _cryptor, outputCurrent, output.Length - outputBytes, out bytesWritten, out errorCode); outputBytes += bytesWritten; } ProcessInteropError(ret, errorCode); if (outputBytes == output.Length) { return output; } if (outputBytes == 0) { return Array.Empty<byte>(); } byte[] userData = new byte[outputBytes]; Buffer.BlockCopy(output, 0, userData, 0, outputBytes); return userData; } private unsafe int CipherUpdate(byte[] input, int inputOffset, int count, byte[] output, int outputOffset) { int ret; int ccStatus; int bytesWritten; if (count == 0) { return 0; } fixed (byte* inputStart = input) fixed (byte* outputStart = output) { byte* inputCurrent = inputStart + inputOffset; byte* outputCurrent = outputStart + outputOffset; ret = Interop.AppleCrypto.CryptorUpdate( _cryptor, inputCurrent, count, outputCurrent, output.Length - outputOffset, out bytesWritten, out ccStatus); } ProcessInteropError(ret, ccStatus); return bytesWritten; } private unsafe void OpenCryptor( Interop.AppleCrypto.PAL_SymmetricAlgorithm algorithm, CipherMode cipherMode, byte[] key) { int ret; int ccStatus; byte[] iv = IV; fixed (byte* pbKey = key) fixed (byte* pbIv = iv) { ret = Interop.AppleCrypto.CryptorCreate( _encrypting ? Interop.AppleCrypto.PAL_SymmetricOperation.Encrypt : Interop.AppleCrypto.PAL_SymmetricOperation.Decrypt, algorithm, GetPalChainMode(cipherMode), Interop.AppleCrypto.PAL_PaddingMode.None, pbKey, key.Length, pbIv, Interop.AppleCrypto.PAL_SymmetricOptions.None, out _cryptor, out ccStatus); } ProcessInteropError(ret, ccStatus); } private Interop.AppleCrypto.PAL_ChainingMode GetPalChainMode(CipherMode cipherMode) { switch (cipherMode) { case CipherMode.CBC: return Interop.AppleCrypto.PAL_ChainingMode.CBC; case CipherMode.ECB: return Interop.AppleCrypto.PAL_ChainingMode.ECB; default: throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CipherModeNotSupported, cipherMode)); } } private unsafe void Reset() { int ret; int ccStatus; byte[] iv = IV; fixed (byte* pbIv = iv) { ret = Interop.AppleCrypto.CryptorReset(_cryptor, pbIv, out ccStatus); } ProcessInteropError(ret, ccStatus); } private static void ProcessInteropError(int functionReturnCode, int ccStatus) { // Success if (functionReturnCode == 1) { return; } // Platform error if (functionReturnCode == 0) { Debug.Assert(ccStatus != 0, "Interop function returned 0 but a system code of success"); throw Interop.AppleCrypto.CreateExceptionForCCError( ccStatus, Interop.AppleCrypto.CCCryptorStatus); } // Usually this will be -1, a general indication of bad inputs. Debug.Fail($"Interop boundary returned unexpected value {functionReturnCode}"); throw new CryptographicException(); } } }
// // SaslMechanism.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Net; using System.Text; namespace MailKit.Security { /// <summary> /// A SASL authentication mechanism. /// </summary> /// <remarks> /// Authenticating via a SASL mechanism may be a multi-step process. /// To determine if the mechanism has completed the necessary steps /// to authentication, check the <see cref="IsAuthenticated"/> after /// each call to <see cref="Challenge(string)"/>. /// </remarks> public abstract class SaslMechanism { /// <summary> /// The supported authentication mechanisms in order of strongest to weakest. /// </summary> /// <remarks> /// Use by the various clients when authenticating via SASL to determine /// which order the SASL mechanisms supported by the server should be tried. /// </remarks> public static readonly string[] AuthMechanismRank = { "XOAUTH2", "SCRAM-SHA-1", "NTLM", "CRAM-MD5", "DIGEST-MD5", "PLAIN", "LOGIN" }; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanism"/> class. /// </summary> /// <remarks> /// Creates a new SASL context. /// </remarks> /// <param name="uri">The URI of the service.</param> /// <param name="credentials">The user's credentials.</param> protected SaslMechanism (Uri uri, ICredentials credentials) { Credentials = credentials; Uri = uri; } /// <summary> /// Gets the name of the mechanism. /// </summary> /// <remarks> /// Gets the name of the mechanism. /// </remarks> /// <value>The name of the mechanism.</value> public abstract string MechanismName { get; } /// <summary> /// Gets the user's credentials. /// </summary> /// <remarks> /// Gets the user's credentials. /// </remarks> /// <value>The user's credentials.</value> public ICredentials Credentials { get; private set; } /// <summary> /// Gets whether or not the mechanism supports an initial response (SASL-IR). /// </summary> /// <remarks> /// SASL mechanisms that support sending an initial client response to the server /// should return <value>true</value>. /// </remarks> /// <value><c>true</c> if the mechanism supports an initial response; otherwise, <c>false</c>.</value> public virtual bool SupportsInitialResponse { get { return false; } } /// <summary> /// Gets or sets whether the SASL mechanism has finished authenticating. /// </summary> /// <remarks> /// Gets or sets whether the SASL mechanism has finished authenticating. /// </remarks> /// <value><c>true</c> if the SASL mechanism has finished authenticating; otherwise, <c>false</c>.</value> public bool IsAuthenticated { get; protected set; } /// <summary> /// Gets or sets the URI of the service. /// </summary> /// <remarks> /// Gets or sets the URI of the service. /// </remarks> /// <value>The URI of the service.</value> public Uri Uri { get; protected set; } /// <summary> /// Parses the server's challenge token and returns the next challenge response. /// </summary> /// <remarks> /// Parses the server's challenge token and returns the next challenge response. /// </remarks> /// <returns>The next challenge response.</returns> /// <param name="token">The server's challenge token.</param> /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param> /// <param name="length">The length of the server's challenge.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> protected abstract byte[] Challenge (byte[] token, int startIndex, int length); /// <summary> /// Decodes the base64-encoded server challenge and returns the next challenge response encoded in base64. /// </summary> /// <remarks> /// Decodes the base64-encoded server challenge and returns the next challenge response encoded in base64. /// </remarks> /// <returns>The next base64-encoded challenge response.</returns> /// <param name="token">The server's base64-encoded challenge token.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> public string Challenge (string token) { byte[] decoded; int length; if (token != null) { decoded = Convert.FromBase64String (token); length = decoded.Length; } else { decoded = null; length = 0; } var challenge = Challenge (decoded, 0, length); if (challenge == null) return null; return Convert.ToBase64String (challenge); } /// <summary> /// Resets the state of the SASL mechanism. /// </summary> /// <remarks> /// Resets the state of the SASL mechanism. /// </remarks> public virtual void Reset () { IsAuthenticated = false; } /// <summary> /// Determines if the specified SASL mechanism is supported by MailKit. /// </summary> /// <remarks> /// Use this method to make sure that a SASL mechanism is supported before calling /// <see cref="Create"/>. /// </remarks> /// <returns><c>true</c> if the specified SASL mechanism is supported; otherwise, <c>false</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="mechanism"/> is <c>null</c>. /// </exception> public static bool IsSupported (string mechanism) { if (mechanism == null) throw new ArgumentNullException ("mechanism"); switch (mechanism) { case "SCRAM-SHA-1": return true; case "DIGEST-MD5": return true; case "CRAM-MD5": return true; case "XOAUTH2": return true; case "PLAIN": return true; case "LOGIN": return true; case "NTLM": return true; default: return false; } } /// <summary> /// Create an instance of the specified SASL mechanism using the uri and credentials. /// </summary> /// <remarks> /// If unsure that a particular SASL mechanism is supported, you should first call /// <see cref="IsSupported"/>. /// </remarks> /// <returns>An instance of the requested SASL mechanism if supported; otherwise <c>null</c>.</returns> /// <param name="mechanism">The name of the SASL mechanism.</param> /// <param name="uri">The URI of the service to authenticate against.</param> /// <param name="credentials">The user's credentials.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="mechanism"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="uri"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="credentials"/> is <c>null</c>.</para> /// </exception> public static SaslMechanism Create (string mechanism, Uri uri, ICredentials credentials) { if (mechanism == null) throw new ArgumentNullException ("mechanism"); if (uri == null) throw new ArgumentNullException ("uri"); if (credentials == null) throw new ArgumentNullException ("credentials"); switch (mechanism) { //case "KERBEROS_V4": return null; case "SCRAM-SHA-1": return new SaslMechanismScramSha1 (uri, credentials); case "DIGEST-MD5": return new SaslMechanismDigestMd5 (uri, credentials); case "CRAM-MD5": return new SaslMechanismCramMd5 (uri, credentials); //case "GSSAPI": return null; case "XOAUTH2": return new SaslMechanismOAuth2 (uri, credentials); case "PLAIN": return new SaslMechanismPlain (uri, credentials); case "LOGIN": return new SaslMechanismLogin (uri, credentials); case "NTLM": return new SaslMechanismNtlm (uri, credentials); default: return null; } } /// <summary> /// Determines if the character is a non-ASCII space. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-C.1.2 /// </remarks> /// <returns><c>true</c> if the character is a non-ASCII space; otherwise, <c>false</c>.</returns> /// <param name="c">The character.</param> static bool IsNonAsciiSpace (char c) { switch (c) { case '\u00A0': // NO-BREAK SPACE case '\u1680': // OGHAM SPACE MARK case '\u2000': // EN QUAD case '\u2001': // EM QUAD case '\u2002': // EN SPACE case '\u2003': // EM SPACE case '\u2004': // THREE-PER-EM SPACE case '\u2005': // FOUR-PER-EM SPACE case '\u2006': // SIX-PER-EM SPACE case '\u2007': // FIGURE SPACE case '\u2008': // PUNCTUATION SPACE case '\u2009': // THIN SPACE case '\u200A': // HAIR SPACE case '\u200B': // ZERO WIDTH SPACE case '\u202F': // NARROW NO-BREAK SPACE case '\u205F': // MEDIUM MATHEMATICAL SPACE case '\u3000': // IDEOGRAPHIC SPACE return true; default: return false; } } /// <summary> /// Determines if the character is commonly mapped to nothing. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-B.1 /// </remarks> /// <returns><c>true</c> if the character is commonly mapped to nothing; otherwise, <c>false</c>.</returns> /// <param name="c">The character.</param> static bool IsCommonlyMappedToNothing (char c) { switch (c) { case '\u00AD': case '\u034F': case '\u1806': case '\u180B': case '\u180C': case '\u180D': case '\u200B': case '\u200C': case '\u200D': case '\u2060': case '\uFE00': case '\uFE01': case '\uFE02': case '\uFE03': case '\uFE04': case '\uFE05': case '\uFE06': case '\uFE07': case '\uFE08': case '\uFE09': case '\uFE0A': case '\uFE0B': case '\uFE0C': case '\uFE0D': case '\uFE0E': case '\uFE0F': case '\uFEFF': return true; default: return false; } } /// <summary> /// Determines if the character is prohibited. /// </summary> /// <remarks> /// This list was obtained from http://tools.ietf.org/html/rfc3454#appendix-C.3 /// </remarks> /// <returns><c>true</c> if the character is prohibited; otherwise, <c>false</c>.</returns> /// <param name="s">The string.</param> /// <param name="index">The character index.</param> static bool IsProhibited (string s, int index) { int u = char.ConvertToUtf32 (s, index); // Private Use characters: http://tools.ietf.org/html/rfc3454#appendix-C.3 if ((u >= 0xE000 && u <= 0xF8FF) || (u >= 0xF0000 && u <= 0xFFFFD) || (u >= 0x100000 && u <= 0x10FFFD)) return true; // Non-character code points: http://tools.ietf.org/html/rfc3454#appendix-C.4 if ((u >= 0xFDD0 && u <= 0xFDEF) || (u >= 0xFFFE && u <= 0xFFFF) || (u >= 0x1FFFE & u <= 0x1FFFF) || (u >= 0x2FFFE & u <= 0x2FFFF) || (u >= 0x3FFFE & u <= 0x3FFFF) || (u >= 0x4FFFE & u <= 0x4FFFF) || (u >= 0x5FFFE & u <= 0x5FFFF) || (u >= 0x6FFFE & u <= 0x6FFFF) || (u >= 0x7FFFE & u <= 0x7FFFF) || (u >= 0x8FFFE & u <= 0x8FFFF) || (u >= 0x9FFFE & u <= 0x9FFFF) || (u >= 0xAFFFE & u <= 0xAFFFF) || (u >= 0xBFFFE & u <= 0xBFFFF) || (u >= 0xCFFFE & u <= 0xCFFFF) || (u >= 0xDFFFE & u <= 0xDFFFF) || (u >= 0xEFFFE & u <= 0xEFFFF) || (u >= 0xFFFFE & u <= 0xFFFFF) || (u >= 0x10FFFE & u <= 0x10FFFF)) return true; // Surrogate code points: http://tools.ietf.org/html/rfc3454#appendix-C.5 if (u >= 0xD800 && u <= 0xDFFF) return true; // Inappropriate for plain text characters: http://tools.ietf.org/html/rfc3454#appendix-C.6 switch (u) { case 0xFFF9: // INTERLINEAR ANNOTATION ANCHOR case 0xFFFA: // INTERLINEAR ANNOTATION SEPARATOR case 0xFFFB: // INTERLINEAR ANNOTATION TERMINATOR case 0xFFFC: // OBJECT REPLACEMENT CHARACTER case 0xFFFD: // REPLACEMENT CHARACTER return true; } // Inappropriate for canonical representation: http://tools.ietf.org/html/rfc3454#appendix-C.7 if (u >= 0x2FF0 && u <= 0x2FFB) return true; // Change display properties or are deprecated: http://tools.ietf.org/html/rfc3454#appendix-C.8 switch (u) { case 0x0340: // COMBINING GRAVE TONE MARK case 0x0341: // COMBINING ACUTE TONE MARK case 0x200E: // LEFT-TO-RIGHT MARK case 0x200F: // RIGHT-TO-LEFT MARK case 0x202A: // LEFT-TO-RIGHT EMBEDDING case 0x202B: // RIGHT-TO-LEFT EMBEDDING case 0x202C: // POP DIRECTIONAL FORMATTING case 0x202D: // LEFT-TO-RIGHT OVERRIDE case 0x202E: // RIGHT-TO-LEFT OVERRIDE case 0x206A: // INHIBIT SYMMETRIC SWAPPING case 0x206B: // ACTIVATE SYMMETRIC SWAPPING case 0x206C: // INHIBIT ARABIC FORM SHAPING case 0x206D: // ACTIVATE ARABIC FORM SHAPING case 0x206E: // NATIONAL DIGIT SHAPES case 0x206F: // NOMINAL DIGIT SHAPES return true; } // Tagging characters: http://tools.ietf.org/html/rfc3454#appendix-C.9 if (u == 0xE0001 || (u >= 0xE0020 & u <= 0xE007F)) return true; return false; } /// <summary> /// Prepares the user name or password string. /// </summary> /// <remarks> /// Prepares a user name or password string according to the rules of rfc4013. /// </remarks> /// <returns>The prepared string.</returns> /// <param name="s">The string to prepare.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="s"/> is <c>null</c>. /// </exception> /// <exception cref="System.ArgumentException"> /// <paramref name="s"/> contains prohibited characters. /// </exception> public static string SaslPrep (string s) { if (s == null) throw new ArgumentNullException ("s"); if (s.Length == 0) return s; var builder = new StringBuilder (s.Length); for (int i = 0; i < s.Length; i++) { if (IsNonAsciiSpace (s[i])) { // non-ASII space characters [StringPrep, C.1.2] that can be // mapped to SPACE (U+0020). builder.Append (' '); } else if (IsCommonlyMappedToNothing (s[i])) { // the "commonly mapped to nothing" characters [StringPrep, B.1] // that can be mapped to nothing. } else if (char.IsControl (s[i])) { throw new ArgumentException ("Control characters are prohibited.", "s"); } else if (IsProhibited (s, i)) { throw new ArgumentException ("One or more characters in the string are prohibited.", "s"); } else { builder.Append (s[i]); } } #if !NETFX_CORE return builder.ToString ().Normalize (NormalizationForm.FormKC); #else return builder.ToString (); #endif } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole // // 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 NUnit.Framework; namespace NUnit.Engine.Internal.Tests { [TestFixture] public class PathUtilTests : PathUtils { [Test] public void CheckDefaults() { Assert.AreEqual( Path.DirectorySeparatorChar, PathUtils.DirectorySeparatorChar ); Assert.AreEqual( Path.AltDirectorySeparatorChar, PathUtils.AltDirectorySeparatorChar ); } } // Local Assert extension internal class Assert : NUnit.Framework.Assert { public static void SamePathOrUnder( string path1, string path2 ) { string msg = "\r\n\texpected: Same path or under <{0}>\r\n\t but was: <{1}>"; Assert.IsTrue( PathUtils.SamePathOrUnder( path1, path2 ), msg, path1, path2 ); } public static void NotSamePathOrUnder( string path1, string path2 ) { string msg = "\r\n\texpected: Not same path or under <{0}>\r\n\t but was: <{1}>"; Assert.IsFalse( PathUtils.SamePathOrUnder( path1, path2 ), msg, path1, path2 ); } } [TestFixture] public class PathUtilTests_Windows : PathUtils { [OneTimeSetUp] public static void SetUpUnixSeparators() { PathUtils.DirectorySeparatorChar = '\\'; PathUtils.AltDirectorySeparatorChar = '/'; } [OneTimeTearDown] public static void RestoreDefaultSeparators() { PathUtils.DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar; PathUtils.AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar; } [Test] public void Canonicalize() { Assert.AreEqual( @"C:\folder1\file.tmp", PathUtils.Canonicalize( @"C:\folder1\.\folder2\..\file.tmp" ) ); Assert.AreEqual( @"folder1\file.tmp", PathUtils.Canonicalize( @"folder1\.\folder2\..\file.tmp" ) ); Assert.AreEqual( @"folder1\file.tmp", PathUtils.Canonicalize( @"folder1\folder2\.\..\file.tmp" ) ); Assert.AreEqual( @"file.tmp", PathUtils.Canonicalize( @"folder1\folder2\..\.\..\file.tmp" ) ); Assert.AreEqual( @"file.tmp", PathUtils.Canonicalize( @"folder1\folder2\..\..\..\file.tmp" ) ); } [Test] [Platform(Exclude="Linux,UNIX,MacOSX")] public void RelativePath() { Assert.AreEqual( @"folder2\folder3", PathUtils.RelativePath( @"c:\folder1", @"c:\folder1\folder2\folder3" ) ); Assert.AreEqual( @"..\folder2\folder3", PathUtils.RelativePath( @"c:\folder1", @"c:\folder2\folder3" ) ); Assert.AreEqual( @"bin\debug", PathUtils.RelativePath( @"c:\folder1", @"bin\debug" ) ); Assert.IsNull( PathUtils.RelativePath( @"C:\folder", @"D:\folder" ), "Unrelated paths should return null" ); Assert.IsNull(PathUtils.RelativePath(@"C:\", @"D:\"), "Unrelated roots should return null"); Assert.IsNull(PathUtils.RelativePath(@"C:", @"D:"), "Unrelated roots (no trailing separators) should return null"); Assert.AreEqual(string.Empty, PathUtils.RelativePath(@"C:\folder1", @"C:\folder1")); Assert.AreEqual(string.Empty, PathUtils.RelativePath(@"C:\", @"C:\")); // First filePath consisting just of a root: Assert.AreEqual(@"folder1\folder2", PathUtils.RelativePath( @"C:\", @"C:\folder1\folder2")); // Trailing directory separator in first filePath shall be ignored: Assert.AreEqual(@"folder2\folder3", PathUtils.RelativePath( @"c:\folder1\", @"c:\folder1\folder2\folder3")); // Case-insensitive behavior, preserving 2nd filePath directories in result: Assert.AreEqual(@"Folder2\Folder3", PathUtils.RelativePath( @"C:\folder1", @"c:\folder1\Folder2\Folder3")); Assert.AreEqual(@"..\Folder2\folder3", PathUtils.RelativePath( @"c:\folder1", @"C:\Folder2\folder3")); } [Test] public void SamePathOrUnder() { Assert.SamePathOrUnder( @"C:\folder1\folder2\folder3", @"c:\folder1\.\folder2\junk\..\folder3" ); Assert.SamePathOrUnder( @"C:\folder1\folder2\", @"c:\folder1\.\folder2\junk\..\folder3" ); Assert.SamePathOrUnder( @"C:\folder1\folder2", @"c:\folder1\.\folder2\junk\..\folder3" ); Assert.SamePathOrUnder( @"C:\folder1\folder2", @"c:\folder1\.\Folder2\junk\..\folder3" ); Assert.NotSamePathOrUnder( @"C:\folder1\folder2", @"c:\folder1\.\folder22\junk\..\folder3" ); Assert.NotSamePathOrUnder( @"C:\folder1\folder2ile.tmp", @"D:\folder1\.\folder2\folder3\file.tmp" ); Assert.NotSamePathOrUnder( @"C:\", @"D:\" ); Assert.SamePathOrUnder( @"C:\", @"c:\" ); Assert.SamePathOrUnder( @"C:\", @"c:\bin\debug" ); } } [TestFixture] public class PathUtilTests_Unix : PathUtils { [OneTimeSetUp] public static void SetUpUnixSeparators() { PathUtils.DirectorySeparatorChar = '/'; PathUtils.AltDirectorySeparatorChar = '\\'; } [OneTimeTearDown] public static void RestoreDefaultSeparators() { PathUtils.DirectorySeparatorChar = System.IO.Path.DirectorySeparatorChar; PathUtils.AltDirectorySeparatorChar = System.IO.Path.AltDirectorySeparatorChar; } [Test] public void Canonicalize() { Assert.AreEqual( "/folder1/file.tmp", PathUtils.Canonicalize( "/folder1/./folder2/../file.tmp" ) ); Assert.AreEqual( "folder1/file.tmp", PathUtils.Canonicalize( "folder1/./folder2/../file.tmp" ) ); Assert.AreEqual( "folder1/file.tmp", PathUtils.Canonicalize( "folder1/folder2/./../file.tmp" ) ); Assert.AreEqual( "file.tmp", PathUtils.Canonicalize( "folder1/folder2/.././../file.tmp" ) ); Assert.AreEqual( "file.tmp", PathUtils.Canonicalize( "folder1/folder2/../../../file.tmp" ) ); } [Test] public void RelativePath() { Assert.AreEqual( "folder2/folder3", PathUtils.RelativePath( "/folder1", "/folder1/folder2/folder3" ) ); Assert.AreEqual( "../folder2/folder3", PathUtils.RelativePath( "/folder1", "/folder2/folder3" ) ); Assert.AreEqual( "bin/debug", PathUtils.RelativePath( "/folder1", "bin/debug" ) ); Assert.AreEqual( "../other/folder", PathUtils.RelativePath( "/folder", "/other/folder" ) ); Assert.AreEqual( "../../d", PathUtils.RelativePath( "/a/b/c", "/a/d" ) ); Assert.AreEqual(string.Empty, PathUtils.RelativePath("/a/b", "/a/b")); Assert.AreEqual(string.Empty, PathUtils.RelativePath("/", "/")); // First filePath consisting just of a root: Assert.AreEqual("folder1/folder2", PathUtils.RelativePath( "/", "/folder1/folder2")); // Trailing directory separator in first filePath shall be ignored: Assert.AreEqual("folder2/folder3", PathUtils.RelativePath( "/folder1/", "/folder1/folder2/folder3")); // Case-sensitive behavior: Assert.AreEqual("../Folder1/Folder2/folder3", PathUtils.RelativePath("/folder1", "/Folder1/Folder2/folder3"), "folders differing in case"); } [Test] public void SamePathOrUnder() { Assert.SamePathOrUnder( "/folder1/folder2/folder3", "/folder1/./folder2/junk/../folder3" ); Assert.SamePathOrUnder( "/folder1/folder2/", "/folder1/./folder2/junk/../folder3" ); Assert.SamePathOrUnder( "/folder1/folder2", "/folder1/./folder2/junk/../folder3" ); Assert.NotSamePathOrUnder( "/folder1/folder2", "/folder1/./Folder2/junk/../folder3" ); Assert.NotSamePathOrUnder( "/folder1/folder2", "/folder1/./folder22/junk/../folder3" ); Assert.SamePathOrUnder( "/", "/" ); Assert.SamePathOrUnder( "/", "/bin/debug" ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Managed ACL wrapper for files & directories. ** ** ===========================================================*/ using Microsoft.Win32.SafeHandles; using Microsoft.Win32; using System.Collections; using System.Diagnostics.Contracts; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; using System; namespace System.Security.AccessControl { // Constants from from winnt.h - search for FILE_WRITE_DATA, etc. [Flags] public enum FileSystemRights { // No None field - An ACE with the value 0 cannot grant nor deny. ReadData = 0x000001, ListDirectory = ReadData, // For directories WriteData = 0x000002, CreateFiles = WriteData, // For directories AppendData = 0x000004, CreateDirectories = AppendData, // For directories ReadExtendedAttributes = 0x000008, WriteExtendedAttributes = 0x000010, ExecuteFile = 0x000020, // For files Traverse = ExecuteFile, // For directories // DeleteSubdirectoriesAndFiles only makes sense on directories, but // the shell explicitly sets it for files in its UI. So we'll include // it in FullControl. DeleteSubdirectoriesAndFiles = 0x000040, ReadAttributes = 0x000080, WriteAttributes = 0x000100, Delete = 0x010000, ReadPermissions = 0x020000, ChangePermissions = 0x040000, TakeOwnership = 0x080000, // From the Core File Services team, CreateFile always requires // SYNCHRONIZE access. Very tricksy, CreateFile is. Synchronize = 0x100000, // Can we wait on the handle? FullControl = 0x1F01FF, // These map to what Explorer sets, and are what most users want. // However, an ACL editor will also want to set the Synchronize // bit when allowing access, and exclude the synchronize bit when // denying access. Read = ReadData | ReadExtendedAttributes | ReadAttributes | ReadPermissions, ReadAndExecute = Read | ExecuteFile, Write = WriteData | AppendData | WriteExtendedAttributes | WriteAttributes, Modify = ReadAndExecute | Write | Delete, } public sealed class FileSystemAccessRule : AccessRule { #region Constructors // // Constructor for creating access rules for file objects // public FileSystemAccessRule( IdentityReference identity, FileSystemRights fileSystemRights, AccessControlType type) : this( identity, AccessMaskFromRights(fileSystemRights, type), false, InheritanceFlags.None, PropagationFlags.None, type) { } public FileSystemAccessRule( String identity, FileSystemRights fileSystemRights, AccessControlType type) : this( new NTAccount(identity), AccessMaskFromRights(fileSystemRights, type), false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Constructor for creating access rules for folder objects // public FileSystemAccessRule( IdentityReference identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( identity, AccessMaskFromRights(fileSystemRights, type), false, inheritanceFlags, propagationFlags, type) { } public FileSystemAccessRule( String identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( new NTAccount(identity), AccessMaskFromRights(fileSystemRights, type), false, inheritanceFlags, propagationFlags, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal FileSystemAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } #endregion #region Public properties public FileSystemRights FileSystemRights { get { return RightsFromAccessMask(base.AccessMask); } } #endregion #region Access mask to rights translation // ACL's on files have a SYNCHRONIZE bit, and CreateFile ALWAYS // asks for it. So for allows, let's always include this bit, // and for denies, let's never include this bit unless we're denying // full control. This is the right thing for users, even if it does // make the model look asymmetrical from a purist point of view. internal static int AccessMaskFromRights(FileSystemRights fileSystemRights, AccessControlType controlType) { if (fileSystemRights < (FileSystemRights)0 || fileSystemRights > FileSystemRights.FullControl) throw new ArgumentOutOfRangeException("fileSystemRights", SR.Format(SR.Argument_InvalidEnumValue, fileSystemRights, "FileSystemRights")); Contract.EndContractBlock(); if (controlType == AccessControlType.Allow) { fileSystemRights |= FileSystemRights.Synchronize; } else if (controlType == AccessControlType.Deny) { if (fileSystemRights != FileSystemRights.FullControl && fileSystemRights != (FileSystemRights.FullControl & ~FileSystemRights.DeleteSubdirectoriesAndFiles)) fileSystemRights &= ~FileSystemRights.Synchronize; } return (int)fileSystemRights; } internal static FileSystemRights RightsFromAccessMask(int accessMask) { return (FileSystemRights)accessMask; } #endregion } public sealed class FileSystemAuditRule : AuditRule { #region Constructors public FileSystemAuditRule( IdentityReference identity, FileSystemRights fileSystemRights, AuditFlags flags) : this( identity, fileSystemRights, InheritanceFlags.None, PropagationFlags.None, flags) { } public FileSystemAuditRule( IdentityReference identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( identity, AccessMaskFromRights(fileSystemRights), false, inheritanceFlags, propagationFlags, flags) { } public FileSystemAuditRule( String identity, FileSystemRights fileSystemRights, AuditFlags flags) : this( new NTAccount(identity), fileSystemRights, InheritanceFlags.None, PropagationFlags.None, flags) { } public FileSystemAuditRule( String identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( new NTAccount(identity), AccessMaskFromRights(fileSystemRights), false, inheritanceFlags, propagationFlags, flags) { } internal FileSystemAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } #endregion #region Private methods private static int AccessMaskFromRights(FileSystemRights fileSystemRights) { if (fileSystemRights < (FileSystemRights)0 || fileSystemRights > FileSystemRights.FullControl) throw new ArgumentOutOfRangeException("fileSystemRights", SR.Format(SR.Argument_InvalidEnumValue, fileSystemRights, "FileSystemRights")); Contract.EndContractBlock(); return (int)fileSystemRights; } #endregion #region Public properties public FileSystemRights FileSystemRights { get { return FileSystemAccessRule.RightsFromAccessMask(base.AccessMask); } } #endregion } public abstract class FileSystemSecurity : NativeObjectSecurity { #region Member variables private const ResourceType s_ResourceType = ResourceType.FileObject; #endregion [System.Security.SecurityCritical] // auto-generated internal FileSystemSecurity(bool isContainer) : base(isContainer, s_ResourceType, _HandleErrorCode, isContainer) { } [System.Security.SecurityCritical] // auto-generated internal FileSystemSecurity(bool isContainer, String name, AccessControlSections includeSections, bool isDirectory) : base(isContainer, s_ResourceType, name, includeSections, _HandleErrorCode, isDirectory) { } [System.Security.SecurityCritical] // auto-generated internal FileSystemSecurity(bool isContainer, SafeFileHandle handle, AccessControlSections includeSections, bool isDirectory) : base(isContainer, s_ResourceType, handle, includeSections, _HandleErrorCode, isDirectory) { } [System.Security.SecurityCritical] // auto-generated private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { System.Exception exception = null; switch (errorCode) { case Interop.mincore.Errors.ERROR_INVALID_NAME: exception = new ArgumentException(SR.Argument_InvalidName, "name"); break; case Interop.mincore.Errors.ERROR_INVALID_HANDLE: exception = new ArgumentException(SR.AccessControl_InvalidHandle); break; case Interop.mincore.Errors.ERROR_FILE_NOT_FOUND: if ((context != null) && (context is bool) && ((bool)context)) { // DirectorySecurity if ((name != null) && (name.Length != 0)) exception = new DirectoryNotFoundException(name); else exception = new DirectoryNotFoundException(); } else { if ((name != null) && (name.Length != 0)) exception = new FileNotFoundException(name); else exception = new FileNotFoundException(); } break; default: break; } return exception; } #region Factories public sealed override AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new FileSystemAccessRule( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public sealed override AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new FileSystemAuditRule( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } #endregion #region Internal Methods internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules = AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } [System.Security.SecurityCritical] // auto-generated internal void Persist(String fullPath) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(fullPath, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } [System.Security.SecuritySafeCritical] // auto-generated internal void Persist(SafeFileHandle handle, String fullPath) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(handle, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } #endregion #region Public Methods public void AddAccessRule(FileSystemAccessRule rule) { base.AddAccessRule(rule); //PersistIfPossible(); } public void SetAccessRule(FileSystemAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(FileSystemAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(FileSystemAccessRule rule) { if (rule == null) throw new ArgumentNullException("rule"); Contract.EndContractBlock(); // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit. // This is to avoid dangling synchronize bit AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { FileSystemAccessRule fsrule = rules[i] as FileSystemAccessRule; if ((fsrule != null) && (fsrule.FileSystemRights == rule.FileSystemRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { return base.RemoveAccessRule(rule); } } // Mask off the synchronize bit (that is automatically added for Allow) // before removing the ACL. The logic here should be same as Deny and hence // fake a call to AccessMaskFromRights as though the ACL is for Deny FileSystemAccessRule ruleNew = new FileSystemAccessRule( rule.IdentityReference, FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny), rule.IsInherited, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType); return base.RemoveAccessRule(ruleNew); } public void RemoveAccessRuleAll(FileSystemAccessRule rule) { // We don't need to worry about the synchronize bit here // AccessMask is ignored anyways in a RemoveAll call base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(FileSystemAccessRule rule) { if (rule == null) throw new ArgumentNullException("rule"); Contract.EndContractBlock(); // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit // This is to avoid dangling synchronize bit AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { FileSystemAccessRule fsrule = rules[i] as FileSystemAccessRule; if ((fsrule != null) && (fsrule.FileSystemRights == rule.FileSystemRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { base.RemoveAccessRuleSpecific(rule); return; } } // Mask off the synchronize bit (that is automatically added for Allow) // before removing the ACL. The logic here should be same as Deny and hence // fake a call to AccessMaskFromRights as though the ACL is for Deny FileSystemAccessRule ruleNew = new FileSystemAccessRule( rule.IdentityReference, FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny), rule.IsInherited, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType); base.RemoveAccessRuleSpecific(ruleNew); } public void AddAuditRule(FileSystemAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(FileSystemAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(FileSystemAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(FileSystemAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(FileSystemAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } #endregion #region some overrides public override Type AccessRightType { get { return typeof(System.Security.AccessControl.FileSystemRights); } } public override Type AccessRuleType { get { return typeof(System.Security.AccessControl.FileSystemAccessRule); } } public override Type AuditRuleType { get { return typeof(System.Security.AccessControl.FileSystemAuditRule); } } #endregion } public sealed class FileSecurity : FileSystemSecurity { #region Constructors [System.Security.SecuritySafeCritical] // auto-generated public FileSecurity() : base(false) { } [System.Security.SecuritySafeCritical] // auto-generated public FileSecurity(String fileName, AccessControlSections includeSections) : base(false, fileName, includeSections, false) { String fullPath = Path.GetFullPath(fileName); } // Warning! Be exceedingly careful with this constructor. Do not make // it public. We don't want to get into a situation where someone can // pass in the string foo.txt and a handle to bar.exe, and we do a // demand on the wrong file name. [System.Security.SecurityCritical] // auto-generated internal FileSecurity(SafeFileHandle handle, String fullPath, AccessControlSections includeSections) : base(false, handle, includeSections, false) { } #endregion } public sealed class DirectorySecurity : FileSystemSecurity { #region Constructors [System.Security.SecuritySafeCritical] // auto-generated public DirectorySecurity() : base(true) { } [System.Security.SecuritySafeCritical] // auto-generated public DirectorySecurity(String name, AccessControlSections includeSections) : base(true, name, includeSections, true) { String fullPath = Path.GetFullPath(name); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; /// <summary> /// Sin(System.Double) /// </summary> public class MathSin { public static int Main(string[] args) { MathSin test = new MathSin(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Sin(System.Double)."); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the result when radian is 0."); try { Double d = Math.Sin(0); if (d != 0) { TestLibrary.TestFramework.LogError("P01.1", "The result is error when radian is 0!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P01.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the result is 1 when radian is Math.PI/2."); try { Double d = Math.Sin(Math.PI/2); if ( d != 1) { TestLibrary.TestFramework.LogError("P02.1", "The result is error when radian is Math.PI/2!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P02.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the result is -1 when radian is -Math.PI/2."); try { Double d = Math.Sin(-Math.PI / 2); if (d != -1) { TestLibrary.TestFramework.LogError("P03.1", "The result is error when radian is -Math.PI/2!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P03.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the result is 1/2 when radian is Math.PI/6."); try { Double d = Math.Round(Math.Sin(Math.PI / 6), 2); if (d != 0.5d) { TestLibrary.TestFramework.LogError("P04.1", "The result is error when radian is Math.PI/6!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P04.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the result is -1/2 when radian is -Math.PI/6."); try { Double d = Math.Round(Math.Sin(-Math.PI / 6), 2); if (d != -0.5d) { TestLibrary.TestFramework.LogError("P05.1", "The result is error when radian is -Math.PI/6!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P05.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the result is NaN when radian is PositiveInfinity."); try { Double d = Math.Sin(Double.PositiveInfinity); if (d.CompareTo(Double.NaN) != 0) { TestLibrary.TestFramework.LogError("P06.1", "The result is error when radian is PositiveInfinity!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P06.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the result is NaN when radian is NegativeInfinity."); try { Double d = Math.Sin(Double.NegativeInfinity); if (d.CompareTo(Double.NaN) != 0) { TestLibrary.TestFramework.LogError("P07.1", "The result is error when radian is NegativeInfinity!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P07.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest8: Verify the result is NaN when radian is NaN."); try { Double d = Math.Sin(Double.NaN); if (d.CompareTo(Double.NaN) != 0) { TestLibrary.TestFramework.LogError("P08.1", "The result is error when radian is NaN!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("P08.2", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
/* ==================================================================== 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.Record.Crypto { using System; using System.IO; using NUnit.Framework; using NPOI.Util; using TestCases.Exceptions; using NPOI.HSSF.Record.Crypto; /** * Tests for {@link Biff8DecryptingStream} * * @author Josh Micich */ [TestFixture] public class TestBiff8DecryptingStream { /** * A mock {@link InputStream} that keeps track of position and also produces * slightly interesting data. Each successive data byte value is one greater * than the previous. */ private class MockStream : MemoryStream { private int _val; private int _position; public MockStream(int InitialValue) { _val = InitialValue & 0xFF; } public override int ReadByte() { _position++; return _val++ & 0xFF; } public int GetPosition() { return _position; } } private class StreamTester { private static bool ONLY_LOG_ERRORS = true; private MockStream _ms; private Biff8DecryptingStream _bds; private bool _errorsOccurred; /** * @param expectedFirstInt expected value of the first int read from the decrypted stream */ public StreamTester(MockStream ms, String keyDigestHex, int expectedFirstInt) { _ms = ms; byte[] keyDigest = HexRead.ReadFromString(keyDigestHex); _bds = new Biff8DecryptingStream(_ms, 0, new Biff8EncryptionKey(keyDigest)); Assert.AreEqual(expectedFirstInt, _bds.ReadInt()); _errorsOccurred = false; } public Biff8DecryptingStream GetBDS() { return _bds; } /** * Used to 'skip over' the uninteresting middle bits of the key blocks. * Also Confirms that read position of the underlying stream is aligned. */ public void RollForward(int fromPosition, int toPosition) { Assert.AreEqual(fromPosition, _ms.GetPosition()); for (int i = fromPosition; i < toPosition; i++) { _bds.ReadByte(); } Assert.AreEqual(toPosition, _ms.GetPosition()); } public void ConfirmByte(int expVal) { cmp(HexDump.ByteToHex(expVal), HexDump.ByteToHex(_bds.ReadUByte())); } public void ConfirmShort(int expVal) { cmp(HexDump.ShortToHex(expVal), HexDump.ShortToHex(_bds.ReadUShort())); } public void ConfirmUShort(int expVal) { cmp(HexDump.ShortToHex(expVal), HexDump.ShortToHex(_bds.ReadUShort())); } public short ReadShort() { return _bds.ReadShort(); } public int ReadUShort() { return _bds.ReadUShort(); } public void ConfirmInt(int expVal) { cmp(HexDump.IntToHex(expVal), HexDump.IntToHex(_bds.ReadInt())); } public void ConfirmLong(long expVal) { cmp(HexDump.LongToHex(expVal), HexDump.LongToHex(_bds.ReadLong())); } private void cmp(char[] exp, char[] act) { if (Arrays.Equals(exp, act)) { return; } _errorsOccurred = true; if (ONLY_LOG_ERRORS) { logErr(3, "Value mismatch " + new String(exp) + " - " + new String(act)); return; } throw new ComparisonFailure("Value mismatch", new String(exp), new String(act)); } public void ConfirmData(String expHexData) { byte[] expData = HexRead.ReadFromString(expHexData); byte[] actData = new byte[expData.Length]; _bds.ReadFully(actData); if (Arrays.Equals(expData, actData)) { return; } _errorsOccurred = true; if (ONLY_LOG_ERRORS) { logErr(2, "Data mismatch " + HexDump.ToHex(expData) + " - " + HexDump.ToHex(actData)); return; } throw new ComparisonFailure("Data mismatch", HexDump.ToHex(expData), HexDump.ToHex(actData)); } private static void logErr(int stackFrameCount, String msg) { // StackTraceElement ste = new Exception().StackTrace[stackFrameCount]; //System.err.Print("(" + ste.FileName + ":" + ste.LineNumber + ") "); //System.err.Println(msg); } public void AssertNoErrors() { Assert.IsFalse(_errorsOccurred, "Some values decrypted incorrectly"); } } /** * Tests Reading of 64,32,16 and 8 bit integers aligned with key changing boundaries */ [Test] public void TestReadsAlignedWithBoundary() { StreamTester st = CreateStreamTester(0x50, "BA AD F0 0D 00", unchecked((int)0x96C66829)); st.RollForward(0x0004, 0x03FF); st.ConfirmByte(0x3E); st.ConfirmByte(0x28); st.RollForward(0x0401, 0x07FE); st.ConfirmShort(0x76CC); st.ConfirmShort(0xD83E); st.RollForward(0x0802, 0x0BFC); st.ConfirmInt(0x25F280EB); st.ConfirmInt(unchecked((int)0xB549E99B)); st.RollForward(0x0C04, 0x0FF8); st.ConfirmLong(0x6AA2D5F6B975D10CL); st.ConfirmLong(0x34248ADF7ED4F029L); // check for signed/unsigned shorts #58069 st.RollForward(0x1008, 0x7213); st.ConfirmUShort(0xFFFF); st.RollForward(0x7215, 0x1B9AD); st.ConfirmShort(-1); st.RollForward(0x1B9AF, 0x37D99); Assert.AreEqual(0xFFFF, st.ReadUShort()); st.RollForward(0x37D9B, 0x4A6F2); Assert.AreEqual(-1, st.ReadShort()); st.AssertNoErrors(); } /** * Tests Reading of 64,32 and 16 bit integers <i>across</i> key changing boundaries */ [Test] public void TestReadsSpanningBoundary() { StreamTester st = CreateStreamTester(0x50, "BA AD F0 0D 00", unchecked((int)0x96C66829)); st.RollForward(0x0004, 0x03FC); st.ConfirmLong(unchecked((long)0x885243283E2A5EEFL)); st.RollForward(0x0404, 0x07FE); st.ConfirmInt( unchecked((int)0xD83E76CC)); st.RollForward(0x0802, 0x0BFF); st.ConfirmShort(0x9B25); st.AssertNoErrors(); } /** * Checks that the BIFF header fields (sid, size) Get read without Applying decryption, * and that the RC4 stream stays aligned during these calls */ [Test] public void TestReadHeaderUshort() { StreamTester st = CreateStreamTester(0x50, "BA AD F0 0D 00", unchecked((int)0x96C66829)); st.RollForward(0x0004, 0x03FF); Biff8DecryptingStream bds = st.GetBDS(); int hval = bds.ReadDataSize(); // unencrypted int nextInt = bds.ReadInt(); if (nextInt == unchecked((int)0x8F534029)) { throw new AssertionException( "Indentified bug in key alignment After call to ReadHeaderUshort()"); } Assert.AreEqual(0x16885243, nextInt); if (hval == 0x283E) { throw new AssertionException("readHeaderUshort() incorrectly decrypted result"); } Assert.AreEqual(0x504F, hval); // confirm next key change st.RollForward(0x0405, 0x07FC); st.ConfirmInt(0x76CC1223); st.ConfirmInt(0x4842D83E); st.AssertNoErrors(); } /** * Tests Reading of byte sequences <i>across</i> and <i>aligned with</i> key changing boundaries */ [Test] public void TestReadByteArrays() { StreamTester st = CreateStreamTester(0x50, "BA AD F0 0D 00", unchecked((int)0x96C66829)); st.RollForward(0x0004, 0x2FFC); st.ConfirmData("66 A1 20 B1 04 A3 35 F5"); // 4 bytes on either side of boundary st.RollForward(0x3004, 0x33F8); st.ConfirmData("F8 97 59 36"); // last 4 bytes in block st.ConfirmData("01 C2 4E 55"); // first 4 bytes in next block st.AssertNoErrors(); } private static StreamTester CreateStreamTester(int mockStreamStartVal, String keyDigestHex, int expectedFirstInt) { return new StreamTester(new MockStream(mockStreamStartVal), keyDigestHex, expectedFirstInt); } } }
#region License /* Copyright (c) 2006 Leslie Sanford * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Contact /* * Leslie Sanford * Email: jabberdabber@hotmail.com */ #endregion using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using Sanford.Multimedia.Timers; namespace Sanford.Multimedia.Midi { public sealed class OutputStream : OutputDeviceBase { [DllImport("winmm.dll")] private static extern int midiStreamOpen(ref IntPtr handle, ref int deviceID, int reserved, OutputDevice.MidiOutProc proc, IntPtr instance, uint flag); [DllImport("winmm.dll")] private static extern int midiStreamClose(IntPtr handle); [DllImport("winmm.dll")] private static extern int midiStreamOut(IntPtr handle, IntPtr headerPtr, int sizeOfMidiHeader); [DllImport("winmm.dll")] private static extern int midiStreamPause(IntPtr handle); [DllImport("winmm.dll")] private static extern int midiStreamPosition(IntPtr handle, ref Time t, int sizeOfTime); [DllImport("winmm.dll")] private static extern int midiStreamProperty(IntPtr handle, ref Property p, uint flags); [DllImport("winmm.dll")] private static extern int midiStreamRestart(IntPtr handle); [DllImport("winmm.dll")] private static extern int midiStreamStop(IntPtr handle); [StructLayout(LayoutKind.Sequential)] private struct Property { public int sizeOfProperty; public int property; } private const uint MIDIPROP_SET = 0x80000000; private const uint MIDIPROP_GET = 0x40000000; private const uint MIDIPROP_TIMEDIV = 0x00000001; private const uint MIDIPROP_TEMPO = 0x00000002; private const byte MEVT_CALLBACK = 0x40; private const byte MEVT_SHORTMSG = 0x00; private const byte MEVT_TEMPO = 0x01; private const byte MEVT_NOP = 0x02; private const byte MEVT_LONGMSG = 0x80; private const byte MEVT_COMMENT = 0x82; private const byte MEVT_VERSION = 0x84; private const int MOM_POSITIONCB = 0x3CA; private const int SizeOfMidiEvent = 12; private const int EventTypeIndex = 11; private const int EventCodeOffset = 8; private MidiOutProc midiOutProc; private int offsetTicks = 0; private byte[] streamID = new byte[4]; private List<byte> events = new List<byte>(); private MidiHeaderBuilder headerBuilder = new MidiHeaderBuilder(); public event EventHandler<NoOpEventArgs> NoOpOccurred; public OutputStream(int deviceID) : base(deviceID) { midiOutProc = HandleMessage; int result = midiStreamOpen(ref handle, ref deviceID, 1, midiOutProc, IntPtr.Zero, CALLBACK_FUNCTION); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } protected override void Dispose(bool disposing) { if(disposing) { lock(lockObject) { Reset(); int result = midiStreamClose(Handle); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } } else { midiOutReset(Handle); midiStreamClose(Handle); } base.Dispose(disposing); } public override void Close() { #region Guard if(IsDisposed) { return; } #endregion Dispose(true); } public void StartPlaying() { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion lock(lockObject) { int result = midiStreamRestart(Handle); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } } public void PausePlaying() { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion lock(lockObject) { int result = midiStreamPause(Handle); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } } public void StopPlaying() { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion lock(lockObject) { int result = midiStreamStop(Handle); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } } public override void Reset() { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion offsetTicks = 0; events.Clear(); base.Reset(); } public void Write(MidiEvent e) { switch(e.MidiMessage.MessageType) { case MessageType.Channel: case MessageType.SystemCommon: case MessageType.SystemRealtime: Write(e.DeltaTicks, (ShortMessage)e.MidiMessage); break; case MessageType.SystemExclusive: Write(e.DeltaTicks, (SysExMessage)e.MidiMessage); break; case MessageType.Meta: Write(e.DeltaTicks, (MetaMessage)e.MidiMessage); break; } } private void Write(int deltaTicks, ShortMessage message) { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion // Delta time. events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); // Stream ID. events.AddRange(streamID); // Event code. byte[] eventCode = message.GetBytes(); eventCode[eventCode.Length - 1] = MEVT_SHORTMSG; events.AddRange(eventCode); offsetTicks = 0; } private void Write(int deltaTicks, SysExMessage message) { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion // Delta time. events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); // Stream ID. events.AddRange(streamID); // Event code. byte[] eventCode = BitConverter.GetBytes(message.Length); eventCode[eventCode.Length - 1] = MEVT_LONGMSG; events.AddRange(eventCode); byte[] sysExData; if(message.Length % 4 != 0) { sysExData = new byte[message.Length + (message.Length % 4)]; message.GetBytes().CopyTo(sysExData, 0); } else { sysExData = message.GetBytes(); } // SysEx data. events.AddRange(sysExData); offsetTicks = 0; } private void Write(int deltaTicks, MetaMessage message) { if(message.MetaType == MetaType.Tempo) { // Delta time. events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); // Stream ID. events.AddRange(streamID); TempoChangeBuilder builder = new TempoChangeBuilder(message); byte[] t = BitConverter.GetBytes(builder.Tempo); t[t.Length - 1] = MEVT_SHORTMSG | MEVT_TEMPO; // Event code. events.AddRange(t); offsetTicks = 0; } else { offsetTicks += deltaTicks; } } public void WriteNoOp(int deltaTicks, int data) { // Delta time. events.AddRange(BitConverter.GetBytes(deltaTicks + offsetTicks)); // Stream ID. events.AddRange(streamID); // Event code. byte[] eventCode = BitConverter.GetBytes(data); eventCode[eventCode.Length - 1] = (byte)(MEVT_NOP | MEVT_CALLBACK); events.AddRange(eventCode); offsetTicks = 0; } public void Flush() { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion lock(lockObject) { headerBuilder.InitializeBuffer(events); headerBuilder.Build(); events.Clear(); int result = midiOutPrepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader); if(result == MidiDeviceException.MMSYSERR_NOERROR) { bufferCount++; } else { headerBuilder.Destroy(); throw new OutputDeviceException(result); } result = midiStreamOut(Handle, headerBuilder.Result, SizeOfMidiHeader); if(result != MidiDeviceException.MMSYSERR_NOERROR) { midiOutUnprepareHeader(Handle, headerBuilder.Result, SizeOfMidiHeader); headerBuilder.Destroy(); throw new OutputDeviceException(result); } } } public Time GetTime(TimeType type) { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion Time t = new Time(); t.type = (int)type; lock(lockObject) { int result = midiStreamPosition(Handle, ref t, Marshal.SizeOf(typeof(Time))); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } return t; } private void OnNoOpOccurred(NoOpEventArgs e) { EventHandler<NoOpEventArgs> handler = NoOpOccurred; if(handler != null) { handler(this, e); } } protected override void HandleMessage(IntPtr hnd, int msg, IntPtr instance, IntPtr param1, IntPtr param2) { if(msg == MOM_POSITIONCB) { delegateQueue.Post(HandleNoOp, param1); } else { base.HandleMessage(handle, msg, instance, param1, param2); } } private void HandleNoOp(object state) { IntPtr headerPtr = (IntPtr)state; MidiHeader header = (MidiHeader)Marshal.PtrToStructure(headerPtr, typeof(MidiHeader)); byte[] midiEvent = new byte[SizeOfMidiEvent]; for(int i = 0; i < midiEvent.Length; i++) { midiEvent[i] = Marshal.ReadByte(header.data, header.offset + i); } // If this is a NoOp event. if((midiEvent[EventTypeIndex] & MEVT_NOP) == MEVT_NOP) { // Clear the event type byte. midiEvent[EventTypeIndex] = 0; NoOpEventArgs e = new NoOpEventArgs(BitConverter.ToInt32(midiEvent, EventCodeOffset)); context.Post(new SendOrPostCallback(delegate(object s) { OnNoOpOccurred(e); }), null); } } public int Division { get { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion Property d = new Property(); d.sizeOfProperty = Marshal.SizeOf(typeof(Property)); lock(lockObject) { int result = midiStreamProperty(Handle, ref d, MIDIPROP_GET | MIDIPROP_TIMEDIV); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } return d.property; } set { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } else if(value < PpqnClock.PpqnMinValue) { throw new ArgumentOutOfRangeException("Ppqn", value, "Pulses per quarter note is smaller than 24."); } #endregion Property d = new Property(); d.sizeOfProperty = Marshal.SizeOf(typeof(Property)); d.property = value; lock(lockObject) { int result = midiStreamProperty(Handle, ref d, MIDIPROP_SET | MIDIPROP_TIMEDIV); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } } } public int Tempo { get { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } #endregion Property t = new Property(); t.sizeOfProperty = Marshal.SizeOf(typeof(Property)); lock(lockObject) { int result = midiStreamProperty(Handle, ref t, MIDIPROP_GET | MIDIPROP_TEMPO); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } return t.property; } set { #region Require if(IsDisposed) { throw new ObjectDisposedException("OutputStream"); } else if(value < 0) { throw new ArgumentOutOfRangeException("Tempo", value, "Tempo out of range."); } #endregion Property t = new Property(); t.sizeOfProperty = Marshal.SizeOf(typeof(Property)); t.property = value; lock(lockObject) { int result = midiStreamProperty(Handle, ref t, MIDIPROP_SET | MIDIPROP_TEMPO); if(result != MidiDeviceException.MMSYSERR_NOERROR) { throw new OutputDeviceException(result); } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Collections.ObjectModel { public abstract partial class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.Collection<TItem> { protected KeyedCollection() { } protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer) { } protected KeyedCollection(System.Collections.Generic.IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) { } public System.Collections.Generic.IEqualityComparer<TKey> Comparer { get { return default(System.Collections.Generic.IEqualityComparer<TKey>); } } protected System.Collections.Generic.IDictionary<TKey, TItem> Dictionary { get { return default(System.Collections.Generic.IDictionary<TKey, TItem>); } } public TItem this[TKey key] { get { return default(TItem); } } protected void ChangeItemKey(TItem item, TKey newKey) { } protected override void ClearItems() { } public bool Contains(TKey key) { return default(bool); } protected abstract TKey GetKeyForItem(TItem item); protected override void InsertItem(int index, TItem item) { } public bool Remove(TKey key) { return default(bool); } protected override void RemoveItem(int index) { } protected override void SetItem(int index, TItem item) { } } public partial class ObservableCollection<T> : System.Collections.ObjectModel.Collection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged { public ObservableCollection() { } public ObservableCollection(System.Collections.Generic.IEnumerable<T> collection) { } public virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } } protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } protected System.IDisposable BlockReentrancy() { return default(System.IDisposable); } protected void CheckReentrancy() { } protected override void ClearItems() { } protected override void InsertItem(int index, T item) { } public void Move(int oldIndex, int newIndex) { } protected virtual void MoveItem(int oldIndex, int newIndex) { } protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { } protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs e) { } protected override void RemoveItem(int index) { } protected override void SetItem(int index, T item) { } } public partial class ReadOnlyDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable { public ReadOnlyDictionary(System.Collections.Generic.IDictionary<TKey, TValue> dictionary) { } public int Count { get { return default(int); } } protected System.Collections.Generic.IDictionary<TKey, TValue> Dictionary { get { return default(System.Collections.Generic.IDictionary<TKey, TValue>); } } public TValue this[TKey key] { get { return default(TValue); } } public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection Keys { get { return default(System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.KeyCollection); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.IsReadOnly { get { return default(bool); } } TValue System.Collections.Generic.IDictionary<TKey, TValue>.this[TKey key] { get { return default(TValue); } set { } } System.Collections.Generic.ICollection<TKey> System.Collections.Generic.IDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.ICollection<TKey>); } } System.Collections.Generic.ICollection<TValue> System.Collections.Generic.IDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.ICollection<TValue>); } } System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Keys { get { return default(System.Collections.Generic.IEnumerable<TKey>); } } System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>.Values { get { return default(System.Collections.Generic.IEnumerable<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } object System.Collections.IDictionary.this[object key] { get { return default(object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection Values { get { return default(System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>.ValueCollection); } } public bool ContainsKey(TKey key) { return default(bool); } public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>>); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Clear() { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> item) { return default(bool); } void System.Collections.Generic.IDictionary<TKey, TValue>.Add(TKey key, TValue value) { } bool System.Collections.Generic.IDictionary<TKey, TValue>.Remove(TKey key) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } void System.Collections.IDictionary.Add(object key, object value) { } void System.Collections.IDictionary.Clear() { } bool System.Collections.IDictionary.Contains(object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } public bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return default(bool); } public sealed partial class KeyCollection : System.Collections.Generic.ICollection<TKey>, System.Collections.Generic.IEnumerable<TKey>, System.Collections.Generic.IReadOnlyCollection<TKey>, System.Collections.ICollection, System.Collections.IEnumerable { internal KeyCollection() { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TKey>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TKey[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<TKey> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TKey>); } void System.Collections.Generic.ICollection<TKey>.Add(TKey item) { } void System.Collections.Generic.ICollection<TKey>.Clear() { } bool System.Collections.Generic.ICollection<TKey>.Contains(TKey item) { return default(bool); } bool System.Collections.Generic.ICollection<TKey>.Remove(TKey item) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } public sealed partial class ValueCollection : System.Collections.Generic.ICollection<TValue>, System.Collections.Generic.IEnumerable<TValue>, System.Collections.Generic.IReadOnlyCollection<TValue>, System.Collections.ICollection, System.Collections.IEnumerable { internal ValueCollection() { } public int Count { get { return default(int); } } bool System.Collections.Generic.ICollection<TValue>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } public void CopyTo(TValue[] array, int arrayIndex) { } public System.Collections.Generic.IEnumerator<TValue> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<TValue>); } void System.Collections.Generic.ICollection<TValue>.Add(TValue item) { } void System.Collections.Generic.ICollection<TValue>.Clear() { } bool System.Collections.Generic.ICollection<TValue>.Contains(TValue item) { return default(bool); } bool System.Collections.Generic.ICollection<TValue>.Remove(TValue item) { return default(bool); } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } } } public partial class ReadOnlyObservableCollection<T> : System.Collections.ObjectModel.ReadOnlyCollection<T>, System.Collections.Specialized.INotifyCollectionChanged, System.ComponentModel.INotifyPropertyChanged { public ReadOnlyObservableCollection(System.Collections.ObjectModel.ObservableCollection<T> list) : base(default(System.Collections.Generic.IList<T>)) { } protected virtual event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged { add { } remove { } } protected virtual event System.ComponentModel.PropertyChangedEventHandler PropertyChanged { add { } remove { } } event System.Collections.Specialized.NotifyCollectionChangedEventHandler System.Collections.Specialized.INotifyCollectionChanged.CollectionChanged { add { } remove { } } event System.ComponentModel.PropertyChangedEventHandler System.ComponentModel.INotifyPropertyChanged.PropertyChanged { add { } remove { } } protected virtual void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs args) { } protected virtual void OnPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) { } } } namespace System.Collections.Specialized { public partial interface INotifyCollectionChanged { event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } public enum NotifyCollectionChangedAction { Add = 0, Move = 3, Remove = 1, Replace = 2, Reset = 4, } public partial class NotifyCollectionChangedEventArgs : System.EventArgs { public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList newItems, System.Collections.IList oldItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int startingIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, System.Collections.IList changedItems, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem) { } public NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { } public System.Collections.Specialized.NotifyCollectionChangedAction Action { get { return default(System.Collections.Specialized.NotifyCollectionChangedAction); } } public System.Collections.IList NewItems { get { return default(System.Collections.IList); } } public int NewStartingIndex { get { return default(int); } } public System.Collections.IList OldItems { get { return default(System.Collections.IList); } } public int OldStartingIndex { get { return default(int); } } } public delegate void NotifyCollectionChangedEventHandler(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e); } namespace System.ComponentModel { public partial class DataErrorsChangedEventArgs : System.EventArgs { public DataErrorsChangedEventArgs(string propertyName) { } public virtual string PropertyName { get { return default(string); } } } public partial interface INotifyDataErrorInfo { bool HasErrors { get; } event System.EventHandler<System.ComponentModel.DataErrorsChangedEventArgs> ErrorsChanged; System.Collections.IEnumerable GetErrors(string propertyName); } public partial interface INotifyPropertyChanged { event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; } public partial interface INotifyPropertyChanging { event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; } public partial class PropertyChangedEventArgs : System.EventArgs { public PropertyChangedEventArgs(string propertyName) { } public virtual string PropertyName { get { return default(string); } } } public delegate void PropertyChangedEventHandler(object sender, System.ComponentModel.PropertyChangedEventArgs e); public partial class PropertyChangingEventArgs : System.EventArgs { public PropertyChangingEventArgs(string propertyName) { } public virtual string PropertyName { get { return default(string); } } } public delegate void PropertyChangingEventHandler(object sender, System.ComponentModel.PropertyChangingEventArgs e); } namespace System.Windows.Input { public partial interface ICommand { event System.EventHandler CanExecuteChanged; bool CanExecute(object parameter); void Execute(object parameter); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Scheduler { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; public partial class SchedulerManagementClient : ServiceClient<SchedulerManagementClient>, ISchedulerManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The subscription id. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The 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 IJobCollectionsOperations. /// </summary> public virtual IJobCollectionsOperations JobCollections { get; private set; } /// <summary> /// Gets the IJobsOperations. /// </summary> public virtual IJobsOperations Jobs { get; private set; } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SchedulerManagementClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SchedulerManagementClient 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 SchedulerManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SchedulerManagementClient 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> protected SchedulerManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SchedulerManagementClient 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> protected SchedulerManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SchedulerManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </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> public SchedulerManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SchedulerManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SchedulerManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </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> public SchedulerManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.JobCollections = new JobCollectionsOperations(this); this.Jobs = new JobsOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-03-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), //// NOTE (pinwang): Scheduler supports Non ISO format TimeSpan and //// SDK Iso8601TimeSpanConverter will only convert ISO format for TimeSpan. ////Converters = new List<JsonConverter> //// { //// new Iso8601TimeSpanConverter() //// } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), //// NOTE (pinwang): Scheduler supports Non ISO format TimeSpan and //// SDK Iso8601TimeSpanConverter will only convert ISO format for TimeSpan. ////Converters = new List<JsonConverter> //// { //// new Iso8601TimeSpanConverter() //// } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// 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.Globalization; using Xunit; namespace System.Data.SqlClient.ManualTesting.Tests { public static class ExceptionTest { // data value and server consts private const string badServer = "NotAServer"; private const string sqlsvrBadConn = "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections."; private const string logonFailedErrorMessage = "Login failed for user '{0}'."; private const string execReaderFailedMessage = "ExecuteReader requires an open and available Connection. The connection's current state is closed."; private const string warningNoiseMessage = "The full-text search condition contained noise word(s)."; private const string warningInfoMessage = "Test of info messages"; private const string orderIdQuery = "select orderid from orders where orderid < 10250"; [Fact] public static void WarningTest() { string connectionString = DataTestClass.SQL2008_Northwind; Action<object, SqlInfoMessageEventArgs> warningCallback = (object sender, SqlInfoMessageEventArgs imevent) => { for (int i = 0; i < imevent.Errors.Count; i++) { Assert.True(imevent.Errors[i].Message.Contains(warningInfoMessage), "FAILED: WarningTest Callback did not contain correct message."); } }; SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback); using (SqlConnection sqlConnection = new SqlConnection(connectionString + ";pooling=false;")) { sqlConnection.InfoMessage += handler; sqlConnection.Open(); SqlCommand cmd = new SqlCommand(string.Format("PRINT N'{0}'", warningInfoMessage), sqlConnection); cmd.ExecuteNonQuery(); sqlConnection.InfoMessage -= handler; cmd.ExecuteNonQuery(); } } [Fact] public static void WarningsBeforeRowsTest() { string connectionString = DataTestClass.SQL2008_Northwind; bool hitWarnings = false; int iteration = 0; Action<object, SqlInfoMessageEventArgs> warningCallback = (object sender, SqlInfoMessageEventArgs imevent) => { for (int i = 0; i < imevent.Errors.Count; i++) { Assert.True(imevent.Errors[i].Message.Contains(warningNoiseMessage), "FAILED: WarningsBeforeRowsTest Callback did not contain correct message. Failed in loop iteration: " + iteration); } hitWarnings = true; }; SqlInfoMessageEventHandler handler = new SqlInfoMessageEventHandler(warningCallback); SqlConnection sqlConnection = new SqlConnection(connectionString); sqlConnection.InfoMessage += handler; sqlConnection.Open(); foreach (string orderClause in new string[] { "", " order by FirstName" }) { foreach (bool messagesOnErrors in new bool[] { true, false }) { iteration++; sqlConnection.FireInfoMessageEventOnUserErrors = messagesOnErrors; // These queries should return warnings because AND here is a noise word. SqlCommand cmd = new SqlCommand("select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"Anne AND\"')" + orderClause, sqlConnection); using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.True(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be TRUE)"); bool receivedRows = false; while (reader.Read()) { receivedRows = true; } Assert.True(receivedRows, "FAILED: Should have received rows from this query."); Assert.True(hitWarnings, "FAILED: Should have received warnings from this query"); } hitWarnings = false; cmd.CommandText = "select FirstName from Northwind.dbo.Employees where contains(FirstName, '\"NotARealPerson AND\"')" + orderClause; using (SqlDataReader reader = cmd.ExecuteReader()) { Assert.False(reader.HasRows, "FAILED: SqlDataReader.HasRows is not correct (should be FALSE)"); bool receivedRows = false; while (reader.Read()) { receivedRows = true; } Assert.False(receivedRows, "FAILED: Should have NOT received rows from this query."); Assert.True(hitWarnings, "FAILED: Should have received warnings from this query"); } } } sqlConnection.Close(); } private static bool CheckThatExceptionsAreDistinctButHaveSameData(SqlException e1, SqlException e2) { Assert.True(e1 != e2, "FAILED: verification of exception cloning in subsequent connection attempts"); Assert.False((e1 == null) || (e2 == null), "FAILED: One of exceptions is null, another is not"); bool equal = (e1.Message == e2.Message) && (e1.HelpLink == e2.HelpLink) && (e1.InnerException == e2.InnerException) && (e1.Source == e2.Source) && (e1.Data.Count == e2.Data.Count) && (e1.Errors == e2.Errors); IDictionaryEnumerator enum1 = e1.Data.GetEnumerator(); IDictionaryEnumerator enum2 = e2.Data.GetEnumerator(); while (equal) { if (!enum1.MoveNext()) break; enum2.MoveNext(); equal = (enum1.Key == enum2.Key) && (enum2.Value == enum2.Value); } Assert.True(equal, string.Format("FAILED: exceptions do not contain the same data (besides call stack):\nFirst: {0}\nSecond: {1}\n", e1, e2)); return true; } [Fact] public static void ExceptionTests() { string connectionString = DataTestClass.SQL2008_Northwind; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); // tests improper server name thrown from constructor of tdsparser SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), sqlsvrBadConn, VerifyException); // tests incorrect password - thrown from the adapter badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty }; string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); // tests incorrect database name - exception thrown from adapter badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { InitialCatalog = "NotADatabase" }; errorMessage = string.Format(CultureInfo.InvariantCulture, "Cannot open database \"{0}\" requested by the login. The login failed.", badBuilder.InitialCatalog); SqlException firstAttemptException = VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 2, 4060, 1, 11)); // Verify that the same error results in a different instance of an exception, but with the same data VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => CheckThatExceptionsAreDistinctButHaveSameData(firstAttemptException, ex)); // tests incorrect user name - exception thrown from adapter badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { UserID = "NotAUser" }; errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); VerifyConnectionFailure<SqlException>(() => GenerateConnectionException(badBuilder.ConnectionString), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); } [Fact] public static void VariousExceptionTests() { string connectionString = DataTestClass.SQL2008_Northwind; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); // Test 1 - A SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = orderIdQuery; VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage); } } // Test 1 - B badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { Password = string.Empty }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { string errorMessage = string.Format(CultureInfo.InvariantCulture, logonFailedErrorMessage, badBuilder.UserID); VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), errorMessage, (ex) => VerifyException(ex, 1, 18456, 1, 14)); } } [Fact] public static void IndependentConnectionExceptionTest() { string connectionString = DataTestClass.SQL2008_Northwind; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectionString); SqlConnectionStringBuilder badBuilder = new SqlConnectionStringBuilder(builder.ConnectionString) { DataSource = badServer, ConnectTimeout = 1 }; using (var sqlConnection = new SqlConnection(badBuilder.ConnectionString)) { // Test 1 VerifyConnectionFailure<SqlException>(() => sqlConnection.Open(), sqlsvrBadConn, VerifyException); // Test 2 using (SqlCommand command = new SqlCommand(orderIdQuery, sqlConnection)) { VerifyConnectionFailure<InvalidOperationException>(() => command.ExecuteReader(), execReaderFailedMessage); } } } private static void GenerateConnectionException(string connectionString) { using (SqlConnection sqlConnection = new SqlConnection(connectionString)) { sqlConnection.Open(); using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = orderIdQuery; command.ExecuteReader(); } } } private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage, Func<TException, bool> exVerifier) where TException : Exception { TException ex = Assert.Throws<TException>(connectAction); Assert.True(ex.Message.Contains(expectedExceptionMessage), string.Format("FAILED: SqlException did not contain expected error message. Actual message: {0}", ex.Message)); Assert.True(exVerifier(ex), "FAILED: Exception verifier failed on the exception."); return ex; } private static TException VerifyConnectionFailure<TException>(Action connectAction, string expectedExceptionMessage) where TException : Exception { return VerifyConnectionFailure<TException>(connectAction, expectedExceptionMessage, (ex) => true); } private static bool VerifyException(SqlException exception) { VerifyException(exception, 1); return true; } private static bool VerifyException(SqlException exception, int count, int? errorNumber = null, int? errorState = null, int? severity = null) { // Verify that there are the correct number of errors in the exception Assert.True(exception.Errors.Count == count, string.Format("FAILED: Incorrect number of errors. Expected: {0}. Actual: {1}.", count, exception.Errors.Count)); // Ensure that all errors have an error-level severity for (int i = 0; i < count; i++) { Assert.True(exception.Errors[i].Class >= 10, "FAILED: verification of Exception! Exception contains a warning!"); } // Check the properties of the exception populated by the server are correct if (errorNumber.HasValue) { Assert.True(errorNumber.Value == exception.Number, string.Format("FAILED: Error number of exception is incorrect. Expected: {0}. Actual: {1}.", errorNumber.Value, exception.Number)); } if (errorState.HasValue) { Assert.True(errorState.Value == exception.State, string.Format("FAILED: Error state of exception is incorrect. Expected: {0}. Actual: {1}.", errorState.Value, exception.State)); } if (severity.HasValue) { Assert.True(severity.Value == exception.Class, string.Format("FAILED: Severity of exception is incorrect. Expected: {0}. Actual: {1}.", severity.Value, exception.Class)); } if ((errorNumber.HasValue) && (errorState.HasValue) && (severity.HasValue)) { string detailsText = string.Format("Error Number:{0},State:{1},Class:{2}", errorNumber.Value, errorState.Value, severity.Value); Assert.True(exception.ToString().Contains(detailsText), string.Format("FAILED: SqlException.ToString does not contain the error number, state and severity information")); } // verify that the this[] function on the collection works, as well as the All function SqlError[] errors = new SqlError[exception.Errors.Count]; exception.Errors.CopyTo(errors, 0); Assert.True((errors[0].Message).Equals(exception.Errors[0].Message), string.Format("FAILED: verification of Exception! ErrorCollection indexer/CopyTo resulted in incorrect value.")); return true; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define DUMP_ALIVE_INFO namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // Debug classes // public abstract class BaseIntermediateRepresentationDumper : IIntermediateRepresentationDumper { // // State // private GrowOnlyHashTable< Expression, string > m_lookupName; private GrowOnlyHashTable< BasicBlock, string > m_lookupLabel; //--// protected BasicBlock[] m_basicBlocks; protected BasicBlock[] m_ancestors; protected Operator[] m_operators; protected VariableExpression[] m_variables; protected VariableExpression[] m_sortedVariables; protected Operator[][] m_useChains; protected BitVector[] m_reachingDefinitions; #if DUMP_ALIVE_INFO protected BitVector[] m_liveness; #endif // // Constructor Methods // protected BaseIntermediateRepresentationDumper() { m_lookupName = HashTableFactory.NewWithReferenceEquality< Expression, string >(); m_lookupLabel = HashTableFactory.NewWithReferenceEquality< BasicBlock, string >(); } //--// public MethodRepresentation[] Sort( IEnumerable< MethodRepresentation > enumerable ) { GrowOnlyHashTable< MethodRepresentation, string > htNames = HashTableFactory.NewWithReferenceEquality< MethodRepresentation, string >(); foreach(MethodRepresentation md in enumerable) { htNames[md] = md.ToShortString(); } MethodRepresentation[] res = new MethodRepresentation[htNames.Count]; int pos = 0; foreach(MethodRepresentation md in htNames.Keys) { res[pos++] = md; } Array.Sort( res, delegate( MethodRepresentation left, MethodRepresentation right ) { return String.Compare( htNames[left], htNames[right] ); } ); return res; } public string FormatOutput( string s , object arg1 ) { return FormatOutputInternal( s, arg1 ); } public string FormatOutput( string s , object arg1 , object arg2 ) { return FormatOutputInternal( s, arg1, arg2 ); } public string FormatOutput( string s , object arg1 , object arg2 , object arg3 ) { return FormatOutputInternal( s, arg1, arg2, arg3 ); } public string FormatOutput( string s , params object[] args ) { return FormatOutputInternal( s, args ); } //--// public virtual void DumpGraph( ControlFlowGraphState cfg ) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; m_lookupName .Clear(); m_lookupLabel.Clear(); //--// m_basicBlocks = cfg2.DataFlow_SpanningTree_BasicBlocks; m_ancestors = cfg2.DataFlow_SpanningTree_Ancestors; m_operators = cfg2.DataFlow_SpanningTree_Operators; m_variables = cfg2.DataFlow_SpanningTree_Variables; m_useChains = cfg2.DataFlow_UseChains; m_reachingDefinitions = cfg2.DataFlow_ReachingDefinitions; #if DUMP_ALIVE_INFO m_liveness = cfg2.LivenessAtOperator; // It's indexed as [<operator index>][<variable index>] #endif cfg2.RenumberVariables(); m_sortedVariables = cfg2.SortVariables(); } public string CreateName( Expression ex ) { string res; if(m_lookupName.TryGetValue( ex, out res ) == false) { res = ex.ToString(); m_lookupName[ex] = res; } return res; } public string CreateLabel( BasicBlock bb ) { string res; if(m_lookupLabel.TryGetValue( bb, out res ) == false) { res = bb.ToShortString(); m_lookupLabel[bb] = res; } return res; } //--// protected string FormatOutputInternal( string s , params object[] args ) { for(int i = 0; i < args.Length; i++) { object o = args[i]; if(o is Expression) { Expression ex = (Expression)o; args[i] = CreateName( ex ); } if(o is BasicBlock) { BasicBlock bb = (BasicBlock)o; args[i] = CreateLabel( bb ); } } return string.Format( s, args ); } } //--// public class TextIntermediateRepresentationDumper : BaseIntermediateRepresentationDumper, IDisposable { // // State // System.IO.TextWriter m_writer; bool m_closeWriter; int m_indent; bool m_fIndented; SourceCodeTracker m_sourceCodeTracker; // // Constructor Methods // public TextIntermediateRepresentationDumper() { m_writer = Console.Out; m_closeWriter = false; Init(); } public TextIntermediateRepresentationDumper( string file ) { m_writer = new System.IO.StreamWriter( file, false, System.Text.Encoding.ASCII, 1024 * 1024 ); m_closeWriter = true; Init(); } public TextIntermediateRepresentationDumper( System.IO.StreamWriter writer ) { m_writer = writer; m_closeWriter = false; Init(); } private void Init() { m_sourceCodeTracker = new SourceCodeTracker(); } //--// public void WriteLine() { WriteIndentation(); m_writer.WriteLine(); m_fIndented = false; } public void WriteLine( string s ) { WriteIndentation(); m_writer.WriteLine( s ); m_fIndented = false; } public void WriteLine( string s , object arg1 ) { WriteIndentedLine( s, arg1 ); } public void WriteLine( string s , object arg1 , object arg2 ) { WriteIndentedLine( s, arg1, arg2 ); } public void WriteLine( string s , object arg1 , object arg2 , object arg3 ) { WriteIndentedLine( s, arg1, arg2, arg3 ); } public void WriteLine( string s , params object[] args ) { WriteIndentedLine( s, args ); } //--// public override void DumpGraph( ControlFlowGraphState cfg ) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; base.DumpGraph( cfg2 ); m_sourceCodeTracker.ExtraLinesToOutput = 3; //--// if(m_sortedVariables.Length > 0) { m_indent += 3; foreach(VariableExpression ex in m_sortedVariables) { WriteLine( "{0} {1} as {2}", m_useChains[ex.SpanningTreeIndex].Length > 0 ? " var" : "unused var", ex, ex.Type ); } m_indent -= 3; WriteLine(); } foreach(BasicBlock bb in m_basicBlocks) { ProcessBasicBlock( bb ); } } private void ProcessBasicBlock( BasicBlock bb ) { m_indent += 1; string label = CreateLabel( bb ); if(label != null) { WriteLine( "{0}: [Index:{1}] [Annotation:{2}]", label, bb.SpanningTreeIndex, bb.Annotation ); } // // Print context for every basic block, even if they are consecutive. // m_sourceCodeTracker.ResetContext(); m_indent += 4; if(bb is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)bb; foreach(ExceptionClause eh in ehBB.HandlerFor) { WriteLine( ".handler for {0}", eh ); } } foreach(ExceptionHandlerBasicBlock bbEh in bb.ProtectedBy) { foreach(ExceptionClause eh in bbEh.HandlerFor) { WriteLine( ".protected by {0} at {1}", eh, CreateLabel( bbEh ) ); } } foreach(BasicBlockEdge edge in bb.Predecessors) { WriteLine( ".edge {0} from {1}", edge.EdgeClass, CreateLabel( edge.Predecessor ) ); } foreach(BasicBlockEdge edge in bb.Successors) { WriteLine( ".edge {0} to {1}", edge.EdgeClass, CreateLabel( edge.Successor ) ); } GrowOnlySet< Expression > used = SetFactory.NewWithReferenceEquality< Expression >(); foreach(Operator op in bb.Operators) { foreach(Expression ex in op.Arguments) { used.Insert( ex ); } } foreach(Expression ex in used) { bool fGot = false; foreach(int opIndex in m_reachingDefinitions[bb.Operators[0].SpanningTreeIndex]) { if(m_operators[opIndex].IsSourceOfExpression( ex )) { if(fGot == false) { WriteIndented( ".reaching {0} <=", ex ); fGot = true; } else { WriteIndented( "," ); } WriteIndented( " Op_{0}", opIndex ); } } if(fGot) { WriteLine(); } } //--// foreach(Operator op in bb.Operators) { DumpOperator( op ); } m_indent -= 4; m_indent -= 1; WriteLine(); } private void DumpOperator( Operator op ) { DumpSourceCode( op.DebugInfo ); #if DUMP_ALIVE_INFO if(op.IsSideEffect == false) { BitVector vec = m_liveness[op.SpanningTreeIndex]; if(vec.Cardinality != 0) { WriteLine(); foreach(int idx in vec) { VariableExpression ex = m_variables[idx]; WriteIndentedLine( ".alive {0}", ex ); } } } #endif string s = op.FormatOutput( this ); foreach(string s2 in s.Split( '\n' )) { WriteLine( "Op_{0,-4}: {1}", op.SpanningTreeIndex, s2 ); } foreach(Annotation an in op.Annotations) { WriteLine( " {0}", an.FormatOutput( this ) ); } } private void DumpSourceCode( Debugging.DebugInfo dbg ) { m_sourceCodeTracker.Print( dbg, delegate ( string format, object[] args ) { m_writer.Write ( ";;;" ); m_writer.WriteLine( format, args ); } ); } //--// private void WriteIndented( string s , params object[] args ) { WriteIndentation(); m_writer.Write( FormatOutputInternal( s, args ) ); } private void WriteIndentedLine( string s , params object[] args ) { WriteIndentation(); m_writer.WriteLine( FormatOutputInternal( s, args ) ); m_fIndented = false; } private void WriteIndentation() { if(m_fIndented == false) { m_fIndented = true; for(int i = 0; i < m_indent; i++) { m_writer.Write( " " ); } } } #region IDisposable Members public void Dispose() { if(m_closeWriter) { m_writer.Flush(); m_writer.Dispose(); m_writer = null; m_closeWriter = false; } } #endregion } //--// public class XmlIntermediateRepresentationDumper : BaseIntermediateRepresentationDumper { // // State // System.Xml.XmlDocument m_doc; System.Xml.XmlNode m_root; // // Constructor Methods // public XmlIntermediateRepresentationDumper( System.Xml.XmlDocument doc , System.Xml.XmlNode root ) { m_doc = doc; m_root = root; } //--// public override void DumpGraph( ControlFlowGraphState cfg ) { ControlFlowGraphStateForCodeTransformation cfg2 = (ControlFlowGraphStateForCodeTransformation)cfg; base.DumpGraph( cfg2 ); //--// System.Xml.XmlNode node = XmlHelper.AddElement( m_root, "Method" ); XmlHelper.AddAttribute( node, "Name", cfg.Method.ToString() ); foreach(VariableExpression ex in cfg2.DataFlow_SpanningTree_Variables) { DumpVariable( node, ex ); } foreach(BasicBlock bb in m_basicBlocks) { ProcessBasicBlock( node, bb ); } } private void DumpVariable( System.Xml.XmlNode node , VariableExpression ex ) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Variable" ); XmlHelper.AddAttribute( subnode, "Name", CreateName( ex ) ); XmlHelper.AddAttribute( subnode, "Type", ex.Type.ToString() ); } private void ProcessBasicBlock( System.Xml.XmlNode node , BasicBlock bb ) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "BasicBlock" ); XmlHelper.AddAttribute( subnode, "Id" , CreateLabel( bb ) ); XmlHelper.AddAttribute( subnode, "Index", bb.SpanningTreeIndex.ToString() ); XmlHelper.AddAttribute( subnode, "Type" , bb.GetType().Name ); foreach(BasicBlockEdge edge in bb.Successors) { DumpEdge( subnode, edge ); } //--// GrowOnlySet< Expression > used = SetFactory.NewWithReferenceEquality< Expression >(); foreach(Operator op in bb.Operators) { foreach(Expression ex in op.Arguments) { used.Insert( ex ); } } foreach(Expression ex in used) { System.Xml.XmlNode reachingNode = null; foreach(int opIndex in m_reachingDefinitions[bb.Operators[0].SpanningTreeIndex]) { if(m_operators[opIndex].IsSourceOfExpression( ex )) { if(reachingNode == null) { reachingNode = XmlHelper.AddElement( subnode, "ReachingDefinition" ); XmlHelper.AddAttribute( reachingNode, "Variable", CreateName( ex ) ); } System.Xml.XmlNode opNode = XmlHelper.AddElement( reachingNode, "Definition" ); XmlHelper.AddAttribute( opNode, "Index", opIndex.ToString() ); } } } if(bb is ExceptionHandlerBasicBlock) { ExceptionHandlerBasicBlock ehBB = (ExceptionHandlerBasicBlock)bb; foreach(ExceptionClause eh in ehBB.HandlerFor) { System.Xml.XmlNode exNode = XmlHelper.AddElement( subnode, "HandlerFor" ); XmlHelper.AddAttribute( exNode, "Type", eh.ToString() ); } } //--// foreach(Operator op in bb.Operators) { DumpOperator( subnode, op ); } } private void DumpOperator( System.Xml.XmlNode node , Operator op ) { string s = op.FormatOutput( this ); foreach(string s2 in s.Split( '\n' )) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Operator" ); XmlHelper.AddAttribute( subnode, "Index", op.SpanningTreeIndex.ToString() ); if(op is CallOperator) { CallOperator op2 = (CallOperator)op; XmlHelper.AddAttribute( subnode, "Call", op2.TargetMethod.ToString() ); } DumpDebug( subnode, op.DebugInfo ); subnode.AppendChild( m_doc.CreateTextNode( s2 ) ); } } private void DumpDebug( System.Xml.XmlNode node , Debugging.DebugInfo dbg ) { if(dbg != null) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Debug" ); XmlHelper.AddAttribute( subnode, "File" , dbg.SrcFileName ); XmlHelper.AddAttribute( subnode, "MethodName" , dbg.MethodName ); XmlHelper.AddAttribute( subnode, "BeginLine" , dbg.BeginLineNumber.ToString() ); XmlHelper.AddAttribute( subnode, "BeginColumn", dbg.BeginColumn .ToString() ); XmlHelper.AddAttribute( subnode, "EndLine" , dbg.EndLineNumber .ToString() ); XmlHelper.AddAttribute( subnode, "EndColumn" , dbg.EndColumn .ToString() ); } } private void DumpEdge( System.Xml.XmlNode node , BasicBlockEdge edge ) { System.Xml.XmlNode subnode = XmlHelper.AddElement( node, "Edge" ); XmlHelper.AddAttribute( subnode, "From", CreateLabel( edge.Predecessor ) ); XmlHelper.AddAttribute( subnode, "To" , CreateLabel( edge.Successor ) ); XmlHelper.AddAttribute( subnode, "Kind", edge.EdgeClass.ToString() ); } } //--// public class PrettyDumper : BaseIntermediateRepresentationDumper { // // State // // // Constructor Methods // public PrettyDumper() { } //--// public override void DumpGraph( ControlFlowGraphState cfg ) { } internal static string Dump( Operator op ) { PrettyDumper dumper = new PrettyDumper(); return op.FormatOutput( dumper ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Creates a <see cref="LambdaExpression"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> [DebuggerTypeProxy(typeof(LambdaExpressionProxy))] public abstract class LambdaExpression : Expression, IParameterProvider { private readonly Expression _body; internal LambdaExpression(Expression body) { _body = body; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type => TypeCore; internal abstract Type TypeCore { get; } internal abstract Type PublicType { get; } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType => ExpressionType.Lambda; /// <summary> /// Gets the parameters of the lambda expression. /// </summary> public ReadOnlyCollection<ParameterExpression> Parameters => GetOrMakeParameters(); /// <summary> /// Gets the name of the lambda expression. /// </summary> /// <remarks>Used for debugging purposes.</remarks> public string Name => NameCore; internal virtual string NameCore => null; /// <summary> /// Gets the body of the lambda expression. /// </summary> public Expression Body => _body; /// <summary> /// Gets the return type of the lambda expression. /// </summary> public Type ReturnType => Type.GetInvokeMethod().ReturnType; /// <summary> /// Gets the value that indicates if the lambda expression will be compiled with /// tail call optimization. /// </summary> public bool TailCall => TailCallCore; internal virtual bool TailCallCore => false; [ExcludeFromCodeCoverage] // Unreachable internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable ParameterExpression IParameterProvider.GetParameter(int index) => GetParameter(index); [ExcludeFromCodeCoverage] // Unreachable internal virtual ParameterExpression GetParameter(int index) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable int IParameterProvider.ParameterCount => ParameterCount; [ExcludeFromCodeCoverage] // Unreachable internal virtual int ParameterCount { get { throw ContractUtils.Unreachable; } } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile() { return Compile(preferInterpretation: false); } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile(bool preferInterpretation) { #if FEATURE_COMPILE #if FEATURE_INTERPRET if (preferInterpretation) { return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); } #endif return Compiler.LambdaCompiler.Compile(this); #else return new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Compiles the lambda into a method definition. /// </summary> /// <param name="method">A <see cref="Emit.MethodBuilder"/> which will be used to hold the lambda's IL.</param> public void CompileToMethod(System.Reflection.Emit.MethodBuilder method) { ContractUtils.RequiresNotNull(method, nameof(method)); ContractUtils.Requires(method.IsStatic, nameof(method)); var type = method.DeclaringType as System.Reflection.Emit.TypeBuilder; if (type == null) throw Error.MethodBuilderDoesNotHaveTypeBuilder(); Compiler.LambdaCompiler.Compile(this, method); } #endif #if FEATURE_COMPILE internal abstract LambdaExpression Accept(Compiler.StackSpiller spiller); #endif /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public Delegate Compile(DebugInfoGenerator debugInfoGenerator) { return Compile(); } } /// <summary> /// Defines a <see cref="Expression{TDelegate}"/> node. /// This captures a block of code that is similar to a .NET method body. /// </summary> /// <typeparam name="TDelegate">The type of the delegate.</typeparam> /// <remarks> /// Lambda expressions take input through parameters and are expected to be fully bound. /// </remarks> public class Expression<TDelegate> : LambdaExpression { internal Expression(Expression body) : base(body) { } internal sealed override Type TypeCore => typeof(TDelegate); internal override Type PublicType => typeof(Expression<TDelegate>); /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile() { return Compile(preferInterpretation: false); } /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="preferInterpretation">A <see cref="bool"/> that indicates if the expression should be compiled to an interpreted form, if available.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile(bool preferInterpretation) { #if FEATURE_COMPILE #if FEATURE_INTERPRET if (preferInterpretation) { return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); } #endif return (TDelegate)(object)Compiler.LambdaCompiler.Compile(this); #else return (TDelegate)(object)new Interpreter.LightCompiler().CompileTop(this).CreateDelegate(); #endif } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="body">The <see cref="LambdaExpression.Body" /> property of the result.</param> /// <param name="parameters">The <see cref="LambdaExpression.Parameters" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public Expression<TDelegate> Update(Expression body, IEnumerable<ParameterExpression> parameters) { if (body == Body) { // Ensure parameters is safe to enumerate twice. // (If this means a second call to ToReadOnly it will return quickly). ICollection<ParameterExpression> pars; if (parameters == null) { pars = null; } else { pars = parameters as ICollection<ParameterExpression>; if (pars == null) { parameters = pars = parameters.ToReadOnly(); } } if (SameParameters(pars)) { return this; } } return Lambda<TDelegate>(body, Name, TailCall, parameters); } [ExcludeFromCodeCoverage] // Unreachable internal virtual bool SameParameters(ICollection<ParameterExpression> parameters) { throw ContractUtils.Unreachable; } [ExcludeFromCodeCoverage] // Unreachable internal virtual Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { throw ContractUtils.Unreachable; } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitLambda(this); } #if FEATURE_COMPILE internal override LambdaExpression Accept(Compiler.StackSpiller spiller) { return spiller.Rewrite(this); } internal static Expression<TDelegate> Create(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters) { if (name == null && !tailCall) { switch (parameters.Count) { case 0: return new Expression0<TDelegate>(body); case 1: return new Expression1<TDelegate>(body, parameters[0]); case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]); case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]); default: return new ExpressionN<TDelegate>(body, parameters); } } return new FullExpression<TDelegate>(body, name, tailCall, parameters); } #endif /// <summary> /// Produces a delegate that represents the lambda expression. /// </summary> /// <param name="debugInfoGenerator">Debugging information generator used by the compiler to mark sequence points and annotate local variables.</param> /// <returns>A delegate containing the compiled version of the lambda.</returns> public new TDelegate Compile(DebugInfoGenerator debugInfoGenerator) { return Compile(); } } #if !FEATURE_COMPILE // Separate expression creation class to hide the CreateExpressionFunc function from users reflecting on Expression<T> public class ExpressionCreator<TDelegate> { public static LambdaExpression CreateExpressionFunc(Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { if (name == null && !tailCall) { switch (parameters.Count) { case 0: return new Expression0<TDelegate>(body); case 1: return new Expression1<TDelegate>(body, parameters[0]); case 2: return new Expression2<TDelegate>(body, parameters[0], parameters[1]); case 3: return new Expression3<TDelegate>(body, parameters[0], parameters[1], parameters[2]); default: return new ExpressionN<TDelegate>(body, parameters); } } return new FullExpression<TDelegate>(body, name, tailCall, parameters); } } #endif internal sealed class Expression0<TDelegate> : Expression<TDelegate> { public Expression0(Expression body) : base(body) { } internal override int ParameterCount => 0; internal override bool SameParameters(ICollection<ParameterExpression> parameters) => parameters == null || parameters.Count == 0; internal override ParameterExpression GetParameter(int index) { throw Error.ArgumentOutOfRange(nameof(index)); } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => EmptyReadOnlyCollection<ParameterExpression>.Instance; internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 0); return Expression.Lambda<TDelegate>(body, parameters); } } internal sealed class Expression1<TDelegate> : Expression<TDelegate> { private object _par0; public Expression1(Expression body, ParameterExpression par0) : base(body) { _par0 = par0; } internal override int ParameterCount => 1; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 1) { using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); return en.Current == ExpressionUtils.ReturnObject<ParameterExpression>(_par0); } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 1); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0)); } } internal sealed class Expression2<TDelegate> : Expression<TDelegate> { private object _par0; private readonly ParameterExpression _par1; public Expression2(Expression body, ParameterExpression par0, ParameterExpression par1) : base(body) { _par0 = par0; _par1 = par1; } internal override int ParameterCount => 2; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); case 1: return _par1; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 2) { ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(parameters, alreadyCollection); } using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); if (en.Current == _par0) { en.MoveNext(); return en.Current == _par1; } } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 2); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1); } } internal sealed class Expression3<TDelegate> : Expression<TDelegate> { private object _par0; private readonly ParameterExpression _par1; private readonly ParameterExpression _par2; public Expression3(Expression body, ParameterExpression par0, ParameterExpression par1, ParameterExpression par2) : base(body) { _par0 = par0; _par1 = par1; _par2 = par2; } internal override int ParameterCount => 3; internal override ParameterExpression GetParameter(int index) { switch (index) { case 0: return ExpressionUtils.ReturnObject<ParameterExpression>(_par0); case 1: return _par1; case 2: return _par2; default: throw Error.ArgumentOutOfRange(nameof(index)); } } internal override bool SameParameters(ICollection<ParameterExpression> parameters) { if (parameters != null && parameters.Count == 3) { ReadOnlyCollection<ParameterExpression> alreadyCollection = _par0 as ReadOnlyCollection<ParameterExpression>; if (alreadyCollection != null) { return ExpressionUtils.SameElements(parameters, alreadyCollection); } using (IEnumerator<ParameterExpression> en = parameters.GetEnumerator()) { en.MoveNext(); if (en.Current == _par0) { en.MoveNext(); if (en.Current == _par1) { en.MoveNext(); return en.Current == _par2; } } } } return false; } internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(this, ref _par0); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == 3); if (parameters != null) { return Expression.Lambda<TDelegate>(body, parameters); } return Expression.Lambda<TDelegate>(body, ExpressionUtils.ReturnObject<ParameterExpression>(_par0), _par1, _par2); } } internal class ExpressionN<TDelegate> : Expression<TDelegate> { private IReadOnlyList<ParameterExpression> _parameters; public ExpressionN(Expression body, IReadOnlyList<ParameterExpression> parameters) : base(body) { _parameters = parameters; } internal override int ParameterCount => _parameters.Count; internal override ParameterExpression GetParameter(int index) => _parameters[index]; internal override bool SameParameters(ICollection<ParameterExpression> parameters) => ExpressionUtils.SameElements(parameters, _parameters); internal override ReadOnlyCollection<ParameterExpression> GetOrMakeParameters() => ExpressionUtils.ReturnReadOnly(ref _parameters); internal override Expression<TDelegate> Rewrite(Expression body, ParameterExpression[] parameters) { Debug.Assert(body != null); Debug.Assert(parameters == null || parameters.Length == _parameters.Count); return Expression.Lambda<TDelegate>(body, Name, TailCall, parameters ?? _parameters); } } internal sealed class FullExpression<TDelegate> : ExpressionN<TDelegate> { public FullExpression(Expression body, string name, bool tailCall, IReadOnlyList<ParameterExpression> parameters) : base(body, parameters) { NameCore = name; TailCallCore = tailCall; } internal override string NameCore { get; } internal override bool TailCallCore { get; } } public partial class Expression { /// <summary> /// Creates an Expression{T} given the delegate type. Caches the /// factory method to speed up repeated creations for the same T. /// </summary> internal static LambdaExpression CreateLambda(Type delegateType, Expression body, string name, bool tailCall, ReadOnlyCollection<ParameterExpression> parameters) { // Get or create a delegate to the public Expression.Lambda<T> // method and call that will be used for creating instances of this // delegate type Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression> fastPath; CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> factories = s_lambdaFactories; if (factories == null) { s_lambdaFactories = factories = new CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>>(50); } MethodInfo create = null; if (!factories.TryGetValue(delegateType, out fastPath)) { #if FEATURE_COMPILE create = typeof(Expression<>).MakeGenericType(delegateType).GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic); #else create = typeof(ExpressionCreator<>).MakeGenericType(delegateType).GetMethod("CreateExpressionFunc", BindingFlags.Static | BindingFlags.Public); #endif if (delegateType.CanCache()) { factories[delegateType] = fastPath = (Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)create.CreateDelegate(typeof(Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>)); } } if (fastPath != null) { return fastPath(body, name, tailCall, parameters); } Debug.Assert(create != null); return (LambdaExpression)create.Invoke(null, new object[] { body, name, tailCall, parameters }); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda<TDelegate>(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, null, tailCall, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda<TDelegate>(body, name, false, parameters); } /// <summary> /// Creates an <see cref="Expression{TDelegate}"/> where the delegate type is known at compile time. /// </summary> /// <typeparam name="TDelegate">The delegate type.</typeparam> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name of the lambda. Used for generating debugging info.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <returns>An <see cref="Expression{TDelegate}"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static Expression<TDelegate> Lambda<TDelegate>(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly(); ValidateLambdaArgs(typeof(TDelegate), ref body, parameterList, nameof(TDelegate)); return (Expression<TDelegate>)CreateLambda(typeof(TDelegate), body, name, tailCall, parameterList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, params ParameterExpression[] parameters) { return Lambda(body, false, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(body, tailCall, (IEnumerable<ParameterExpression>)parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An array that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, params ParameterExpression[] parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, bool tailCall, IEnumerable<ParameterExpression> parameters) { return Lambda(delegateType, body, null, tailCall, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, IEnumerable<ParameterExpression> parameters) { return Lambda(body, name, false, parameters); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ContractUtils.RequiresNotNull(body, nameof(body)); ReadOnlyCollection<ParameterExpression> parameterList = parameters.ToReadOnly(); int paramCount = parameterList.Count; Type[] typeArgs = new Type[paramCount + 1]; if (paramCount > 0) { var set = new HashSet<ParameterExpression>(); for (int i = 0; i < paramCount; i++) { ParameterExpression param = parameterList[i]; ContractUtils.RequiresNotNull(param, "parameter"); typeArgs[i] = param.IsByRef ? param.Type.MakeByRefType() : param.Type; if (!set.Add(param)) { throw Error.DuplicateVariable(param, nameof(parameters), i); } } } typeArgs[paramCount] = body.Type; Type delegateType = Compiler.DelegateHelpers.MakeDelegateType(typeArgs); return CreateLambda(delegateType, body, name, tailCall, parameterList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType)); return CreateLambda(delegateType, body, name, false, paramList); } /// <summary> /// Creates a <see cref="LambdaExpression"/> by first constructing a delegate type. /// </summary> /// <param name="delegateType">A <see cref="Type"/> representing the delegate signature for the lambda.</param> /// <param name="body">An <see cref="Expression"/> to set the <see cref="LambdaExpression.Body"/> property equal to.</param> /// <param name="name">The name for the lambda. Used for emitting debug information.</param> /// <param name="tailCall">A <see cref="bool"/> that indicates if tail call optimization will be applied when compiling the created expression.</param> /// <param name="parameters">An <see cref="IEnumerable{T}"/> that contains <see cref="ParameterExpression"/> objects to use to populate the <see cref="LambdaExpression.Parameters"/> collection.</param> /// <returns>A <see cref="LambdaExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Lambda"/> and the <see cref="LambdaExpression.Body"/> and <see cref="LambdaExpression.Parameters"/> properties set to the specified values.</returns> public static LambdaExpression Lambda(Type delegateType, Expression body, string name, bool tailCall, IEnumerable<ParameterExpression> parameters) { ReadOnlyCollection<ParameterExpression> paramList = parameters.ToReadOnly(); ValidateLambdaArgs(delegateType, ref body, paramList, nameof(delegateType)); return CreateLambda(delegateType, body, name, tailCall, paramList); } private static void ValidateLambdaArgs(Type delegateType, ref Expression body, ReadOnlyCollection<ParameterExpression> parameters, string paramName) { ContractUtils.RequiresNotNull(delegateType, nameof(delegateType)); ExpressionUtils.RequiresCanRead(body, nameof(body)); if (!typeof(MulticastDelegate).IsAssignableFrom(delegateType) || delegateType == typeof(MulticastDelegate)) { throw Error.LambdaTypeMustBeDerivedFromSystemDelegate(paramName); } TypeUtils.ValidateType(delegateType, nameof(delegateType), allowByRef: true, allowPointer: true); MethodInfo mi; CacheDict<Type, MethodInfo> ldc = s_lambdaDelegateCache; if (!ldc.TryGetValue(delegateType, out mi)) { mi = delegateType.GetInvokeMethod(); if (delegateType.CanCache()) { ldc[delegateType] = mi; } } ParameterInfo[] pis = mi.GetParametersCached(); if (pis.Length > 0) { if (pis.Length != parameters.Count) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } var set = new HashSet<ParameterExpression>(); for (int i = 0, n = pis.Length; i < n; i++) { ParameterExpression pex = parameters[i]; ParameterInfo pi = pis[i]; ExpressionUtils.RequiresCanRead(pex, nameof(parameters), i); Type pType = pi.ParameterType; if (pex.IsByRef) { if (!pType.IsByRef) { //We cannot pass a parameter of T& to a delegate that takes T or any non-ByRef type. throw Error.ParameterExpressionNotValidAsDelegate(pex.Type.MakeByRefType(), pType); } pType = pType.GetElementType(); } if (!TypeUtils.AreReferenceAssignable(pex.Type, pType)) { throw Error.ParameterExpressionNotValidAsDelegate(pex.Type, pType); } if (!set.Add(pex)) { throw Error.DuplicateVariable(pex, nameof(parameters), i); } } } else if (parameters.Count > 0) { throw Error.IncorrectNumberOfLambdaDeclarationParameters(); } if (mi.ReturnType != typeof(void) && !TypeUtils.AreReferenceAssignable(mi.ReturnType, body.Type)) { if (!TryQuote(mi.ReturnType, ref body)) { throw Error.ExpressionTypeDoesNotMatchReturn(body.Type, mi.ReturnType); } } } private enum TryGetFuncActionArgsResult { Valid, ArgumentNull, ByRef, PointerOrVoid } private static TryGetFuncActionArgsResult ValidateTryGetFuncActionArgs(Type[] typeArgs) { if (typeArgs == null) { return TryGetFuncActionArgsResult.ArgumentNull; } for (int i = 0; i < typeArgs.Length; i++) { Type a = typeArgs[i]; if (a == null) { return TryGetFuncActionArgsResult.ArgumentNull; } if (a.IsByRef) { return TryGetFuncActionArgsResult.ByRef; } if (a == typeof(void) || a.IsPointer) { return TryGetFuncActionArgsResult.PointerOrVoid; } } return TryGetFuncActionArgsResult.Valid; } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param> /// <returns>The type of a System.Func delegate that has the specified type arguments.</returns> public static Type GetFuncType(params Type[] typeArgs) { switch (ValidateTryGetFuncActionArgs(typeArgs)) { case TryGetFuncActionArgsResult.ArgumentNull: throw new ArgumentNullException(nameof(typeArgs)); case TryGetFuncActionArgsResult.ByRef: throw Error.TypeMustNotBeByRef(nameof(typeArgs)); default: // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetFuncType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForFunc(nameof(typeArgs)); } return result; } } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Func delegate type that has specific type arguments. /// The last type argument specifies the return type of the created delegate. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Func delegate type.</param> /// <param name="funcType">When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Func delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetFuncType(Type[] typeArgs, out Type funcType) { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { return (funcType = Compiler.DelegateHelpers.GetFuncType(typeArgs)) != null; } funcType = null; return false; } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param> /// <returns>The type of a System.Action delegate that has the specified type arguments.</returns> public static Type GetActionType(params Type[] typeArgs) { switch (ValidateTryGetFuncActionArgs(typeArgs)) { case TryGetFuncActionArgsResult.ArgumentNull: throw new ArgumentNullException(nameof(typeArgs)); case TryGetFuncActionArgsResult.ByRef: throw Error.TypeMustNotBeByRef(nameof(typeArgs)); default: // This includes pointers or void. We allow the exception that comes // from trying to use them as generic arguments to pass through. Type result = Compiler.DelegateHelpers.GetActionType(typeArgs); if (result == null) { throw Error.IncorrectNumberOfTypeArgsForAction(nameof(typeArgs)); } return result; } } /// <summary> /// Creates a <see cref="System.Type"/> object that represents a generic System.Action delegate type that has specific type arguments. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments for the System.Action delegate type.</param> /// <param name="actionType">When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the <paramref name="typeArgs"/>.This parameter is passed uninitialized.</param> /// <returns>true if generic System.Action delegate type was created for specific <paramref name="typeArgs"/>; false otherwise.</returns> public static bool TryGetActionType(Type[] typeArgs, out Type actionType) { if (ValidateTryGetFuncActionArgs(typeArgs) == TryGetFuncActionArgsResult.Valid) { return (actionType = Compiler.DelegateHelpers.GetActionType(typeArgs)) != null; } actionType = null; return false; } /// <summary> /// Gets a <see cref="System.Type"/> object that represents a generic System.Func or System.Action delegate type that has specific type arguments. /// The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom /// delegate type. /// </summary> /// <param name="typeArgs">An array of <see cref="System.Type"/> objects that specify the type arguments of the delegate type.</param> /// <returns>The delegate type.</returns> /// <remarks> /// As with Func, the last argument is the return type. It can be set /// to <see cref="System.Void"/> to produce an Action.</remarks> public static Type GetDelegateType(params Type[] typeArgs) { ContractUtils.RequiresNotEmpty(typeArgs, nameof(typeArgs)); ContractUtils.RequiresNotNullItems(typeArgs, nameof(typeArgs)); return Compiler.DelegateHelpers.MakeDelegateType(typeArgs); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Tests for the ProjectChooseElement class (and for ProjectWhenElement and ProjectOtherwiseElement).</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Microsoft.Build.Evaluation; using Microsoft.Build.Construction; using Microsoft.Build.Shared; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; using Xunit; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Tests for the ProjectChooseElement class (and for ProjectWhenElement and ProjectOtherwiseElement) /// </summary> public class ProjectChooseElement_Tests { /// <summary> /// Read choose with unexpected attribute /// </summary> [Fact] public void ReadInvalidAttribute() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose X='Y'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read choose with unexpected Condition attribute. /// Condition is not currently allowed on Choose. /// </summary> [Fact] public void ReadInvalidConditionAttribute() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose Condition='true'/> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read choose with unexpected child /// </summary> [Fact] public void ReadInvalidChild() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <X/> </Choose> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read choose with a When containing no Condition attribute /// </summary> [Fact] public void ReadInvalidWhen() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <When> <PropertyGroup><x/></PropertyGroup> </When> <Otherwise> <PropertyGroup><y/></PropertyGroup> </Otherwise> </Choose> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read choose with only an otherwise /// </summary> [Fact] public void ReadInvalidOnlyOtherwise() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <Otherwise/> </Choose> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read choose with two otherwises /// </summary> [Fact] public void ReadInvalidTwoOtherwise() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <Otherwise/> <Otherwise/> </Choose> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read choose with otherwise before when /// </summary> [Fact] public void ReadInvalidOtherwiseBeforeWhen() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <Otherwise/> <When Condition='c'/> </Choose> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Read empty choose /// </summary> /// <remarks> /// One might think this should work but 2.0 required at least one When. /// </remarks> [Fact] public void ReadInvalidEmptyChoose() { Assert.Throws<InvalidProjectFileException>(() => { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose/> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children); Assert.Equal(null, Helpers.GetFirst(choose.Children)); } ); } /// <summary> /// Read choose with only a when /// </summary> [Fact] public void ReadChooseOnlyWhen() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <When Condition='c'/> </Choose> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children); Assert.Equal(1, Helpers.Count(choose.WhenElements)); Assert.Equal(null, choose.OtherwiseElement); } /// <summary> /// Read basic choose /// </summary> [Fact] public void ReadChooseBothWhenOtherwise() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <When Condition='c1'/> <When Condition='c2'/> <Otherwise/> </Choose> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children); List<ProjectWhenElement> whens = Helpers.MakeList(choose.WhenElements); Assert.Equal(2, whens.Count); Assert.Equal("c1", whens[0].Condition); Assert.Equal("c2", whens[1].Condition); Assert.NotNull(choose.OtherwiseElement); } /// <summary> /// Test stack overflow is prevented. /// </summary> [Fact] public void ExcessivelyNestedChoose() { Assert.Throws<InvalidProjectFileException>(() => { StringBuilder builder1 = new StringBuilder(); StringBuilder builder2 = new StringBuilder(); for (int i = 0; i < 52; i++) { builder1.Append("<Choose><When Condition='true'>"); builder2.Append("</When></Choose>"); } string content = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>"; content += builder1.ToString(); content += builder2.ToString(); content += @"</Project>"; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } ); } /// <summary> /// Setting a When's condition should dirty the project /// </summary> [Fact] public void SettingWhenConditionDirties() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <Choose> <When Condition='true'> <PropertyGroup> <p>v1</p> </PropertyGroup> </When> </Choose> </Project> "; Project project = new Project(XmlReader.Create(new StringReader(content))); ProjectChooseElement choose = Helpers.GetFirst(project.Xml.ChooseElements); ProjectWhenElement when = Helpers.GetFirst(choose.WhenElements); when.Condition = "false"; Assert.Equal("v1", project.GetPropertyValue("p")); project.ReevaluateIfNecessary(); Assert.Equal(String.Empty, project.GetPropertyValue("p")); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorMailModule.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Diagnostics; using System.Globalization; using System.Web; using System.IO; using System.Net.Mail; using MailAttachment = System.Net.Mail.Attachment; using IDictionary = System.Collections.IDictionary; using ThreadPool = System.Threading.ThreadPool; using WaitCallback = System.Threading.WaitCallback; using Encoding = System.Text.Encoding; using NetworkCredential = System.Net.NetworkCredential; #endregion public sealed class ErrorMailEventArgs : EventArgs { private readonly Error _error; private readonly MailMessage _mail; public ErrorMailEventArgs(Error error, MailMessage mail) { if (error == null) throw new ArgumentNullException("error"); if (mail == null) throw new ArgumentNullException("mail"); _error = error; _mail = mail; } public Error Error { get { return _error; } } public MailMessage Mail { get { return _mail; } } } public delegate void ErrorMailEventHandler(object sender, ErrorMailEventArgs args); /// <summary> /// HTTP module that sends an e-mail whenever an unhandled exception /// occurs in an ASP.NET web application. /// </summary> public class ErrorMailModule : HttpModuleBase, IExceptionFiltering { private string _mailSender; private string _mailRecipient; private string _mailCopyRecipient; private string _mailSubjectFormat; private MailPriority _mailPriority; private bool _reportAsynchronously; private string _smtpServer; private int _smtpPort; private string _authUserName; private string _authPassword; private bool _noYsod; private bool _useSsl; public event ExceptionFilterEventHandler Filtering; public event ErrorMailEventHandler Mailing; public event ErrorMailEventHandler Mailed; public event ErrorMailEventHandler DisposingMail; /// <summary> /// Initializes the module and prepares it to handle requests. /// </summary> protected override void OnInit(HttpApplication application) { if (application == null) throw new ArgumentNullException("application"); // // Get the configuration section of this module. // If it's not there then there is nothing to initialize or do. // In this case, the module is as good as mute. // var config = (IDictionary) GetConfig(); if (config == null) return; // // Extract the settings. // var mailRecipient = GetSetting(config, "to"); var mailSender = GetSetting(config, "from", mailRecipient); var mailCopyRecipient = GetSetting(config, "cc", string.Empty); var mailSubjectFormat = GetSetting(config, "subject", string.Empty); var mailPriority = (MailPriority) Enum.Parse(typeof(MailPriority), GetSetting(config, "priority", MailPriority.Normal.ToString()), true); var reportAsynchronously = Convert.ToBoolean(GetSetting(config, "async", bool.TrueString)); var smtpServer = GetSetting(config, "smtpServer", string.Empty); var smtpPort = Convert.ToUInt16(GetSetting(config, "smtpPort", "0"), CultureInfo.InvariantCulture); var authUserName = GetSetting(config, "userName", string.Empty); var authPassword = GetSetting(config, "password", string.Empty); var sendYsod = Convert.ToBoolean(GetSetting(config, "noYsod", bool.FalseString)); var useSsl = Convert.ToBoolean(GetSetting(config, "useSsl", bool.FalseString)); // // Hook into the Error event of the application. // application.Error += new EventHandler(OnError); ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled); // // Finally, commit the state of the module if we got this far. // Anything beyond this point should not cause an exception. // _mailRecipient = mailRecipient; _mailSender = mailSender; _mailCopyRecipient = mailCopyRecipient; _mailSubjectFormat = mailSubjectFormat; _mailPriority = mailPriority; _reportAsynchronously = reportAsynchronously; _smtpServer = smtpServer; _smtpPort = smtpPort; _authUserName = authUserName; _authPassword = authPassword; _noYsod = sendYsod; _useSsl = useSsl; } /// <summary> /// Determines whether the module will be registered for discovery /// in partial trust environments or not. /// </summary> protected override bool SupportDiscoverability { get { return true; } } /// <summary> /// Gets the e-mail address of the sender. /// </summary> protected virtual string MailSender { get { return _mailSender; } } /// <summary> /// Gets the e-mail address of the recipient, or a /// comma-/semicolon-delimited list of e-mail addresses in case of /// multiple recipients. /// </summary> /// <remarks> /// When using System.Web.Mail components under .NET Framework 1.x, /// multiple recipients must be semicolon-delimited. /// When using System.Net.Mail components under .NET Framework 2.0 /// or later, multiple recipients must be comma-delimited. /// </remarks> protected virtual string MailRecipient { get { return _mailRecipient; } } /// <summary> /// Gets the e-mail address of the recipient for mail carbon /// copy (CC), or a comma-/semicolon-delimited list of e-mail /// addresses in case of multiple recipients. /// </summary> /// <remarks> /// When using System.Web.Mail components under .NET Framework 1.x, /// multiple recipients must be semicolon-delimited. /// When using System.Net.Mail components under .NET Framework 2.0 /// or later, multiple recipients must be comma-delimited. /// </remarks> protected virtual string MailCopyRecipient { get { return _mailCopyRecipient; } } /// <summary> /// Gets the text used to format the e-mail subject. /// </summary> /// <remarks> /// The subject text specification may include {0} where the /// error message (<see cref="Error.Message"/>) should be inserted /// and {1} <see cref="Error.Type"/> where the error type should /// be insert. /// </remarks> protected virtual string MailSubjectFormat { get { return _mailSubjectFormat; } } /// <summary> /// Gets the priority of the e-mail. /// </summary> protected virtual MailPriority MailPriority { get { return _mailPriority; } } /// <summary> /// Gets the SMTP server host name used when sending the mail. /// </summary> protected string SmtpServer { get { return _smtpServer; } } /// <summary> /// Gets the SMTP port used when sending the mail. /// </summary> protected int SmtpPort { get { return _smtpPort; } } /// <summary> /// Gets the user name to use if the SMTP server requires authentication. /// </summary> protected string AuthUserName { get { return _authUserName; } } /// <summary> /// Gets the clear-text password to use if the SMTP server requires /// authentication. /// </summary> protected string AuthPassword { get { return _authPassword; } } /// <summary> /// Indicates whether <a href="http://en.wikipedia.org/wiki/Screens_of_death#ASP.NET">YSOD</a> /// is attached to the e-mail or not. If <c>true</c>, the YSOD is /// not attached. /// </summary> protected bool NoYsod { get { return _noYsod; } } /// <summary> /// Determines if SSL will be used to encrypt communication with the /// mail server. /// </summary> protected bool UseSsl { get { return _useSsl; } } /// <summary> /// The handler called when an unhandled exception bubbles up to /// the module. /// </summary> protected virtual void OnError(object sender, EventArgs e) { var context = new HttpContextWrapper(((HttpApplication) sender).Context); OnError(context.Server.GetLastError(), context); } /// <summary> /// The handler called when an exception is explicitly signaled. /// </summary> protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args) { using (args.Exception.TryScopeCallerInfo(args.CallerInfo)) OnError(args.Exception, args.Context); } /// <summary> /// Reports the exception. /// </summary> protected virtual void OnError(Exception e, HttpContextBase context) { if (e == null) throw new ArgumentNullException("e"); // // Fire an event to check if listeners want to filter out // reporting of the uncaught exception. // var args = new ExceptionFilterEventArgs(e, context); OnFiltering(args); if (args.Dismissed) return; // // Get the last error and then report it synchronously or // asynchronously based on the configuration. // var error = new Error(e, context); if (_reportAsynchronously) ReportErrorAsync(error); else ReportError(error); } /// <summary> /// Raises the <see cref="Filtering"/> event. /// </summary> protected virtual void OnFiltering(ExceptionFilterEventArgs args) { var handler = Filtering; if (handler != null) handler(this, args); } /// <summary> /// Schedules the error to be e-mailed asynchronously. /// </summary> /// <remarks> /// The default implementation uses the <see cref="ThreadPool"/> /// to queue the reporting. /// </remarks> protected virtual void ReportErrorAsync(Error error) { if (error == null) throw new ArgumentNullException("error"); // // Schedule the reporting at a later time using a worker from // the system thread pool. This makes the implementation // simpler, but it might have an impact on reducing the // number of workers available for processing ASP.NET // requests in the case where lots of errors being generated. // ThreadPool.QueueUserWorkItem(new WaitCallback(ReportError), error); } private void ReportError(object state) { try { ReportError((Error) state); } // // Catch and trace COM/SmtpException here because this // method will be called on a thread pool thread and // can either fail silently in 1.x or with a big band in // 2.0. For latter, see the following MS KB article for // details: // // Unhandled exceptions cause ASP.NET-based applications // to unexpectedly quit in the .NET Framework 2.0 // http://support.microsoft.com/kb/911816 // catch (SmtpException e) { Trace.TraceError(e.ToString()); } } /// <summary> /// Schedules the error to be e-mailed synchronously. /// </summary> protected virtual void ReportError(Error error) { if (error == null) throw new ArgumentNullException("error"); // // Start by checking if we have a sender and a recipient. // These values may be null if someone overrides the // implementation of OnInit but does not override the // MailSender and MailRecipient properties. // var sender = this.MailSender ?? string.Empty; var recipient = this.MailRecipient ?? string.Empty; var copyRecipient = this.MailCopyRecipient ?? string.Empty; if (recipient.Length == 0) return; // // Create the mail, setting up the sender and recipient and priority. // var mail = new MailMessage(); mail.Priority = this.MailPriority; mail.From = new MailAddress(sender); mail.To.Add(recipient); if (copyRecipient.Length > 0) mail.CC.Add(copyRecipient); // // Format the mail subject. // var subjectFormat = Mask.EmptyString(this.MailSubjectFormat, "Error ({1}): {0}"); mail.Subject = string.Format(subjectFormat, error.Message, error.Type). Replace('\r', ' ').Replace('\n', ' '); // // Format the mail body. // var formatter = CreateErrorFormatter(); var bodyWriter = new StringWriter(); formatter.Format(bodyWriter, error); mail.Body = bodyWriter.ToString(); switch (formatter.MimeType) { case "text/html": mail.IsBodyHtml = true; break; case "text/plain": mail.IsBodyHtml = false; break; default : { throw new ApplicationException(string.Format( "The error mail module does not know how to handle the {1} media type that is created by the {0} formatter.", formatter.GetType().FullName, formatter.MimeType)); } } var args = new ErrorMailEventArgs(error, mail); try { // // If an HTML message was supplied by the web host then attach // it to the mail if not explicitly told not to do so. // if (!NoYsod && error.WebHostHtmlMessage.Length > 0) { var ysodAttachment = CreateHtmlAttachment("YSOD", error.WebHostHtmlMessage); if (ysodAttachment != null) mail.Attachments.Add(ysodAttachment); } // // Send off the mail with some chance to pre- or post-process // using event. // OnMailing(args); SendMail(mail); OnMailed(args); } finally { OnDisposingMail(args); mail.Dispose(); } } private static MailAttachment CreateHtmlAttachment(string name, string html) { Debug.AssertStringNotEmpty(name); Debug.AssertStringNotEmpty(html); return MailAttachment.CreateAttachmentFromString(html, name + ".html", Encoding.UTF8, "text/html"); } /// <summary> /// Creates the <see cref="ErrorTextFormatter"/> implementation to /// be used to format the body of the e-mail. /// </summary> protected virtual ErrorTextFormatter CreateErrorFormatter() { return new ErrorMailHtmlFormatter(); } /// <summary> /// Sends the e-mail using SmtpMail or SmtpClient. /// </summary> protected virtual void SendMail(MailMessage mail) { if (mail == null) throw new ArgumentNullException("mail"); // // Under .NET Framework 2.0, the authentication settings // go on the SmtpClient object rather than mail message // so these have to be set up here. // var client = new SmtpClient(); var host = SmtpServer ?? string.Empty; if (host.Length > 0) { client.Host = host; client.DeliveryMethod = SmtpDeliveryMethod.Network; } var port = SmtpPort; if (port > 0) client.Port = port; var userName = AuthUserName ?? string.Empty; var password = AuthPassword ?? string.Empty; if (userName.Length > 0 && password.Length > 0) client.Credentials = new NetworkCredential(userName, password); client.EnableSsl = UseSsl; client.Send(mail); } /// <summary> /// Fires the <see cref="Mailing"/> event. /// </summary> protected virtual void OnMailing(ErrorMailEventArgs args) { if (args == null) throw new ArgumentNullException("args"); var handler = Mailing; if (handler != null) handler(this, args); } /// <summary> /// Fires the <see cref="Mailed"/> event. /// </summary> protected virtual void OnMailed(ErrorMailEventArgs args) { if (args == null) throw new ArgumentNullException("args"); var handler = Mailed; if (handler != null) handler(this, args); } /// <summary> /// Fires the <see cref="DisposingMail"/> event. /// </summary> protected virtual void OnDisposingMail(ErrorMailEventArgs args) { if (args == null) throw new ArgumentNullException("args"); var handler = DisposingMail; if (handler != null) handler(this, args); } /// <summary> /// Gets the configuration object used by <see cref="OnInit"/> to read /// the settings for module. /// </summary> protected virtual object GetConfig() { return Configuration.GetSubsection("errorMail"); } private static string GetSetting(IDictionary config, string name) { return GetSetting(config, name, null); } private static string GetSetting(IDictionary config, string name, string defaultValue) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(name); var value = ((string) config[name]) ?? string.Empty; if (value.Length == 0) { if (defaultValue == null) { throw new ApplicationException(string.Format( "The required configuration setting '{0}' is missing for the error mailing module.", name)); } value = defaultValue; } return value; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.propertytype; using umbraco.interfaces; using Umbraco.Core; namespace umbraco.NodeFactory { /// <summary> /// Summary description for Node. /// </summary> [Serializable] [XmlType(Namespace = "http://umbraco.org/webservices/")] public class Node : INode { private Hashtable _aliasToNames = new Hashtable(); private bool _initialized = false; private Nodes _children = new Nodes(); private Node _parent = null; private int _id; private int _template; private string _name; private string _nodeTypeAlias; private string _writerName; private string _creatorName; private int _writerID; private int _creatorID; private string _urlName; private string _path; private DateTime _createDate; private DateTime _updateDate; private Guid _version; private Properties _properties = new Properties(); private XmlNode _pageXmlNode; private int _sortOrder; private int _level; public Nodes Children { get { if (!_initialized) initialize(); return _children; } } public INode Parent { get { if (!_initialized) initialize(); return _parent; } } public int Id { get { if (!_initialized) initialize(); return _id; } } public int template { get { if (!_initialized) initialize(); return _template; } } public int SortOrder { get { if (!_initialized) initialize(); return _sortOrder; } } public string Name { get { if (!_initialized) initialize(); return _name; } } public string Url { get { return library.NiceUrl(Id); } } public string NodeTypeAlias { get { if (!_initialized) initialize(); return _nodeTypeAlias; } } public string WriterName { get { if (!_initialized) initialize(); return _writerName; } } public string CreatorName { get { if (!_initialized) initialize(); return _creatorName; } } public int WriterID { get { if (!_initialized) initialize(); return _writerID; } } public int CreatorID { get { if (!_initialized) initialize(); return _creatorID; } } public string Path { get { if (!_initialized) initialize(); return _path; } } public DateTime CreateDate { get { if (!_initialized) initialize(); return _createDate; } } public DateTime UpdateDate { get { if (!_initialized) initialize(); return _updateDate; } } public Guid Version { get { if (!_initialized) initialize(); return _version; } } public string UrlName { get { if (!_initialized) initialize(); return _urlName; } } public string NiceUrl { get { return library.NiceUrl(Id); } } public int Level { get { if (!_initialized) initialize(); return _level; } } public List<IProperty> PropertiesAsList { get { return Properties.Cast<IProperty>().ToList(); } } public Properties Properties { get { if (!_initialized) initialize(); return _properties; } } public Node() { _pageXmlNode = ((IHasXmlNode)library.GetXmlNodeCurrent().Current).GetNode(); initializeStructure(); initialize(); } public Node(XmlNode NodeXmlNode) { _pageXmlNode = NodeXmlNode; initializeStructure(); initialize(); } public Node(XmlNode NodeXmlNode, bool DisableInitializing) { _pageXmlNode = NodeXmlNode; initializeStructure(); if (!DisableInitializing) initialize(); } /// <summary> /// Special constructor for by-passing published vs. preview xml to use /// when updating the SiteMapProvider /// </summary> /// <param name="NodeId"></param> /// <param name="forcePublishedXml"></param> public Node(int NodeId, bool forcePublishedXml) { if (forcePublishedXml) { if (NodeId != -1) _pageXmlNode = content.Instance.XmlContent.GetElementById(NodeId.ToString()); else { _pageXmlNode = content.Instance.XmlContent.DocumentElement; } initializeStructure(); initialize(); } else { throw new ArgumentException("Use Node(int NodeId) if not forcing published xml"); } } public Node(int NodeId) { if (NodeId != -1) _pageXmlNode = ((IHasXmlNode)library.GetXmlNodeById(NodeId.ToString()).Current).GetNode(); else { if (presentation.UmbracoContext.Current != null) { _pageXmlNode = umbraco.presentation.UmbracoContext.Current.GetXml().DocumentElement; } else { _pageXmlNode = content.Instance.XmlContent.DocumentElement; } } initializeStructure(); initialize(); } public IProperty GetProperty(string Alias) { foreach (Property p in Properties) { if (p.Alias == Alias) return p; } return null; } public IProperty GetProperty(string Alias, out bool propertyExists) { foreach (Property p in Properties) { if (p.Alias == Alias) { propertyExists = true; return p; } } propertyExists = false; return null; } public static Node GetNodeByXpath(string xpath) { XPathNodeIterator itNode = library.GetXmlNodeByXPath(xpath); XmlNode nodeXmlNode = null; if (itNode.MoveNext()) { nodeXmlNode = ((IHasXmlNode)itNode.Current).GetNode(); } if (nodeXmlNode != null) { return new Node(nodeXmlNode); } return null; } public List<INode> ChildrenAsList { get { return Children.Cast<INode>().ToList(); } } public DataTable ChildrenAsTable() { return GenerateDataTable(this); } public DataTable ChildrenAsTable(string nodeTypeAliasFilter) { return GenerateDataTable(this, nodeTypeAliasFilter); } private DataTable GenerateDataTable(INode node, string nodeTypeAliasFilter = "") { var firstNode = nodeTypeAliasFilter.IsNullOrWhiteSpace() ? node.ChildrenAsList.Any() ? node.ChildrenAsList[0] : null : node.ChildrenAsList.FirstOrDefault(x => x.NodeTypeAlias == nodeTypeAliasFilter); if (firstNode == null) return new DataTable(); //no children found //use new utility class to create table so that we don't have to maintain code in many places, just one var dt = Umbraco.Core.DataTableExtensions.GenerateDataTable( //pass in the alias of the first child node since this is the node type we're rendering headers for firstNode.NodeTypeAlias, //pass in the callback to extract the Dictionary<string, string> of column aliases to names alias => { var userFields = ContentType.GetAliasesAndNames(alias); //ensure the standard fields are there var allFields = new Dictionary<string, string>() { {"Id", "Id"}, {"NodeName", "NodeName"}, {"NodeTypeAlias", "NodeTypeAlias"}, {"CreateDate", "CreateDate"}, {"UpdateDate", "UpdateDate"}, {"CreatorName", "CreatorName"}, {"WriterName", "WriterName"}, {"Url", "Url"} }; foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key))) { allFields.Add(f.Key, f.Value); } return allFields; }, //pass in a callback to populate the datatable, yup its a bit ugly but it's already legacy and we just want to maintain code in one place. () => { //create all row data var tableData = Umbraco.Core.DataTableExtensions.CreateTableData(); //loop through each child and create row data for it foreach (Node n in Children) { if (!nodeTypeAliasFilter.IsNullOrWhiteSpace()) { if (n.NodeTypeAlias != nodeTypeAliasFilter) continue; //skip this one, it doesn't match the filter } var standardVals = new Dictionary<string, object>() { {"Id", n.Id}, {"NodeName", n.Name}, {"NodeTypeAlias", n.NodeTypeAlias}, {"CreateDate", n.CreateDate}, {"UpdateDate", n.UpdateDate}, {"CreatorName", n.CreatorName}, {"WriterName", n.WriterName}, {"Url", library.NiceUrl(n.Id)} }; var userVals = new Dictionary<string, object>(); foreach (var p in from Property p in n.Properties where p.Value != null select p) { userVals[p.Alias] = p.Value; } //add the row data Umbraco.Core.DataTableExtensions.AddRowData(tableData, standardVals, userVals); } return tableData; } ); return dt; } private void initializeStructure() { // Load parent if it exists and is a node if (_pageXmlNode != null && _pageXmlNode.SelectSingleNode("..") != null) { XmlNode parent = _pageXmlNode.SelectSingleNode(".."); if (parent != null && (parent.Name == "node" || (parent.Attributes != null && parent.Attributes.GetNamedItem("isDoc") != null))) _parent = new Node(parent, true); } } private void initialize() { if (_pageXmlNode != null) { _initialized = true; if (_pageXmlNode.Attributes != null) { _id = int.Parse(_pageXmlNode.Attributes.GetNamedItem("id").Value); if (_pageXmlNode.Attributes.GetNamedItem("template") != null) _template = int.Parse(_pageXmlNode.Attributes.GetNamedItem("template").Value); if (_pageXmlNode.Attributes.GetNamedItem("sortOrder") != null) _sortOrder = int.Parse(_pageXmlNode.Attributes.GetNamedItem("sortOrder").Value); if (_pageXmlNode.Attributes.GetNamedItem("nodeName") != null) _name = _pageXmlNode.Attributes.GetNamedItem("nodeName").Value; if (_pageXmlNode.Attributes.GetNamedItem("writerName") != null) _writerName = _pageXmlNode.Attributes.GetNamedItem("writerName").Value; if (_pageXmlNode.Attributes.GetNamedItem("urlName") != null) _urlName = _pageXmlNode.Attributes.GetNamedItem("urlName").Value; // Creatorname is new in 2.1, so published xml might not have it! try { _creatorName = _pageXmlNode.Attributes.GetNamedItem("creatorName").Value; } catch { _creatorName = _writerName; } //Added the actual userID, as a user cannot be looked up via full name only... if (_pageXmlNode.Attributes.GetNamedItem("creatorID") != null) _creatorID = int.Parse(_pageXmlNode.Attributes.GetNamedItem("creatorID").Value); if (_pageXmlNode.Attributes.GetNamedItem("writerID") != null) _writerID = int.Parse(_pageXmlNode.Attributes.GetNamedItem("writerID").Value); if (UmbracoSettings.UseLegacyXmlSchema) { if (_pageXmlNode.Attributes.GetNamedItem("nodeTypeAlias") != null) _nodeTypeAlias = _pageXmlNode.Attributes.GetNamedItem("nodeTypeAlias").Value; } else { _nodeTypeAlias = _pageXmlNode.Name; } if (_pageXmlNode.Attributes.GetNamedItem("path") != null) _path = _pageXmlNode.Attributes.GetNamedItem("path").Value; if (_pageXmlNode.Attributes.GetNamedItem("version") != null) _version = new Guid(_pageXmlNode.Attributes.GetNamedItem("version").Value); if (_pageXmlNode.Attributes.GetNamedItem("createDate") != null) _createDate = DateTime.Parse(_pageXmlNode.Attributes.GetNamedItem("createDate").Value); if (_pageXmlNode.Attributes.GetNamedItem("updateDate") != null) _updateDate = DateTime.Parse(_pageXmlNode.Attributes.GetNamedItem("updateDate").Value); if (_pageXmlNode.Attributes.GetNamedItem("level") != null) _level = int.Parse(_pageXmlNode.Attributes.GetNamedItem("level").Value); } // load data string dataXPath = UmbracoSettings.UseLegacyXmlSchema ? "data" : "* [not(@isDoc)]"; foreach (XmlNode n in _pageXmlNode.SelectNodes(dataXPath)) _properties.Add(new Property(n)); // load children string childXPath = UmbracoSettings.UseLegacyXmlSchema ? "node" : "* [@isDoc]"; XPathNavigator nav = _pageXmlNode.CreateNavigator(); XPathExpression expr = nav.Compile(childXPath); expr.AddSort("@sortOrder", XmlSortOrder.Ascending, XmlCaseOrder.None, "", XmlDataType.Number); XPathNodeIterator iterator = nav.Select(expr); while (iterator.MoveNext()) { _children.Add( new Node(((IHasXmlNode)iterator.Current).GetNode(), true) ); } } // else // throw new ArgumentNullException("Node xml source is null"); } public static Node GetCurrent() { int id = getCurrentNodeId(); return new Node(id); } public static int getCurrentNodeId() { XmlNode n = ((IHasXmlNode)library.GetXmlNodeCurrent().Current).GetNode(); if (n.Attributes == null || n.Attributes.GetNamedItem("id") == null) throw new ArgumentException("Current node is null. This might be due to previewing an unpublished node. As the NodeFactory works with published data, macros using the node factory won't work in preview mode.", "Current node is " + System.Web.HttpContext.Current.Items["pageID"].ToString()); return int.Parse(n.Attributes.GetNamedItem("id").Value); } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; /// Standard implementation for a mathematical model to make the virtual controller approximate the /// physical location of the Daydream controller. public class GvrArmModel : GvrBaseArmModel{ /// Position of the elbow joint relative to the head before the arm model is applied. public Vector3 elbowRestPosition = DEFAULT_ELBOW_REST_POSITION; /// Position of the wrist joint relative to the elbow before the arm model is applied. public Vector3 wristRestPosition = DEFAULT_WRIST_REST_POSITION; /// Position of the controller joint relative to the wrist before the arm model is applied. public Vector3 controllerRestPosition = DEFAULT_CONTROLLER_REST_POSITION; /// Offset applied to the elbow position as the controller is rotated upwards. public Vector3 armExtensionOffset = DEFAULT_ARM_EXTENSION_OFFSET; /// Ratio of the controller's rotation to apply to the rotation of the elbow. /// The remaining rotation is applied to the wrist's rotation. [Range(0.0f, 1.0f)] public float elbowBendRatio = DEFAULT_ELBOW_BEND_RATIO; /// Offset in front of the controller to determine what position to use when determing if the /// controller should fade. This is useful when objects are attached to the controller. [Range(0.0f, 0.4f)] public float fadeControllerOffset = 0.0f; /// Controller distance from the front/back of the head after which the controller disappears (meters). [Range(0.0f, 0.4f)] public float fadeDistanceFromHeadForward = 0.25f; /// Controller distance from the left/right of the head after which the controller disappears (meters). [Range(0.0f, 0.4f)] public float fadeDistanceFromHeadSide = 0.15f; /// Controller distance from face after which the tooltips appear (meters). [Range(0.4f, 0.6f)] public float tooltipMinDistanceFromFace = 0.45f; /// When the angle (degrees) between the controller and the head is larger than /// this value, the tooltips disappear. /// If the value is 180, then the tooltips are always shown. /// If the value is 90, the tooltips are only shown when they are facing the camera. [Range(0, 180)] public int tooltipMaxAngleFromCamera = 80; /// If true, the root of the pose is locked to the local position of the player's neck. public bool isLockedToNeck = false; /// Represents the controller's position relative to the user's head. public override Vector3 ControllerPositionFromHead { get { return controllerPosition; } } /// Represent the controller's rotation relative to the user's head. public override Quaternion ControllerRotationFromHead { get { return controllerRotation; } } /// The suggested rendering alpha value of the controller. /// This is to prevent the controller from intersecting the face. /// The range is always 0 - 1. public override float PreferredAlpha { get { return preferredAlpha; } } /// The suggested rendering alpha value of the controller tooltips. /// This is to only display the tooltips when the player is looking /// at the controller, and also to prevent the tooltips from intersecting the /// player's face. public override float TooltipAlphaValue { get { return tooltipAlphaValue; } } /// Represent the neck's position relative to the user's head. /// If isLockedToNeck is true, this will be the InputTracking position of the Head node modified /// by an inverse neck model to approximate the neck position. /// Otherwise, it is always zero. public Vector3 NeckPosition { get { return neckPosition; } } /// Represent the shoulder's position relative to the user's head. /// This is not actually used as part of the arm model calculations, and exists for debugging. public Vector3 ShoulderPosition { get { Vector3 shoulderPosition = neckPosition + torsoRotation * Vector3.Scale(SHOULDER_POSITION, handedMultiplier); return shoulderPosition; } } /// Represent the shoulder's rotation relative to the user's head. /// This is not actually used as part of the arm model calculations, and exists for debugging. public Quaternion ShoulderRotation { get { return torsoRotation; } } /// Represent the elbow's position relative to the user's head. public Vector3 ElbowPosition { get { return elbowPosition; } } /// Represent the elbow's rotation relative to the user's head. public Quaternion ElbowRotation { get { return elbowRotation; } } /// Represent the wrist's position relative to the user's head. public Vector3 WristPosition { get { return wristPosition; } } /// Represent the wrist's rotation relative to the user's head. public Quaternion WristRotation { get { return wristRotation; } } protected Vector3 neckPosition; protected Vector3 elbowPosition; protected Quaternion elbowRotation; protected Vector3 wristPosition; protected Quaternion wristRotation; protected Vector3 controllerPosition; protected Quaternion controllerRotation; protected float preferredAlpha; protected float tooltipAlphaValue; /// Multiplier for handedness such that 1 = Right, 0 = Center, -1 = left. protected Vector3 handedMultiplier; /// Forward direction of user's torso. protected Vector3 torsoDirection; /// Orientation of the user's torso. protected Quaternion torsoRotation; // Default values for tuning variables. public static readonly Vector3 DEFAULT_ELBOW_REST_POSITION = new Vector3(0.195f, -0.5f, 0.005f); public static readonly Vector3 DEFAULT_WRIST_REST_POSITION = new Vector3(0.0f, 0.0f, 0.25f); public static readonly Vector3 DEFAULT_CONTROLLER_REST_POSITION = new Vector3(0.0f, 0.0f, 0.05f); public static readonly Vector3 DEFAULT_ARM_EXTENSION_OFFSET = new Vector3(-0.13f, 0.14f, 0.08f); public const float DEFAULT_ELBOW_BEND_RATIO = 0.6f; /// Increases elbow bending as the controller moves up (unitless). protected const float EXTENSION_WEIGHT = 0.4f; /// Rest position for shoulder joint. protected static readonly Vector3 SHOULDER_POSITION = new Vector3(0.17f, -0.2f, -0.03f); /// Neck offset used to apply the inverse neck model when locked to the head. protected static readonly Vector3 NECK_OFFSET = new Vector3(0.0f, 0.075f, 0.08f); /// Amount of normalized alpha transparency to change per second. protected const float DELTA_ALPHA = 4.0f; /// Angle ranges the for arm extension offset to start and end (degrees). protected const float MIN_EXTENSION_ANGLE = 7.0f; protected const float MAX_EXTENSION_ANGLE = 60.0f; protected virtual void OnEnable() { // Register the controller update listener. GvrControllerInput.OnControllerInputUpdated += OnControllerInputUpdated; // Force the torso direction to match the gaze direction immediately. // Otherwise, the controller will not be positioned correctly if the ArmModel was enabled // when the user wasn't facing forward. UpdateTorsoDirection(true); // Update immediately to avoid a frame delay before the arm model is applied. OnControllerInputUpdated(); } protected virtual void OnDisable() { GvrControllerInput.OnControllerInputUpdated -= OnControllerInputUpdated; } protected virtual void OnControllerInputUpdated() { UpdateHandedness(); UpdateTorsoDirection(false); UpdateNeckPosition(); ApplyArmModel(); UpdateTransparency(); } protected virtual void UpdateHandedness() { // Update user handedness if the setting has changed GvrSettings.UserPrefsHandedness handedness = GvrSettings.Handedness; // Determine handedness multiplier. handedMultiplier.Set(0, 1, 1); if (handedness == GvrSettings.UserPrefsHandedness.Right) { handedMultiplier.x = 1.0f; } else if (handedness == GvrSettings.UserPrefsHandedness.Left) { handedMultiplier.x = -1.0f; } } protected virtual void UpdateTorsoDirection(bool forceImmediate) { // Determine the gaze direction horizontally. Vector3 gazeDirection = GvrVRHelpers.GetHeadForward(); gazeDirection.y = 0.0f; gazeDirection.Normalize(); // Use the gaze direction to update the forward direction. if (GvrControllerInput.Recentered || forceImmediate) { torsoDirection = gazeDirection; } else { float angularVelocity = GvrControllerInput.Gyro.magnitude; float gazeFilterStrength = Mathf.Clamp((angularVelocity - 0.2f) / 45.0f, 0.0f, 0.1f); torsoDirection = Vector3.Slerp(torsoDirection, gazeDirection, gazeFilterStrength); } // Calculate the torso rotation. torsoRotation = Quaternion.FromToRotation(Vector3.forward, torsoDirection); } protected virtual void UpdateNeckPosition() { if (isLockedToNeck) { // Returns the center of the eyes. // However, we actually want to lock to the center of the head. neckPosition = GvrVRHelpers.GetHeadPosition(); // Find the approximate neck position by Applying an inverse neck model. // This transforms the head position to the center of the head and also accounts // for the head's rotation so that the motion feels more natural. neckPosition = ApplyInverseNeckModel(neckPosition); } else { neckPosition = Vector3.zero; } } protected virtual void ApplyArmModel() { // Set the starting positions of the joints before they are transformed by the arm model. SetUntransformedJointPositions(); // Get the controller's orientation. Quaternion controllerOrientation; Quaternion xyRotation; float xAngle; GetControllerRotation(out controllerOrientation, out xyRotation, out xAngle); // Offset the elbow by the extension offset. float extensionRatio = CalculateExtensionRatio(xAngle); ApplyExtensionOffset(extensionRatio); // Calculate the lerp rotation, which is used to control how much the rotation of the // controller impacts each joint. Quaternion lerpRotation = CalculateLerpRotation(xyRotation, extensionRatio); CalculateFinalJointRotations(controllerOrientation, xyRotation, lerpRotation); ApplyRotationToJoints(); } /// Set the starting positions of the joints before they are transformed by the arm model. protected virtual void SetUntransformedJointPositions() { elbowPosition = Vector3.Scale(elbowRestPosition, handedMultiplier); wristPosition = Vector3.Scale(wristRestPosition, handedMultiplier); controllerPosition = Vector3.Scale(controllerRestPosition, handedMultiplier); } /// Calculate the extension ratio based on the angle of the controller along the x axis. protected virtual float CalculateExtensionRatio(float xAngle) { float normalizedAngle = (xAngle - MIN_EXTENSION_ANGLE) / (MAX_EXTENSION_ANGLE - MIN_EXTENSION_ANGLE); float extensionRatio = Mathf.Clamp(normalizedAngle, 0.0f, 1.0f); return extensionRatio; } /// Offset the elbow by the extension offset. protected virtual void ApplyExtensionOffset(float extensionRatio) { Vector3 extensionOffset = Vector3.Scale(armExtensionOffset, handedMultiplier); elbowPosition += extensionOffset * extensionRatio; } /// Calculate the lerp rotation, which is used to control how much the rotation of the /// controller impacts each joint. protected virtual Quaternion CalculateLerpRotation(Quaternion xyRotation, float extensionRatio) { float totalAngle = Quaternion.Angle(xyRotation, Quaternion.identity); float lerpSuppresion = 1.0f - Mathf.Pow(totalAngle / 180.0f, 6.0f); float inverseElbowBendRatio = 1.0f - elbowBendRatio; float lerpValue = inverseElbowBendRatio + elbowBendRatio * extensionRatio * EXTENSION_WEIGHT; lerpValue *= lerpSuppresion; return Quaternion.Lerp(Quaternion.identity, xyRotation, lerpValue); } /// Determine the final joint rotations relative to the head. protected virtual void CalculateFinalJointRotations(Quaternion controllerOrientation, Quaternion xyRotation, Quaternion lerpRotation) { elbowRotation = torsoRotation * Quaternion.Inverse(lerpRotation) * xyRotation; wristRotation = elbowRotation * lerpRotation; controllerRotation = torsoRotation * controllerOrientation; } /// Apply the joint rotations to the positions of the joints to determine the final pose. protected virtual void ApplyRotationToJoints() { elbowPosition = neckPosition + torsoRotation * elbowPosition; wristPosition = elbowPosition + elbowRotation * wristPosition; controllerPosition = wristPosition + wristRotation * controllerPosition; } /// Transform the head position into an approximate neck position. protected virtual Vector3 ApplyInverseNeckModel(Vector3 headPosition) { Quaternion headRotation = GvrVRHelpers.GetHeadRotation(); Vector3 rotatedNeckOffset = headRotation * NECK_OFFSET - NECK_OFFSET.y * Vector3.up; headPosition -= rotatedNeckOffset; return headPosition; } /// Controls the transparency of the controller to prevent the controller from clipping through /// the user's head. Also, controls the transparency of the tooltips so they are only visible /// when the controller is held up. protected virtual void UpdateTransparency() { Vector3 controllerForward = controllerRotation * Vector3.forward; Vector3 offsetControllerPosition = controllerPosition + (controllerForward * fadeControllerOffset); Vector3 controllerRelativeToHead = offsetControllerPosition - neckPosition; Vector3 headForward = GvrVRHelpers.GetHeadForward(); float distanceToHeadForward = Vector3.Scale(controllerRelativeToHead, headForward).magnitude; Vector3 headRight = Vector3.Cross(headForward, Vector3.up); float distanceToHeadSide = Vector3.Scale(controllerRelativeToHead, headRight).magnitude; float distanceToHeadUp = Mathf.Abs(controllerRelativeToHead.y); bool shouldFadeController = distanceToHeadForward < fadeDistanceFromHeadForward && distanceToHeadUp < fadeDistanceFromHeadForward && distanceToHeadSide < fadeDistanceFromHeadSide; // Determine how vertical the controller is pointing. float animationDelta = DELTA_ALPHA * Time.unscaledDeltaTime; if (shouldFadeController) { preferredAlpha = Mathf.Max(0.0f, preferredAlpha - animationDelta); } else { preferredAlpha = Mathf.Min(1.0f, preferredAlpha + animationDelta); } float dot = Vector3.Dot(controllerRotation * Vector3.up, -controllerRelativeToHead.normalized); float minDot = (tooltipMaxAngleFromCamera - 90.0f) / -90.0f; float distToFace = Vector3.Distance(controllerRelativeToHead, Vector3.zero); if (shouldFadeController || distToFace > tooltipMinDistanceFromFace || dot < minDot) { tooltipAlphaValue = Mathf.Max(0.0f, tooltipAlphaValue - animationDelta); } else { tooltipAlphaValue = Mathf.Min(1.0f, tooltipAlphaValue + animationDelta); } } /// Get the controller's orientation. protected void GetControllerRotation(out Quaternion rotation, out Quaternion xyRotation, out float xAngle) { // Find the controller's orientation relative to the player. rotation = GvrControllerInput.Orientation; rotation = Quaternion.Inverse(torsoRotation) * rotation; // Extract just the x rotation angle. Vector3 controllerForward = rotation * Vector3.forward; xAngle = 90.0f - Vector3.Angle(controllerForward, Vector3.up); // Remove the z rotation from the controller. xyRotation = Quaternion.FromToRotation(Vector3.forward, controllerForward); } #if UNITY_EDITOR protected virtual void OnDrawGizmosSelected() { if (!enabled) { return; } if (transform.parent == null) { return; } Vector3 worldShoulder = transform.parent.TransformPoint(ShoulderPosition); Vector3 worldElbow = transform.parent.TransformPoint(elbowPosition); Vector3 worldwrist = transform.parent.TransformPoint(wristPosition); Vector3 worldcontroller = transform.parent.TransformPoint(controllerPosition); Gizmos.color = Color.red; Gizmos.DrawSphere(worldShoulder, 0.02f); Gizmos.DrawLine(worldShoulder, worldElbow); Gizmos.color = Color.green; Gizmos.DrawSphere(worldElbow, 0.02f); Gizmos.DrawLine(worldElbow, worldwrist); Gizmos.color = Color.cyan; Gizmos.DrawSphere(worldwrist, 0.02f); Gizmos.color = Color.blue; Gizmos.DrawSphere(worldcontroller, 0.02f); } #endif // UNITY_EDITOR }
using System; using System.Runtime.InteropServices; namespace murrayju { internal class CreateProcessAsUser { #region Win32 Constants private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400; private const int CREATE_NO_WINDOW = 0x08000000; private const int CREATE_NEW_CONSOLE = 0x00000010; private const uint INVALID_SESSION_ID = 0xFFFFFFFF; private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero; #endregion #region DllImports [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern bool CreateProcessAsUser( IntPtr hToken, String lpApplicationName, String lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandle, uint dwCreationFlags, IntPtr lpEnvironment, String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")] public static extern bool DuplicateTokenEx( IntPtr ExistingTokenHandle, uint dwDesiredAccess, IntPtr lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle); [DllImport("userenv.dll", SetLastError = true)] public static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit); [DllImport("userenv.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool CloseHandle(IntPtr hSnapshot); [DllImport("kernel32.dll")] private static extern uint WTSGetActiveConsoleSessionId(); [DllImport("Wtsapi32.dll")] private static extern uint WTSQueryUserToken(uint SessionId, ref IntPtr phToken); [DllImport("wtsapi32.dll", SetLastError = true)] private static extern int WTSEnumerateSessions( IntPtr hServer, int Reserved, int Version, ref IntPtr ppSessionInfo, ref int pCount); #endregion #region Win32 Structs public enum SW { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_MAX = 10 } public enum WTS_CONNECTSTATE_CLASS { WTSActive, WTSConnected, WTSConnectQuery, WTSShadow, WTSDisconnected, WTSIdle, WTSListen, WTSReset, WTSDown, WTSInit } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public uint dwProcessId; public uint dwThreadId; } private enum SECURITY_IMPERSONATION_LEVEL { SecurityAnonymous = 0, SecurityIdentification = 1, SecurityImpersonation = 2, SecurityDelegation = 3, } [StructLayout(LayoutKind.Sequential)] public struct STARTUPINFO { public int cb; public String lpReserved; public String lpDesktop; public String lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public short wShowWindow; public short cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } private enum TOKEN_TYPE { TokenPrimary = 1, TokenImpersonation = 2 } [StructLayout(LayoutKind.Sequential)] private struct WTS_SESSION_INFO { public readonly UInt32 SessionID; [MarshalAs(UnmanagedType.LPStr)] public readonly String pWinStationName; public readonly WTS_CONNECTSTATE_CLASS State; } #endregion private static bool GetSessionUserToken(ref IntPtr phUserToken) { var bResult = false; var hImpersonationToken = IntPtr.Zero; var activeSessionId = INVALID_SESSION_ID; var pSessionInfo = IntPtr.Zero; var sessionCount = 0; // Get a handle to the user access token for the current active session. if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref sessionCount) != 0) { var arrayElementSize = Marshal.SizeOf(typeof (WTS_SESSION_INFO)); var current = (int) pSessionInfo; for (var i = 0; i < sessionCount; i++) { var si = (WTS_SESSION_INFO) Marshal.PtrToStructure((IntPtr) current, typeof (WTS_SESSION_INFO)); current += arrayElementSize; if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive) { activeSessionId = si.SessionID; } } } // If enumerating did not work, fall back to the old method if (activeSessionId == INVALID_SESSION_ID) { activeSessionId = WTSGetActiveConsoleSessionId(); } if (WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != 0) { // Convert the impersonation token to a primary token bResult = DuplicateTokenEx(hImpersonationToken, 0, IntPtr.Zero, (int) SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int) TOKEN_TYPE.TokenPrimary, ref phUserToken); CloseHandle(hImpersonationToken); } return bResult; } public static bool LaunchUserProcess(string appPath, string cmdLine, string workDir, bool visible) { var hUserToken = IntPtr.Zero; var startInfo = new STARTUPINFO(); var procInfo = new PROCESS_INFORMATION(); var pEnv = IntPtr.Zero; int iResultOfCreateProcessAsUser; startInfo.cb = Marshal.SizeOf(typeof (STARTUPINFO)); try { if (!GetSessionUserToken(ref hUserToken)) { throw new Exception("LaunchUserProcess: GetSessionUserToken failed."); } uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW); startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE); startInfo.lpDesktop = "winsta0\\default"; if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false)) { throw new Exception("LaunchUserProcess: CreateEnvironmentBlock failed."); } if (!CreateProcessAsUser(hUserToken, appPath, // Application Name cmdLine, // Command Line IntPtr.Zero, IntPtr.Zero, false, dwCreationFlags, pEnv, workDir, // Working directory ref startInfo, out procInfo)) { throw new Exception("LaunchUserProcess: CreateProcessAsUser failed.\n"); } iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error(); } finally { CloseHandle(hUserToken); if (pEnv != IntPtr.Zero) { DestroyEnvironmentBlock(pEnv); } CloseHandle(procInfo.hThread); CloseHandle(procInfo.hProcess); } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Xunit; namespace System.Drawing.Drawing2D.Tests { public class PathGradientBrushTests { private readonly Point[] _defaultIntPoints = new Point[2] { new Point(1, 2), new Point(20, 30) }; private readonly PointF[] _defaultFloatPoints = new PointF[2] { new PointF(1, 2), new PointF(20, 30) }; private readonly RectangleF _defaultRectangle = new RectangleF(1, 2, 19, 28); [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Points_ReturnsExpected() { using (PathGradientBrush bi = new PathGradientBrush(_defaultIntPoints)) using (PathGradientBrush bf = new PathGradientBrush(_defaultFloatPoints)) { AssertDefaults(bi); Assert.Equal(WrapMode.Clamp, bi.WrapMode); AssertDefaults(bf); Assert.Equal(WrapMode.Clamp, bf.WrapMode); } } public static IEnumerable<object[]> WrapMode_TestData() { yield return new object[] { WrapMode.Clamp }; yield return new object[] { WrapMode.Tile }; yield return new object[] { WrapMode.TileFlipX }; yield return new object[] { WrapMode.TileFlipXY }; yield return new object[] { WrapMode.TileFlipY }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(WrapMode_TestData))] public void Ctor_PointsWrapMode_ReturnsExpected(WrapMode wrapMode) { using (PathGradientBrush brushInt = new PathGradientBrush(_defaultIntPoints, wrapMode)) using (PathGradientBrush brushFloat = new PathGradientBrush(_defaultFloatPoints, wrapMode)) { AssertDefaults(brushInt); Assert.Equal(wrapMode, brushInt.WrapMode); AssertDefaults(brushFloat); Assert.Equal(wrapMode, brushFloat.WrapMode); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_PointsNull_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("points", () => new PathGradientBrush((Point[])null)); AssertExtensions.Throws<ArgumentNullException>("points", () => new PathGradientBrush((PointF[])null)); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0)] [InlineData(1)] public void Ctor_PointsLengthLessThenTwo_ThrowsOutOfMemoryException(int pointsLength) { Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new Point[pointsLength])); Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new Point[pointsLength], WrapMode.Clamp)); Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new PointF[pointsLength])); Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(new PointF[pointsLength], WrapMode.Clamp)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_InvalidWrapMode_ThrowsInvalidEnumArgumentException() { Assert.ThrowsAny<ArgumentException>(() => new PathGradientBrush(_defaultIntPoints, (WrapMode)int.MaxValue)); Assert.ThrowsAny<ArgumentException>(() => new PathGradientBrush(_defaultFloatPoints, (WrapMode)int.MaxValue)); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Path_ReturnsExpected() { using (GraphicsPath path = new GraphicsPath(_defaultFloatPoints, new byte[] { 0, 1 })) using (PathGradientBrush brush = new PathGradientBrush(path)) { AssertDefaults(brush); Assert.Equal(WrapMode.Clamp, brush.WrapMode); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Path_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("path", () => new PathGradientBrush((GraphicsPath)null)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_PathWithLessThenTwoPoints_ThrowsOutOfMemoryException() { using (GraphicsPath path = new GraphicsPath()) { Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(path)); path.AddLines(new PointF[] { new PointF(1, 1) }); Assert.Throws<OutOfMemoryException>(() => new PathGradientBrush(path)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void Clone_ReturnsExpected() { using (GraphicsPath path = new GraphicsPath(_defaultFloatPoints, new byte[] { 0, 1 })) using (PathGradientBrush brush = new PathGradientBrush(path)) using (PathGradientBrush clone = Assert.IsType<PathGradientBrush>(brush.Clone())) { AssertDefaults(clone); Assert.Equal(WrapMode.Clamp, clone.WrapMode); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Clone_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.Clone()); } [ConditionalFact(Helpers.IsDrawingSupported)] public void CenterColor_ReturnsExpected() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { Assert.Equal(Color.Black.ToArgb(), brush.CenterColor.ToArgb()); brush.CenterColor = Color.Blue; Assert.Equal(Color.Blue.ToArgb(), brush.CenterColor.ToArgb()); brush.CenterColor = Color.Transparent; Assert.Equal(Color.Transparent.ToArgb(), brush.CenterColor.ToArgb()); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CenterColor_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.CenterColor = Color.Blue); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void SurroundColors_ReturnsExpected() { Color[] expectedColors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) }; Color[] sameColors = new Color[2] { Color.FromArgb(255, 255, 255, 0), Color.FromArgb(255, 255, 255, 0) }; Color[] expectedSameColors = new Color[1] { Color.FromArgb(255, 255, 255, 0) }; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.SurroundColors = expectedColors; Assert.Equal(expectedColors, brush.SurroundColors); brush.SurroundColors = sameColors; Assert.Equal(expectedSameColors, brush.SurroundColors); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SurroundColors_CannotChange() { Color[] colors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) }; Color[] defaultColors = new Color[1] { Color.FromArgb(255, 255, 255, 255) }; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.SurroundColors.ToList().AddRange(colors); Assert.Equal(defaultColors, brush.SurroundColors); brush.SurroundColors[0] = Color.FromArgb(255, 0, 0, 255); Assert.NotEqual(Color.FromArgb(255, 0, 0, 255), brush.SurroundColors[0]); Assert.Equal(defaultColors, brush.SurroundColors); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SurroundColors_Disposed_ThrowsArgumentException() { Color[] colors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) }; PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.SurroundColors = colors); } public static IEnumerable<object[]> SurroundColors_InvalidColorsLength_TestData() { yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) }, new Color[0] }; yield return new object[] { new Point[2] { new Point(1, 1), new Point(2, 2) }, new Color[3] }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(SurroundColors_InvalidColorsLength_TestData))] public void SurroundColors_InvalidColorsLength_ThrowsArgumentException(Point[] points, Color[] colors) { using (PathGradientBrush brush = new PathGradientBrush(points)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.SurroundColors = colors); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SurroundColors_Null_ThrowsNullReferenceException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<NullReferenceException>(() => brush.SurroundColors = null); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CenterPoint_ReturnsExpected() { PointF centralPoint = new PointF(float.MaxValue, float.MinValue); PointF defaultCentralPoint = new PointF(10.5f, 16f); using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints, WrapMode.TileFlipXY)) { Assert.Equal(defaultCentralPoint, brush.CenterPoint); brush.CenterPoint = centralPoint; Assert.Equal(centralPoint, brush.CenterPoint); centralPoint.X = float.NaN; centralPoint.Y = float.NegativeInfinity; brush.CenterPoint = centralPoint; Assert.Equal(float.NaN, brush.CenterPoint.X); Assert.Equal(float.NegativeInfinity, brush.CenterPoint.Y); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void CenterPoint_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.CenterPoint); } public static IEnumerable<object[]> Blend_FactorsPositions_TestData() { yield return new object[] { new float[1] { 1 }, new float[1] { 0 } }; yield return new object[] { new float[2] { 1, 1 }, new float[2] { 0, 1 } }; yield return new object[] { new float[3] { 1, 0, 1 }, new float[3] { 0, 3, 1 } }; yield return new object[] { new float[1] { 1 }, new float[3] { 0, 3, 1 } }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Blend_FactorsPositions_TestData))] public void Blend_ReturnsExpected(float[] factors, float[] positions) { int expectedSize = factors.Length; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints, WrapMode.TileFlipXY)) { brush.Blend = new Blend { Factors = factors, Positions = positions }; Assert.Equal(factors, brush.Blend.Factors); Assert.Equal(expectedSize, brush.Blend.Positions.Length); if (expectedSize == positions.Length && expectedSize != 1) { Assert.Equal(factors, brush.Blend.Factors); Assert.Equal(positions, brush.Blend.Positions); } else { Assert.Equal(factors, brush.Blend.Factors); Assert.Equal(1, brush.Blend.Positions.Length); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Blend_CannotChange() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints, WrapMode.TileFlipXY)) { brush.Blend.Factors = new float[0]; Assert.Equal(1, brush.Blend.Factors.Length); brush.Blend.Factors = new float[2]; Assert.Equal(1, brush.Blend.Factors.Length); brush.Blend.Positions = new float[0]; Assert.Equal(1, brush.Blend.Positions.Length); brush.Blend.Positions = new float[2]; Assert.Equal(1, brush.Blend.Positions.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Blend_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.Blend); } public static IEnumerable<object[]> Blend_InvalidFactorsPositions_TestData() { yield return new object[] { new Blend() { Factors = new float[0], Positions = new float[0] } }; yield return new object[] { new Blend() { Factors = new float[2], Positions = new float[2] { 1, 1 } } }; yield return new object[] { new Blend() { Factors = new float[2], Positions = new float[2] { 0, 5 } } }; yield return new object[] { new Blend() { Factors = new float[3], Positions = new float[3] { 0, 1, 5 } } }; yield return new object[] { new Blend() { Factors = new float[3], Positions = new float[3] { 1, 1, 1 } } }; } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(Blend_InvalidFactorsPositions_TestData))] public void Blend_InvalidFactorPositions_ThrowsArgumentException(Blend blend) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.Blend = blend); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Blend_InvalidFactorPositionsLengthMismatch_ThrowsArgumentOutOfRangeException() { Blend invalidBlend = new Blend() { Factors = new float[2], Positions = new float[1] }; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentOutOfRangeException>(null, () => brush.Blend = invalidBlend); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Blend_Null_ThrowsNullReferenceException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { Assert.Throws<NullReferenceException>(() => brush.Blend = null); Assert.Throws<NullReferenceException>(() => brush.Blend = new Blend() { Factors = null, Positions = null}); Assert.Throws<NullReferenceException>(() => brush.Blend = new Blend() { Factors = null, Positions = new float[0] }); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Blend_NullBlendProperites_ThrowsArgumentNullException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentNullException>("source", () => brush.Blend = new Blend() { Factors = new float[0], Positions = null }); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(1f)] [InlineData(0f)] [InlineData(0.5f)] public void SetSigmaBellShape_Focus_Success(float focus) { float defaultScale = 1f; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.SetSigmaBellShape(focus); Assert.True(brush.Transform.IsIdentity); if (focus == 0f) { Assert.Equal(focus, brush.Blend.Positions[0]); Assert.Equal(defaultScale, brush.Blend.Factors[0]); Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]); Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]); } else if (focus == 1f) { Assert.Equal(0f, brush.Blend.Positions[0]); Assert.Equal(0f, brush.Blend.Factors[0]); Assert.Equal(focus, brush.Blend.Positions[brush.Blend.Positions.Length - 1]); Assert.Equal(defaultScale, brush.Blend.Factors[brush.Blend.Factors.Length - 1]); } else { Assert.Equal(0f, brush.Blend.Positions[0]); Assert.Equal(0f, brush.Blend.Factors[0]); Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]); Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]); } } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(1f)] [InlineData(0f)] [InlineData(0.5f)] public void SetSigmaBellShape_FocusScale_Success(float focus) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.SetSigmaBellShape(focus); Assert.True(brush.Transform.IsIdentity); if (focus == 0f) { Assert.Equal(256, brush.Blend.Positions.Length); Assert.Equal(256, brush.Blend.Factors.Length); Assert.Equal(focus, brush.Blend.Positions[0]); Assert.Equal(1f, brush.Blend.Factors[0]); Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]); Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]); } else if (focus == 1f) { Assert.Equal(256, brush.Blend.Positions.Length); Assert.Equal(256, brush.Blend.Factors.Length); Assert.Equal(0f, brush.Blend.Positions[0]); Assert.Equal(0f, brush.Blend.Factors[0]); Assert.Equal(focus, brush.Blend.Positions[brush.Blend.Positions.Length - 1]); Assert.Equal(1f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]); } else { Assert.Equal(511, brush.Blend.Positions.Length); Assert.Equal(511, brush.Blend.Factors.Length); Assert.Equal(0f, brush.Blend.Positions[0]); Assert.Equal(0f, brush.Blend.Factors[0]); Assert.Equal(focus, brush.Blend.Positions[255]); Assert.Equal(1f, brush.Blend.Factors[255]); Assert.Equal(1f, brush.Blend.Positions[brush.Blend.Positions.Length - 1]); Assert.Equal(0f, brush.Blend.Factors[brush.Blend.Factors.Length - 1]); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SetSigmaBellShape_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(1f)); AssertExtensions.Throws<ArgumentException>(null, () => brush.SetSigmaBellShape(1f, 1f)); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(-1)] [InlineData(1.1f)] public void SetSigmaBellShape_InvalidFocus_ThrowsArgumentException(float focus) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetSigmaBellShape(focus)); AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetSigmaBellShape(focus, 1f)); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(-1)] [InlineData(1.1f)] public void SetSigmaBellShape_InvalidScale_ThrowsArgumentException(float scale) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>("scale", null, () => brush.SetSigmaBellShape(1f, scale)); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(1f)] [InlineData(0f)] [InlineData(0.5f)] public void SetBlendTriangularShape_Focus_Success(float focus) { float defaultScale = 1f; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.SetBlendTriangularShape(focus); Assert.True(brush.Transform.IsIdentity); if (focus == 0f) { Assert.Equal(new float[2] { defaultScale, 0f }, brush.Blend.Factors); Assert.Equal(new float[2] { focus, 1f }, brush.Blend.Positions); } else if (focus == 1f) { Assert.Equal(new float[2] { 0f, defaultScale }, brush.Blend.Factors); Assert.Equal(new float[2] { 0f, focus }, brush.Blend.Positions); } else { Assert.Equal(new float[3] { 0f, defaultScale, 0f }, brush.Blend.Factors); Assert.Equal(new float[3] { 0f, focus, 1f }, brush.Blend.Positions); } } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(1f)] [InlineData(0f)] [InlineData(0.5f)] public void SetBlendTriangularShape_FocusScale_Success(float focus) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.SetBlendTriangularShape(focus); Assert.True(brush.Transform.IsIdentity); Assert.True(brush.Transform.IsIdentity); if (focus == 0f) { Assert.Equal(new float[2] { 1f, 0f }, brush.Blend.Factors); Assert.Equal(new float[2] { focus, 1f }, brush.Blend.Positions); } else if (focus == 1f) { Assert.Equal(new float[2] { 0f, 1f }, brush.Blend.Factors); Assert.Equal(new float[2] { 0f, focus }, brush.Blend.Positions); } else { Assert.Equal(new float[3] { 0f, 1f, 0f }, brush.Blend.Factors); Assert.Equal(new float[3] { 0f, focus, 1f }, brush.Blend.Positions); } } } [ConditionalFact(Helpers.IsDrawingSupported)] public void SetBlendTriangularShape_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(1f)); AssertExtensions.Throws<ArgumentException>(null, () => brush.SetBlendTriangularShape(1f, 1f)); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(-1)] [InlineData(1.1f)] public void SetBlendTriangularShape_InvalidFocus_ThrowsArgumentException(float focus) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetBlendTriangularShape(focus)); AssertExtensions.Throws<ArgumentException>("focus", null, () => brush.SetBlendTriangularShape(focus, 1f)); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(-1)] [InlineData(1.1f)] public void SetBlendTriangularShape_InvalidScale_ThrowsArgumentException(float scale) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>("scale", null, () => brush.SetBlendTriangularShape(1f, scale)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_ReturnsExpected() { Color[] expectedColors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) }; float[] expectedPositions = new float[] { 0, 1 }; Color[] sameColors = new Color[2] { Color.FromArgb(255, 255, 255, 0), Color.FromArgb(255, 255, 255, 0) }; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.InterpolationColors = new ColorBlend() { Colors = expectedColors, Positions = expectedPositions }; Assert.Equal(expectedColors, brush.InterpolationColors.Colors); Assert.Equal(expectedPositions, brush.InterpolationColors.Positions); brush.InterpolationColors = new ColorBlend() { Colors = sameColors, Positions = expectedPositions }; Assert.Equal(sameColors, brush.InterpolationColors.Colors); Assert.Equal(expectedPositions, brush.InterpolationColors.Positions); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_CannotChange() { Color[] colors = new Color[2] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 255, 0, 0) }; Color[] defaultColors = new Color[1] { Color.Empty }; using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.InterpolationColors.Colors.ToList().AddRange(colors); Assert.Equal(defaultColors, brush.InterpolationColors.Colors); brush.InterpolationColors.Colors = colors; Assert.Equal(defaultColors, brush.InterpolationColors.Colors); brush.InterpolationColors.Colors[0] = Color.Pink; Assert.NotEqual(Color.Pink, brush.InterpolationColors.Colors[0]); Assert.Equal(defaultColors, brush.InterpolationColors.Colors); brush.InterpolationColors.Positions = new float[0]; Assert.Equal(1, brush.InterpolationColors.Positions.Length); brush.InterpolationColors.Positions = new float[2]; Assert.Equal(1, brush.InterpolationColors.Positions.Length); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.InterpolationColors); } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_Null_ThrowsNullReferenceException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { Assert.Throws<NullReferenceException>(() => brush.InterpolationColors = null); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_NullColors_ThrowsNullReferenceException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { Assert.Throws<NullReferenceException>(() => brush.InterpolationColors = new ColorBlend() { Colors = null, Positions = null }); Assert.Throws<NullReferenceException>(() => brush.InterpolationColors = new ColorBlend() { Colors = null, Positions = new float[2] }); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_NullPoints_ArgumentNullException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentNullException>("source", () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = null }); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_Empty_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.InterpolationColors = new ColorBlend()); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_EmptyColors_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[0], Positions = new float[0] }); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_PointsLengthGreaterThenColorsLength_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.InterpolationColors = new ColorBlend() { Colors = new Color[1], Positions = new float[2] }); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void InterpolationColors_ColorsLengthGreaterThenPointsLength_ThrowsArgumentOutOfRangeException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { Assert.Throws<ArgumentOutOfRangeException>(() => brush.InterpolationColors = new ColorBlend() { Colors = new Color[2], Positions = new float[1] }); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_ReturnsExpected() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1)) { Assert.Equal(defaultMatrix, brush.Transform); brush.Transform = matrix; Assert.Equal(matrix, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_EmptyMatrix_ReturnsExpected() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix()) { brush.Transform = matrix; Assert.True(brush.Transform.IsIdentity); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.Transform); } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_Null_ArgumentNullException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentNullException>("value", "matrix", () => brush.Transform = null); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void Transform_NonInvertible_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix nonInvertible = new Matrix(123, 24, 82, 16, 47, 30)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.Transform = nonInvertible); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ResetTransform_Success() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1)) { Assert.Equal(defaultMatrix, brush.Transform); brush.Transform = matrix; Assert.Equal(matrix, brush.Transform); brush.ResetTransform(); Assert.Equal(defaultMatrix, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ResetTransform_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.ResetTransform()); } [ConditionalFact(Helpers.IsDrawingSupported)] public void MultiplyTransform_Matrix_Success() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1)) { defaultMatrix.Multiply(matrix, MatrixOrder.Prepend); brush.MultiplyTransform(matrix); Assert.Equal(defaultMatrix, brush.Transform); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(MatrixOrder.Append)] [InlineData(MatrixOrder.Prepend)] public void MultiplyTransform_MatrixMatrixOrder_Success(MatrixOrder matrixOrder) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix defaultMatrix = new Matrix(1, 0, 0, 1, 0, 0)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1)) { defaultMatrix.Multiply(matrix, matrixOrder); brush.MultiplyTransform(matrix, matrixOrder); Assert.Equal(defaultMatrix, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void MultiplyTransform_Disposed_ThrowsArgumentException() { using (Matrix matrix = new Matrix(1, 0, 0, 1, 1, 1)) { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(matrix, MatrixOrder.Append)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void MultiplyTransform_NullMatrix_ThrowsArgumentNullException() { using (var brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null)); AssertExtensions.Throws<ArgumentNullException>("matrix", () => brush.MultiplyTransform(null, MatrixOrder.Append)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void MultiplyTransform_DisposedMatrix_Nop() { using (var brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix transform = brush.Transform) { var matrix = new Matrix(); matrix.Dispose(); brush.MultiplyTransform(matrix); brush.MultiplyTransform(matrix, MatrixOrder.Append); Assert.Equal(transform, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void MultiplyTransform_InvalidMatrixOrder_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 1, 1, 1, 1, 1)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(matrix, (MatrixOrder)int.MinValue)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void MultiplyTransform_NonInvertible_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix nonInvertible = new Matrix(123, 24, 82, 16, 47, 30)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(nonInvertible)); AssertExtensions.Throws<ArgumentException>(null, () => brush.MultiplyTransform(nonInvertible, MatrixOrder.Append)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void TranslateTransform_Offset_Success() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0)) { matrix.Translate(20f, 30f, MatrixOrder.Prepend); brush.TranslateTransform(20f, 30f); Assert.Equal(matrix, brush.Transform); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(MatrixOrder.Append)] [InlineData(MatrixOrder.Prepend)] public void TranslateTransform_OffsetMatrixOrder_Success(MatrixOrder matrixOrder) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0)) { matrix.Translate(20f, 30f, matrixOrder); brush.TranslateTransform(20f, 30f, matrixOrder); Assert.Equal(matrix, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void TranslateTransform_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.TranslateTransform(20f, 30f, MatrixOrder.Append)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void TranslateTransform_InvalidMatrixOrder_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.TranslateTransform(20f, 30f, (MatrixOrder)int.MinValue)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ScaleTransform_Scale_Success() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0)) { matrix.Scale(2, 4, MatrixOrder.Prepend); brush.ScaleTransform(2, 4); Assert.Equal(matrix, brush.Transform); matrix.Scale(0.5f, 0.25f, MatrixOrder.Prepend); brush.ScaleTransform(0.5f, 0.25f); Assert.True(brush.Transform.IsIdentity); matrix.Scale(float.MaxValue, float.MinValue, MatrixOrder.Prepend); brush.ScaleTransform(float.MaxValue, float.MinValue); Assert.Equal(matrix, brush.Transform); matrix.Scale(float.MinValue, float.MaxValue, MatrixOrder.Prepend); brush.ScaleTransform(float.MinValue, float.MaxValue); Assert.Equal(matrix, brush.Transform); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(MatrixOrder.Append)] [InlineData(MatrixOrder.Prepend)] public void ScaleTransform_ScaleMatrixOrder_Success(MatrixOrder matrixOrder) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0)) { matrix.Scale(0.25f, 2, matrixOrder); brush.ScaleTransform(0.25f, 2, matrixOrder); Assert.Equal(matrix, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void ScaleTransform_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.ScaleTransform(0.25f, 2, MatrixOrder.Append)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void ScaleTransform_InvalidMatrixOrder_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.ScaleTransform(1, 1, (MatrixOrder)int.MinValue)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void RotateTransform_Angle_Success() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0)) { matrix.Rotate(90, MatrixOrder.Prepend); brush.RotateTransform(90); Assert.Equal(matrix, brush.Transform); brush.RotateTransform(270); Assert.True(brush.Transform.IsIdentity); } } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(MatrixOrder.Append)] [InlineData(MatrixOrder.Prepend)] public void RotateTransform_AngleMatrixOrder_Success(MatrixOrder matrixOrder) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) using (Matrix matrix = new Matrix(1, 0, 0, 1, 0, 0)) { matrix.Rotate(45, matrixOrder); brush.RotateTransform(45, matrixOrder); Assert.Equal(matrix, brush.Transform); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void RotateTransform_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.RotateTransform(45, MatrixOrder.Append)); } [ConditionalFact(Helpers.IsDrawingSupported)] public void RotateTransform_InvalidMatrixOrder_ArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { AssertExtensions.Throws<ArgumentException>(null, () => brush.RotateTransform(45, (MatrixOrder)int.MinValue)); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void FocusScales_ReturnsExpected() { var point = new PointF(2.5f, 3.4f); using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.FocusScales = point; Assert.Equal(point, brush.FocusScales); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void FocusScales_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.FocusScales); } [ConditionalTheory(Helpers.IsDrawingSupported)] [MemberData(nameof(WrapMode_TestData))] public void WrapMode_ReturnsExpected(WrapMode wrapMode) { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { brush.WrapMode = wrapMode; Assert.Equal(wrapMode, brush.WrapMode); } } [ConditionalFact(Helpers.IsDrawingSupported)] public void WrapMode_Disposed_ThrowsArgumentException() { PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints); brush.Dispose(); AssertExtensions.Throws<ArgumentException>(null, () => brush.WrapMode); } [ConditionalFact(Helpers.IsDrawingSupported)] public void WrapMode_Invalid_InvalidEnumArgumentException() { using (PathGradientBrush brush = new PathGradientBrush(_defaultFloatPoints)) { Assert.ThrowsAny<ArgumentException>(() => brush.WrapMode = (WrapMode)int.MinValue); } } private void AssertDefaults(PathGradientBrush brush) { Assert.Equal(_defaultRectangle, brush.Rectangle); Assert.Equal(new float[] { 1 }, brush.Blend.Factors); Assert.Equal(1, brush.Blend.Positions.Length); Assert.Equal(new PointF(10.5f, 16f), brush.CenterPoint); Assert.Equal(new Color[] { Color.Empty }, brush.InterpolationColors.Colors); Assert.Equal(new Color[] { Color.FromArgb(255, 255, 255, 255) }, brush.SurroundColors); Assert.Equal(new float[] { 0 }, brush.InterpolationColors.Positions); Assert.True(brush.Transform.IsIdentity); Assert.True(brush.FocusScales.IsEmpty); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Threading; using NUnit.Framework; using QuantConnect.Algorithm; using QuantConnect.Brokerages; using QuantConnect.Brokerages.Backtesting; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.Results; using QuantConnect.Lean.Engine.TransactionHandlers; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Securities.Crypto; using QuantConnect.Securities.Positions; using QuantConnect.Tests.Engine; using QuantConnect.Tests.Engine.DataFeeds; namespace QuantConnect.Tests.Common.Securities { [TestFixture, Parallelizable(ParallelScope.Fixtures)] public class CashBuyingPowerModelTests { private Crypto _btcusd; private Crypto _btceur; private Crypto _ethusd; private Crypto _ethbtc; private SecurityPortfolioManager _portfolio; private BacktestingTransactionHandler _transactionHandler; private BacktestingBrokerage _brokerage; private IBuyingPowerModel _buyingPowerModel; private QCAlgorithm _algorithm; private LocalTimeKeeper _timeKeeper; private ITimeKeeper _globalTimeKeeper; private IResultHandler _resultHandler; [SetUp] public void Initialize() { _algorithm = new QCAlgorithm(); _algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(_algorithm)); _portfolio = _algorithm.Portfolio; _portfolio.CashBook.Add("EUR", 0, 1.20m); _portfolio.CashBook.Add("BTC", 0, 15000m); _portfolio.CashBook.Add("ETH", 0, 1000m); _algorithm.SetBrokerageModel(BrokerageName.GDAX, AccountType.Cash); _transactionHandler = new BacktestingTransactionHandler(); _brokerage = new BacktestingBrokerage(_algorithm); _resultHandler = new TestResultHandler(); _transactionHandler.Initialize(_algorithm, _brokerage, _resultHandler); _algorithm.Transactions.SetOrderProcessor(_transactionHandler); var tz = TimeZones.NewYork; _btcusd = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook[Currencies.USD], new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCUSD, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("BTCUSD", Currencies.USD, 1, 0.01m, 0.00000001m, string.Empty), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); _ethusd = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook[Currencies.USD], new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHUSD, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("ETHUSD", Currencies.USD, 1, 0.01m, 0.00000001m, string.Empty), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); _btceur = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook["EUR"], new SubscriptionDataConfig(typeof(TradeBar), Symbols.BTCEUR, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("BTCEUR", "EUR", 1, 0.01m, 0.00000001m, string.Empty), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); _ethbtc = new Crypto( SecurityExchangeHours.AlwaysOpen(tz), _portfolio.CashBook["BTC"], new SubscriptionDataConfig(typeof(TradeBar), Symbols.ETHBTC, Resolution.Minute, tz, tz, true, false, false), new SymbolProperties("ETHBTC", "BTC", 1, 0.00001m, 0.00000001m, string.Empty), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); _globalTimeKeeper = new TimeKeeper(new DateTime(2019, 11, 7)); _timeKeeper = _globalTimeKeeper.GetLocalTimeKeeper(tz); _buyingPowerModel = new BuyingPowerModelComparator( new CashBuyingPowerModel(), new SecurityPositionGroupBuyingPowerModel(), _portfolio, _globalTimeKeeper ); _btcusd.SetLocalTimeKeeper(_timeKeeper); _ethusd.SetLocalTimeKeeper(_timeKeeper); _btceur.SetLocalTimeKeeper(_timeKeeper); _ethbtc.SetLocalTimeKeeper(_timeKeeper); } [TearDown] public void TearDown() { _transactionHandler.Exit(); _resultHandler.Exit(); } [Test] public void InitializesCorrectly() { Assert.AreEqual(1m, _buyingPowerModel.GetLeverage(_btcusd)); Assert.AreEqual(0m, _buyingPowerModel.GetReservedBuyingPowerForPosition(_btcusd)); } [Test] public void SetLeverageDoesNotUpdateLeverage() { Assert.Throws<InvalidOperationException>(() => _buyingPowerModel.SetLeverage(_btcusd, 50m)); } [Test] public void LimitBuyBtcWithUsdRequiresUsdInPortfolio() { _portfolio.SetCash(20000); // Available cash = 20000 USD, can buy 2 BTC at 10000 var order = new LimitOrder(_btcusd.Symbol, 2m, 10000m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // Available cash = 20000 USD, cannot buy 2.1 BTC at 10000, need 21000 order = new LimitOrder(_btcusd.Symbol, 2.1m, 10000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // Available cash = 20000 USD, cannot buy 2 BTC at 11000, need 22000 order = new LimitOrder(_btcusd.Symbol, 2m, 11000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void LimitBuyBtcWithEurRequiresEurInPortfolio() { _portfolio.SetCash("EUR", 20000m, 1.20m); // Available cash = 20000 EUR, can buy 2 BTC at 10000 var order = new LimitOrder(_btceur.Symbol, 2m, 10000m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); // Available cash = 20000 EUR, cannot buy 2.1 BTC at 10000, need 21000 order = new LimitOrder(_btceur.Symbol, 2.1m, 10000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); // Available cash = 20000 EUR, cannot buy 2 BTC at 11000, need 22000 order = new LimitOrder(_btceur.Symbol, 2m, 11000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); } [Test] public void LimitSellOrderRequiresBaseCurrencyInPortfolio() { _portfolio.SetCash(0); _portfolio.CashBook["BTC"].SetAmount(0.5m); // 0.5 BTC in portfolio, can sell 0.5 BTC at any price var order = new LimitOrder(_btcusd.Symbol, -0.5m, 10000m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 0.5 BTC in portfolio, cannot sell 0.6 BTC at any price order = new LimitOrder(_btcusd.Symbol, -0.6m, 10000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void LimitBuyOrderChecksOpenOrders() { _portfolio.SetCash(5000); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _ethusd = _algorithm.AddCrypto("ETHUSD"); _ethusd.SetMarketPrice(new Tick { Value = 1000m }); _algorithm.SetFinishedWarmingUp(); // BTCUSD buy order decreases available USD (5000 - 1500 = 3500 USD) SubmitLimitOrder(_btcusd.Symbol, 0.1m, 15000m); // ETHUSD buy order decreases available USD (3500 - 3000 = 500 USD) SubmitLimitOrder(_ethusd.Symbol, 3m, 1000m); // 500 USD available, can buy 0.048 BTC at 10000 var order = new LimitOrder(_btcusd.Symbol, 0.048m, 10000m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 500 USD available, cannot buy 0.06 BTC at 10000 order = new LimitOrder(_btcusd.Symbol, 0.06m, 10000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void LimitSellOrderChecksOpenOrders() { _portfolio.SetCash(5000); _portfolio.CashBook["BTC"].SetAmount(1m); _portfolio.CashBook["ETH"].SetAmount(3m); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _ethusd = _algorithm.AddCrypto("ETHUSD"); _ethusd.SetMarketPrice(new Tick { Value = 1000m }); _ethbtc = _algorithm.AddCrypto("ETHBTC"); _ethbtc.SetMarketPrice(new Tick { Value = 0.1m }); _algorithm.SetFinishedWarmingUp(); // BTCUSD sell limit order decreases available BTC (1 - 0.1 = 0.9 BTC) SubmitLimitOrder(_btcusd.Symbol, -0.1m, 15000m); // ETHUSD sell limit order decreases available ETH (3 - 1 = 2 ETH) SubmitLimitOrder(_ethusd.Symbol, -1m, 1000m); // ETHBTC buy limit order decreases available BTC (0.9 - 0.1 = 0.8 BTC) SubmitLimitOrder(_ethbtc.Symbol, 1m, 0.1m); // BTCUSD sell stop order decreases available BTC (0.8 - 0.1 = 0.7 BTC) SubmitStopMarketOrder(_btcusd.Symbol, -0.1m, 5000m); // 0.7 BTC available, can sell 0.7 BTC at any price var order = new LimitOrder(_btcusd.Symbol, -0.7m, 10000m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 0.7 BTC available, cannot sell 0.8 BTC at any price order = new LimitOrder(_btcusd.Symbol, -0.8m, 10000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 2 ETH available, can sell 2 ETH at any price order = new LimitOrder(_ethusd.Symbol, -2m, 1200m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethusd, order).IsSufficient); // 2 ETH available, cannot sell 2.1 ETH at any price order = new LimitOrder(_ethusd.Symbol, -2.1m, 2000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethusd, order).IsSufficient); // 0.7 BTC available, can sell stop 0.7 BTC at any price var stopOrder = new StopMarketOrder(_btcusd.Symbol, -0.7m, 5000m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, stopOrder).IsSufficient); // 0.7 BTC available, cannot sell stop 0.8 BTC at any price stopOrder = new StopMarketOrder(_btcusd.Symbol, -0.8m, 5000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, stopOrder).IsSufficient); } [Test] public void MarketBuyBtcWithUsdRequiresUsdInPortfolioPlusFees() { _portfolio.SetCash(20000); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m }); // Available cash = 20000 USD, cannot buy 2 BTC at 10000 (fees are excluded) var order = new MarketOrder(_btcusd.Symbol, 2m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // Maximum we can market buy with 20000 USD is 1.99004975 BTC Assert.AreEqual(1.99004975m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1, 0).Quantity); _btcusd.SetMarketPrice(new Tick { Value = 9900m }); // Available cash = 20000 USD, can buy 2 BTC at 9900 (plus fees) order = new MarketOrder(_btcusd.Symbol, 2m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void MarketBuyBtcWithEurRequiresEurInPortfolioPlusFees() { _portfolio.SetCash("EUR", 20000m, 1.20m); _btceur.SetLocalTimeKeeper(_timeKeeper); _btceur.SetMarketPrice(new Tick { Value = 10000m }); // Available cash = 20000 EUR, cannot buy 2 BTC at 10000 (fees are excluded) var order = new MarketOrder(_btceur.Symbol, 2m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); // Maximum we can market buy with 20000 EUR is 1.99004975 BTC var targetValue = 20000m * _portfolio.CashBook["EUR"].ConversionRate / _portfolio.TotalPortfolioValue; Assert.AreEqual(1.99004975m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btceur, targetValue, 0).Quantity); _btceur.SetMarketPrice(new Tick { Value = 9900m }); // Available cash = 20000 EUR, can buy 2 BTC at 9900 (plus fees) order = new MarketOrder(_btceur.Symbol, 2m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); } [Test] public void MarketSellOrderRequiresBaseCurrencyInPortfolioPlusFees() { _portfolio.SetCash(0); _btcusd.SetMarketPrice(new Tick { Value = 10000m }); _portfolio.SetCash("BTC", 0.5m, 10000m); // 0.5 BTC in portfolio, can sell 0.5 BTC var order = new MarketOrder(_btcusd.Symbol, -0.5m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 0.5 BTC in portfolio, cannot sell 0.51 BTC order = new MarketOrder(_btcusd.Symbol, -0.51m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // Maximum we can market sell with 0.5 BTC is 0.5 BTC Assert.AreEqual(-0.5m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0, 0).Quantity); } [Test] public void MarketBuyOrderChecksOpenOrders() { _portfolio.SetCash(5000); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _ethusd = _algorithm.AddCrypto("ETHUSD"); _ethusd.SetMarketPrice(new Tick { Value = 1000m }); _algorithm.SetFinishedWarmingUp(); // BTCUSD buy order decreases available USD (5000 - 1500 = 3500 USD) SubmitLimitOrder(_btcusd.Symbol, 0.1m, 15000m); // ETHUSD buy order decreases available USD (3500 - 3000 = 500 USD) SubmitLimitOrder(_ethusd.Symbol, 3m, 1000m); // Maximum we can market buy with 500 USD is 0.03316749 BTC var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 500 / _portfolio.TotalPortfolioValue, 0).Quantity; Assert.AreEqual(0.03316749m, quantity); // 500 USD available, can buy `quantity` BTC at 15000 var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 500 USD available, cannot buy `quantity` + _btcusd.SymbolProperties.LotSize BTC at 15000 order = new MarketOrder(_btcusd.Symbol, quantity + _btcusd.SymbolProperties.LotSize, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void MarketSellOrderChecksOpenOrders() { _portfolio.SetCash(5000); _portfolio.CashBook["BTC"].SetAmount(1m); _portfolio.CashBook["ETH"].SetAmount(3m); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _ethusd = _algorithm.AddCrypto("ETHUSD"); _ethusd.SetMarketPrice(new Tick { Value = 1000m }); _ethbtc = _algorithm.AddCrypto("ETHBTC"); _ethbtc.SetMarketPrice(new Tick { Value = 0.1m }); _algorithm.SetFinishedWarmingUp(); // BTCUSD sell order decreases available BTC (1 - 0.1 = 0.9 BTC) SubmitLimitOrder(_btcusd.Symbol, -0.1m, 15000m); // ETHBTC buy order decreases available BTC (0.9 - 0.1 = 0.8 BTC) SubmitLimitOrder(_ethbtc.Symbol, 1m, 0.1m); // Maximum we can market sell with 0.8 BTC is -0.7960199 BTC (for a target position of 0.2 BTC) // target value = (1 - 0.8) * price Assert.AreEqual(-0.7960199m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0.2m * 15000 / _portfolio.TotalPortfolioValue, 0).Quantity); // 0.8 BTC available, can sell 0.80 BTC at market var order = new MarketOrder(_btcusd.Symbol, -0.80m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 0.8 BTC available, cannot sell 0.81 BTC at market order = new MarketOrder(_btcusd.Symbol, -0.81m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void LimitBuyOrderIncludesFees() { _portfolio.SetCash(20000); _btcusd.FeeModel = new ConstantFeeModel(50); // Available cash = 20000, cannot buy 2 BTC at 10000 because of order fee var order = new LimitOrder(_btcusd.Symbol, 2m, 10000m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // deposit another 50 USD _portfolio.CashBook[Currencies.USD].AddAmount(50); // now the order is allowed Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void CalculatesMaximumOrderQuantityCorrectly() { _portfolio.SetCash(10000); _portfolio.SetCash("EUR", 10000m, 1.20m); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _ethusd = _algorithm.AddCrypto("ETHUSD"); _ethusd.SetLocalTimeKeeper(_timeKeeper); _ethusd.SetMarketPrice(new Tick { Value = 1000m }); _ethbtc = _algorithm.AddCrypto("ETHBTC"); _ethbtc.SetLocalTimeKeeper(_timeKeeper); _ethbtc.SetMarketPrice(new Tick { Value = 0.1m }); _btceur = _algorithm.AddCrypto("BTCEUR"); _btceur.SetLocalTimeKeeper(_timeKeeper); _btceur.SetMarketPrice(new Tick { Value = 12000m }); _algorithm.SetFinishedWarmingUp(); // 0.66334991 * 15000 + fees + price buffer <= 10000 USD var targetValue = 10000 / _portfolio.TotalPortfolioValue; var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, targetValue, 0).Quantity; Assert.AreEqual(0.66334991m, getMaximumOrderQuantityForTargetValueResult); var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); // 9.95024875 * 1000 + fees <= 10000 USD getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _ethusd, targetValue, 0).Quantity; Assert.AreEqual(9.95024875m, getMaximumOrderQuantityForTargetValueResult); order = new MarketOrder(_ethusd.Symbol, getMaximumOrderQuantityForTargetValueResult, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethusd, order).IsSufficient); // no BTC in portfolio, but GetMaximumOrderQuantityForTargetBuyingPower does not care var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _ethbtc, 1, 0).Quantity; Assert.AreNotEqual(0m, quantity); // HasSufficientBuyingPowerForOrder does check margin requirements order = new MarketOrder(_ethbtc.Symbol, quantity, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _ethbtc, order).IsSufficient); // 0.82918739 * 12000 + fees <= 10000 EUR targetValue = 10000m * _portfolio.CashBook["EUR"].ConversionRate / _portfolio.TotalPortfolioValue; getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btceur, targetValue, 0).Quantity; Assert.AreEqual(0.82918739m, getMaximumOrderQuantityForTargetValueResult); order = new MarketOrder(_btceur.Symbol, getMaximumOrderQuantityForTargetValueResult, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); } [Test] public void CalculatesMaximumOrderQuantityCorrectlySmallerTarget() { _portfolio.SetCash(10000); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _algorithm.SetFinishedWarmingUp(); var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0.1m, 0); // Quantity * 15000m + fees + price buffer <= 1000 USD Target Assert.AreEqual(0.06633499m, getMaximumOrderQuantityForTargetValueResult.Quantity); var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void CalculatesMaximumOrderQuantityCorrectlyBiggerTarget() { _portfolio.SetCash(10000); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _algorithm.SetFinishedWarmingUp(); var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 10m, 0); // Quantity * 15000m + fees + price buffer <= 100000 USD Target Assert.AreEqual(6.63349917m, getMaximumOrderQuantityForTargetValueResult.Quantity); var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void CalculatesMaximumOrderQuantityCorrectlyForAlmostNoCashRemaining() { _portfolio.SetCash(0.00000000001m); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _algorithm.SetFinishedWarmingUp(); var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 10000 / _portfolio.TotalPortfolioValue, 0); // We don't have enough cash, but GetMaximumOrderQuantityForTargetValue does not care about this :) Assert.AreEqual(0.66334991m, getMaximumOrderQuantityForTargetValueResult.Quantity); var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void CalculatesMaximumOrderQuantityCorrectlyForNoOrderFee() { _portfolio.SetCash(100000m); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _algorithm.Securities[_btcusd.Symbol].SetFeeModel(new ConstantFeeModel(0)); _btcusd.SetMarketPrice(new Tick { Value = 15000m }); _algorithm.SetFinishedWarmingUp(); var getMaximumOrderQuantityForTargetValueResult = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 0.1m, 0); // Quantity * 15000m + fees (0) + price buffer <= 10000 USD Target Assert.AreEqual(0.66666666m, getMaximumOrderQuantityForTargetValueResult.Quantity); var order = new MarketOrder(_btcusd.Symbol, getMaximumOrderQuantityForTargetValueResult.Quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void MarketBuyOrderChecksExistingHoldings() { _portfolio.SetCash(8000); _portfolio.CashBook.Add("BTC", 0.2m, 10000m); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m }); _algorithm.SetFinishedWarmingUp(); Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue); // Maximum we can market buy for (10000-2000) = 8000 USD is 0.7960199 BTC var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 10000m / _portfolio.TotalPortfolioValue, 0).Quantity; Assert.AreEqual(0.7960199m, quantity); // the maximum order quantity can be executed var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void MarketBuyBtcWithEurCalculatesBuyingPowerProperlyWithExistingHoldings() { _portfolio.SetCash("EUR", 20000m, 1.20m); _portfolio.CashBook.Add("BTC", 1m, 12000m); _btceur.SetLocalTimeKeeper(_timeKeeper); _btceur.SetMarketPrice(new Tick { Value = 10000m }); // Maximum we can market buy with 20000 EUR is 1.99004975 BTC // target value = 30000 EUR = 20000 EUR in cash + 10000 EUR in BTC var targetValue = 30000m * _portfolio.CashBook["EUR"].ConversionRate / _portfolio.TotalPortfolioValue; Assert.AreEqual(1.99004975m, _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btceur, targetValue, 0).Quantity); // Available cash = 20000 EUR, can buy 1.99 BTC at 10000 (plus fees) var order = new MarketOrder(_btceur.Symbol, 1.99m, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); // Available cash = 20000 EUR, cannot buy 2 BTC at 10000 (plus fees) order = new MarketOrder(_btceur.Symbol, 2m, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btceur, order).IsSufficient); } [Test] public void MarketBuyOrderUsesAskPriceIfAvailable() { _portfolio.SetCash(10000); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue); // Maximum we can market buy at ask price with 10000 USD is 0.9900745 BTC var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity; Assert.AreEqual(0.9900745m, quantity); // the maximum order quantity can be executed var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void ZeroTargetWithZeroHoldingsIsNotAnError() { _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); var result = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_algorithm.Portfolio, _btcusd, 0, 0); var order = new MarketOrder(_btcusd.Symbol, result.Quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); Assert.AreEqual(0, result.Quantity); Assert.AreEqual(string.Empty, result.Reason); Assert.AreEqual(false, result.IsError); } [Test] public void ZeroTargetWithNonZeroHoldingsReturnsNegativeOfQuantity() { _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _portfolio.CashBook.Add("BTC", 1m, 12000m); var result = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_algorithm.Portfolio, _btcusd, 0, 0); var order = new MarketOrder(_btcusd.Symbol, result.Quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); Assert.AreEqual(-1, result.Quantity); Assert.AreEqual(string.Empty, result.Reason); Assert.AreEqual(false, result.IsError); } [Test] public void NonAccountCurrencyFees() { _portfolio.SetCash(10000); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); _btcusd.FeeModel = new NonAccountCurrencyCustomFeeModel(); Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue); // 0.24875621 * 100050 (ask price) + 0.5 (fee) * 15000 (conversion rate, because its BTC) = 9999.9999105 var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity; Assert.AreEqual(0.24875621m, quantity); // the maximum order quantity can be executed var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void NonAccountCurrency_NoQuoteCurrencyCash() { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency("EUR"); _algorithm.Portfolio.SetCash(10000); Assert.AreEqual(10000m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); _algorithm.Portfolio.CashBook[Currencies.USD].ConversionRate = 0.88m; // we don't have any USD ! cash model shouldn't let us trade var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity; Assert.AreNotEqual(0m, quantity); // HasSufficientBuyingPowerForOrder does check margin requirements var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); var result = _buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order); Assert.IsFalse(result.IsSufficient); Assert.IsTrue(result.Reason.Contains("only a total value of 0 USD is available.")); } [TestCase("EUR")] [TestCase("ARG")] public void ZeroNonAccountCurrency_GetMaximumOrderQuantityForTargetValue(string accountCurrency) { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency(accountCurrency); _algorithm.Portfolio.SetCash(0); _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m); Assert.AreEqual(8800m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); // Maximum we can market buy at ask price with 10000 USD is 0.9900745 BTC => Account currency should not matter var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity; Assert.AreEqual(0.9900745m, quantity); var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); var fee = _btcusd.FeeModel.GetOrderFee(new OrderFeeParameters(_btcusd, order)); var feeAsAccountCurrency = _algorithm.Portfolio.CashBook.ConvertToAccountCurrency(fee.Value); var expectedQuantity = (8800 - feeAsAccountCurrency.Amount) / (_btcusd.AskPrice * 0.88m); expectedQuantity -= expectedQuantity % _btcusd.SymbolProperties.LotSize; Assert.AreEqual(expectedQuantity, quantity); // the maximum order quantity can be executed Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [Test] public void ZeroNonAccountCurrency_GetBuyingPower() { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency("EUR"); _algorithm.Portfolio.SetCash(0); _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m); Assert.AreEqual(8800m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); var quantity = _buyingPowerModel.GetBuyingPower(new BuyingPowerParameters(_portfolio, _btcusd, OrderDirection.Buy)).Value; Assert.AreEqual(1m, quantity); } [Test] public void ZeroNonAccountCurrency_GetReservedBuyingPowerForPosition() { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency("EUR"); _algorithm.Portfolio.SetCash(0); _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m); Assert.AreEqual(8800m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); _btcusd.Holdings.SetHoldings(_btcusd.Price, 100); var res = _buyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(_btcusd)); // Always returns 0. Since we're purchasing currencies outright, the position doesn't consume buying power Assert.AreEqual(0m, res.AbsoluteUsedBuyingPower); } [Test] public void NonAccountCurrency_GetBuyingPower() { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency("EUR"); _algorithm.Portfolio.SetCash(10000); _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m); Assert.AreEqual(18800m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); var quantity = _buyingPowerModel.GetBuyingPower(new BuyingPowerParameters(_portfolio, _btcusd, OrderDirection.Buy)).Value; Assert.AreEqual(1m, quantity); } [Test] public void NonAccountCurrency_ZeroQuoteCurrency_GetBuyingPower() { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency("EUR"); _algorithm.Portfolio.SetCash(10000); _algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); Assert.AreEqual(10000, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); var quantity = _buyingPowerModel.GetBuyingPower(new BuyingPowerParameters(_portfolio, _btcusd, OrderDirection.Buy)).Value; Assert.AreEqual(0m, quantity); } [TestCase("EUR")] [TestCase("ARG")] public void NonZeroNonAccountCurrency_UnReachableTarget(string accountCurrency) { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency("EUR"); _algorithm.Portfolio.SetCash(10000); _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m); Assert.AreEqual(18800m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); // Maximum we can market buy at ask price with 10000 USD + (10000 EUR / 0.88 rate) is 2.11515916 BTC var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, 1m, 0).Quantity; Assert.AreEqual(2.11515916m, quantity); // the maximum order quantity can be executed var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); Assert.IsFalse(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } [TestCase("EUR")] [TestCase("ARG")] public void NonZeroNonAccountCurrency_ReachableTarget(string accountCurrency) { _algorithm.Portfolio.CashBook.Clear(); _algorithm.Portfolio.SetAccountCurrency(accountCurrency); _algorithm.Portfolio.SetCash(10000); _algorithm.Portfolio.SetCash(Currencies.USD, 10000, 0.88m); Assert.AreEqual(18800m, _portfolio.TotalPortfolioValue); _btcusd = _algorithm.AddCrypto("BTCUSD"); _btcusd.SetLocalTimeKeeper(_timeKeeper); _btcusd.SetMarketPrice(new Tick { Value = 10000m, BidPrice = 9950, AskPrice = 10050, TickType = TickType.Quote }); _algorithm.SetFinishedWarmingUp(); // only use the USD for determining the target var reachableTarget = 8800m / 18800m; // Maximum we can market buy at ask price with 10000 USD is 0.9900745 BTC => Account currency should not matter var quantity = _buyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower(_portfolio, _btcusd, reachableTarget, 0).Quantity; Assert.AreEqual(0.9900745m, quantity); // the maximum order quantity can be executed var order = new MarketOrder(_btcusd.Symbol, quantity, DateTime.UtcNow); Assert.IsTrue(_buyingPowerModel.HasSufficientBuyingPowerForOrder(_portfolio, _btcusd, order).IsSufficient); } private void SubmitLimitOrder(Symbol symbol, decimal quantity, decimal limitPrice) { using (var resetEvent = new ManualResetEvent(false)) { EventHandler<OrderEvent> handler = (s, e) => { resetEvent.Set(); }; _brokerage.OrderStatusChanged += handler; _algorithm.LimitOrder(symbol, quantity, limitPrice); if (!resetEvent.WaitOne(5000)) { throw new TimeoutException("SubmitLimitOrder"); } _brokerage.OrderStatusChanged -= handler; } } private void SubmitStopMarketOrder(Symbol symbol, decimal quantity, decimal stopPrice) { using (var resetEvent = new ManualResetEvent(false)) { EventHandler<OrderEvent> handler = (s, e) => { resetEvent.Set(); }; _brokerage.OrderStatusChanged += handler; _algorithm.StopMarketOrder(symbol, quantity, stopPrice); if (!resetEvent.WaitOne(5000)) { throw new TimeoutException("SubmitStopMarketOrder"); } _brokerage.OrderStatusChanged -= handler; } } internal class NonAccountCurrencyCustomFeeModel : FeeModel { public string FeeCurrency = "BTC"; public decimal FeeAmount = 0.5m; public override OrderFee GetOrderFee(OrderFeeParameters parameters) { return new OrderFee(new CashAmount(FeeAmount, FeeCurrency)); } } } }
// <copyright file="GPGSUtil.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> namespace GooglePlayGames { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using UnityEditor; using UnityEngine; public static class GPGSUtil { private const string SERVICEIDPLACEHOLDER = "__NEARBY_SERVICE_ID__"; public const string SERVICEIDKEY = "App.NearbdServiceId"; private const string APPIDPLACEHOLDER = "__APP_ID__"; public const string APPIDKEY = "proj.AppId"; private const string CLASSNAMEPLACEHOLDER = "__Class__"; public const string CLASSNAMEKEY = "proj.ConstantsClassName"; private const string WEBCLIENTIDPLACEHOLDER = "__WEB_CLIENTID__"; public const string WEBCLIENTIDKEY = "and.ClientId"; private const string IOSCLIENTIDPLACEHOLDER = "__IOS_CLIENTID__"; public const string IOSCLIENTIDKEY = "ios.ClientId"; private const string IOSBUNDLEIDPLACEHOLDER = "__BUNDLEID__"; public const string IOSBUNDLEIDKEY = "ios.BundleId"; private const string TOKENPERMISSIONSHOLDER = "__TOKEN_PERMISSIONS__"; private const string TOKENPERMISSIONKEY = "proj.tokenPermissions"; private const string NAMESPACESTARTPLACEHOLDER = "__NameSpaceStart__"; private const string NAMESPACEENDPLACEHOLDER = "__NameSpaceEnd__"; private const string CONSTANTSPLACEHOLDER = "__Constant_Properties__"; public const string LASTUPGRADEKEY = "lastUpgrade"; public const string ANDROIDRESOURCEKEY = "and.ResourceData"; public const string IOSRESOURCEKEY = "ios.ResourceData"; private const string GameInfoPath = "Assets/GooglePlayGames/GameInfo.cs"; public const string IOSSETUPDONEKEY = "ios.SetupDone"; private const string TokenPermissions = "<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>\n" + "<uses-permission android:name=\"android.permission.USE_CREDENTIALS\"/>"; /// <summary> /// The map of replacements for filling in code templates. The /// key is the string that appears in the template as a placeholder, /// the value is the key into the GPGSProjectSettings. /// </summary> private static Dictionary<string,string> Replacements = new Dictionary<string, string>() { {SERVICEIDPLACEHOLDER, SERVICEIDKEY}, {APPIDPLACEHOLDER, APPIDKEY}, {CLASSNAMEPLACEHOLDER, CLASSNAMEKEY}, {WEBCLIENTIDPLACEHOLDER, WEBCLIENTIDKEY}, {IOSCLIENTIDPLACEHOLDER, IOSCLIENTIDKEY}, {IOSBUNDLEIDPLACEHOLDER, IOSBUNDLEIDKEY}, {TOKENPERMISSIONSHOLDER, TOKENPERMISSIONKEY} }; public static string SlashesToPlatformSeparator(string path) { return path.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()); } public static string ReadFile(string filePath) { filePath = SlashesToPlatformSeparator(filePath); if (!File.Exists(filePath)) { Alert("Plugin error: file not found: " + filePath); return null; } StreamReader sr = new StreamReader(filePath); string body = sr.ReadToEnd(); sr.Close(); return body; } public static string ReadEditorTemplate(string name) { return ReadFile(SlashesToPlatformSeparator("Assets/GooglePlayGames/Editor/" + name + ".txt")); } public static string ReadFully(string path) { return ReadFile(SlashesToPlatformSeparator(path)); } public static void WriteFile(string file, string body) { file = SlashesToPlatformSeparator(file); using (var wr = new StreamWriter(file, false)) { wr.Write(body); } } public static bool LooksLikeValidServiceId(string s) { if (s.Length < 3) { return false; } foreach (char c in s) { if (!char.IsLetterOrDigit(c) && c != '.') { return false; } } return true; } public static bool LooksLikeValidAppId(string s) { if (s.Length < 5) { return false; } foreach (char c in s) { if (c < '0' || c > '9') { return false; } } return true; } public static bool LooksLikeValidClientId(string s) { return s.EndsWith(".googleusercontent.com"); } public static bool LooksLikeValidBundleId(string s) { return s.Length > 3; } public static bool LooksLikeValidPackageName(string s) { return !s.Contains(" ") && s.Split(new char[] { '.' }).Length > 1; } /// <summary> /// Makes legal identifier from string. /// Returns a legal C# identifier from the given string. The transformations are: /// - spaces => underscore _ /// - punctuation => empty string /// - leading numbers are prefixed with underscore. /// </summary> /// <returns>the id</returns> /// <param name="key">Key.</param> static string makeIdentifier (string key) { string s; string retval = ""; if (string.IsNullOrEmpty (key)) { return "_"; } s = key.Trim().Replace (' ', '_'); foreach (char c in s) { if (char.IsLetterOrDigit(c) || c == '_') { retval += c; } } return retval; } public static void Alert(string s) { Alert(GPGSStrings.Error, s); } public static void Alert(string title, string s) { EditorUtility.DisplayDialog(title, s, GPGSStrings.Ok); } public static string GetAndroidSdkPath() { string sdkPath = EditorPrefs.GetString("AndroidSdkRoot"); if (sdkPath != null && (sdkPath.EndsWith("/") || sdkPath.EndsWith("\\"))) { sdkPath = sdkPath.Substring(0, sdkPath.Length - 1); } return sdkPath; } public static bool HasAndroidSdk() { string sdkPath = GetAndroidSdkPath(); return sdkPath != null && sdkPath.Trim() != string.Empty && System.IO.Directory.Exists(sdkPath); } public static void CopySupportLibs() { string sdkPath = GetAndroidSdkPath(); string supportJarPath = sdkPath + GPGSUtil.SlashesToPlatformSeparator( "/extras/android/support/v4/android-support-v4.jar"); string supportJarDest = GPGSUtil.SlashesToPlatformSeparator("Assets/Plugins/Android/libs/android-support-v4.jar"); string libProjPath = sdkPath + GPGSUtil.SlashesToPlatformSeparator( "/extras/google/google_play_services/libproject/google-play-services_lib"); string libProjAM = libProjPath + GPGSUtil.SlashesToPlatformSeparator("/AndroidManifest.xml"); string libProjDestDir = GPGSUtil.SlashesToPlatformSeparator( "Assets/Plugins/Android/google-play-services_lib"); // check that the Google Play Services lib project is there if (!System.IO.Directory.Exists(libProjPath) || !System.IO.File.Exists(libProjAM)) { Debug.LogError("Google Play Services lib project not found at: " + libProjPath); EditorUtility.DisplayDialog(GPGSStrings.AndroidSetup.LibProjNotFound, GPGSStrings.AndroidSetup.LibProjNotFoundBlurb, GPGSStrings.Ok); return; } // check version int version = GetGPSVersion(libProjPath); if (version < 0) { Debug.LogError("Google Play Services lib version cannot be found!"); } if (version < PluginVersion.MinGmsCoreVersionCode) { if (!EditorUtility.DisplayDialog(string.Format( GPGSStrings.AndroidSetup.LibProjVerTooOld, version, PluginVersion.MinGmsCoreVersionCode), GPGSStrings.Ok, GPGSStrings.Cancel)) { Debug.LogError("Google Play Services lib is too old! " + " Found version " + version + " require at least version " + PluginVersion.MinGmsCoreVersionCode); return; } Debug.Log("Ignoring the version mismatch and continuing the build."); } // clear out the destination library project GPGSUtil.DeleteDirIfExists(libProjDestDir); // Copy Google Play Services library FileUtil.CopyFileOrDirectory(libProjPath, libProjDestDir); if (!System.IO.File.Exists(supportJarPath)) { // check for the new location supportJarPath = sdkPath + GPGSUtil.SlashesToPlatformSeparator( "/extras/android/support/v7/appcompat/libs/android-support-v4.jar"); Debug.LogError("Android support library v4 not found at: " + supportJarPath); if (!System.IO.File.Exists(supportJarPath)) { EditorUtility.DisplayDialog(GPGSStrings.AndroidSetup.SupportJarNotFound, GPGSStrings.AndroidSetup.SupportJarNotFoundBlurb, GPGSStrings.Ok); return; } } // create needed directories GPGSUtil.EnsureDirExists("Assets/Plugins"); GPGSUtil.EnsureDirExists("Assets/Plugins/Android"); // Clear out any stale version of the support jar. File.Delete(supportJarDest); // Copy Android Support Library FileUtil.CopyFileOrDirectory(supportJarPath, supportJarDest); } public static void GenerateAndroidManifest(bool needTokenPermissions) { string destFilename = GPGSUtil.SlashesToPlatformSeparator( "Assets/Plugins/Android/MainLibProj/AndroidManifest.xml"); // Generate AndroidManifest.xml string manifestBody = GPGSUtil.ReadEditorTemplate("template-AndroidManifest"); Dictionary<string,string> overrideValues = new Dictionary<string,string>(); if (!needTokenPermissions) { overrideValues[TOKENPERMISSIONKEY] = ""; overrideValues[WEBCLIENTIDPLACEHOLDER] = ""; } else { overrideValues[TOKENPERMISSIONKEY] = TokenPermissions; } foreach(KeyValuePair<string, string> ent in Replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value, overrideValues); manifestBody = manifestBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(destFilename, manifestBody); GPGSUtil.UpdateGameInfo(); } public static void WriteResourceIds(string className, Hashtable resourceKeys) { string constantsValues = string.Empty; string[] parts = className.Split('.'); string dirName = "Assets"; string nameSpace = string.Empty; for (int i = 0; i < parts.Length - 1; i++) { dirName += "/" + parts[i]; if (nameSpace != string.Empty) { nameSpace += "."; } nameSpace += parts[i]; } EnsureDirExists(dirName); foreach (DictionaryEntry ent in resourceKeys) { string key = makeIdentifier ((string)ent.Key); constantsValues += " public const string " + key + " = \"" + ent.Value + "\"; // <GPGSID>\n"; } string fileBody = GPGSUtil.ReadEditorTemplate("template-Constants"); if (nameSpace != string.Empty) { fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, "namespace " + nameSpace + "\n{"); } else { fileBody = fileBody.Replace(NAMESPACESTARTPLACEHOLDER, ""); } fileBody = fileBody.Replace(CLASSNAMEPLACEHOLDER, parts[parts.Length - 1]); fileBody = fileBody.Replace(CONSTANTSPLACEHOLDER, constantsValues); if (nameSpace != string.Empty) { fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, "}"); } else { fileBody = fileBody.Replace(NAMESPACEENDPLACEHOLDER, ""); } WriteFile(dirName + "/" + parts[parts.Length-1] + ".cs", fileBody); } public static void UpdateGameInfo() { string fileBody = GPGSUtil.ReadEditorTemplate("template-GameInfo"); foreach(KeyValuePair<string, string> ent in Replacements) { string value = GPGSProjectSettings.Instance.Get(ent.Value); fileBody = fileBody.Replace(ent.Key, value); } GPGSUtil.WriteFile(GameInfoPath, fileBody); } public static void EnsureDirExists(string dir) { dir = dir.Replace("/", System.IO.Path.DirectorySeparatorChar.ToString()); if (!System.IO.Directory.Exists(dir)) { System.IO.Directory.CreateDirectory(dir); } } public static void DeleteDirIfExists(string dir) { if (System.IO.Directory.Exists(dir)) { System.IO.Directory.Delete(dir, true); } } static int GetGPSVersion(string libProjPath) { string versionFile = libProjPath + "/res/values/version.xml"; XmlTextReader reader = new XmlTextReader(new StreamReader(versionFile)); bool inResource = false; int version = -1; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "integer") { if ("google_play_services_version".Equals( reader.GetAttribute("name"))) { reader.Read(); Debug.Log("Read version string: " + reader.Value); version = Convert.ToInt32(reader.Value); } } } reader.Close(); return version; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; namespace Settlement { class WorldGenerator { Noise perlinNoise; public WorldGenerator() { int seed = 123; // Change to whatever int octaves = 1; // Number of layers of perlin noise (stick with 1 for now) double amplitude = 256; // affects world height (default 4) double persistence = 1; // How much it stays at a particular height. Only has any affect when octaves > 1 double frequency = 0.023; // Adjust for mountains/hills/plains (default 0.01) perlinNoise = new Noise(persistence, frequency, amplitude, octaves, seed); } public byte BlockCategoryAtPosition(Vector3 blockPos) { // Takes in the blockPos, which is relative to world space // Returns what category block it should be byte cat; double posHeight = perlinNoise.Get3D(blockPos.X, blockPos.Y, blockPos.Z); //double posHeight = perlinNoise.Get2D(blockPos.X, blockPos.Z); //double posHeight = perlinNoise.Get2D((int)blockPos.X, (int)blockPos.Z); if (blockPos.Y < posHeight) cat = 1; // Stone else cat = 0; // Air return cat; } } class Noise { double persistence; double frequency; double amplitude; int octaves; int randomSeed; public Noise(double persistence, double frequency, double amplitude, int octaves, int randomSeed) { this.persistence = persistence; this.frequency = frequency; this.amplitude = amplitude; this.octaves = octaves; this.randomSeed = randomSeed; } /// *** \\\ /// GET \\\ /// *** \\\ public double Get2D(double x, double y) { double total = 0; double tempAmplitude = amplitude; double tempFrequency = frequency; for (int i = 0; i < octaves; i++) { //tempFrequency = Math.Pow(2,i); //double tempAmplitude = Math.Pow(persistence,i); total += Gradient2D(x * tempFrequency, y * tempFrequency, randomSeed) * tempAmplitude; tempAmplitude *= persistence; tempFrequency *= 2; } return total; } public double Get3D(double x, double y, double z) { double total = 0; double tempAmplitude = amplitude; double tempFrequency = frequency; for (int i = 0; i < octaves; i++) { //tempFrequency = Math.Pow(2,i); //double tempAmplitude = Math.Pow(persistence,i); total += Gradient3D(x * tempFrequency, y * tempFrequency, z * tempFrequency, randomSeed) * tempAmplitude; tempAmplitude *= persistence; tempFrequency *= 2; } return total; } /// ***** \\\ /// NOISE \\\ /// ***** \\\ // Returns a random number based upon the number it is given // The big numbers are prime numbers and can be changed to other primes public double PerlinNoise1D(int x, int seed) { int n = (x * WorldGenConst.NOISE_MAGIC_X + WorldGenConst.NOISE_MAGIC_SEED * seed) & 0x7fffffff; n = (n << 13) ^ n; return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0); } public double PerlinNoise2D(int x, int y, int seed) { int n = (x * WorldGenConst.NOISE_MAGIC_X + y * WorldGenConst.NOISE_MAGIC_Y * WorldGenConst.NOISE_MAGIC_SEED * seed) & 0x7fffffff; n = (n << 13) ^ n; return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0); } public double PerlinNoise3D(int x, int y, int z, int seed) { int n = (x * WorldGenConst.NOISE_MAGIC_X + y * WorldGenConst.NOISE_MAGIC_Y + z * WorldGenConst.NOISE_MAGIC_Z * WorldGenConst.NOISE_MAGIC_SEED * seed) & 0x7fffffff; n = (n << 13) ^ n; return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0); } /// ************** \\\ /// SEAMLESS NOISE \\\ /// ************** \\\ /// NOTE: These functions are WIP public double NoiseSeamlessTest2D(int x, int y, int seed) { //return NoiseSeamless2D(x, y, seed, 1, 1); //return NoiseSeamlessX2D(x, y, seed, 16); return 0; } // Make noise seamless in X and Y direction, wrapping at w and h public double NoiseSeamless2D(int x, int y, int seed, int w, int h) { double total = 0; total += PerlinNoise2D(x, y, seed) * (w - x) * (h - y); total += PerlinNoise2D(x - w, y, seed) * (x) * (h - y); total += PerlinNoise2D(x - w, y - h, seed) * (x) * (y); total += PerlinNoise2D(x, y - h, seed) * (w - x) * (y); return total / (w * h); } // Make noise seamless in just the X direction, wrapping at w public double NoiseSeamlessX2D(int x, int y, int seed, int w) { return ((w - x) * PerlinNoise2D(x, y, seed) + (x) * PerlinNoise2D(x - w, y, seed)) / w; } /// ******** \\\ /// GRADIENT \\\ /// ******** \\\ public double Gradient2D(double x, double y, int seed) { // Calculate integer coordinates int integerX = (x > 0.0 ? (int)x : (int)x - 1); int integerY = (y > 0.0 ? (int)y : (int)y - 1); // Calculate remainder of coordinates double fractionalX = x - (double)integerX; double fractionalY = y - (double)integerY; // Get values for corners double v1 = Smooth2D(integerX, integerY, seed); double v2 = Smooth2D(integerX + 1, integerY, seed); double v3 = Smooth2D(integerX, integerY + 1, seed); double v4 = Smooth2D(integerX + 1, integerY + 1, seed); // Interpolate X double i1 = InterpolateCosine(v1, v2, fractionalX); double i2 = InterpolateCosine(v3, v4, fractionalX); // Interpolate Y return InterpolateCosine(i1, i2, fractionalY); } public double Gradient3D(double x, double y, double z, int seed) { // Calculate integer coordinates int integerX = (x > 0.0 ? (int)x : (int)x - 1); int integerY = (y > 0.0 ? (int)y : (int)y - 1); int integerZ = (z > 0.0 ? (int)z : (int)z - 1); // Calculate remainder of coordinates double fractionalX = x - (double)integerX; double fractionalY = y - (double)integerY; double fractionalZ = z - (double)integerZ; // Get values for corners double v1 = Smooth3D(integerX, integerY, integerZ, seed); double v2 = Smooth3D(integerX + 1, integerY, integerZ, seed); double v3 = Smooth3D(integerX, integerY + 1, integerZ, seed); double v4 = Smooth3D(integerX + 1, integerY + 1, integerZ, seed); double v5 = Smooth3D(integerX, integerY, integerZ + 1, seed); double v6 = Smooth3D(integerX + 1, integerY, integerZ + 1, seed); double v7 = Smooth3D(integerX, integerY + 1, integerZ + 1, seed); double v8 = Smooth3D(integerX + 1, integerY + 1, integerZ + 1, seed); // Interpolate X double ii1 = InterpolateCosine(v1, v2, fractionalX); double ii2 = InterpolateCosine(v3, v4, fractionalX); double ii3 = InterpolateCosine(v5, v6, fractionalX); double ii4 = InterpolateCosine(v7, v8, fractionalX); // Interpolate Y double i1 = InterpolateCosine(ii1, ii2, fractionalY); double i2 = InterpolateCosine(ii3, ii4, fractionalY); // Interpolate Z return InterpolateCosine(i1, i2, fractionalZ); } /// ************* \\\ /// INTERPOLATING \\\ /// ************* \\\ // Interpolate linearly between two points, a and b, based upon the value x (which is between 0 and 1) // When x is 0, a is returned // When x is 1, b is returned // Linear interpolation is the fastest but has most jagged output public double InterpolateLinear(double a, double b, double x) { return a * (1 - x) + b * x; } // Slightly slower than linear interpolation but much smoother public double InterpolateCosine(double a, double b, double x) { double ft = x * Math.PI; double f = (1 - Math.Cos(ft)) * 0.5; return a * (1 - f) + b * f; } // Much slower than cosine and linear interpolation, but very smooth // v1 = a, v2 = b // v0 = point before a, v3 = point after b public double InterpolateCubic(double v0, double v1, double v2, double v3, float x) { double p = (v3 - v2) - (v0 - v1); double q = (v0 - v1) - p; double r = v2 - v0; double s = v1; return p * x * x * x + q * x * x + r * x + s; } /// ********* \\\ /// SMOOTHING \\\ /// ********* \\\ public double Smooth1D(int x, int seed) { // 1/4 + 1/4 + 1/2 = 1; return PerlinNoise1D(x, seed) / 2 + PerlinNoise1D(x - 1, seed) / 4 + PerlinNoise1D(x + 1, seed) / 4; } public double Smooth2D(int x, int y, int seed) { // 4/16 + 4/8 + 1/4 = 1 // -- +- -+ ++ double corners = (PerlinNoise2D(x - 1, y - 1, seed) + PerlinNoise2D(x + 1, y - 1, seed) + PerlinNoise2D(x - 1, y + 1, seed) + PerlinNoise2D(x + 1, y + 1, seed)) / 16; // -0 +0 0- 0+ double sides = (PerlinNoise2D(x - 1, y, seed) + PerlinNoise2D(x + 1, y, seed) + PerlinNoise2D(x, y - 1, seed) + PerlinNoise2D(x, y + 1, seed)) / 8; // 00 double center = PerlinNoise2D(x, y, seed) / 4; return corners + sides + center; } public double Smooth3D(int x, int y, int z, int seed) { // 12/48 + 8/32 + 6/16 + 1/8 = 1 // ++0 -+0 0++ 0+- +-0 --0 0-+ 0-- +0+ +0- -0+ -0- double edges = 0; edges += PerlinNoise3D(x + 1, y + 1, z, seed) + PerlinNoise3D(x - 1, y + 1, z, seed) + PerlinNoise3D(x, y + 1, z + 1, seed) + PerlinNoise3D(x, y + 1, z - 1, seed); edges += PerlinNoise3D(x + 1, y - 1, z, seed) + PerlinNoise3D(x - 1, y - 1, z, seed) + PerlinNoise3D(x, y - 1, z + 1, seed) + PerlinNoise3D(x, y - 1, z - 1, seed); edges += PerlinNoise3D(x + 1, y, z + 1, seed) + PerlinNoise3D(x + 1, y, z - 1, seed) + PerlinNoise3D(x - 1, y, z + 1, seed) + PerlinNoise3D(x - 1, y, z - 1, seed); edges /= 48; // --- --+ -+- -++ +-- +-+ ++- +++ double corners = 0; corners += PerlinNoise3D(x - 1, y - 1, z - 1, seed) + PerlinNoise3D(x - 1, y - 1, z + 1, seed) + PerlinNoise3D(x - 1, y + 1, z - 1, seed) + PerlinNoise3D(x - 1, y + 1, z + 1, seed); corners += PerlinNoise3D(x + 1, y - 1, z - 1, seed) + PerlinNoise3D(x + 1, y - 1, z + 1, seed) + PerlinNoise3D(x + 1, y + 1, z - 1, seed) + PerlinNoise3D(x + 1, y + 1, z + 1, seed); corners /= 32; // +00 -00 0+0 0-0 00+ 00- double sides = 0; corners += PerlinNoise3D(x - 1, y, z, seed) + PerlinNoise3D(x - 1, y, z, seed) + PerlinNoise3D(x, y + 1, z, seed); corners += PerlinNoise3D(x, y - 1, z, seed) + PerlinNoise3D(x, y, z + 1, seed) + PerlinNoise3D(x, y, z - 1, seed); corners /= 16; // 000 double center = PerlinNoise3D(x, y, z, seed) / 8; return corners + sides + center; } } public static class WorldGenConst { public static int NOISE_MAGIC_X = 1619; public static int NOISE_MAGIC_Y = 31337; public static int NOISE_MAGIC_Z = 52591; public static int NOISE_MAGIC_SEED = 1013; } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; namespace LF2.IDE { public partial class FormTransparencyTools : Form { MainForm mainForm; public FormTransparencyTools(string path, MainForm main) { InitializeComponent(); mainForm = main; Bitmap img = HelperTools.GetClonedBitmap(path); bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppRgb); using (Graphics g = Graphics.FromImage(bmp)) g.DrawImage(img, new Rectangle(0, 0, img.Width, img.Height)); original = (Bitmap)bmp.Clone(); this.path = path; } readonly Bitmap original; Bitmap bmp; string path; public bool[,] texture { get { return FormTextureEditor.Texture; } set { FormTextureEditor.Texture = value; } } void FormTransparentLoad(object sender, EventArgs e) { pictureBoxOriginal.Image = original; pictureBoxModified.Image = (Image)bmp.Clone(); hScrollBarO.Maximum = Math.Max(0, pictureBoxOriginal.Width - panelOriginal.Width); vScrollBarO.Maximum = Math.Max(0, pictureBoxOriginal.Height - panelOriginal.Height); hScrollBarM.Maximum = Math.Max(0, pictureBoxModified.Width - panelModified.Width); vScrollBarM.Maximum = Math.Max(0, pictureBoxModified.Height - panelModified.Height); Bitmap bits = new Bitmap(texture.GetLength(0), texture.GetLength(1)); for (int i = 0; i < bits.Width; i++) { for (int j = 0; j < bits.Height; j++) { bits.SetPixel(i, j, texture[i, j] ? Color.Black : Color.White); } } pictureBoxTexture.BackgroundImage = bits; VerticalDraw(); HorizontalDraw(); } void PanelOriginalResize(object sender, EventArgs e) { hScrollBarO.Maximum = Math.Max(0, pictureBoxOriginal.Width - panelOriginal.Width); vScrollBarO.Maximum = Math.Max(0, pictureBoxOriginal.Height - panelOriginal.Height); hScrollBarO.Value = vScrollBarO.Value = 0; } void PanelModifiedResize(object sender, EventArgs e) { hScrollBarM.Maximum = Math.Max(0, pictureBoxModified.Width - panelModified.Width); vScrollBarM.Maximum = Math.Max(0, pictureBoxModified.Height - panelModified.Height); hScrollBarM.Value = vScrollBarO.Value = 0; } void HScrollBarOValueChanged(object sender, EventArgs e) { pictureBoxOriginal.Left = -hScrollBarO.Value; } void VScrollBarOValueChanged(object sender, EventArgs e) { pictureBoxOriginal.Top = -vScrollBarO.Value; } void HScrollBarMValueChanged(object sender, EventArgs e) { pictureBoxModified.Left = -hScrollBarM.Value; } void VScrollBarMValueChanged(object sender, EventArgs e) { pictureBoxModified.Top = -vScrollBarM.Value; } void ButtonPxApplyClick(object sender, EventArgs e) { bool rewrite = checkBoxPxRewrite.Checked; bool even = checkBoxPxEven.Checked; int percent = (int)numericUpDownPxProper.Value; int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); switch (percent) { case 0: for (int i = x; i < r; i++) { for (int j = y; j < b; j++) { if (rewrite) bmp.SetPixel(i, j, original.GetPixel(i, j)); } } break; case 25: for (int i = x; i < r; i++) { for (int j = y; j < b; j++) { if (even ? (i % 2 == 0 && j % 2 == 0) : (i % 2 == 1 && j % 2 == 1)) bmp.SetPixel(i, j, Color.Black); else if (rewrite) bmp.SetPixel(i, j, original.GetPixel(i, j)); } } break; case 50: for (int i = x, k = 0; i < r; i++, k++) { for (int j = y, l = 0; j < b; j++, l++) { if (even ? ((k + l) % 2 == 0) : ((k + l) % 2 == 1)) bmp.SetPixel(i, j, Color.Black); else if (rewrite) bmp.SetPixel(i, j, original.GetPixel(i, j)); } } break; case 75: for (int i = pictureBoxOriginal.Rectangle.X; i < r; i++) { for (int j = pictureBoxOriginal.Rectangle.Y; j < b; j++) { if (even ? (i % 2 == 0 || j % 2 == 0) : (i % 2 == 1 || j % 2 == 1)) bmp.SetPixel(i, j, Color.Black); else if (rewrite) bmp.SetPixel(i, j, original.GetPixel(i, j)); } } break; case 100: for (int i = x; i < r; i++) { for (int j = y; j < b; j++) { bmp.SetPixel(i, j, Color.Black); } } break; } pictureBoxModified.Image = (Image)bmp.Clone(); numericUpDownPxProper.Focus(); } void ButtonPxRandClick(object sender, EventArgs e) { bool rewrite = checkBoxPxRewrite.Checked; double percent = (double)numericUpDownPxRand.Value / 100d; Random rand = new Random(); int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); for (int i = x; i < r; i++) { for (int j = y; j < b; j++) { if (rand.NextDouble() <= percent) bmp.SetPixel(i, j, Color.Black); else if (rewrite) bmp.SetPixel(i, j, original.GetPixel(i, j)); } } pictureBoxModified.Image = (Image)bmp.Clone(); numericUpDownPxRand.Focus(); } static FormTextureEditor bitEditor = null; void ButtonEditTextureClick(object sender, EventArgs e) { if (bitEditor == null || bitEditor.IsDisposed) bitEditor = new FormTextureEditor(pictureBoxTexture, mainForm); if (bitEditor.Visible) bitEditor.Hide(); bitEditor.Show(this); } void ButtonTextureClick(object sender, EventArgs e) { bool rewrite = checkBoxTxRewrite.Checked; int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); for (int i = x; i < r; i++) { for (int j = y; j < b; j++) { if (checkBoxTxIndex.Checked && texture[i % texture.GetLength(0), j % texture.GetLength(1)] || !checkBoxTxIndex.Checked && texture[(i - x) % texture.Length, (j - y) % texture.GetLength(0)]) bmp.SetPixel(i, j, Color.Black); else if (rewrite) bmp.SetPixel(i, j, original.GetPixel(i, j)); } } pictureBoxModified.Image = (Image)bmp.Clone(); } void ButtonSelectAllClick(object sender, EventArgs e) { pictureBoxOriginal.Rectangle = new Rectangle(Point.Empty, original.Size); } void ButtonScrollRClick(object sender, EventArgs e) { pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.Right + 1, pictureBoxOriginal.Rectangle.Y, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); } void ButtonScrollLClick(object sender, EventArgs e) { pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X - pictureBoxOriginal.Rectangle.Width - 1, pictureBoxOriginal.Rectangle.Y, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); } void ButtonScrollDClick(object sender, EventArgs e) { pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X, pictureBoxOriginal.Rectangle.Bottom + 1, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); } void ButtonScrollUClick(object sender, EventArgs e) { pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X, pictureBoxOriginal.Rectangle.Y - pictureBoxOriginal.Rectangle.Height - 1, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); } void FormTransparentKeyDown(object sender, KeyEventArgs e) { bool handled = true; switch (e.KeyData) { case Keys.W: buttonScrollU.PerformClick(); break; case Keys.S: buttonScrollD.PerformClick(); break; case Keys.D: buttonScrollR.PerformClick(); break; case Keys.A: buttonScrollL.PerformClick(); break; case Keys.T: ScrollVertical(false); break; case Keys.G: ScrollVertical(true); break; case Keys.H: ScrollHorizontal(true); break; case Keys.F: ScrollHorizontal(false); break; default: handled = false; break; } e.Handled = e.SuppressKeyPress = handled; } void ScrollHorizontal(bool right) { if (right) pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X + 1, pictureBoxOriginal.Rectangle.Y, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); else pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X - 1, pictureBoxOriginal.Rectangle.Y, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); } void ScrollVertical(bool down) { if (down) pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X, pictureBoxOriginal.Rectangle.Y + 1, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); else pictureBoxOriginal.Rectangle = new Rectangle(pictureBoxOriginal.Rectangle.X, pictureBoxOriginal.Rectangle.Y - 1, pictureBoxOriginal.Rectangle.Width, pictureBoxOriginal.Rectangle.Height); } void ButtonSaveClick(object sender, EventArgs e) { FormImageSaver saver = new FormImageSaver(bmp, path, false, mainForm); saver.ShowDialog(); } void VLdraw(object sender, EventArgs e) { VerticalDraw(); } void HLdraw(object sender, EventArgs e) { HorizontalDraw(); } void VerticalDraw() { int w = (int)(numericUpDownVLBlackW.Value + numericUpDownVLWhiteW.Value); Bitmap image = new Bitmap(w, 1); if (checkBoxVLBlackFirst.Checked) { for (int i = 0; i < numericUpDownVLBlackW.Value; i++) image.SetPixel(i, 0, Color.Black); for (int i = 0; i < numericUpDownVLWhiteW.Value; i++) image.SetPixel((int)(i + numericUpDownVLBlackW.Value), 0, Color.White); } else { for (int i = 0; i < numericUpDownVLWhiteW.Value; i++) image.SetPixel(i, 0, Color.White); for (int i = 0; i < numericUpDownVLBlackW.Value; i++) image.SetPixel((int)(i + numericUpDownVLWhiteW.Value), 0, Color.Black); } pictureBoxVL.BackgroundImage = image; } void HorizontalDraw() { int h = (int)(numericUpDownHLBlackW.Value + numericUpDownHLWhiteW.Value); Bitmap image = new Bitmap(1, h); if (checkBoxHLBlackFirst.Checked) { for (int i = 0; i < numericUpDownHLBlackW.Value; i++) image.SetPixel(0, i, Color.Black); for (int i = 0; i < numericUpDownHLWhiteW.Value; i++) image.SetPixel(0, (int)(i + numericUpDownHLBlackW.Value), Color.White); } else { for (int i = 0; i < numericUpDownHLWhiteW.Value; i++) image.SetPixel(0, i, Color.White); for (int i = 0; i < numericUpDownHLBlackW.Value; i++) image.SetPixel(0, (int)(i + numericUpDownHLWhiteW.Value), Color.Black); } pictureBoxHL.BackgroundImage = image; } void ButtonVLApplyClick(object sender, EventArgs e) { bool rewrite = checkBoxVLRewrite.Checked; int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); int black = (int)numericUpDownVLBlackW.Value, color = (int)numericUpDownVLWhiteW.Value; int w = black + color; for (int i = y; i < b; i++) { for (int j = x; j < r; j += w) { if (checkBoxVLBlackFirst.Checked) { for (int k = j; k < black + j && k < r; k++) bmp.SetPixel(k, i, Color.Black); if (rewrite) { for (int l = j + black; l < w + j && l < r; l++) bmp.SetPixel(l, i, original.GetPixel(l, i)); } } else { if (rewrite) { for (int l = j; l < color + j && l < r; l++) bmp.SetPixel(l, i, original.GetPixel(l, i)); } for (int k = j + color; k < w + j && k < r; k++) bmp.SetPixel(k, i, Color.Black); } } } pictureBoxModified.Image = (Image)bmp.Clone(); } void ButtonHLApplyClick(object sender, EventArgs e) { bool rewrite = checkBoxHLRewrite.Checked; int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); int black = (int)numericUpDownHLBlackW.Value, color = (int)numericUpDownHLWhiteW.Value; int h = black + color; for (int i = x; i < r; i++) { for (int j = y; j < b; j += h) { if (checkBoxHLBlackFirst.Checked) { for (int k = j; k < black + j && k < b; k++) bmp.SetPixel(i, k, Color.Black); if (rewrite) { for (int l = j + black; l < h + j && l < b; l++) bmp.SetPixel(i, l, original.GetPixel(i, l)); } } else { if (rewrite) { for (int l = j; l < color + j && l < b; l++) bmp.SetPixel(i, l, original.GetPixel(i, l)); } for (int k = j + color; k < h + j && k < b; k++) bmp.SetPixel(i, k, Color.Black); } } } pictureBoxModified.Image = (Image)bmp.Clone(); } void ButtonVLRandApplyClick(object sender, EventArgs e) { bool rewrite = checkBoxVLRewrite.Checked; double d = ((double)numericUpDownVLRand.Value) / 100d; int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); Random rnd = new Random(); using (Graphics g = Graphics.FromImage(bmp)) { for (int i = x; i < r; i++) { if (rnd.NextDouble() <= d) { g.DrawLine(Pens.Black, i, y, i, b); } else { if (rewrite) { for (int j = y; j < b; j++) { bmp.SetPixel(i, j, original.GetPixel(i, j)); } } } } } pictureBoxModified.Image = (Bitmap)bmp.Clone(); } void ButtonHLRandApplyClick(object sender, EventArgs e) { bool rewrite = checkBoxHLRewrite.Checked; double d = ((double)numericUpDownHLRand.Value) / 100d; int x = Math.Max(0, pictureBoxOriginal.Rectangle.X), y = Math.Max(0, pictureBoxOriginal.Rectangle.Y), r = Math.Min(pictureBoxOriginal.Rectangle.Right, bmp.Width), b = Math.Min(pictureBoxOriginal.Rectangle.Bottom, bmp.Height); Random rnd = new Random(); using (Graphics g = Graphics.FromImage(bmp)) { for (int i = y; i < b; i++) { if (rnd.NextDouble() <= d) { g.DrawLine(Pens.Black, x, i, r, i); } else { if (rewrite) { for (int j = x; j < r; j++) { bmp.SetPixel(j, i, original.GetPixel(j, i)); } } } } } pictureBoxModified.Image = (Bitmap)bmp.Clone(); } bool editing = false; private int editingLevel = 0; public void EditIn() { editingLevel++; editing = editingLevel > 0; } public void EditOut() { editingLevel--; editing = editingLevel > 0; } void BoundTextChanged(object sender, EventArgs e) { if (editing) return; try { pictureBoxOriginal.Rectangle = new Rectangle(int.Parse(xBox.Text), int.Parse(yBox.Text), int.Parse(wBox.Text), int.Parse(hBox.Text)); } catch { } } void PictureBoxOriginalRectangleChanged(object sender, EventArgs e) { EditIn(); try { xBox.Text = pictureBoxOriginal.Rectangle.X.ToString(); yBox.Text = pictureBoxOriginal.Rectangle.Y.ToString(); wBox.Text = pictureBoxOriginal.Rectangle.Width.ToString(); hBox.Text = pictureBoxOriginal.Rectangle.Height.ToString(); rightBox.Text = pictureBoxOriginal.Rectangle.Right.ToString(); bottomBox.Text = pictureBoxOriginal.Rectangle.Bottom.ToString(); xBox.Refresh(); yBox.Refresh(); wBox.Refresh(); hBox.Refresh(); rightBox.Refresh(); bottomBox.Refresh(); } finally { EditOut(); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/12/2009 11:39:36 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { public class AzimuthalEquidistant : EllipticalTransform { #region Private Variables private const double TOL = 1E-14; private double _cosph0; private double[] _en; private double _g; private double _he; private bool _isGuam; private double _m1; private Modes _mode; private double _mp; private double _n1; private double _sinph0; #endregion #region Constructors /// <summary> /// Creates a new instance of AzimuthalEquidistant /// </summary> public AzimuthalEquidistant() { Proj4Name = "aeqd"; Name = "Azimuthal_Equidistant"; } #endregion #region Methods /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { Phi0 = projInfo.Phi0; if (Math.Abs(Math.Abs(Phi0) - HALF_PI) < EPS10) { _mode = Phi0 < 0 ? Modes.SouthPole : Modes.NorthPole; _sinph0 = Phi0 < 0 ? -1 : 1; _cosph0 = 0; } else if (Math.Abs(Phi0) < EPS10) { _mode = Modes.Equitorial; _sinph0 = 0; _cosph0 = 1; } else { _mode = Modes.Oblique; _sinph0 = Math.Sin(Phi0); _cosph0 = Math.Cos(Phi0); } if (Es == 0) return; _en = Proj.Enfn(Es); if (projInfo.guam.HasValue && projInfo.guam.Value) { _m1 = Proj.Mlfn(Phi0, _sinph0, _cosph0, _en); _isGuam = true; } else { switch (_mode) { case Modes.NorthPole: _mp = Proj.Mlfn(HALF_PI, 1, 0, _en); break; case Modes.SouthPole: _mp = Proj.Mlfn(-HALF_PI, -1, 0, _en); break; case Modes.Equitorial: case Modes.Oblique: _n1 = 1 / Math.Sqrt(1 - Es * _sinph0 * _sinph0); _g = _sinph0 * (_he = E / Math.Sqrt(OneEs)); _he *= _cosph0; break; } } } /// <inheritdoc /> protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinphi = Math.Sin(lp[phi]); double cosphi = Math.Cos(lp[phi]); double coslam = Math.Cos(lp[lam]); switch (_mode) { case Modes.Equitorial: case Modes.Oblique: if (_mode == Modes.Equitorial) { xy[y] = cosphi * coslam; } else { xy[y] = _sinph0 * sinphi + _cosph0 * cosphi * coslam; } if (Math.Abs(Math.Abs(xy[y]) - 1) < TOL) { if (xy[y] < 0) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[x] = xy[y] = 0; } else { xy[y] = Math.Acos(xy[y]); xy[y] /= Math.Sin(xy[y]); xy[x] = xy[y] * cosphi * Math.Sin(lp[lam]); xy[y] *= (_mode == Modes.Equitorial) ? sinphi : _cosph0 * sinphi - _sinph0 * cosphi * coslam; } break; case Modes.NorthPole: case Modes.SouthPole: if (_mode == Modes.NorthPole) { lp[phi] = -lp[phi]; coslam = -coslam; } if (Math.Abs(lp[phi] - HALF_PI) < EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[x] = (xy[y] = (HALF_PI + lp[phi])) * Math.Sin(lp[lam]); xy[y] *= coslam; break; } } } /// <inheritdoc /> protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints) { if (_isGuam) { GuamForward(lp, xy, startIndex, numPoints); return; } for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double coslam = Math.Cos(lp[lam]); double cosphi = Math.Cos(lp[phi]); double sinphi = Math.Sin(lp[phi]); switch (_mode) { case Modes.NorthPole: case Modes.SouthPole: if (_mode == Modes.NorthPole) coslam = -coslam; double rho; xy[x] = (rho = Math.Abs(_mp - Proj.Mlfn(lp[phi], sinphi, cosphi, _en))) * Math.Sin(lp[lam]); xy[y] = rho * coslam; break; case Modes.Equitorial: case Modes.Oblique: if (Math.Abs(lp[lam]) < EPS10 && Math.Abs(lp[phi] - Phi0) < EPS10) { xy[x] = xy[y] = 0; break; } double t = Math.Atan2(OneEs * sinphi + Es * _n1 * _sinph0 * Math.Sqrt(1 - Es * sinphi * sinphi), cosphi); double ct = Math.Cos(t); double st = Math.Sin(t); double az = Math.Atan2(Math.Sin(lp[lam]) * ct, _cosph0 * st - _sinph0 * coslam * ct); double cA = Math.Cos(az); double sA = Math.Sin(az); double s = Math.Asin(Math.Abs(sA) < TOL ? (_cosph0 * st - _sinph0 * coslam * ct) / cA : Math.Sin(lp[lam]) * ct / sA); double h = _he * cA; double h2 = h * h; double c = _n1 * s * (1 + s * s * (-h2 * (1 - h2) / 6 + s * (_g * h * (1 - 2 * h2 * h2) / 8 + s * ((h2 * (4 - 7 * h2) - 3 * _g * _g * (1 - 7 * h2)) / 120 - s * _g * h / 48)))); xy[x] = c * sA; xy[y] = c * cA; break; } } } private void GuamForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cosphi = Math.Cos(lp[phi]); double sinphi = Math.Sin(lp[phi]); double t = 1 / Math.Sqrt(1 - Es * sinphi * sinphi); xy[x] = lp[lam] * cosphi * t; xy[y] = Proj.Mlfn(lp[phi], sinphi, cosphi, _en) - _m1 + .5 * lp[lam] * lp[lam] * cosphi * sinphi * t; } } /// <inheritdoc /> protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cRh; if ((cRh = Proj.Hypot(xy[x], xy[y])) > Math.PI) { if (cRh - EPS10 > Math.PI) { lp[phi] = double.NaN; lp[lam] = double.NaN; continue; } cRh = Math.PI; } else if (cRh < EPS10) { lp[phi] = Phi0; lp[lam] = 0; continue; } if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { double sinc = Math.Sin(cRh); double cosc = Math.Cos(cRh); if (_mode == Modes.Equitorial) { lp[phi] = Proj.Aasin(xy[y] * sinc / cRh); xy[x] *= sinc; xy[y] = cosc * cRh; } else { lp[phi] = Proj.Aasin(cosc * _sinph0 + xy[y] * sinc * _cosph0 / cRh); xy[y] = (cosc - _sinph0 * Math.Sin(lp[phi])) * cRh; xy[x] *= sinc * _cosph0; } lp[lam] = xy[y] == 0 ? 0 : Math.Atan2(xy[x], xy[y]); } else if (_mode == Modes.NorthPole) { lp[phi] = HALF_PI - cRh; lp[lam] = Math.Atan2(xy[x], -xy[y]); } else { lp[phi] = cRh - HALF_PI; lp[lam] = Math.Atan2(xy[x], xy[y]); } } } /// <inheritdoc /> protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { if (_isGuam) { GuamInverse(xy, lp, startIndex, numPoints); } for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double c; if ((c = Proj.Hypot(xy[x], xy[y])) < EPS10) { lp[phi] = Phi0; lp[lam] = 0; continue; } if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { double az; double cosAz = Math.Cos(az = Math.Atan2(xy[x], xy[y])); double t = _cosph0 * cosAz; double b = Es * t / OneEs; double a = -b * t; b *= 3 * (1 - a) * _sinph0; double d = c / _n1; double e = d * (1 - d * d * (a * (1 + a) / 6 + b * (1 + 3 * a) * d / 24)); double f = 1 - e * e * (a / 2 + b * e / 6); double psi = Proj.Aasin(_sinph0 * Math.Cos(e) + t * Math.Sin(e)); lp[lam] = Proj.Aasin(Math.Sin(az) * Math.Sin(e) / Math.Cos(psi)); if ((t = Math.Abs(psi)) < EPS10) lp[phi] = 0; else if (Math.Abs(t - HALF_PI) < 0) lp[phi] = HALF_PI; else { lp[phi] = Math.Atan((1 - Es * f * _sinph0 / Math.Sin(psi)) * Math.Tan(psi) / OneEs); } } else { /* Polar */ lp[phi] = Proj.InvMlfn(_mode == Modes.NorthPole ? _mp - c : _mp + c, Es, _en); lp[lam] = Math.Atan2(xy[x], _mode == Modes.NorthPole ? -xy[y] : xy[y]); } } } private void GuamInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double t = 0; int j; double x2 = 0.5 * xy[x] * xy[x]; lp[phi] = Phi0; for (j = 0; j < 3; ++j) { t = E * Math.Sin(lp[phi]); lp[phi] = Proj.InvMlfn(_m1 + xy[y] - x2 * Math.Tan(lp[phi]) * (t = Math.Sqrt(1 - t * t)), Es, _en); } lp[lam] = xy[x] * t / Math.Cos(lp[phi]); } } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvc = Google.Ads.GoogleAds.V8.Common; using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCustomerFeedServiceClientTest { [Category("Autogenerated")][Test] public void GetCustomerFeedRequestObject() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); GetCustomerFeedRequest request = new GetCustomerFeedRequest { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::CustomerFeed expectedResponse = new gagvr::CustomerFeed { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), PlaceholderTypes = { gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer, }, MatchingFunction = new gagvc::MatchingFunction(), Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled, FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetCustomerFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerFeed response = client.GetCustomerFeed(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerFeedRequestObjectAsync() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); GetCustomerFeedRequest request = new GetCustomerFeedRequest { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::CustomerFeed expectedResponse = new gagvr::CustomerFeed { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), PlaceholderTypes = { gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer, }, MatchingFunction = new gagvc::MatchingFunction(), Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled, FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetCustomerFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerFeed>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerFeed responseCallSettings = await client.GetCustomerFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerFeed responseCancellationToken = await client.GetCustomerFeedAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerFeed() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); GetCustomerFeedRequest request = new GetCustomerFeedRequest { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::CustomerFeed expectedResponse = new gagvr::CustomerFeed { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), PlaceholderTypes = { gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer, }, MatchingFunction = new gagvc::MatchingFunction(), Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled, FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetCustomerFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerFeed response = client.GetCustomerFeed(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerFeedAsync() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); GetCustomerFeedRequest request = new GetCustomerFeedRequest { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::CustomerFeed expectedResponse = new gagvr::CustomerFeed { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), PlaceholderTypes = { gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer, }, MatchingFunction = new gagvc::MatchingFunction(), Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled, FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetCustomerFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerFeed>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerFeed responseCallSettings = await client.GetCustomerFeedAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerFeed responseCancellationToken = await client.GetCustomerFeedAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCustomerFeedResourceNames() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); GetCustomerFeedRequest request = new GetCustomerFeedRequest { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::CustomerFeed expectedResponse = new gagvr::CustomerFeed { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), PlaceholderTypes = { gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer, }, MatchingFunction = new gagvc::MatchingFunction(), Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled, FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetCustomerFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerFeed response = client.GetCustomerFeed(request.ResourceNameAsCustomerFeedName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCustomerFeedResourceNamesAsync() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); GetCustomerFeedRequest request = new GetCustomerFeedRequest { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::CustomerFeed expectedResponse = new gagvr::CustomerFeed { ResourceNameAsCustomerFeedName = gagvr::CustomerFeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), PlaceholderTypes = { gagve::PlaceholderTypeEnum.Types.PlaceholderType.AdCustomizer, }, MatchingFunction = new gagvc::MatchingFunction(), Status = gagve::FeedLinkStatusEnum.Types.FeedLinkStatus.Enabled, FeedAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetCustomerFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerFeed>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::CustomerFeed responseCallSettings = await client.GetCustomerFeedAsync(request.ResourceNameAsCustomerFeedName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CustomerFeed responseCancellationToken = await client.GetCustomerFeedAsync(request.ResourceNameAsCustomerFeedName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerFeedsRequestObject() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); MutateCustomerFeedsRequest request = new MutateCustomerFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerFeedOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCustomerFeedsResponse expectedResponse = new MutateCustomerFeedsResponse { Results = { new MutateCustomerFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerFeedsResponse response = client.MutateCustomerFeeds(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerFeedsRequestObjectAsync() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); MutateCustomerFeedsRequest request = new MutateCustomerFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerFeedOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCustomerFeedsResponse expectedResponse = new MutateCustomerFeedsResponse { Results = { new MutateCustomerFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerFeedsResponse responseCallSettings = await client.MutateCustomerFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerFeedsResponse responseCancellationToken = await client.MutateCustomerFeedsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCustomerFeeds() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); MutateCustomerFeedsRequest request = new MutateCustomerFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerFeedOperation(), }, }; MutateCustomerFeedsResponse expectedResponse = new MutateCustomerFeedsResponse { Results = { new MutateCustomerFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerFeedsResponse response = client.MutateCustomerFeeds(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCustomerFeedsAsync() { moq::Mock<CustomerFeedService.CustomerFeedServiceClient> mockGrpcClient = new moq::Mock<CustomerFeedService.CustomerFeedServiceClient>(moq::MockBehavior.Strict); MutateCustomerFeedsRequest request = new MutateCustomerFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CustomerFeedOperation(), }, }; MutateCustomerFeedsResponse expectedResponse = new MutateCustomerFeedsResponse { Results = { new MutateCustomerFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCustomerFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CustomerFeedServiceClient client = new CustomerFeedServiceClientImpl(mockGrpcClient.Object, null); MutateCustomerFeedsResponse responseCallSettings = await client.MutateCustomerFeedsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCustomerFeedsResponse responseCancellationToken = await client.MutateCustomerFeedsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Insights; using Microsoft.Azure.Management.Insights.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Insights { /// <summary> /// Operations for managing service diagnostic settings. /// </summary> internal partial class ServiceDiagnosticSettingsOperations : IServiceOperations<InsightsManagementClient>, IServiceDiagnosticSettingsOperations { /// <summary> /// Initializes a new instance of the /// ServiceDiagnosticSettingsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServiceDiagnosticSettingsOperations(InsightsManagementClient client) { this._client = client; } private InsightsManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Insights.InsightsManagementClient. /// </summary> public InsightsManagementClient Client { get { return this._client; } } /// <summary> /// Deletes the diagnostic settings for the specified resource. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public async Task<EmptyResponse> DeleteAsync(string resourceUri, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/diagnosticSettings/service"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result EmptyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new EmptyResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the active diagnostic settings. To get the diagnostic settings /// being applied, use GetStatus. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<ServiceDiagnosticSettingsGetResponse> GetAsync(string resourceUri, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/diagnosticSettings/service"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceDiagnosticSettingsGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceDiagnosticSettingsGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); result.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); result.Location = locationInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServiceDiagnosticSettings propertiesInstance = new ServiceDiagnosticSettings(); result.Properties = propertiesInstance; JToken storageAccountNameValue = propertiesValue["storageAccountName"]; if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null) { string storageAccountNameInstance = ((string)storageAccountNameValue); propertiesInstance.StorageAccountName = storageAccountNameInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { DiagnosticSettingsStatus statusInstance = ((DiagnosticSettingsStatus)Enum.Parse(typeof(DiagnosticSettingsStatus), ((string)statusValue), true)); propertiesInstance.Status = statusInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of the diagnostic settings being applied. Once it /// is successfull, it will replace the current diagnostic settings. /// To get the active one, use Get. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<ServiceDiagnosticSettingsGetResponse> GetStatusAsync(string resourceUri, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); TracingAdapter.Enter(invocationId, this, "GetStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/diagnosticSettings/service/poll"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceDiagnosticSettingsGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceDiagnosticSettingsGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); result.Name = nameInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); result.Location = locationInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServiceDiagnosticSettings propertiesInstance = new ServiceDiagnosticSettings(); result.Properties = propertiesInstance; JToken storageAccountNameValue = propertiesValue["storageAccountName"]; if (storageAccountNameValue != null && storageAccountNameValue.Type != JTokenType.Null) { string storageAccountNameInstance = ((string)storageAccountNameValue); propertiesInstance.StorageAccountName = storageAccountNameInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { DiagnosticSettingsStatus statusInstance = ((DiagnosticSettingsStatus)Enum.Parse(typeof(DiagnosticSettingsStatus), ((string)statusValue), true)); propertiesInstance.Status = statusInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update new diagnostic settings for the specified /// resource. This operation is long running. Use GetStatus to check /// the status of this operation. /// </summary> /// <param name='resourceUri'> /// Required. The resource identifier of the configuration. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Generic empty response. We only pass it to ensure json error /// handling /// </returns> public async Task<EmptyResponse> PutAsync(string resourceUri, ServiceDiagnosticSettingsPutParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceUri == null) { throw new ArgumentNullException("resourceUri"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "PutAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; url = url + Uri.EscapeDataString(resourceUri); url = url + "/diagnosticSettings/service"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serviceDiagnosticSettingsPutParametersValue = new JObject(); requestDoc = serviceDiagnosticSettingsPutParametersValue; if (parameters.Properties != null) { JObject propertiesValue = new JObject(); serviceDiagnosticSettingsPutParametersValue["properties"] = propertiesValue; if (parameters.Properties.StorageAccountName != null) { propertiesValue["storageAccountName"] = parameters.Properties.StorageAccountName; } propertiesValue["status"] = parameters.Properties.Status.ToString(); } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result EmptyResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new EmptyResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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.IO; using System.Net.Security; using System.Net.Sockets; using System.Net.Test.Common; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.NetFramework, "netfx: dotnet/corefx #16805, uap: dotnet/corefx #20010")] public partial class HttpClientHandler_SslProtocols_Test { [Fact] public void DefaultProtocols_MatchesExpected() { using (var handler = new HttpClientHandler()) { Assert.Equal(SslProtocols.None, handler.SslProtocols); } } [Theory] [InlineData(SslProtocols.None)] [InlineData(SslProtocols.Tls)] [InlineData(SslProtocols.Tls11)] [InlineData(SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11)] [InlineData(SslProtocols.Tls11 | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls12)] [InlineData(SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)] public void SetGetProtocols_Roundtrips(SslProtocols protocols) { using (var handler = new HttpClientHandler()) { handler.SslProtocols = protocols; Assert.Equal(protocols, handler.SslProtocols); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsSslConfiguration))] public async Task SetProtocols_AfterRequest_ThrowsException() { using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server), client.GetAsync(url)); }); Assert.Throws<InvalidOperationException>(() => handler.SslProtocols = SslProtocols.Tls12); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(~SslProtocols.None)] #pragma warning disable 0618 // obsolete warning [InlineData(SslProtocols.Ssl2)] [InlineData(SslProtocols.Ssl3)] [InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3)] [InlineData(SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12)] #pragma warning restore 0618 public void DisabledProtocols_SetSslProtocols_ThrowsException(SslProtocols disabledProtocols) { using (var handler = new HttpClientHandler()) { Assert.Throws<NotSupportedException>(() => handler.SslProtocols = disabledProtocols); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(BackendSupportsSslConfiguration))] [InlineData(SslProtocols.Tls, false)] [InlineData(SslProtocols.Tls, true)] [InlineData(SslProtocols.Tls11, false)] [InlineData(SslProtocols.Tls11, true)] [InlineData(SslProtocols.Tls12, false)] [InlineData(SslProtocols.Tls12, true)] public async Task GetAsync_AllowedSSLVersion_Succeeds(SslProtocols acceptedProtocol, bool requestOnlyThisProtocol) { using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { if (requestOnlyThisProtocol) { handler.SslProtocols = acceptedProtocol; } var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } public static readonly object [][] SupportedSSLVersionServers = { new object[] {SslProtocols.Tls, Configuration.Http.TLSv10RemoteServer}, new object[] {SslProtocols.Tls11, Configuration.Http.TLSv11RemoteServer}, new object[] {SslProtocols.Tls12, Configuration.Http.TLSv12RemoteServer}, }; // This test is logically the same as the above test, albeit using remote servers // instead of local ones. We're keeping it for now (as outerloop) because it helps // to validate against another SSL implementation that what we mean by a particular // TLS version matches that other implementation. [OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")] [Theory] [MemberData(nameof(SupportedSSLVersionServers))] public async Task GetAsync_SupportedSSLVersion_Succeeds(SslProtocols sslProtocols, string url) { using (HttpClientHandler handler = new HttpClientHandler()) { if (PlatformDetection.IsCentos7) { // Default protocol selection is always TLSv1 on Centos7 libcurl 7.29.0 // Hence, set the specific protocol on HttpClient that is required by test handler.SslProtocols = sslProtocols; } using (var client = new HttpClient(handler)) { (await client.GetAsync(url)).Dispose(); } } } public static readonly object[][] NotSupportedSSLVersionServers = { new object[] {"SSLv2", Configuration.Http.SSLv2RemoteServer}, new object[] {"SSLv3", Configuration.Http.SSLv3RemoteServer}, }; // It would be easy to remove the dependency on these remote servers if we didn't // explicitly disallow creating SslStream with SSLv2/3. Since we explicitly throw // when trying to use such an SslStream, we can't stand up a localhost server that // only speaks those protocols. [OuterLoop("Avoid www.ssllabs.com dependency in innerloop.")] [ConditionalTheory(nameof(SSLv3DisabledByDefault))] [MemberData(nameof(NotSupportedSSLVersionServers))] public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url) { using (var client = new HttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [OuterLoop] // TODO: Issue #11345 [ConditionalFact(nameof(BackendSupportsSslConfiguration), nameof(SslDefaultsToTls12))] public async Task GetAsync_NoSpecifiedProtocol_DefaultsToTls12() { using (var handler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( client.GetAsync(url), LoopbackServer.AcceptSocketAsync(server, async (s, stream, reader, writer) => { Assert.Equal(SslProtocols.Tls12, Assert.IsType<SslStream>(stream).SslProtocol); await LoopbackServer.ReadWriteAcceptedAsync(s, reader, writer); return null; }, options)); }, options); } } [OuterLoop] // TODO: Issue #11345 [ConditionalTheory(nameof(BackendSupportsSslConfiguration))] [InlineData(SslProtocols.Tls11, SslProtocols.Tls, typeof(IOException))] [InlineData(SslProtocols.Tls12, SslProtocols.Tls11, typeof(IOException))] [InlineData(SslProtocols.Tls, SslProtocols.Tls12, typeof(AuthenticationException))] public async Task GetAsync_AllowedSSLVersionDiffersFromServer_ThrowsException( SslProtocols allowedProtocol, SslProtocols acceptedProtocol, Type exceptedServerException) { using (var handler = new HttpClientHandler() { SslProtocols = allowedProtocol, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { var options = new LoopbackServer.Options { UseSsl = true, SslProtocols = acceptedProtocol }; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( Assert.ThrowsAsync(exceptedServerException, () => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)), Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url))); }, options); } } [OuterLoop] // TODO: Issue #11345 [ActiveIssue(8538, TestPlatforms.Windows)] [Fact] public async Task GetAsync_DisallowTls10_AllowTls11_AllowTls12() { using (var handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls11 | SslProtocols.Tls12, ServerCertificateCustomValidationCallback = LoopbackServer.AllowAllCertificates }) using (var client = new HttpClient(handler)) { if (BackendSupportsSslConfiguration) { LoopbackServer.Options options = new LoopbackServer.Options { UseSsl = true }; options.SslProtocols = SslProtocols.Tls; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( Assert.ThrowsAsync<IOException>(() => LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options)), Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url))); }, options); foreach (var prot in new[] { SslProtocols.Tls11, SslProtocols.Tls12 }) { options.SslProtocols = prot; await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( LoopbackServer.ReadRequestAndSendResponseAsync(server, options: options), client.GetAsync(url)); }, options); } } else { await Assert.ThrowsAnyAsync<NotSupportedException>(() => client.GetAsync($"http://{Guid.NewGuid().ToString()}/")); } } } private static bool SslDefaultsToTls12 => !PlatformDetection.IsWindows7; // TLS 1.2 may not be enabled on Win7 // https://technet.microsoft.com/en-us/library/dn786418.aspx#BKMK_SchannelTR_TLS12 } }
using System; using System.IO; using System.Windows.Forms; namespace UPnPStackBuilder { /// <summary> /// Summary description for SourceCodeRepository. /// </summary> public class SourceCodeRepository { #region EULA // -=S3P4R470R=- {EULA} // -=S3P4R470R=- {EULA} #endregion #region UPnPMicroStack.c // -=S3P4R470R=- {UPnPMicroStack_C} // -=S3P4R470R=- {UPnPMicroStack_C} #endregion #region UPnPMicroStack.h // -=S3P4R470R=- {UPnPMicroStack_H} // -=S3P4R470R=- {UPnPMicroStack_H} #endregion #region ILibParsers.c // -=S3P4R470R=- {ILibParsers_C} // -=S3P4R470R=- {ILibParsers_C} #endregion #region ILibParsers.h // -=S3P4R470R=- {ILibParsers_H} // -=S3P4R470R=- {ILibParsers_H} #endregion #region ILibAsyncSocket.c // -=S3P4R470R=- {ILibAsyncSocket_C} // -=S3P4R470R=- {ILibAsyncSocket_C} #endregion #region ILibAsyncSocket.h // -=S3P4R470R=- {ILibAsyncSocket_H} // -=S3P4R470R=- {ILibAsyncSocket_H} #endregion #region ILibAsyncServerSocket.c // -=S3P4R470R=- {ILibAsyncServerSocket_C} // -=S3P4R470R=- {ILibAsyncServerSocket_C} #endregion #region ILibAsyncServerSocket.h // -=S3P4R470R=- {ILibAsyncServerSocket_H} // -=S3P4R470R=- {ILibAsyncServerSocket_H} #endregion #region ILibWebClient.c // -=S3P4R470R=- {ILibWebClient_C} // -=S3P4R470R=- {ILibWebClient_C} #endregion #region ILibWebClient.h // -=S3P4R470R=- {ILibWebClient_H} // -=S3P4R470R=- {ILibWebClient_H} #endregion #region ILibWebServer.c // -=S3P4R470R=- {ILibWebServer_C} // -=S3P4R470R=- {ILibWebServer_C} #endregion #region ILibWebServer.h // -=S3P4R470R=- {ILibWebServer_H} // -=S3P4R470R=- {ILibWebServer_H} #endregion #region ILibSSDPClient.c // -=S3P4R470R=- {ILibSSDPClient_C} // -=S3P4R470R=- {ILibSSDPClient_C} #endregion #region ILibSSDPClient.h // -=S3P4R470R=- {ILibSSDPClient_H} // -=S3P4R470R=- {ILibSSDPClient_H} #endregion #region UPnPControlPointStructs.h // -=S3P4R470R=- {UPnPControlPointStructs_H} // -=S3P4R470R=- {UPnPControlPointStructs_H} #endregion public SourceCodeRepository() { } public static string GetMicroStack_C_Template(string PreFix) { return(GetEULA(PreFix+"MicroStack.c","") + RemoveOldEULA(UPnPMicroStack_C)); } public static string GetMicroStack_H_Template(string PreFix) { return(GetEULA(PreFix+"MicroStack.h","") + RemoveOldEULA(UPnPMicroStack_H)); } private static string GetEULA(string FileName, string Settings) { string RetVal = EULA; if(Settings=="") {Settings="*";} RetVal = RetVal.Replace("<REVISION>","#"+Application.ProductVersion); RetVal = RetVal.Replace("<DATE>",DateTime.Now.ToLongDateString()); RetVal = RetVal.Replace("<FILE>",FileName); RetVal = RetVal.Replace("<SETTINGS>",Settings); return(RetVal); } private static string RemoveOldEULA(string InVal) { string RetVal = InVal; RetVal = RetVal.Substring(2+RetVal.IndexOf("*/")); return(RetVal); } public static void Generate_Parsers(string PreFix, DirectoryInfo outputDir) { StreamWriter writer; string lib; lib = GetEULA(PreFix+"Parsers.h","") + RemoveOldEULA(ILibParsers_H); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"Parsers.h"); writer.Write(lib); writer.Close(); lib = GetEULA(PreFix+"Parsers.c","") + RemoveOldEULA(ILibParsers_C); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"Parsers.c"); writer.Write(lib); writer.Close(); } public static void Generate_AsyncSocket(string PreFix, DirectoryInfo outputDir) { StreamWriter writer; string lib; lib = GetEULA(PreFix+"AsyncSocket.h","") + RemoveOldEULA(ILibAsyncSocket_H); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"AsyncSocket.h"); writer.Write(lib); writer.Close(); lib = GetEULA(PreFix+"AsyncSocket.c","") + RemoveOldEULA(ILibAsyncSocket_C); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"AsyncSocket.c"); writer.Write(lib); writer.Close(); } public static void Generate_AsyncServerSocket(string PreFix, DirectoryInfo outputDir) { StreamWriter writer; string lib; lib = GetEULA(PreFix+"AsyncServerSocket.h","") + RemoveOldEULA(ILibAsyncServerSocket_H); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"AsyncServerSocket.h"); writer.Write(lib); writer.Close(); lib = GetEULA(PreFix+"AsyncServerSocket.c","") + RemoveOldEULA(ILibAsyncServerSocket_C); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"AsyncServerSocket.c"); writer.Write(lib); writer.Close(); } public static void Generate_WebClient(string PreFix, DirectoryInfo outputDir, bool Legacy) { StreamWriter writer; string lib; lib = GetEULA(PreFix+"WebClient.h","") + RemoveOldEULA(ILibWebClient_H); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"WebClient.h"); writer.Write(lib); writer.Close(); lib = GetEULA(PreFix+"WebClient.c","") + RemoveOldEULA(ILibWebClient_C); lib = lib.Replace("ILib",PreFix); if(Legacy) { // Remove HTTP/1.1 Specific Code string xx = "//{{{ REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT--> }}}"; string yy = "//{{{ <--REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT }}}"; int ix = lib.IndexOf(xx); int iy; while(ix!=-1) { iy = lib.IndexOf(yy) + yy.Length; lib = lib.Remove(ix,iy-ix); ix = lib.IndexOf(xx); } } writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"WebClient.c"); writer.Write(lib); writer.Close(); } public static void Generate_WebServer(string PreFix, DirectoryInfo outputDir, bool Legacy) { StreamWriter writer; string lib; lib = GetEULA(PreFix+"WebServer.h","") + RemoveOldEULA(ILibWebServer_H); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"WebServer.h"); writer.Write(lib); writer.Close(); lib = GetEULA(PreFix+"WebServer.c","") + "\r\n"; if(Legacy) { lib += "#define HTTPVERSION \"1.0\""; } else { lib += "#define HTTPVERSION \"1.1\""; } lib += RemoveOldEULA(ILibWebServer_C); lib = lib.Replace("ILib",PreFix); if(Legacy) { // Remove HTTP/1.1 Specific Code string xx = "//{{{ REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT--> }}}"; string yy = "//{{{ <--REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT }}}"; int ix = lib.IndexOf(xx); int iy; while(ix!=-1) { iy = lib.IndexOf(yy) + yy.Length; lib = lib.Remove(ix,iy-ix); ix = lib.IndexOf(xx); } } writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"WebServer.c"); writer.Write(lib); writer.Close(); } public static string RemoveAndClearTag(string BeginTag, string EndTag, string data) { // Remove HTTP/1.1 Specific Code int ix = data.IndexOf(BeginTag); int iy; while(ix!=-1) { iy = data.IndexOf(EndTag) + EndTag.Length; data = data.Remove(ix,iy-ix); ix = data.IndexOf(BeginTag); } return(data); } public static string RemoveTag(string BeginTag, string EndTag, string data) { data = data.Replace(BeginTag,""); data = data.Replace(EndTag,""); return(data); } public static void Generate_SSDPClient(string PreFix, DirectoryInfo outputDir) { StreamWriter writer; string lib; lib = GetEULA(PreFix+"SSDPClient.h","") + RemoveOldEULA(ILibSSDPClient_H); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"SSDPClient.h"); writer.Write(lib); writer.Close(); lib = GetEULA(PreFix+"SSDPClient.c","") + RemoveOldEULA(ILibSSDPClient_C); lib = lib.Replace("ILib",PreFix); writer = File.CreateText(outputDir.FullName + "\\"+PreFix+"SSDPClient.c"); writer.Write(lib); writer.Close(); } public static void Generate_UPnPControlPointStructs(string PreFix, string ReplaceText,DirectoryInfo outputDir) { StreamWriter writer; string lib; lib = GetEULA("UPnPControlPointStructs.h","") + RemoveOldEULA(UPnPControlPointStructs_H); lib = lib.Replace("ILib",PreFix); lib = lib.Replace("<REPLACE>",ReplaceText); writer = File.CreateText(outputDir.FullName + "\\UPnPControlPointStructs.h"); writer.Write(lib); writer.Close(); } } }
// // XslNumber.cs // // Authors: // Ben Maurer (bmaurer@users.sourceforge.net) // Atsushi Enomoto (ginga@kit.hi-ho.ne.jp) // // (C) 2003 Ben Maurer // (C) 2003 Atsushi Enomoto // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using System.Text; using Mono.Xml.XPath; namespace Mono.Xml.Xsl.Operations { internal class XslNumber : XslCompiledElement { // <xsl:number // level = "single" | "multiple" | "any" XslNumberingLevel level; // count = pattern Pattern count; // from = pattern Pattern from; // value = number-expression XPathExpression value; // format = { string } XslAvt format; // lang = { nmtoken } XslAvt lang; // letter-value = { "alphabetic" | "traditional" } XslAvt letterValue; // grouping-separator = { char } XslAvt groupingSeparator; // grouping-size = { number } /> XslAvt groupingSize; public XslNumber (Compiler c) : base (c) {} // This behaves differently from Math.Round. For n + 0.5, // Math.Round() truncates, while XSLT expects ceiling. public static double Round (double n) { double f = System.Math.Floor (n); return (n - f >= 0.5) ? f + 1.0 : f; } protected override void Compile (Compiler c) { if (c.Debugger != null) c.Debugger.DebugCompile (this.DebugInput); c.CheckExtraAttributes ("number", "level", "count", "from", "value", "format", "lang", "letter-value", "grouping-separator", "grouping-size"); switch (c.GetAttribute ("level")) { case "single": level = XslNumberingLevel.Single; break; case "multiple": level = XslNumberingLevel.Multiple; break; case "any": level = XslNumberingLevel.Any; break; case null: case "": default: level = XslNumberingLevel.Single; // single == default break; } count = c.CompilePattern (c.GetAttribute ("count"), c.Input); from = c.CompilePattern (c.GetAttribute ("from"), c.Input); value = c.CompileExpression (c.GetAttribute ("value")); format = c.ParseAvtAttribute ("format"); lang = c.ParseAvtAttribute ("lang"); letterValue = c.ParseAvtAttribute ("letter-value"); groupingSeparator = c.ParseAvtAttribute ("grouping-separator"); groupingSize = c.ParseAvtAttribute ("grouping-size"); } public override void Evaluate (XslTransformProcessor p) { if (p.Debugger != null) p.Debugger.DebugExecute (p, this.DebugInput); string formatted = GetFormat (p); if (formatted != String.Empty) p.Out.WriteString (formatted); } XslNumberFormatter GetNumberFormatter (XslTransformProcessor p) { string formatStr = "1"; string lang = null; string letterValue = null; char groupingSeparatorChar = '\0'; decimal groupingSize = 0; if (this.format != null) formatStr = this.format.Evaluate (p); if (this.lang != null) lang = this.lang.Evaluate (p); if (this.letterValue != null) letterValue = this.letterValue.Evaluate (p); if (groupingSeparator != null) groupingSeparatorChar = this.groupingSeparator.Evaluate (p) [0]; if (this.groupingSize != null) groupingSize = decimal.Parse (this.groupingSize.Evaluate (p), CultureInfo.InvariantCulture); //FIXME: Negative test compliency: .NET throws exception on negative grouping-size if (groupingSize > Int32.MaxValue || groupingSize < 1) groupingSize = 0; return new XslNumberFormatter (formatStr, lang, letterValue, groupingSeparatorChar, (int)groupingSize); } string GetFormat (XslTransformProcessor p) { XslNumberFormatter nf = GetNumberFormatter (p); if (this.value != null) { double result = p.EvaluateNumber (this.value); //Do we need to round the result here??? //result = (int) ((result - (int) result >= 0.5) ? result + 1 : result); return nf.Format (result); } switch (this.level) { case XslNumberingLevel.Single: int hit = NumberSingle (p); return nf.Format (hit, hit != 0); case XslNumberingLevel.Multiple: return nf.Format (NumberMultiple (p)); case XslNumberingLevel.Any: hit = NumberAny (p); return nf.Format (hit, hit != 0); default: throw new XsltException ("Should not get here", null, p.CurrentNode); } } int [] NumberMultiple (XslTransformProcessor p) { ArrayList nums = new ArrayList (); XPathNavigator n = p.CurrentNode.Clone (); bool foundFrom = false; do { if (MatchesFrom (n, p)) { foundFrom = true; break; } if (MatchesCount (n, p)) { int i = 1; while (n.MoveToPrevious ()) { if (MatchesCount (n, p)) i++; } nums.Add (i); } } while (n.MoveToParent ()); if (!foundFrom) return new int [0]; int [] ret = new int [nums.Count]; int pos = nums.Count; for (int i = 0; i < nums.Count; i++) ret [--pos] = (int) nums [i]; return ret; } int NumberAny (XslTransformProcessor p) { int i = 0; XPathNavigator n = p.CurrentNode.Clone (); n.MoveToRoot (); bool countable = (from == null); do { if (from != null && MatchesFrom (n, p)) { countable = true; i = 0; } // Here this *else* is important else if (countable && MatchesCount (n, p)) i++; if (n.IsSamePosition (p.CurrentNode)) return i; if (!n.MoveToFirstChild ()) { while (!n.MoveToNext ()) { if (!n.MoveToParent ()) // returned to Root return 0; }; } } while (true); } int NumberSingle (XslTransformProcessor p) { XPathNavigator n = p.CurrentNode.Clone (); while (!MatchesCount (n, p)) { if (from != null && MatchesFrom (n, p)) return 0; if (!n.MoveToParent ()) return 0; } if (from != null) { XPathNavigator tmp = n.Clone (); if (MatchesFrom (tmp, p)) // Was not desc of closest matches from return 0; bool found = false; while (tmp.MoveToParent ()) if (MatchesFrom (tmp, p)) { found = true; break; } if (!found) // not desc of matches from return 0; } int i = 1; while (n.MoveToPrevious ()) { if (MatchesCount (n, p)) i++; } return i; } bool MatchesCount (XPathNavigator item, XslTransformProcessor p) { if (count == null) return item.NodeType == p.CurrentNode.NodeType && item.LocalName == p.CurrentNode.LocalName && item.NamespaceURI == p.CurrentNode.NamespaceURI; else return p.Matches (count, item); } bool MatchesFrom (XPathNavigator item, XslTransformProcessor p) { if (from == null) return item.NodeType == XPathNodeType.Root; else return p.Matches (from, item); } class XslNumberFormatter { string firstSep, lastSep; ArrayList fmtList = new ArrayList (); public XslNumberFormatter (string format, string lang, string letterValue, char groupingSeparator, int groupingSize) { // We dont do any i18n now, so we ignore lang and letterValue. if (format == null || format == "") fmtList.Add (FormatItem.GetItem (null, "1", groupingSeparator, groupingSize)); else { NumberFormatterScanner s = new NumberFormatterScanner (format); string itm; string sep = "."; firstSep = s.Advance (false); itm = s.Advance (true); if (itm == null) { // Only separator is specified sep = firstSep; firstSep = null; fmtList.Add (FormatItem.GetItem (sep, "1", groupingSeparator, groupingSize)); } else { // The first format item. fmtList.Add (FormatItem.GetItem (".", itm, groupingSeparator, groupingSize)); do { sep = s.Advance (false); itm = s.Advance (true); if (itm == null) { lastSep = sep; break; } fmtList.Add (FormatItem.GetItem (sep, itm, groupingSeparator, groupingSize)); } while (itm != null); } } } // return the format for a single value, ie, if using Single or Any public string Format (double value) { return Format (value, true); } public string Format (double value, bool formatContent) { StringBuilder b = new StringBuilder (); if (firstSep != null) b.Append (firstSep); if (formatContent) ((FormatItem)fmtList [0]).Format (b, value); if (lastSep != null) b.Append (lastSep); return b.ToString (); } // format for an array of numbers. public string Format (int [] values) { StringBuilder b = new StringBuilder (); if (firstSep != null) b.Append (firstSep); int formatIndex = 0; int formatMax = fmtList.Count - 1; if (values.Length > 0) { if (fmtList.Count > 0) { FormatItem itm = (FormatItem)fmtList [formatIndex]; itm.Format (b, values [0]); } if (formatIndex < formatMax) formatIndex++; } for (int i = 1; i < values.Length; i++) { FormatItem itm = (FormatItem)fmtList [formatIndex]; b.Append (itm.sep); int v = values [i]; itm.Format (b, v); if (formatIndex < formatMax) formatIndex++; } if (lastSep != null) b.Append (lastSep); return b.ToString (); } class NumberFormatterScanner { int pos = 0, len; string fmt; public NumberFormatterScanner (string fmt) { this.fmt = fmt; len = fmt.Length; } public string Advance (bool alphaNum) { int start = pos; while ((pos < len) && (char.IsLetterOrDigit (fmt, pos) == alphaNum)) pos++; if (pos == start) return null; else return fmt.Substring (start, pos - start); } } abstract class FormatItem { public readonly string sep; public FormatItem (string sep) { this.sep = sep; } public abstract void Format (StringBuilder b, double num); public static FormatItem GetItem (string sep, string item, char gpSep, int gpSize) { switch (item [0]) { default: // See XSLT 1.0 spec 7.7.1. return new DigitItem (sep, 1, gpSep, gpSize); case '0': case '1': int len = 1; for (; len < item.Length; len++) if (!Char.IsDigit (item, len)) break; return new DigitItem (sep, len, gpSep, gpSize); case 'a': return new AlphaItem (sep, false); case 'A': return new AlphaItem (sep, true); case 'i': return new RomanItem (sep, false); case 'I': return new RomanItem (sep, true); } } } class AlphaItem : FormatItem { bool uc; static readonly char [] ucl = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; static readonly char [] lcl = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public AlphaItem (string sep, bool uc) : base (sep) { this.uc = uc; } public override void Format (StringBuilder b, double num) { alphaSeq (b, num, uc ? ucl : lcl); } static void alphaSeq (StringBuilder b, double n, char [] alphabet) { n = XslNumber.Round (n); if (n == 0) return; if (n > alphabet.Length) alphaSeq (b, System.Math.Floor ((n - 1) / alphabet.Length), alphabet); b.Append (alphabet [((int) n - 1) % alphabet.Length]); } } class RomanItem : FormatItem { bool uc; public RomanItem (string sep, bool uc) : base (sep) { this.uc = uc; } static readonly string [] ucrDigits = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; static readonly string [] lcrDigits = { "m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i" }; static readonly int [] decValues = {1000, 900 , 500, 400 , 100, 90 , 50 , 40 , 10 , 9 , 5 , 4 , 1 }; public override void Format (StringBuilder b, double num) { if (num < 1 || num > 4999) { b.Append (num); return; } num = XslNumber.Round (num); for (int i = 0; i < decValues.Length; i++) { while (decValues [i] <= num) { if (uc) b.Append (ucrDigits [i]); else b.Append (lcrDigits [i]); num -= decValues [i]; } if (num == 0) break; } } } class DigitItem : FormatItem { NumberFormatInfo nfi; int decimalSectionLength; StringBuilder numberBuilder; public DigitItem (string sep, int len, char gpSep, int gpSize) : base (sep) { nfi = new NumberFormatInfo (); nfi.NumberDecimalDigits = 0; nfi.NumberGroupSizes = new int [] {0}; if (gpSep != '\0' && gpSize > 0) { // ignored if either of them doesn't exist. nfi.NumberGroupSeparator = gpSep.ToString (); nfi.NumberGroupSizes = new int [] {gpSize}; } decimalSectionLength = len; } public override void Format (StringBuilder b, double num) { string number = num.ToString ("N", nfi); int len = decimalSectionLength; if (len > 1) { if (numberBuilder == null) numberBuilder = new StringBuilder (); for (int i = len; i > number.Length; i--) numberBuilder.Append ('0'); numberBuilder.Append (number.Length <= len ? number : number.Substring (number.Length - len, len)); number = numberBuilder.ToString (); numberBuilder.Length = 0; } b.Append (number); } } } } internal enum XslNumberingLevel { Single, Multiple, Any } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERLevel { /// <summary> /// A07Level1111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="A07Level1111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="A06Level111"/> collection. /// </remarks> [Serializable] public partial class A07Level1111ReChild : BusinessBase<A07Level1111ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int cLarentID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_Child_Name, "Level_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="A07Level1111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="A07Level1111ReChild"/> object.</returns> internal static A07Level1111ReChild NewA07Level1111ReChild() { return DataPortal.CreateChild<A07Level1111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="A07Level1111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="A07Level1111ReChild"/> object.</returns> internal static A07Level1111ReChild GetA07Level1111ReChild(SafeDataReader dr) { A07Level1111ReChild obj = new A07Level1111ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="A07Level1111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private A07Level1111ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="A07Level1111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="A07Level1111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_Child_Name")); cLarentID2 = dr.GetInt32("CLarentID2"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="A07Level1111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(A06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddA07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="A07Level1111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(A06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateA07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="A07Level1111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(A06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteA07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonPlayer.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH // </copyright> // <summary> // Represents a player, identified by actorID (a.k.a. ActorNumber). // Caches properties of a player. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- using System.Collections.Generic; using ExitGames.Client.Photon; using UnityEngine; using Hashtable = ExitGames.Client.Photon.Hashtable; /// <summary> /// Summarizes a "player" within a room, identified (in that room) by actorID. /// </summary> /// <remarks> /// Each player has an actorId (or ID), valid for that room. It's -1 until it's assigned by server. /// Each client can set it's player's custom properties with SetCustomProperties, even before being in a room. /// They are synced when joining a room. /// </remarks> /// \ingroup publicApi public class PhotonPlayer { /// <summary>This player's actorID</summary> public int ID { get { return this.actorID; } } /// <summary>Identifier of this player in current room.</summary> private int actorID = -1; private string nameField = ""; /// <summary>Nickname of this player.</summary> /// <remarks>Set the PhotonNetwork.playerName to make the name synchronized in a room.</remarks> public string name { get { return this.nameField; } set { if (!this.isLocal) { Debug.LogError("Error: Cannot change the name of a remote player!"); return; } if (string.IsNullOrEmpty(value) || value.Equals(this.nameField)) { return; } this.nameField = value; PhotonNetwork.playerName = value; // this will sync the local player's name in a room } } ///// <summary>UserId of the player. Sent when room gets created with RoomOptions.publishUserId = true. Useful for FindFriends and blocking slots in a room for expected players.</summary> //public string userId { get; internal set; } /// <summary>Only one player is controlled by each client. Others are not local.</summary> public readonly bool isLocal = false; /// <summary> /// True if this player is the Master Client of the current room. /// </summary> /// <remarks> /// See also: PhotonNetwork.masterClient. /// </remarks> public bool isMasterClient { get { return (PhotonNetwork.networkingPeer.mMasterClientId == this.ID); } } /// <summary>Read-only cache for custom properties of player. Set via PhotonPlayer.SetCustomProperties.</summary> /// <remarks> /// Don't modify the content of this Hashtable. Use SetCustomProperties and the /// properties of this class to modify values. When you use those, the client will /// sync values with the server. /// </remarks> /// <see cref="SetCustomProperties"/> public Hashtable customProperties { get; internal set; } /// <summary>Creates a Hashtable with all properties (custom and "well known" ones).</summary> /// <remarks>If used more often, this should be cached.</remarks> public Hashtable allProperties { get { Hashtable allProps = new Hashtable(); allProps.Merge(this.customProperties); allProps[ActorProperties.PlayerName] = this.name; return allProps; } } /// <summary>Can be used to store a reference that's useful to know "by player".</summary> /// <remarks>Example: Set a player's character as Tag by assigning the GameObject on Instantiate.</remarks> public object TagObject; /// <summary> /// Creates a PhotonPlayer instance. /// </summary> /// <param name="isLocal">If this is the local peer's player (or a remote one).</param> /// <param name="actorID">ID or ActorNumber of this player in the current room (a shortcut to identify each player in room)</param> /// <param name="name">Name of the player (a "well known property").</param> public PhotonPlayer(bool isLocal, int actorID, string name) { this.customProperties = new Hashtable(); this.isLocal = isLocal; this.actorID = actorID; this.nameField = name; } /// <summary> /// Internally used to create players from event Join /// </summary> internal protected PhotonPlayer(bool isLocal, int actorID, Hashtable properties) { this.customProperties = new Hashtable(); this.isLocal = isLocal; this.actorID = actorID; this.InternalCacheProperties(properties); } /// <summary> /// Makes PhotonPlayer comparable /// </summary> public override bool Equals(object p) { PhotonPlayer pp = p as PhotonPlayer; return (pp != null && this.GetHashCode() == pp.GetHashCode()); } public override int GetHashCode() { return this.ID; } /// <summary> /// Used internally, to update this client's playerID when assigned. /// </summary> internal void InternalChangeLocalID(int newID) { if (!this.isLocal) { Debug.LogError("ERROR You should never change PhotonPlayer IDs!"); return; } this.actorID = newID; } /// <summary> /// Caches custom properties for this player. /// </summary> internal void InternalCacheProperties(Hashtable properties) { if (properties == null || properties.Count == 0 || this.customProperties.Equals(properties)) { return; } if (properties.ContainsKey(ActorProperties.PlayerName)) { this.nameField = (string)properties[ActorProperties.PlayerName]; } //if (properties.ContainsKey(ActorProperties.UserId)) //{ // this.userId = (string)properties[ActorProperties.UserId]; //} if (properties.ContainsKey(ActorProperties.IsInactive)) { } this.customProperties.MergeStringKeys(properties); this.customProperties.StripKeysWithNullValues(); } /// <summary> /// Updates the this player's Custom Properties with new/updated key-values. /// </summary> /// <remarks> /// Custom Properties are a key-value set (Hashtable) which is available to all players in a room. /// They can relate to the room or individual players and are useful when only the current value /// of something is of interest. For example: The map of a room. /// All keys must be strings. /// /// The Room and the PhotonPlayer class both have SetCustomProperties methods. /// Also, both classes offer access to current key-values by: customProperties. /// /// Always use SetCustomProperties to change values. /// To reduce network traffic, set only values that actually changed. /// New properties are added, existing values are updated. /// Other values will not be changed, so only provide values that changed or are new. /// /// To delete a named (custom) property of this room, use null as value. /// /// Locally, SetCustomProperties will update it's cache without delay. /// Other clients are updated through Photon (the server) with a fitting operation. /// /// <b>Check and Swap</b> /// /// SetCustomProperties have the option to do a server-side Check-And-Swap (CAS): /// Values only get updated if the expected values are correct. /// The expectedValues can be different key/values than the propertiesToSet. So you can /// check some key and set another key's value (if the check succeeds). /// /// If the client's knowledge of properties is wrong or outdated, it can't set values with CAS. /// This can be useful to keep players from concurrently setting values. For example: If all players /// try to pickup some card or item, only one should get it. With CAS, only the first SetProperties /// gets executed server-side and any other (sent at the same time) fails. /// /// The server will broadcast successfully changed values and the local "cache" of customProperties /// only gets updated after a roundtrip (if anything changed). /// /// You can do a "webForward": Photon will send the changed properties to a WebHook defined /// for your application. /// /// <b>OfflineMode</b> /// /// While PhotonNetwork.offlineMode is true, the expectedValues and webForward parameters are ignored. /// In OfflineMode, the local customProperties values are immediately updated (without the roundtrip). /// </remarks> /// <param name="propertiesToSet">The new properties to be set. </param> /// <param name="expectedValues">At least one property key/value set to check server-side. Key and value must be correct. Ignored in OfflineMode.</param> /// <param name="webForward">Set to true, to forward the set properties to a WebHook, defined for this app (in Dashboard). Ignored in OfflineMode.</param> public void SetCustomProperties(Hashtable propertiesToSet, Hashtable expectedValues = null, bool webForward = false) { if (propertiesToSet == null) { return; } Hashtable customProps = propertiesToSet.StripToStringKeys() as Hashtable; Hashtable customPropsToCheck = expectedValues.StripToStringKeys() as Hashtable; // no expected values -> set and callback bool noCas = customPropsToCheck == null || customPropsToCheck.Count == 0; bool inOnlineRoom = this.actorID > 0 && !PhotonNetwork.offlineMode; if (inOnlineRoom) { PhotonNetwork.networkingPeer.OpSetPropertiesOfActor(this.actorID, customProps, customPropsToCheck, webForward); } if (!inOnlineRoom || noCas) { this.InternalCacheProperties(customProps); NetworkingPeer.SendMonoMessage(PhotonNetworkingMessage.OnPhotonPlayerPropertiesChanged, this, customProps); } } /// <summary> /// Try to get a specific player by id. /// </summary> /// <param name="ID">ActorID</param> /// <returns>The player with matching actorID or null, if the actorID is not in use.</returns> public static PhotonPlayer Find(int ID) { if (PhotonNetwork.networkingPeer != null) { return PhotonNetwork.networkingPeer.GetPlayerWithId(ID); } return null; } public PhotonPlayer Get(int id) { return Find(id); } public PhotonPlayer GetNext() { return this.GetNextFor(this.ID); } public PhotonPlayer GetNextFor(PhotonPlayer currentPlayer) { if (currentPlayer == null) { return null; } return this.GetNextFor(currentPlayer.ID); } public PhotonPlayer GetNextFor(int currentPlayerId) { if (PhotonNetwork.networkingPeer == null || PhotonNetwork.networkingPeer.mActors == null || PhotonNetwork.networkingPeer.mActors.Count < 2) { return null; } Dictionary<int, PhotonPlayer> players = PhotonNetwork.networkingPeer.mActors; int nextHigherId = int.MaxValue; // we look for the next higher ID int lowestId = currentPlayerId; // if we are the player with the highest ID, there is no higher and we return to the lowest player's id foreach (int playerid in players.Keys) { if (playerid < lowestId) { lowestId = playerid; // less than any other ID (which must be at least less than this player's id). } else if (playerid > currentPlayerId && playerid < nextHigherId) { nextHigherId = playerid; // more than our ID and less than those found so far. } } //UnityEngine.Debug.LogWarning("Debug. " + currentPlayerId + " lower: " + lowestId + " higher: " + nextHigherId + " "); //UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(currentPlayerId)); //UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(lowestId)); //if (nextHigherId != int.MaxValue) UnityEngine.Debug.LogWarning(this.RoomReference.GetPlayer(nextHigherId)); return (nextHigherId != int.MaxValue) ? players[nextHigherId] : players[lowestId]; } /// <summary> /// Brief summary string of the PhotonPlayer. Includes name or player.ID and if it's the Master Client. /// </summary> public override string ToString() { if (string.IsNullOrEmpty(this.name)) { return string.Format("#{0:00}{1}", this.ID, this.isMasterClient ? "(master)":""); } return string.Format("'{0}'{1}", this.name, this.isMasterClient ? "(master)" : ""); } /// <summary> /// String summary of the PhotonPlayer: player.ID, name and all custom properties of this user. /// </summary> /// <remarks> /// Use with care and not every frame! /// Converts the customProperties to a String on every single call. /// </remarks> public string ToStringFull() { return string.Format("#{0:00} '{1}' {2}", this.ID, this.name, this.customProperties.ToStringFull()); } }
// 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 AutoGen; // We were receiving an assert on IA64 because the code we were using to determine if a range // check statically fails was invalid. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50606.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AutoGen { public struct VType1 { public sbyte f0; public sbyte f1; public VType1(int v) { f0 = ((sbyte)(v)); f1 = ((sbyte)(v)); } } public struct VType2 { public long f0; public long f1; public VType2(int v) { f0 = ((long)(v)); f1 = ((long)(v)); } } public class Program { private int[] _callDepthTable; private int[] _paramValueTable; public Program() { _callDepthTable = new int[6]; _paramValueTable = new int[12]; int i; for (i = 0; (i < _callDepthTable.Length); i = (i + 1)) { _callDepthTable[i] = i; } for (i = 0; (i < _paramValueTable.Length); i = (i + 1)) { _paramValueTable[i] = i; } } public virtual VType1 Func1(VType1 p0, long p1, uint p2, VType2 p3) { if ((_callDepthTable[0] < 5)) { _callDepthTable[0] = (_callDepthTable[0] + 1); } else { return p0; } int acc2 = 0; int i2 = 0; int[] arr02 = new int[5]; int[] arr12 = new int[5]; int[] arr22 = new int[5]; int[] arr32 = new int[5]; int[] arr42 = new int[5]; int[] arr52 = new int[5]; for (i2 = 0; (i2 < 5); i2 = (i2 + 1)) { arr02[i2] = i2; arr12[i2] = arr02[i2]; arr22[i2] = arr12[i2]; arr32[i2] = arr22[i2]; arr42[i2] = arr32[i2]; arr52[i2] = arr42[i2]; } i2 = 0; acc2 = 0; for (; i2 < 5; i2++) { acc2 = (acc2 + arr02[i2]); } if ((acc2 == 0)) { acc2 = arr02[10]; } if ((acc2 == 1)) { acc2 = arr12[10]; } if ((acc2 == 2)) { acc2 = arr22[10]; } if ((acc2 == 3)) { acc2 = arr32[10]; } if ((acc2 == 4)) { acc2 = arr42[10]; } if ((acc2 == 5)) { acc2 = arr52[10]; } if ((acc2 == 6)) { acc2 = arr02[10]; } if ((acc2 == 7)) { acc2 = arr12[10]; } if ((acc2 == 8)) { acc2 = arr22[10]; } if ((acc2 == 9)) { acc2 = arr32[10]; } int i4 = 0; int[] arr04 = new int[7]; int[] arr14 = new int[7]; int[] arr24 = new int[7]; int[] arr34 = new int[7]; int[] arr44 = new int[7]; for (i4 = 0; (i4 < 7); i4 = (i4 + 1)) { arr04[i4] = i4; arr14[i4] = arr04[i4]; arr24[i4] = arr14[i4]; arr34[i4] = arr24[i4]; arr44[i4] = arr34[i4]; } int acc5 = 0; int i5 = 0; int[] arr05 = new int[3]; int[] arr15 = new int[3]; int[] arr25 = new int[3]; int[] arr35 = new int[3]; int[] arr45 = new int[3]; int[] arr55 = new int[3]; for (i5 = 0; (i5 < 3); i5 = (i5 + 1)) { arr05[i5] = i5; arr15[i5] = arr05[i5]; arr25[i5] = arr15[i5]; arr35[i5] = arr25[i5]; arr45[i5] = arr35[i5]; arr55[i5] = arr45[i5]; } i5 = 0; acc5 = 0; for (; (i5 < 3); i5 = (i5 + 1)) { acc5 = (acc5 + arr05[i5]); for (; (i5 < 3); i5 = (i5 + 1)) { acc5 = (acc5 + arr15[i5]); for (; (i5 < 3); i5 = (i5 + 1)) { acc5 = (acc5 + arr25[i5]); for (; (i5 < 3); i5 = (i5 + 1)) { acc5 = (acc5 + arr35[i5]); for (; (i5 < 3); i5 = (i5 + 1)) { acc5 = (acc5 + arr45[i5]); for (; (i5 < 3); i5 = (i5 + 1)) { acc5 = (acc5 + arr55[i5]); } } } } } } if ((acc5 == 0)) { acc5 = arr05[3]; } if ((acc5 == 1)) { acc5 = arr15[3]; } if ((acc5 == 2)) { acc5 = arr25[3]; } if ((arr05.Length < 0)) { goto L2; } acc5 = 0; bool stop2 = (arr05.Length > 0); for (i5 = 0; (stop2 && (i5 <= arr05[i5])); i5 = (i5 + 1)) { arr05[i5] = i5; acc5 = (acc5 + arr05[i5]); for (i5 = 0; (stop2 && (i5 <= arr15[i5])); i5 = (i5 + 1)) { acc5 = (acc5 + arr15[i5]); i5 = arr15[i5]; for (i5 = 0; (stop2 && (i5 <= arr25[i5])); i5 = (i5 + 1)) { acc5 = (acc5 + arr25[i5]); for (i5 = 0; (stop2 && (i5 <= arr35[i5])); i5 = (i5 + 1)) { acc5 = (acc5 + arr35[i5]); for (i5 = 0; (stop2 && (i5 <= arr45[i5])); i5 = (i5 + 1)) { acc5 = (acc5 + arr45[i5]); for (i5 = 0; (stop2 && (i5 <= arr55[i5])); i5 = (i5 + 1)) { acc5 = (acc5 + arr55[i5]); i5 = arr55[i5]; stop2 = (i5 < 2); } stop2 = (i5 < 2); } stop2 = (i5 < 2); } stop2 = (i5 < 2); } stop2 = (i5 < 2); } stop2 = (i5 < 2); } L2: i5 = 0; int acc6 = 0; int i6 = 0; int[] arr6 = new int[4]; for (i6 = 0; i6 < 4; i6++) { arr6[i6] = i6; } i6 = 0; acc6 = 0; for (; i6 < 4; i6++) { acc6 = (acc6 + arr6[i6]); } if ((acc6 == 0)) { acc6 = arr6[6]; } return p0; } public virtual int Run() { try { this.Func1(new VType1(_paramValueTable[10]), ((long)(_paramValueTable[6])), ((uint)(_paramValueTable[5])), new VType2(_paramValueTable[11])); } catch (System.Exception exp) { System.Console.WriteLine("Application Check Failed!"); System.Console.WriteLine(exp); return 1; } return 100; } public static int Main() { Program prog = new Program(); int rc = prog.Run(); System.Console.WriteLine("rc = {0}", rc); return rc; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Serialization.Json; using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace ReleaseNotesUtil { public static class Program { public static void Main(string[] args) { if (!((args.Length == 4 && args[0] == "getrulesjson") || ((args.Length == 4 || args.Length == 5) && args[0] == "diffrules"))) { PrintUsage(); return; } string command = args[0]; switch (command) { case "getrulesjson": GetRulesJson(args[1], args[2], args[3]); break; case "diffrules": DiffRules(args[1], args[2], args[3], args.Length > 4 ? args[4] : null); break; default: throw new ArgumentException($"Unhandled command {command}"); } } private static void PrintUsage() { Console.WriteLine("Usage: ReleaseNoteUtil command commandArgs ..."); Console.WriteLine(" getrulesjson pathToNugetInstalledPackages netAnalyzersVersion out.json"); Console.WriteLine(" diffrules old.json new.json out.md"); } private static void GetRulesJson(string nugetInstalledPackagesPath, string version, string outputPath) { IEnumerable<string> dllPaths = GetNetAnalyzerBinaries(nugetInstalledPackagesPath, version); RuleFileContent ruleFileContent = new RuleFileContent { Rules = GetRules(dllPaths) }; ruleFileContent.Rules.Sort(CategoryThenIdComparer.Instance); WriteRuleFileContent(ruleFileContent, outputPath); } private static void DiffRules( string oldRulesJsonPath, string newRulesJsonPath, string outputPath, string? latestRulesJsonPath = null) { RuleFileContent oldContent = ReadRuleFileContent(oldRulesJsonPath); RuleFileContent newContent = ReadRuleFileContent(newRulesJsonPath); // If we have the latest rules, we can backfill missing help link URLs. if (!string.IsNullOrWhiteSpace(latestRulesJsonPath)) { RuleFileContent latestContent = ReadRuleFileContent(latestRulesJsonPath); Dictionary<string, RuleInfo> latestRulesById = latestContent.Rules.Where(r => r.Id != null).ToDictionary(r => r.Id!); foreach (RuleInfo rule in oldContent.Rules.Concat(newContent.Rules)) { if (string.IsNullOrWhiteSpace(rule.HelpLink) && rule.Id != null && latestRulesById.TryGetValue(rule.Id, out RuleInfo? latestRule)) { rule.HelpLink = latestRule.HelpLink; } } } Dictionary<string, RuleInfo> oldRulesById = oldContent.Rules.Where(r => r.Id != null).ToDictionary(r => r.Id!); Dictionary<string, RuleInfo> newRulesById = newContent.Rules.Where(r => r.Id != null).ToDictionary(r => r.Id!); IEnumerable<RuleInfo> addedRules = newContent.Rules .Where(r => r.Id != null && !oldRulesById.ContainsKey(r.Id)); IEnumerable<RuleInfo> removedRules = oldContent.Rules .Where(r => r.Id != null && !newRulesById.ContainsKey(r.Id)); IEnumerable<RuleInfo> changedRules = newContent.Rules .Where(r => r.Id != null && oldRulesById.TryGetValue(r.Id, out RuleInfo? oldRule) && r.IsEnabledByDefault != oldRule.IsEnabledByDefault); StringBuilder sb = new StringBuilder(); GenerateAddRemovedRulesDiffMarkdown(sb, "### Added", addedRules); GenerateAddRemovedRulesDiffMarkdown(sb, "### Removed", removedRules); GenerateChangedRulesDiffMarkdown(sb, "### Changed", changedRules); File.WriteAllText(outputPath, sb.ToString()); } private static void WriteRuleFileContent(RuleFileContent ruleFileContent, string outputPath) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RuleFileContent)); using FileStream fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.None); serializer.WriteObject(fs, ruleFileContent); } private static RuleFileContent ReadRuleFileContent(string path) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(RuleFileContent)); using FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); return (RuleFileContent)serializer.ReadObject(fs); } private static void GenerateAddRemovedRulesDiffMarkdown(StringBuilder sb, string heading, IEnumerable<RuleInfo> rules) { if (!rules.Any()) { return; } IEnumerable<RuleInfo> sortedRules = rules.OrderBy(r => r, CategoryThenIdComparer.Instance); sb.AppendLine(heading); string? previousCategory = null; foreach (RuleInfo rule in sortedRules) { if (rule.Category != previousCategory) { sb.AppendLine($"- {rule.Category}"); previousCategory = rule.Category; } sb.AppendLine($" - {rule.IdWithHelpLinkMarkdown}: {rule.Title}{(rule.IsEnabledByDefault ? " -- **Enabled by default**" : "")}"); } } private static void GenerateChangedRulesDiffMarkdown(StringBuilder sb, string heading, IEnumerable<RuleInfo> rules) { if (!rules.Any()) { return; } IEnumerable<RuleInfo> sortedRules = rules.OrderBy(r => r, CategoryThenIdComparer.Instance); sb.AppendLine(heading); string? previousCategory = null; foreach (RuleInfo rule in sortedRules) { if (rule.Category != previousCategory) { sb.AppendLine($"- {rule.Category}"); previousCategory = rule.Category; } sb.AppendLine($" - {rule.IdWithHelpLinkMarkdown}: {rule.Title} -- {(rule.IsEnabledByDefault ? "Now **enabled by default**" : "Now disabled by default")}"); } } private static IEnumerable<string> GetNetAnalyzerBinaries(string nugetInstalledPackagesPath, string version) { if (!Directory.Exists(nugetInstalledPackagesPath)) { throw new ArgumentException($"'{nugetInstalledPackagesPath}' is not a directory or doesn't exist"); } string[] roslynAnalyzerPackages = new string[] { "Microsoft.CodeQuality.Analyzers", "Microsoft.NetCore.Analyzers", "Microsoft.NetFramework.Analyzers", "Text.Analyzers", // deprecated "Microsoft.CodeAnalysis.VersionCheckAnalyzer", }; foreach (string roslynAnalyzerPackage in roslynAnalyzerPackages) { string packageWithVersion = $"{roslynAnalyzerPackage}.{version}"; string packageDirectory = Path.Combine(nugetInstalledPackagesPath, packageWithVersion); foreach (string dllFile in GetAllAnalyzerBinaries(packageDirectory)) { yield return dllFile; } } } private static readonly string[] LanguageDirectoryNames = new string[] { "cs", "vb" }; private static IEnumerable<string> GetAllAnalyzerBinaries(string nugetInstalledPackagePath) { // Assuming analyzers are located in directories as in // https://github.com/dotnet/roslyn-analyzers/blob/32d8f1e397439035f0ecb5f61a9e672225f0ecdb/tools/AnalyzerCodeGenerator/template/src/REPLACE.ME/Core/install.ps1 string analyzersDirectory = Path.Combine(nugetInstalledPackagePath, "analyzers"); if (!Directory.Exists(analyzersDirectory)) { yield break; } foreach (string frameworkDirectory in Directory.EnumerateDirectories(analyzersDirectory)) { foreach (string dllFile in Directory.EnumerateFiles(frameworkDirectory, "*.dll")) { yield return dllFile; } foreach (string languageName in LanguageDirectoryNames) { string languageDirectory = Path.Combine(frameworkDirectory, languageName); if (Directory.Exists(languageDirectory)) { foreach (string languageDllFile in Directory.EnumerateFiles(languageDirectory, "*.dll")) { yield return languageDllFile; } } } } } private static List<RuleInfo> GetRules(IEnumerable<string> dllPaths) { List<RuleInfo> ruleInfos = new List<RuleInfo>(); foreach (string dllPath in dllPaths) { AnalyzerFileReference analyzerFileReference = new AnalyzerFileReference( dllPath, AnalyzerAssemblyLoader.Instance); ImmutableArray<DiagnosticAnalyzer> analyzers = analyzerFileReference.GetAnalyzersForAllLanguages(); IEnumerable<DiagnosticDescriptor> descriptors = analyzers .SelectMany(a => a.SupportedDiagnostics) .Distinct(DiagnosticIdComparer.Instance); HashSet<string> fixableDiagnosticIds = analyzerFileReference .GetFixers() .SelectMany(fixer => fixer.FixableDiagnosticIds).ToHashSet(); Console.WriteLine($"{dllPath} has {analyzers.Length} analyzers, {descriptors.Count()} diagnostics, and {fixableDiagnosticIds.Count} fixers"); foreach (DiagnosticDescriptor descriptor in descriptors) { if (ruleInfos.Any(r => r.Id == descriptor.Id)) { continue; } ruleInfos.Add( new RuleInfo( descriptor.Id, descriptor.Title.ToString(CultureInfo.InvariantCulture), descriptor.Category, descriptor.IsEnabledByDefault, fixableDiagnosticIds.Contains(descriptor.Id), descriptor.MessageFormat.ToString(CultureInfo.InvariantCulture), descriptor.Description.ToString(CultureInfo.InvariantCulture), descriptor.HelpLinkUri)); } } return ruleInfos; } private static void AnalyzerFileReference_AnalyzerLoadFailed(object sender, AnalyzerLoadFailureEventArgs e) { Console.WriteLine($"Analyzer load failed: ErrorCode: {e.ErrorCode} Message: {e.Message} Exception:{e.Exception}"); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Styling; using Avalonia.VisualTree; using Xunit; namespace Avalonia.Controls.UnitTests { public class ListBoxTests_Single { [Fact] public void Focusing_Item_With_Tab_Should_Not_Select_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new GotFocusEventArgs { RoutedEvent = InputElement.GotFocusEvent, NavigationMethod = NavigationMethod.Tab, }); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Focusing_Item_With_Arrow_Key_Should_Select_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new GotFocusEventArgs { RoutedEvent = InputElement.GotFocusEvent, NavigationMethod = NavigationMethod.Directional, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Item_Should_Select_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Selected_Item_Should_Not_Deselect_It() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); target.SelectedIndex = 0; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Item_Should_Select_It_When_SelectionMode_Toggle() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Single | SelectionMode.Toggle, }; ApplyTemplate(target); target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Selected_Item_Should_Deselect_It_When_SelectionMode_Toggle() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Toggle, }; ApplyTemplate(target); target.SelectedIndex = 0; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(-1, target.SelectedIndex); } [Fact] public void Clicking_Selected_Item_Should_Not_Deselect_It_When_SelectionMode_ToggleAlwaysSelected() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Toggle | SelectionMode.AlwaysSelected, }; ApplyTemplate(target); target.SelectedIndex = 0; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Clicking_Another_Item_Should_Select_It_When_SelectionMode_Toggle() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, SelectionMode = SelectionMode.Single | SelectionMode.Toggle, }; ApplyTemplate(target); target.SelectedIndex = 1; target.Presenter.Panel.Children[0].RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(0, target.SelectedIndex); } [Fact] public void Setting_Item_IsSelected_Sets_ListBox_Selection() { var target = new ListBox { Template = new FuncControlTemplate(CreateListBoxTemplate), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplate(target); ((ListBoxItem)target.GetLogicalChildren().ElementAt(1)).IsSelected = true; Assert.Equal("Bar", target.SelectedItem); Assert.Equal(1, target.SelectedIndex); } private Control CreateListBoxTemplate(ITemplatedControl parent) { return new ScrollViewer { Template = new FuncControlTemplate(CreateScrollViewerTemplate), Content = new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent.GetObservable(ItemsControl.ItemsProperty).AsBinding(), } }; } private Control CreateScrollViewerTemplate(ITemplatedControl parent) { return new ScrollContentPresenter { Name = "PART_ContentPresenter", [~ContentPresenter.ContentProperty] = parent.GetObservable(ContentControl.ContentProperty).AsBinding(), }; } private void ApplyTemplate(ListBox target) { // Apply the template to the ListBox itself. target.ApplyTemplate(); // Then to its inner ScrollViewer. var scrollViewer = (ScrollViewer)target.GetVisualChildren().Single(); scrollViewer.ApplyTemplate(); // Then make the ScrollViewer create its child. ((ContentPresenter)scrollViewer.Presenter).UpdateChild(); // Now the ItemsPresenter should be reigstered, so apply its template. target.Presenter.ApplyTemplate(); } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using Newtonsoft.Json.Linq; namespace KatanaContrib.Security.Github { internal class GithubAuthenticationHandler : AuthenticationHandler<GithubAuthenticationOptions> { private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; private const string TokenEndpoint = "https://github.com/login/oauth/access_token"; private const string ApiEndpoint = "https://api.github.com/user?access_token="; private readonly ILogger _logger; private readonly HttpClient _httpClient; public GithubAuthenticationHandler(HttpClient httpClient, ILogger logger) { _httpClient = httpClient; _logger = logger; } protected override async Task<AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList<string> values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return null; } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return new AuthenticationTicket(null, properties); } string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; string tokenRequest = "grant_type=authorization_code" + "&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&client_id=" + Uri.EscapeDataString(Options.ClientId) + "&client_secret=" + Uri.EscapeDataString(Options.ClientSecret); //Set accept header to request details as a JSON Object _httpClient.DefaultRequestHeaders.Add("accept", "application/json"); HttpResponseMessage tokenResponse = await _httpClient.GetAsync(TokenEndpoint + "?" + tokenRequest, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); //Parsing the string to a JSON Object JObject jsonText = JObject.Parse(text); //Extracting the access token from the JSON Object JToken accessToken; jsonText.TryGetValue("access_token", out accessToken); //Set the expiration time 60 days (5183999 seconds) string expires = "5183999"; //As Github required to include a User Agent in all requests, set User Agent in the request header _httpClient.DefaultRequestHeaders.Add("user-agent", "OwinContrib Security Github"); HttpResponseMessage API_Response = await _httpClient.GetAsync( ApiEndpoint + Uri.EscapeDataString(accessToken.ToString()), Request.CallCancelled); API_Response.EnsureSuccessStatusCode(); text = await API_Response.Content.ReadAsStringAsync(); JObject user = JObject.Parse(text); var context = new GithubAuthenticatedContext(Context, user, accessToken.ToString(), expires); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); //Add context properties to the Claims Identity if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Url)) { context.Identity.AddClaim(new Claim("urn:github:link", context.Url, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Login)) { context.Identity.AddClaim(new Claim("urn:github:login", context.Login, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return new AuthenticationTicket(context.Identity, context.Properties); } catch (Exception ex) { _logger.WriteError(ex.Message); } return new AuthenticationTicket(null, properties); } protected override Task ApplyResponseChallengeAsync() { if (Response.StatusCode != 401) { return Task.FromResult<object>(null); } AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); if (challenge != null) { string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase; string currentUri = baseUri + Request.Path + Request.QueryString; string redirectUri = baseUri + Options.CallbackPath; AuthenticationProperties properties = challenge.Properties; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = currentUri; } // OAuth2 10.12 CSRF GenerateCorrelationId(properties); // comma separated string scope = string.Join(",", Options.Scope); string state = Options.StateDataFormat.Protect(properties); string authorizationEndpoint = "https://github.com/login/oauth/authorize" + "?response_type=code" + "&client_id=" + Uri.EscapeDataString(Options.ClientId) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&scope=" + Uri.EscapeDataString(scope) + "&state=" + Uri.EscapeDataString(state); Response.Redirect(authorizationEndpoint); } return Task.FromResult<object>(null); } public override async Task<bool> InvokeAsync() { return await InvokeReplyPathAsync(); } private async Task<bool> InvokeReplyPathAsync() { if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) { // TODO: error responses AuthenticationTicket ticket = await AuthenticateAsync(); if (ticket == null) { _logger.WriteWarning("Invalid return state, unable to redirect."); Response.StatusCode = 500; return true; } var context = new GithubReturnEndpointContext(Context, ticket); context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType; context.RedirectUri = ticket.Properties.RedirectUri; await Options.Provider.ReturnEndpoint(context); if (context.SignInAsAuthenticationType != null && context.Identity != null) { ClaimsIdentity grantIdentity = context.Identity; if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal)) { grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType); } Context.Authentication.SignIn(context.Properties, grantIdentity); } if (!context.IsRequestCompleted && context.RedirectUri != null) { string redirectUri = context.RedirectUri; if (context.Identity == null) { // add a redirect hint that sign-in failed in some way redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied"); } Response.Redirect(redirectUri); context.RequestCompleted(); } return context.IsRequestCompleted; } return false; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.PythonTools.Debugger.Concord.Proxies; using Microsoft.PythonTools.Debugger.Concord.Proxies.Structs; using Microsoft.PythonTools.Infrastructure; using Microsoft.Python.Parsing; using Microsoft.Python.Parsing.Ast; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.Python.Core.Text; namespace Microsoft.PythonTools.Debugger.Concord { internal class ExpressionEvaluator : DkmDataItem { // Value of this constant must always remain in sync with DebuggerHelper/trace.cpp. private const int ExpressionEvaluationBufferSize = 0x1000; private const int MaxDebugChildren = 1000; private const int ExpressionEvaluationTimeout = 3000; // ms private readonly DkmProcess _process; private readonly UInt64Proxy _evalLoopThreadId, _evalLoopFrame, _evalLoopResult, _evalLoopExcType, _evalLoopExcValue, _evalLoopExcStr; private readonly UInt32Proxy _evalLoopSEHCode; private readonly CStringProxy _evalLoopInput; public ExpressionEvaluator(DkmProcess process) { _process = process; var pyrtInfo = process.GetPythonRuntimeInfo(); _evalLoopThreadId = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopThreadId"); _evalLoopFrame = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopFrame"); _evalLoopResult = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopResult"); _evalLoopExcType = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcType"); _evalLoopExcValue = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcValue"); _evalLoopExcStr = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcStr"); _evalLoopSEHCode = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt32Proxy>("evalLoopSEHCode"); _evalLoopInput = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CStringProxy>("evalLoopInput"); LocalComponent.CreateRuntimeDllExportedFunctionBreakpoint(pyrtInfo.DLLs.DebuggerHelper, "OnEvalComplete", OnEvalComplete, enable: true); } private interface IPythonEvaluationResult { List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext); } private interface IPythonEvaluationResultAsync { void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine); } private class RawEvaluationResult : DkmDataItem { public object Value { get; set; } } /// <summary> /// Data item attached to a <see cref="DkmEvaluationResult"/> that represents a Python object (a variable, field of another object, collection item etc). /// </summary> private class PyObjectEvaluationResult : DkmDataItem, IPythonEvaluationResult { // Maps CLR types as returned from IValueStore.Read() to corresponding Python types. // Used to compute the expected Python type for a T_* slot of a native object, since we don't have the actual PyObject value yet. private static readonly Dictionary<Type, string> _typeMapping = new Dictionary<Type, string>() { { typeof(sbyte), "int" }, { typeof(byte), "int" }, { typeof(short), "int" }, { typeof(ushort), "int" }, { typeof(int), "int" }, { typeof(uint), "int" }, { typeof(long), "int" }, { typeof(ulong), "int" }, { typeof(float), "float" }, { typeof(double), "float" }, { typeof(Complex), "complex" }, { typeof(bool), "bool" }, { typeof(string), "str" }, { typeof(AsciiString), "bytes" }, }; // 2.x-specific mappings that override the ones above. private static readonly Dictionary<Type, string> _typeMapping2x = new Dictionary<Type, string>() { { typeof(string), "unicode" }, { typeof(AsciiString), "str" }, }; public PyObjectEvaluationResult(DkmProcess process, string fullName, IValueStore<PyObject> valueStore, string cppTypeName, bool hasCppView, bool isOwned) { Process = process; FullName = fullName; ValueStore = valueStore; CppTypeName = cppTypeName; HasCppView = hasCppView; IsOwned = isOwned; } public DkmProcess Process { get; private set; } public string FullName { get; private set; } public IValueStore<PyObject> ValueStore { get; private set; } /// <summary> /// Should this object show a child [C++ view] node? /// </summary> public bool HasCppView { get; private set; } /// <summary> /// Name of the C++ struct type corresponding to this object value. /// </summary> public string CppTypeName { get; private set; } /// <summary> /// Name of the native module containing <see cref="CppTypeName"/>. /// </summary> public string CppTypeModuleName { get; private set; } /// <summary> /// Whether this object needs to be decref'd once the evaluation result goes away. /// </summary> public bool IsOwned { get; private set; } protected override void OnClose() { base.OnClose(); if (IsOwned) { var obj = ValueStore.Read(); Process.GetDataItem<PyObjectAllocator>().QueueForDecRef(obj); } } public List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext) { var stackFrame = result.StackFrame; var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var obj = ValueStore.Read(); var evalResults = new List<DkmEvaluationResult>(); var reprOptions = new ReprOptions(inspectionContext); var reprBuilder = new ReprBuilder(reprOptions); if (DebuggerOptions.ShowCppViewNodes && !HasCppView) { if (CppTypeName == null) { // Try to guess the object's C++ type by looking at function pointers in its PyTypeObject. If they are pointing // into a module for which symbols are available, C++ EE should be able to resolve them into something like // "0x1e120d50 {python33_d.dll!list_dealloc(PyListObject *)}". If we are lucky, one of those functions will have // the first argument declared as a strongly typed pointer, rather than PyObject* or void*. CppTypeName = "PyObject"; CppTypeModuleName = Process.GetPythonRuntimeInfo().DLLs.Python.Name; foreach (string methodField in _methodFields) { var funcPtrEvalResult = cppEval.TryEvaluateObject(CppTypeModuleName, "PyObject", obj.Address, ".ob_type->" + methodField) as DkmSuccessEvaluationResult; if (funcPtrEvalResult == null || funcPtrEvalResult.Value.IndexOf('{') < 0) { continue; } var match = _cppFirstArgTypeFromFuncPtrRegex.Match(funcPtrEvalResult.Value); string module = match.Groups["module"].Value; string firstArgType = match.Groups["type"].Value; if (firstArgType != "void" && firstArgType != "PyObject" && firstArgType != "_object") { CppTypeName = firstArgType; CppTypeModuleName = module; break; } } } string cppExpr = CppExpressionEvaluator.GetExpressionForObject(CppTypeModuleName, CppTypeName, obj.Address, ",!"); var evalResult = DkmIntermediateEvaluationResult.Create( inspectionContext, stackFrame, "[C++ view]", "{C++}" + cppExpr, cppExpr, CppExpressionEvaluator.CppLanguage, stackFrame.Process.GetNativeRuntimeInstance(), null); evalResults.Add(evalResult); } int i = 0; foreach (var child in obj.GetDebugChildren(reprOptions).Take(MaxDebugChildren)) { if (child.Name == null) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0:PY}]", i++); child.Name = reprBuilder.ToString(); } DkmEvaluationResult evalResult; if (child.ValueStore is IValueStore<PyObject>) { evalResult = exprEval.CreatePyObjectEvaluationResult(inspectionContext, stackFrame, FullName, child, cppEval); } else { var value = child.ValueStore.Read(); reprBuilder.Clear(); reprBuilder.AppendLiteral(value); string type = null; if (Process.GetPythonRuntimeInfo().LanguageVersion <= PythonLanguageVersion.V27) { _typeMapping2x.TryGetValue(value.GetType(), out type); } if (type == null) { _typeMapping.TryGetValue(value.GetType(), out type); } var flags = DkmEvaluationResultFlags.ReadOnly; if (value is string) { flags |= DkmEvaluationResultFlags.RawString; } string childFullName = child.Name; if (FullName != null) { if (childFullName.EndsWithOrdinal("()")) { // len() childFullName = childFullName.Substring(0, childFullName.Length - 2) + "(" + FullName + ")"; } else { if (!childFullName.StartsWithOrdinal("[")) { // [0], ['fob'] etc childFullName = "." + childFullName; } childFullName = FullName + childFullName; } } evalResult = DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, child.Name, childFullName, flags, reprBuilder.ToString(), null, type, child.Category, child.AccessType, child.StorageType, child.TypeModifierFlags, null, null, null, new RawEvaluationResult { Value = value }); } evalResults.Add(evalResult); } return evalResults; } } /// <summary> /// Data item attached to the <see cref="DkmEvaluationResult"/> representing the [Globals] node. /// </summary> private class GlobalsEvaluationResult : DkmDataItem, IPythonEvaluationResult { public PyDictObject Globals { get; set; } public List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext) { var stackFrame = result.StackFrame; var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var evalResults = new List<DkmEvaluationResult>(); foreach (var pair in Globals.ReadElements()) { var name = pair.Key as IPyBaseStringObject; if (name == null) { continue; } var evalResult = exprEval.CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(pair.Value, name.ToString()), cppEval); evalResults.Add(evalResult); } return evalResults.OrderBy(er => er.Name).ToList(); } } /// <summary> /// Data item attached to the <see cref="DkmEvaluationResult"/> representing the [C++ view] node. /// </summary> private class CppViewEvaluationResult : DkmDataItem, IPythonEvaluationResultAsync { public DkmSuccessEvaluationResult CppEvaluationResult { get; set; } public void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { CppEvaluationResult.GetChildren(workList, initialRequestSize, CppEvaluationResult.InspectionContext, (cppResult) => { completionRoutine(cppResult); }); } } private class EvaluationResults : DkmDataItem { public IEnumerable<DkmEvaluationResult> Results { get; set; } } // Names of fields of PyTypeObject struct that contain function pointers corresponding to standard methods of the type. // These are in rough descending order of probability of being non-null and strongly typed (so that we don't waste time eval'ing unnecessary). private static readonly string[] _methodFields = { "tp_init", "tp_dealloc", "tp_repr", "tp_hash", "tp_str", "tp_call", "tp_iter", "tp_iternext", "tp_richcompare", "tp_print", "tp_del", "tp_clear", "tp_traverse", "tp_getattr", "tp_setattr", "tp_getattro", "tp_setattro", }; // Given something like "0x1e120d50 {python33_d.dll!list_dealloc(PyListObject *)}", extract "python33_d.dll" and "PyListObject". private static readonly Regex _cppFirstArgTypeFromFuncPtrRegex = new Regex(@"^.*?\{(?<module>.*?)\!.*?\((?<type>[0-9A-Za-z_:]*?)\s*\*(,.*?)?\)\}$", RegexOptions.CultureInvariant); /// <summary> /// Create a DkmEvaluationResult representing a Python object. /// </summary> /// <param name="cppEval">C++ evaluator to use to provide the [C++ view] node for this object.</param> /// <param name="cppTypeName"> /// C++ struct name corresponding to this object type, for use by [C++ view] node. If not specified, it will be inferred from values of /// various function pointers in <c>ob_type</c>, if possible. <c>PyObject</c> is the ultimate fallback. /// </param> public DkmEvaluationResult CreatePyObjectEvaluationResult(DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, string parentName, PythonEvaluationResult pyEvalResult, CppExpressionEvaluator cppEval, string cppTypeName = null, bool hasCppView = false, bool isOwned = false) { var name = pyEvalResult.Name; var valueStore = pyEvalResult.ValueStore as IValueStore<PyObject>; if (valueStore == null) { Debug.Fail("Non-PyObject PythonEvaluationResult passed to CreateEvaluationResult."); throw new ArgumentException(); } var valueObj = valueStore.Read(); string typeName = valueObj.ob_type.Read().tp_name.Read().ReadUnicode(); var reprOptions = new ReprOptions(inspectionContext); string repr = valueObj.Repr(reprOptions); var flags = pyEvalResult.Flags; if (DebuggerOptions.ShowCppViewNodes || valueObj.GetDebugChildren(reprOptions).Any()) { flags |= DkmEvaluationResultFlags.Expandable; } if (!(valueStore is IWritableDataProxy)) { flags |= DkmEvaluationResultFlags.ReadOnly; } if (valueObj is IPyBaseStringObject) { flags |= DkmEvaluationResultFlags.RawString; } var boolObj = valueObj as IPyBoolObject; if (boolObj != null) { flags |= DkmEvaluationResultFlags.Boolean; if (boolObj.ToBoolean()) { flags |= DkmEvaluationResultFlags.BooleanTrue; } } string fullName = name; if (parentName != null) { if (!fullName.StartsWithOrdinal("[")) { fullName = "." + fullName; } fullName = parentName + fullName; } var pyObjEvalResult = new PyObjectEvaluationResult(stackFrame.Process, fullName, valueStore, cppTypeName, hasCppView, isOwned); return DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, name, fullName, flags, repr, null, typeName, pyEvalResult.Category, pyEvalResult.AccessType, pyEvalResult.StorageType, pyEvalResult.TypeModifierFlags, null, null, null, pyObjEvalResult); } public void GetFrameLocals(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmGetFrameLocalsAsyncResult> completionRoutine) { var pythonFrame = PyFrameObject.TryCreate(stackFrame); if (pythonFrame == null) { Debug.Fail("Non-Python frame passed to GetFrameLocals."); throw new NotSupportedException(); } var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var evalResults = new List<DkmEvaluationResult>(); var f_code = pythonFrame.f_code.Read(); var f_localsplus = pythonFrame.f_localsplus; // Process cellvars and freevars first, because function arguments can appear in both cellvars and varnames if the argument is captured by a closure, // in which case we want to use the cellvar because the regular var slot will then be unused by Python (and in Python 3.4+, nulled out). var namesSeen = new HashSet<string>(); var cellNames = f_code.co_cellvars.Read().ReadElements().Concat(f_code.co_freevars.Read().ReadElements()); var cellSlots = f_localsplus.Skip(f_code.co_nlocals.Read()); foreach (var pair in cellNames.Zip(cellSlots, (nameObj, cellSlot) => new { nameObj, cellSlot = cellSlot })) { var nameObj = pair.nameObj; var cellSlot = pair.cellSlot; var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } namesSeen.Add(name); if (cellSlot.IsNull) { continue; } var cell = cellSlot.Read() as PyCellObject; if (cell == null) { continue; } var localPtr = cell.ob_ref; if (localPtr.IsNull) { continue; } var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(localPtr, name), cppEval); evalResults.Add(evalResult); } PyTupleObject co_varnames = f_code.co_varnames.Read(); foreach (var pair in co_varnames.ReadElements().Zip(f_localsplus, (nameObj, varSlot) => new { nameObj, cellSlot = varSlot })) { var nameObj = pair.nameObj; var varSlot = pair.cellSlot; var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } // Check for function argument that was promoted to a cell. if (!namesSeen.Add(name)) { continue; } if (varSlot.IsNull) { continue; } var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(varSlot, name), cppEval); evalResults.Add(evalResult); } var globals = pythonFrame.f_globals.TryRead(); if (globals != null) { var globalsEvalResult = new GlobalsEvaluationResult { Globals = globals }; // TODO: Localization: is it safe to localize [Globals] ? Appears twice in this file DkmEvaluationResult evalResult = DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, "[Globals]", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable, null, null, null, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None, DkmEvaluationResultTypeModifierFlags.None, null, null, null, globalsEvalResult); // If it is a top-level module frame, show globals inline; otherwise, show them under the [Globals] node. if (f_code.co_name.Read().ToStringOrNull() == "<module>") { evalResults.AddRange(globalsEvalResult.GetChildren(this, evalResult, inspectionContext)); } else { evalResults.Add(evalResult); // Show any globals that are directly referenced by the function inline even in local frames. var globalVars = (from pair in globals.ReadElements() let nameObj = pair.Key as IPyBaseStringObject where nameObj != null select new { Name = nameObj.ToString(), Value = pair.Value } ).ToLookup(v => v.Name, v => v.Value); PyTupleObject co_names = f_code.co_names.Read(); foreach (var nameObj in co_names.ReadElements()) { var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } // If this is a used name but it was not in varnames or freevars, it is a directly referenced global. if (!namesSeen.Add(name)) { continue; } var varSlot = globalVars[name].FirstOrDefault(); if (varSlot.Process != null) { evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(varSlot, name), cppEval); evalResults.Add(evalResult); } } } } var enumContext = DkmEvaluationResultEnumContext.Create(evalResults.Count, stackFrame, inspectionContext, new EvaluationResults { Results = evalResults.OrderBy(er => er.Name) }); completionRoutine(new DkmGetFrameLocalsAsyncResult(enumContext)); } public void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var asyncEvalResult = result.GetDataItem<CppViewEvaluationResult>(); if (asyncEvalResult != null) { asyncEvalResult.GetChildren(result, workList, initialRequestSize, inspectionContext, completionRoutine); return; } var pyEvalResult = (IPythonEvaluationResult)result.GetDataItem<PyObjectEvaluationResult>() ?? (IPythonEvaluationResult)result.GetDataItem<GlobalsEvaluationResult>(); if (pyEvalResult != null) { var childResults = pyEvalResult.GetChildren(this, result, inspectionContext); completionRoutine( new DkmGetChildrenAsyncResult( childResults.Take(initialRequestSize).ToArray(), DkmEvaluationResultEnumContext.Create( childResults.Count, result.StackFrame, inspectionContext, new EvaluationResults { Results = childResults.ToArray() }))); return; } Debug.Fail("GetChildren called on an unsupported DkmEvaluationResult."); throw new NotSupportedException(); } public void GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var evalResults = enumContext.GetDataItem<EvaluationResults>(); if (evalResults == null) { Debug.Fail("GetItems called on a DkmEvaluationResultEnumContext without an associated EvaluationResults."); throw new NotSupportedException(); } var result = evalResults.Results.Skip(startIndex).Take(count).ToArray(); completionRoutine(new DkmEvaluationEnumAsyncResult(result)); } public void EvaluateExpression(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var name = expression.Text; GetFrameLocals(inspectionContext, workList, stackFrame, getFrameLocalsResult => { getFrameLocalsResult.EnumContext.GetItems(workList, 0, int.MaxValue, localGetItemsResult => { var vars = localGetItemsResult.Items.OfType<DkmSuccessEvaluationResult>(); // TODO: Localization: is it safe to localize [Globals] ? Appears twice in this file var globals = vars.FirstOrDefault(er => er.Name == "[Globals]"); if (globals == null) { if (!EvaluateExpressionByWalkingObjects(vars, inspectionContext, workList, expression, stackFrame, completionRoutine)) { EvaluateExpressionViaInterpreter(inspectionContext, workList, expression, stackFrame, completionRoutine); } } else { globals.GetChildren(workList, 0, inspectionContext, globalsGetChildrenResult => { globalsGetChildrenResult.EnumContext.GetItems(workList, 0, int.MaxValue, globalsGetItemsResult => { vars = vars.Concat(globalsGetItemsResult.Items.OfType<DkmSuccessEvaluationResult>()); if (!EvaluateExpressionByWalkingObjects(vars, inspectionContext, workList, expression, stackFrame, completionRoutine)) { EvaluateExpressionViaInterpreter(inspectionContext, workList, expression, stackFrame, completionRoutine); } }); }); } }); }); } /// <summary> /// Tries to evaluate the given expression by treating it as a chain of member access and indexing operations (e.g. <c>fob[0].oar.baz['abc'].blah</c>), /// and looking up the corresponding members in data model provided by <see cref="GetFrameLocals"/>. /// </summary> /// <param name="vars">List of variables, in the context of which the expression is evaluated.</param> /// <returns> /// <c>true</c> if evaluation was successful, or if it failed and no fallback is possible (e.g. expression is invalid). /// <c>false</c> if evaluation was not successful due to the limitations of this evaluator, and it may be possible to evaluate it correctly by other means. /// </returns> private bool EvaluateExpressionByWalkingObjects(IEnumerable<DkmSuccessEvaluationResult> vars, DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var pyrtInfo = stackFrame.Thread.Process.GetPythonRuntimeInfo(); var parserOptions = new ParserOptions { ErrorSink = new StringErrorSink() }; var parser = Parser.CreateParser(new StringReader(expression.Text), pyrtInfo.LanguageVersion, parserOptions); var expr = ((ReturnStatement)parser.ParseTopExpression(null).Body).Expression; string errorText = parserOptions.ErrorSink.ToString(); if (!string.IsNullOrEmpty(errorText)) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, errorText, DkmEvaluationResultFlags.Invalid, null))); return true; } // Unroll the AST into a sequence of member access and indexing operations, if possible. var path = new Stack<string>(); var reprBuilder = new ReprBuilder(new ReprOptions(stackFrame.Thread.Process)); while (true) { var memberExpr = expr as MemberExpression; if (memberExpr != null) { path.Push(memberExpr.Name); expr = memberExpr.Target; continue; } var indexingExpr = expr as IndexExpression; if (indexingExpr != null) { var indexExpr = indexingExpr.Index as ConstantExpression; if (indexExpr != null) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0:PY}]", indexExpr.Value); path.Push(reprBuilder.ToString()); expr = indexingExpr.Target; continue; } } break; } var varExpr = expr as NameExpression; if (varExpr == null) { return false; } path.Push(varExpr.Name); // Walk the path through Locals while (true) { var name = path.Pop(); var evalResult = vars.FirstOrDefault(er => er.Name == name); if (evalResult == null) { return false; } if (path.Count == 0) { // Clone the evaluation result, but use expression text as its name. DkmDataItem dataItem = (DkmDataItem)evalResult.GetDataItem<PyObjectEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<GlobalsEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<CppViewEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<RawEvaluationResult>(); evalResult = DkmSuccessEvaluationResult.Create( evalResult.InspectionContext, evalResult.StackFrame, expression.Text, expression.Text, evalResult.Flags, evalResult.Value, evalResult.EditableValue, evalResult.Type, evalResult.Category, evalResult.Access, evalResult.StorageType, evalResult.TypeModifierFlags, evalResult.Address, evalResult.CustomUIVisualizers, evalResult.ExternalModules, dataItem); completionRoutine(new DkmEvaluateExpressionAsyncResult(evalResult)); return true; } var childWorkList = DkmWorkList.Create(null); evalResult.GetChildren(childWorkList, 0, inspectionContext, getChildrenResult => getChildrenResult.EnumContext.GetItems(childWorkList, 0, int.MaxValue, getItemsResult => vars = getItemsResult.Items.OfType<DkmSuccessEvaluationResult>())); childWorkList.Execute(); } } private AutoResetEvent _evalCompleteEvent, _evalAbortedEvent; private void EvaluateExpressionViaInterpreter(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var thread = stackFrame.Thread; var process = thread.Process; if (_evalLoopThreadId.Read() != (ulong)thread.SystemPart.Id) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugArbitraryExpressionOnStoppedThreadOnly, DkmEvaluationResultFlags.Invalid, null))); return; } var pythonFrame = PyFrameObject.TryCreate(stackFrame); if (pythonFrame == null) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugNoPythonFrameForCurrentFrame, DkmEvaluationResultFlags.Invalid, null))); return; } byte[] input = Encoding.UTF8.GetBytes(expression.Text + "\0"); if (input.Length > ExpressionEvaluationBufferSize) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugTooLongExpression, DkmEvaluationResultFlags.Invalid, null))); return; } _evalLoopFrame.Write(pythonFrame.Address); process.WriteMemory(_evalLoopInput.Address, input); bool timedOut; using (_evalCompleteEvent = new AutoResetEvent(false)) { thread.BeginFuncEvalExecution(DkmFuncEvalFlags.None); timedOut = !_evalCompleteEvent.WaitOne(ExpressionEvaluationTimeout); _evalCompleteEvent = null; } if (timedOut) { new RemoteComponent.AbortingEvalExecutionRequest().SendLower(process); // We need to stop the process before we can report end of func eval completion using (_evalAbortedEvent = new AutoResetEvent(false)) { process.AsyncBreak(false); if (!_evalAbortedEvent.WaitOne(20000)) { // This is a catastrophic error, since we can't report func eval completion unless we can stop the process, // and VS will stop responding until we do report completion. At this point we can only kill the debuggee so that the // VS at least gets back to a reasonable state. _evalAbortedEvent = null; process.Terminate(1); completionRoutine(DkmEvaluateExpressionAsyncResult.CreateErrorResult( new Exception(Strings.DebugCouldNotAbortFailedExpressionEvaluation))); return; } _evalAbortedEvent = null; } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugEvaluationTimedOut, DkmEvaluationResultFlags.Invalid, null))); return; } ulong objPtr = _evalLoopResult.Read(); var obj = PyObject.FromAddress(process, objPtr); var exc_type = PyObject.FromAddress(process, _evalLoopExcType.Read()); var exc_value = PyObject.FromAddress(process, _evalLoopExcValue.Read()); var exc_str = (PyObject.FromAddress(process, _evalLoopExcStr.Read()) as IPyBaseStringObject).ToStringOrNull(); var sehCode = _evalLoopSEHCode.Read(); if (obj != null) { var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var pyEvalResult = new PythonEvaluationResult(obj, expression.Text) { Flags = DkmEvaluationResultFlags.SideEffect }; var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, pyEvalResult, cppEval, null, hasCppView: true, isOwned: true); _evalLoopResult.Write(0); // don't let the eval loop decref the object - we will do it ourselves later, when eval result is closed completionRoutine(new DkmEvaluateExpressionAsyncResult(evalResult)); } else if (sehCode != 0) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Enum.IsDefined(typeof(EXCEPTION_CODE), sehCode) ? Strings.DebugStructuredExceptionWhileEvaluatingExpression.FormatUI(sehCode, (EXCEPTION_CODE)sehCode) : Strings.DebugStructuredExceptionWhileEvaluatingExpressionNotAnEnumValue.FormatUI(sehCode), DkmEvaluationResultFlags.Invalid, null))); } else if (exc_type != null) { string typeName; var typeObject = exc_type as PyTypeObject; if (typeObject != null) { typeName = typeObject.tp_name.Read().ReadUnicode(); } else { typeName = Strings.DebugUnknownExceptionType; } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugErrorWhileEvaluatingExpression.FormatUI(typeName, exc_str), DkmEvaluationResultFlags.Invalid, null))); } else { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, Strings.DebugUnknownErrorWhileEvaluatingExpression, DkmEvaluationResultFlags.Invalid, null))); } } private void OnEvalComplete(DkmThread thread, ulong frameBase, ulong vframe, ulong returnAddress) { var e = _evalCompleteEvent; if (e != null) { new RemoteComponent.EndFuncEvalExecutionRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); e.Set(); } } public void OnAsyncBreakComplete(DkmThread thread) { var e = _evalAbortedEvent; if (e != null) { new RemoteComponent.EndFuncEvalExecutionRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); e.Set(); } } public string GetUnderlyingString(DkmEvaluationResult result) { var rawResult = result.GetDataItem<RawEvaluationResult>(); if (rawResult != null && rawResult.Value is string) { return (string)rawResult.Value; } var objResult = result.GetDataItem<PyObjectEvaluationResult>(); if (objResult == null) { return null; } var str = objResult.ValueStore.Read() as IPyBaseStringObject; return str.ToStringOrNull(); } private class StringErrorSink : ErrorSink { private readonly StringBuilder _builder = new StringBuilder(); public override void Add(string message, SourceSpan span, int errorCode, Severity severity) { _builder.AppendLine(message); } public override string ToString() { return _builder.ToString(); } } public unsafe void SetValueAsString(DkmEvaluationResult result, string value, int timeout, out string errorText) { var pyEvalResult = result.GetDataItem<PyObjectEvaluationResult>(); if (pyEvalResult == null) { Debug.Fail("SetValueAsString called on a DkmEvaluationResult without an associated PyObjectEvaluationResult."); throw new NotSupportedException(); } var proxy = pyEvalResult.ValueStore as IWritableDataProxy; if (proxy == null) { Debug.Fail("SetValueAsString called on a DkmEvaluationResult that does not correspond to an IWritableDataProxy."); throw new InvalidOperationException(); } errorText = null; var process = result.StackFrame.Process; var pyrtInfo = process.GetPythonRuntimeInfo(); var parserOptions = new ParserOptions { ErrorSink = new StringErrorSink() }; var parser = Parser.CreateParser(new StringReader(value), pyrtInfo.LanguageVersion, parserOptions); var body = (ReturnStatement)parser.ParseTopExpression(null).Body; errorText = parserOptions.ErrorSink.ToString(); if (!string.IsNullOrEmpty(errorText)) { return; } var expr = body.Expression; while (true) { var parenExpr = expr as ParenthesisExpression; if (parenExpr == null) { break; } expr = parenExpr.Expression; } int sign; expr = ForceExplicitSign(expr, out sign); PyObject newObj = null; var constExpr = expr as ConstantExpression; if (constExpr != null) { if (constExpr.Value == null) { newObj = PyObject.None(process); } else if (constExpr.Value is bool) { // In 2.7, 'True' and 'False' are reported as identifiers, not literals, and are handled separately below. newObj = PyBoolObject33.Create(process, (bool)constExpr.Value); } else if (constExpr.Value is string) { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { newObj = PyUnicodeObject27.Create(process, (string)constExpr.Value); } else { newObj = PyUnicodeObject33.Create(process, (string)constExpr.Value); } } else if (constExpr.Value is AsciiString) { newObj = PyBytesObject.Create(process, (AsciiString)constExpr.Value); } } else { var unaryExpr = expr as UnaryExpression; if (unaryExpr != null && sign != 0) { constExpr = unaryExpr.Expression as ConstantExpression; if (constExpr != null) { if (constExpr.Value is BigInteger) { newObj = PyLongObject.Create(process, (BigInteger)constExpr.Value * sign); } else if (constExpr.Value is int) { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { newObj = PyIntObject.Create(process, (int)constExpr.Value * sign); } else { newObj = PyLongObject.Create(process, (int)constExpr.Value * sign); } } else if (constExpr.Value is double) { newObj = PyFloatObject.Create(process, (double)constExpr.Value * sign); } else if (constExpr.Value is Complex) { newObj = PyComplexObject.Create(process, (Complex)constExpr.Value * sign); } } } else { var binExpr = expr as BinaryExpression; if (binExpr != null && (binExpr.Operator == PythonOperator.Add || binExpr.Operator == PythonOperator.Subtract)) { int realSign; var realExpr = ForceExplicitSign(binExpr.Left, out realSign) as UnaryExpression; int imagSign; var imagExpr = ForceExplicitSign(binExpr.Right, out imagSign) as UnaryExpression; if (realExpr != null && realSign != 0 && imagExpr != null && imagSign != 0) { var realConst = realExpr.Expression as ConstantExpression; var imagConst = imagExpr.Expression as ConstantExpression; if (realConst != null && imagConst != null) { var realVal = (realConst.Value as int? ?? realConst.Value as double?) as IConvertible; var imagVal = imagConst.Value as Complex?; if (realVal != null && imagVal != null) { double real = realVal.ToDouble(null) * realSign; double imag = imagVal.Value.Imaginary * imagSign * (binExpr.Operator == PythonOperator.Add ? 1 : -1); newObj = PyComplexObject.Create(process, new Complex(real, imag)); } } } } else { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { // 'True' and 'False' are not literals in 2.x, but we want to treat them as such. var name = expr as NameExpression; if (name != null) { if (name.Name == "True") { newObj = PyBoolObject27.Create(process, true); } else if (name.Name == "False") { newObj = PyBoolObject27.Create(process, false); } } } } } } if (newObj != null) { var oldObj = proxy.Read() as PyObject; if (oldObj != null) { // We can't free the original value without running some code in the process, and it may be holding heap locks. // So don't decrement refcount now, but instead add it to the list of objects for TraceFunc to GC when it gets // a chance to run next time. _process.GetDataItem<PyObjectAllocator>().QueueForDecRef(oldObj); } newObj.ob_refcnt.Increment(); proxy.Write(newObj); } else { errorText = Strings.DebugOnlyBoolNumericStringAndNoneSupported; } } private static Expression ForceExplicitSign(Expression expr, out int sign) { var constExpr = expr as ConstantExpression; if (constExpr != null && (constExpr.Value is int || constExpr.Value is double || constExpr.Value is BigInteger || constExpr.Value is Complex)) { sign = 1; return new UnaryExpression(PythonOperator.Pos, constExpr); } var unaryExpr = expr as UnaryExpression; if (unaryExpr != null) { switch (unaryExpr.Op) { case PythonOperator.Pos: sign = 1; return unaryExpr; case PythonOperator.Negate: sign = -1; return unaryExpr; } } sign = 0; return expr; } } internal class PythonEvaluationResult { /// <summary> /// A store containing the evaluated value. /// </summary> public IValueStore ValueStore { get; set; } /// <summary> /// For named results, name of the result. For unnamed results, <c>null</c>. /// </summary> public string Name { get; set; } public DkmEvaluationResultCategory Category { get; set; } public DkmEvaluationResultAccessType AccessType { get; set; } public DkmEvaluationResultStorageType StorageType { get; set; } public DkmEvaluationResultTypeModifierFlags TypeModifierFlags { get; set; } public DkmEvaluationResultFlags Flags { get; set; } public PythonEvaluationResult(IValueStore valueStore, string name = null) { ValueStore = valueStore; Name = name; Category = DkmEvaluationResultCategory.Data; } } }
using AutoMapper; using FizzWare.NBuilder; using NUnit.Framework; using ReMi.BusinessEntities.Auth; using ReMi.BusinessEntities.BusinessRules; using ReMi.BusinessEntities.DeploymentTool; using ReMi.BusinessEntities.ProductRequests; using ReMi.BusinessEntities.Products; using ReMi.BusinessEntities.ReleasePlan; using ReMi.Common.Constants.BusinessRules; using ReMi.Common.Constants.ReleasePlan; using ReMi.DataAccess.AutoMapper; using ReMi.TestUtils.UnitTests; using System; using System.Collections.Generic; using System.Linq; namespace ReMi.DataAccess.Tests.AutoMapper { [TestFixture] public class BusinessEntityToDataEntityMappingProfileTests : TestClassFor<IMappingEngine> { protected override IMappingEngine ConstructSystemUnderTest() { Mapper.Initialize( c => c.AddProfile<BusinessEntityToDataEntityMappingProfile>()); return Mapper.Engine; } [Test] public void ReleaseContentMapping_ShouldReturnTicket_WhenMapInvoked() { var ticket = Builder<ReleaseContentTicket>.CreateNew() .With(x => x.Comment, RandomData.RandomString(10)) .With(x => x.TicketDescription, RandomData.RandomString(10)) .With(x => x.Assignee, RandomData.RandomString(10)) .With(x => x.TicketId, Guid.NewGuid()) .With(x => x.TicketName, "RM-" + RandomData.RandomInt(4)) .With(x => x.Risk, RandomData.RandomEnum<TicketRisk>()) .With(x => x.LastChangedByAccount, Guid.NewGuid()) .Build(); var expected = Builder<DataEntities.ReleasePlan.ReleaseContent>.CreateNew() .With(x => x.Comment, ticket.Comment) .With(x => x.Description, ticket.TicketDescription) .With(x => x.Assignee, ticket.Assignee) .With(x => x.TicketKey, ticket.TicketName) .With(x => x.TicketId, ticket.TicketId) .With(x => x.TicketRisk, ticket.Risk) .With(x => x.LastChangedByAccount, Builder<DataEntities.Auth.Account>.CreateNew() .With(y => y.ExternalId, ticket.LastChangedByAccount) .Build()) .Build(); var actual = Sut.Map<ReleaseContentTicket, DataEntities.ReleasePlan.ReleaseContent>(ticket); Assert.AreEqual(expected.Comment, actual.Comment); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.Assignee, actual.Assignee); Assert.AreEqual(expected.TicketId, actual.TicketId); Assert.AreEqual(expected.TicketKey, actual.TicketKey); Assert.AreEqual(expected.TicketRisk, actual.TicketRisk); Assert.AreEqual(expected.LastChangedByAccount.ExternalId, actual.LastChangedByAccount.ExternalId); } [Test] public void RoleMapping_ShouldReturnRole_WhenMapInvoked() { var role = Builder<Role>.CreateNew() .With(x => x.Name, RandomData.RandomString(10)) .With(x => x.Description, RandomData.RandomString(10)) .With(x => x.ExternalId, Guid.NewGuid()) .Build(); var expected = Builder<DataEntities.Auth.Role>.CreateNew() .With(x => x.Name, role.Name) .With(x => x.Description, role.Description) .With(x => x.ExternalId, role.ExternalId) .Build(); var actual = Sut.Map<Role, DataEntities.Auth.Role>(role); Assert.AreEqual(expected.Name, actual.Name); Assert.AreEqual(expected.Description, actual.Description); Assert.AreEqual(expected.ExternalId, actual.ExternalId); Assert.AreEqual(0, actual.Id); } [Test] public void ProductRequestType_ShouldReturnValidType_WhenMapInvoked() { var source = Builder<ProductRequestType>.CreateNew() .With(x => x.Name, RandomData.RandomString(100)) .With(x => x.ExternalId, Guid.NewGuid()) .With(x => x.RequestGroups, Builder<ProductRequestGroup>.CreateListOfSize(1) .All() .With(o => o.ExternalId) .Build() ) .Build(); var actual = Sut.Map<ProductRequestType, DataEntities.ProductRequests.ProductRequestType>(source); Assert.IsNull(actual.RequestGroups, "request groups"); Assert.AreEqual(source.Name, actual.Name, "name"); Assert.AreEqual(source.ExternalId, actual.ExternalId, "external id"); } [Test] public void ProductRequestGroupAssignee_ShouldReturnValidType_WhenMapInvoked() { var source = Builder<Account>.CreateNew() .With(x => x.FullName, RandomData.RandomString(100)) .With(x => x.ExternalId, Guid.NewGuid()) .With(x => x.Email, RandomData.RandomEmail()) .Build(); var actual = Sut.Map<Account, DataEntities.ProductRequests.ProductRequestGroupAssignee>(source); Assert.IsNull(actual.RequestGroup, "request group"); Assert.IsNotNull(actual.Account, "account"); Assert.AreEqual(source.ExternalId, actual.Account.ExternalId, "external id"); Assert.AreEqual(source.FullName, actual.Account.FullName, "full name"); } [Test] public void BusinessRuleParameterMapping_ShouldReturnProperType_WhenConvertingToBusinessType() { var parameter = new BusinessRuleParameter { ExternalId = Guid.NewGuid(), Name = RandomData.RandomString(10), Type = "int", TestData = new BusinessRuleTestData { ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) } }; var actual = Sut.Map<BusinessRuleParameter, DataEntities.BusinessRules.BusinessRuleParameter>(parameter); Assert.AreEqual(parameter.Type, actual.Type); Assert.AreEqual(parameter.ExternalId, actual.ExternalId); Assert.AreEqual(parameter.Name, actual.Name); Assert.AreEqual(parameter.TestData.JsonData, actual.TestData.JsonData); Assert.AreEqual(parameter.TestData.ExternalId, actual.TestData.ExternalId); } [Test] public void BusinessRuleTestDataMapping_ShouldReturnProperType_WhenConvertingToBusinessType() { var testData = new BusinessRuleTestData { ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) }; var actual = Sut.Map<BusinessRuleTestData, DataEntities.BusinessRules.BusinessRuleTestData>(testData); Assert.AreEqual(testData.JsonData, actual.JsonData); Assert.AreEqual(testData.ExternalId, actual.ExternalId); } [Test] public void BusinessRuleAccountTestDataMapping_ShouldReturnProperType_WhenConvertingToBusinessType() { var testData = new BusinessRuleAccountTestData { ExternalId = Guid.NewGuid(), JsonData = RandomData.RandomString(10) }; var actual = Sut.Map<BusinessRuleAccountTestData, DataEntities.BusinessRules.BusinessRuleAccountTestData>(testData); Assert.AreEqual(testData.JsonData, actual.JsonData); Assert.AreEqual(testData.ExternalId, actual.ExternalId); } [Test] public void BusinessRuleDescriptionMapping_ShouldReturnProperEnumType_WhenConvertingToBusinessType() { var rule = new BusinessRuleDescription { Script = RandomData.RandomString(10), Group = RandomData.RandomEnum<BusinessRuleGroup>(), ExternalId = Guid.NewGuid(), Parameters = new List<BusinessRuleParameter> { new BusinessRuleParameter { ExternalId = Guid.NewGuid(), Name = RandomData.RandomString(10), Type = "System.Int32" } } }; var actual = Sut.Map<BusinessRuleDescription, DataEntities.BusinessRules.BusinessRuleDescription>(rule); Assert.AreEqual(rule.Group, actual.Group); Assert.AreEqual(rule.ExternalId, actual.ExternalId); Assert.AreEqual(rule.Script, actual.Script); Assert.AreEqual(rule.Parameters.Count(), actual.Parameters.Count); } [Test] public void ProductRequestRegistration() { var source = Builder<ProductRequestRegistration>.CreateNew() .With(x => x.Description, RandomData.RandomString(100)) .With(x => x.ExternalId, Guid.NewGuid()) .With(x => x.CreatedOn, DateTime.Now) .With(x => x.CreatedBy, RandomData.RandomString(1, 20)) .With(x => x.CreatedByAccountId, Guid.NewGuid()) .With(x => x.Tasks, Builder<ProductRequestRegistrationTask>.CreateListOfSize(RandomData.RandomInt(1, 5)) .All() .With(o => o.ProductRequestTaskId, Guid.NewGuid()) .Build()) .Build(); var actual = Sut.Map<ProductRequestRegistration, DataEntities.ProductRequests.ProductRequestRegistration>(source); Assert.IsNotNull(actual, "request registration"); Assert.AreEqual(source.Description, actual.Description); Assert.AreEqual(source.ExternalId, actual.ExternalId); Assert.IsNull(actual.CreatedBy); Assert.AreEqual(source.CreatedOn, actual.CreatedOn.ToLocalTime()); Assert.AreEqual(DateTimeKind.Utc, actual.CreatedOn.Kind); Assert.IsNull(actual.Tasks, "tasks"); } [Test] public void ProductRequestRegistrationTask() { var source = Builder<ProductRequestRegistrationTask>.CreateNew() .With(x => x.IsCompleted, RandomData.RandomBool()) .With(x => x.ProductRequestTaskId, Guid.NewGuid()) .With(x => x.LastChangedOn, DateTime.Now) .With(x => x.LastChangedBy, RandomData.RandomString(1, 20)) .With(x => x.LastChangedByAccountId, Guid.NewGuid()) .Build(); var actual = Sut.Map<ProductRequestRegistrationTask, DataEntities.ProductRequests.ProductRequestRegistrationTask>(source); Assert.IsNotNull(actual, "request registration task"); Assert.AreEqual(source.IsCompleted, actual.IsCompleted); Assert.IsNull(actual.ProductRequestTask); Assert.IsNull(actual.LastChangedBy); Assert.IsNull(actual.LastChangedOn); } [Test] public void ReleaseJob_ShouldReturnDataReleaseJob_WhenMapFromBusinessEntity() { var releaseJob = new ReleaseJob { ExternalId = Guid.NewGuid(), IsIncluded = RandomData.RandomBool(), JobId = Guid.NewGuid(), Name = RandomData.RandomString(10), Order = RandomData.RandomInt(100) }; var result = Sut.Map<ReleaseJob, DataEntities.ReleasePlan.ReleaseJob>(releaseJob); Assert.AreEqual(releaseJob.ExternalId, result.ExternalId); Assert.AreEqual(releaseJob.IsIncluded, result.IsIncluded); Assert.AreEqual(releaseJob.JobId, result.JobId); Assert.AreEqual(releaseJob.Name, result.Name); Assert.AreEqual(releaseJob.Order, result.Order); } [Test] public void BusinessUnit_ShouldReturnDataBusinessUnit_WhenMapFromBusinessEntity() { var businessUnit = new BusinessUnit { ExternalId = Guid.NewGuid(), Description = RandomData.RandomString(10), Name = RandomData.RandomString(10), Packages = Builder<Product>.CreateListOfSize(5).Build() }; var result = Sut.Map<BusinessUnit, DataEntities.Products.BusinessUnit>(businessUnit); Assert.AreEqual(businessUnit.ExternalId, result.ExternalId); Assert.AreEqual(businessUnit.Description, result.Description); Assert.AreEqual(businessUnit.Name, result.Name); Assert.IsNull(result.Packages); } } }
namespace WYZTracker { partial class SongProperties { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SongProperties)); this.songTempo = new System.Windows.Forms.NumericUpDown(); this.songBindingSource = new System.Windows.Forms.BindingSource(this.components); this.lblTempo = new System.Windows.Forms.Label(); this.cboChannels = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.txtSongName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.chkLooped = new System.Windows.Forms.CheckBox(); this.cboFrequency = new System.Windows.Forms.ComboBox(); this.label3 = new System.Windows.Forms.Label(); this.numLoopTo = new System.Windows.Forms.NumericUpDown(); this.lblCurrentTempo = new System.Windows.Forms.Label(); this.rbPAL = new System.Windows.Forms.RadioButton(); this.rbNTSC = new System.Windows.Forms.RadioButton(); ((System.ComponentModel.ISupportInitialize)(this.songTempo)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.songBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numLoopTo)).BeginInit(); this.SuspendLayout(); // // songTempo // resources.ApplyResources(this.songTempo, "songTempo"); this.songTempo.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.songBindingSource, "Tempo", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.songTempo.Maximum = new decimal(new int[] { 255, 0, 0, 0}); this.songTempo.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.songTempo.Name = "songTempo"; this.songTempo.Value = new decimal(new int[] { 120, 0, 0, 0}); // // songBindingSource // this.songBindingSource.DataSource = typeof(WYZTracker.Song); // // lblTempo // resources.ApplyResources(this.lblTempo, "lblTempo"); this.lblTempo.Name = "lblTempo"; // // cboChannels // resources.ApplyResources(this.cboChannels, "cboChannels"); this.cboChannels.DataBindings.Add(new System.Windows.Forms.Binding("SelectedItem", this.songBindingSource, "Channels", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.cboChannels.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboChannels.FormattingEnabled = true; this.cboChannels.Items.AddRange(new object[] { resources.GetString("cboChannels.Items"), resources.GetString("cboChannels.Items1"), resources.GetString("cboChannels.Items2"), resources.GetString("cboChannels.Items3"), resources.GetString("cboChannels.Items4"), resources.GetString("cboChannels.Items5"), resources.GetString("cboChannels.Items6"), resources.GetString("cboChannels.Items7")}); this.cboChannels.Name = "cboChannels"; this.cboChannels.SelectedIndexChanged += new System.EventHandler(this.cboChannels_SelectedIndexChanged); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // txtSongName // resources.ApplyResources(this.txtSongName, "txtSongName"); this.txtSongName.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.songBindingSource, "Name", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.txtSongName.Name = "txtSongName"; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // chkLooped // resources.ApplyResources(this.chkLooped, "chkLooped"); this.chkLooped.DataBindings.Add(new System.Windows.Forms.Binding("Checked", this.songBindingSource, "Looped", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.chkLooped.Name = "chkLooped"; this.chkLooped.UseVisualStyleBackColor = true; // // cboFrequency // resources.ApplyResources(this.cboFrequency, "cboFrequency"); this.cboFrequency.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.songBindingSource, "ChipFrequency", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.cboFrequency.DisplayMember = "Key"; this.cboFrequency.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboFrequency.FormattingEnabled = true; this.cboFrequency.Name = "cboFrequency"; this.cboFrequency.ValueMember = "Value"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // numLoopTo // resources.ApplyResources(this.numLoopTo, "numLoopTo"); this.numLoopTo.DataBindings.Add(new System.Windows.Forms.Binding("Value", this.songBindingSource, "LoopToPattern", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.numLoopTo.Maximum = new decimal(new int[] { 9999999, 0, 0, 0}); this.numLoopTo.Name = "numLoopTo"; this.numLoopTo.ValueChanged += new System.EventHandler(this.numLoopTo_ValueChanged); // // lblCurrentTempo // resources.ApplyResources(this.lblCurrentTempo, "lblCurrentTempo"); this.lblCurrentTempo.Name = "lblCurrentTempo"; // // rbPAL // resources.ApplyResources(this.rbPAL, "rbPAL"); this.rbPAL.Name = "rbPAL"; this.rbPAL.TabStop = true; this.rbPAL.UseVisualStyleBackColor = true; this.rbPAL.CheckedChanged += new System.EventHandler(this.rbPAL_CheckedChanged); // // rbNTSC // resources.ApplyResources(this.rbNTSC, "rbNTSC"); this.rbNTSC.Name = "rbNTSC"; this.rbNTSC.TabStop = true; this.rbNTSC.UseVisualStyleBackColor = true; this.rbNTSC.CheckedChanged += new System.EventHandler(this.rbNTSC_CheckedChanged); // // SongProperties // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.rbNTSC); this.Controls.Add(this.rbPAL); this.Controls.Add(this.lblCurrentTempo); this.Controls.Add(this.numLoopTo); this.Controls.Add(this.label3); this.Controls.Add(this.cboFrequency); this.Controls.Add(this.chkLooped); this.Controls.Add(this.songTempo); this.Controls.Add(this.lblTempo); this.Controls.Add(this.cboChannels); this.Controls.Add(this.label2); this.Controls.Add(this.txtSongName); this.Controls.Add(this.label1); this.Name = "SongProperties"; ((System.ComponentModel.ISupportInitialize)(this.songTempo)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.songBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numLoopTo)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.NumericUpDown songTempo; private System.Windows.Forms.Label lblTempo; private System.Windows.Forms.ComboBox cboChannels; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtSongName; private System.Windows.Forms.Label label1; private System.Windows.Forms.BindingSource songBindingSource; private System.Windows.Forms.CheckBox chkLooped; private System.Windows.Forms.ComboBox cboFrequency; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown numLoopTo; private System.Windows.Forms.Label lblCurrentTempo; private System.Windows.Forms.RadioButton rbPAL; private System.Windows.Forms.RadioButton rbNTSC; } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.CodeGeneration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans { internal class InvokableObjectManager : IDisposable { private readonly CancellationTokenSource disposed = new CancellationTokenSource(); private readonly ConcurrentDictionary<ObserverGrainId, LocalObjectData> localObjects = new ConcurrentDictionary<ObserverGrainId, LocalObjectData>(); private readonly IGrainContext rootGrainContext; private readonly IRuntimeClient runtimeClient; private readonly ILogger logger; private readonly SerializationManager serializationManager; private readonly MessagingTrace messagingTrace; private readonly Func<object, Task> dispatchFunc; public InvokableObjectManager( IGrainContext rootGrainContext, IRuntimeClient runtimeClient, SerializationManager serializationManager, MessagingTrace messagingTrace, ILogger logger) { this.rootGrainContext = rootGrainContext; this.runtimeClient = runtimeClient; this.serializationManager = serializationManager; this.messagingTrace = messagingTrace; this.logger = logger; this.dispatchFunc = o => this.LocalObjectMessagePumpAsync((LocalObjectData) o); } public bool TryRegister(IAddressable obj, ObserverGrainId objectId, IGrainMethodInvoker invoker) { return this.localObjects.TryAdd(objectId, new LocalObjectData(obj, objectId, invoker, this.rootGrainContext)); } public bool TryDeregister(ObserverGrainId objectId) { return this.localObjects.TryRemove(objectId, out _); } public void Dispatch(Message message) { if (!ObserverGrainId.TryParse(message.TargetGrain, out var observerId)) { this.logger.LogError( (int)ErrorCode.ProxyClient_OGC_TargetNotFound_2, "Message is not addresses to an observer. {Message}", message); return; } if (this.localObjects.TryGetValue(observerId, out var objectData)) { this.Invoke(objectData, message); } else { this.logger.Error( ErrorCode.ProxyClient_OGC_TargetNotFound, String.Format( "Unexpected target grain in request: {0}. Message={1}", message.TargetGrain, message)); } } private void Invoke(LocalObjectData objectData, Message message) { var obj = (IAddressable)objectData.LocalObject.Target; if (obj == null) { //// Remove from the dictionary record for the garbage collected object? But now we won't be able to detect invalid dispatch IDs anymore. this.logger.Warn( ErrorCode.Runtime_Error_100162, string.Format( "Object associated with Observer ID {0} has been garbage collected. Deleting object reference and unregistering it. Message = {1}", objectData.ObserverId, message)); // Try to remove. If it's not there, we don't care. this.TryDeregister(objectData.ObserverId); return; } bool start; lock (objectData.Messages) { objectData.Messages.Enqueue(message); start = !objectData.Running; objectData.Running = true; } if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace($"InvokeLocalObjectAsync {message} start {start}"); if (start) { // we want to ensure that the message pump operates asynchronously // with respect to the current thread. see // http://channel9.msdn.com/Events/TechEd/Europe/2013/DEV-B317#fbid=aIWUq0ssW74 // at position 54:45. // // according to the information posted at: // http://stackoverflow.com/questions/12245935/is-task-factory-startnew-guaranteed-to-use-another-thread-than-the-calling-thr // this idiom is dependent upon the a TaskScheduler not implementing the // override QueueTask as task inlining (as opposed to queueing). this seems // implausible to the author, since none of the .NET schedulers do this and // it is considered bad form (the OrleansTaskScheduler does not do this). // // if, for some reason this doesn't hold true, we can guarantee what we // want by passing a placeholder continuation token into Task.StartNew() // instead. i.e.: // // return Task.StartNew(() => ..., new CancellationToken()); // We pass these options to Task.Factory.StartNew as they make the call identical // to Task.Run. See: https://blogs.msdn.microsoft.com/pfxteam/2011/10/24/task-run-vs-task-factory-startnew/ Task.Factory.StartNew( this.dispatchFunc, objectData, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default).Ignore(); } } private async Task LocalObjectMessagePumpAsync(LocalObjectData objectData) { while (true) { try { Message message; lock (objectData.Messages) { if (objectData.Messages.Count == 0) { objectData.Running = false; break; } message = objectData.Messages.Dequeue(); } if (message.IsExpired) { this.messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Invoke); continue; } RequestContextExtensions.Import(message.RequestContextData); InvokeMethodRequest request = null; try { request = (InvokeMethodRequest) message.BodyObject; } catch (Exception deserializationException) { if (this.logger.IsEnabled(LogLevel.Warning)) { this.logger.LogWarning( "Exception during message body deserialization in " + nameof(LocalObjectMessagePumpAsync) + " for message: {Message}, Exception: {Exception}", message, deserializationException); } this.runtimeClient.SendResponse(message, Response.ExceptionResponse(deserializationException)); continue; } var targetOb = (IAddressable)objectData.LocalObject.Target; object resultObject = null; Exception caught = null; try { // exceptions thrown within this scope are not considered to be thrown from user code // and not from runtime code. var resultPromise = objectData.Invoker.Invoke(objectData, request); if (resultPromise != null) // it will be null for one way messages { resultObject = await resultPromise; } } catch (Exception exc) { // the exception needs to be reported in the log or propagated back to the caller. caught = exc; } if (caught != null) this.ReportException(message, caught); else if (message.Direction != Message.Directions.OneWay) this.SendResponseAsync(message, resultObject); } catch (Exception outerException) { // ignore, keep looping. this.logger.LogWarning("Exception in " + nameof(LocalObjectMessagePumpAsync) + ": {Exception}", outerException); } finally { RequestContext.Clear(); } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void SendResponseAsync(Message message, object resultObject) { if (message.IsExpired) { this.messagingTrace.OnDropExpiredMessage(message, MessagingStatisticsGroup.Phase.Respond); return; } object deepCopy; try { // we're expected to notify the caller if the deep copy failed. deepCopy = this.serializationManager.DeepCopy(resultObject); } catch (Exception exc2) { this.runtimeClient.SendResponse(message, Response.ExceptionResponse(exc2)); this.logger.Warn( ErrorCode.ProxyClient_OGC_SendResponseFailed, "Exception trying to send a response.", exc2); return; } // the deep-copy succeeded. this.runtimeClient.SendResponse(message, new Response(deepCopy)); return; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ReportException(Message message, Exception exception) { var request = (InvokeMethodRequest)message.BodyObject; switch (message.Direction) { case Message.Directions.OneWay: { this.logger.Error( ErrorCode.ProxyClient_OGC_UnhandledExceptionInOneWayInvoke, String.Format( "Exception during invocation of notification method {0}, interface {1}. Ignoring exception because this is a one way request.", request.MethodId, request.InterfaceTypeCode), exception); break; } case Message.Directions.Request: { Exception deepCopy; try { // we're expected to notify the caller if the deep copy failed. deepCopy = (Exception)this.serializationManager.DeepCopy(exception); } catch (Exception ex2) { this.runtimeClient.SendResponse(message, Response.ExceptionResponse(ex2)); this.logger.Warn( ErrorCode.ProxyClient_OGC_SendExceptionResponseFailed, "Exception trying to send an exception response", ex2); return; } // the deep-copy succeeded. var response = Response.ExceptionResponse(deepCopy); this.runtimeClient.SendResponse(message, response); break; } default: throw new InvalidOperationException($"Unrecognized direction for message {message}, request {request}, which resulted in exception: {exception}"); } } public class LocalObjectData : IGrainContext { private readonly IGrainContext _rootGrainContext; internal LocalObjectData(IAddressable obj, ObserverGrainId observerId, IGrainMethodInvoker invoker, IGrainContext rootGrainContext) { this.LocalObject = new WeakReference(obj); this.ObserverId = observerId; this.Invoker = invoker; this.Messages = new Queue<Message>(); this.Running = false; _rootGrainContext = rootGrainContext; } internal WeakReference LocalObject { get; } internal IGrainMethodInvoker Invoker { get; } internal ObserverGrainId ObserverId { get; } internal Queue<Message> Messages { get; } internal bool Running { get; set; } GrainId IGrainContext.GrainId => this.ObserverId.GrainId; GrainReference IGrainContext.GrainReference => (this.LocalObject.Target as IAddressable).AsReference(); IAddressable IGrainContext.GrainInstance => this.LocalObject.Target as IAddressable; ActivationId IGrainContext.ActivationId => throw new NotImplementedException(); ActivationAddress IGrainContext.Address => throw new NotImplementedException(); IServiceProvider IGrainContext.ActivationServices => throw new NotSupportedException(); IGrainLifecycle IGrainContext.ObservableLifecycle => throw new NotImplementedException(); void IGrainContext.SetComponent<TComponent>(TComponent value) { if (this.LocalObject.Target is TComponent component) { throw new ArgumentException("Cannot override a component which is implemented by this grain"); } _rootGrainContext.SetComponent(value); } TComponent IGrainContext.GetComponent<TComponent>() { if (this.LocalObject.Target is TComponent component) { return component; } return _rootGrainContext.GetComponent<TComponent>(); } bool IEquatable<IGrainContext>.Equals(IGrainContext other) => ReferenceEquals(this, other); } public void Dispose() { var tokenSource = this.disposed; Utils.SafeExecute(() => tokenSource?.Cancel(false)); Utils.SafeExecute(() => tokenSource?.Dispose()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableInterlockedTests { private delegate bool UpdateDelegate<T>(ref T location, Func<T, T> transformer); [Fact] public void Update_StartWithNull() { UpdateHelper<ImmutableList<int>>(func => { ImmutableList<int> list = null; Assert.True(func(ref list, l => { Assert.Null(l); return ImmutableList.Create(1); })); Assert.Equal(1, list.Count); Assert.Equal(1, list[0]); }); } [Fact] public void Update_IncrementalUpdate() { UpdateHelper<ImmutableList<int>>(func => { ImmutableList<int> list = ImmutableList.Create(1); Assert.True(func(ref list, l => l.Add(2))); Assert.Equal(2, list.Count); Assert.Equal(1, list[0]); Assert.Equal(2, list[1]); }); } [Fact] public void Update_FuncThrowsThrough() { UpdateHelper<ImmutableList<int>>(func => { ImmutableList<int> list = ImmutableList.Create(1); Assert.Throws<InvalidOperationException>(() => func(ref list, l => { throw new InvalidOperationException(); })); }); } [Fact] public void Update_NoEffectualChange() { UpdateHelper<ImmutableList<int>>(func => { ImmutableList<int> list = ImmutableList.Create<int>(1); Assert.False(func(ref list, l => l)); }); } [Fact] public void Update_HighConcurrency() { UpdateHelper<ImmutableList<int>>(func => { ImmutableList<int> list = ImmutableList.Create<int>(); int concurrencyLevel = Environment.ProcessorCount; int iterations = 500; Task[] tasks = new Task[concurrencyLevel]; var barrier = new Barrier(tasks.Length); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Run(delegate { // Maximize concurrency by blocking this thread until all the other threads are ready to go as well. barrier.SignalAndWait(); for (int j = 0; j < iterations; j++) { Assert.True(func(ref list, l => l.Add(l.Count))); } }); } Task.WaitAll(tasks); Assert.Equal(concurrencyLevel * iterations, list.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(i, list[i]); } }); } [Fact] public void Update_CarefullyScheduled() { UpdateHelper<ImmutableHashSet<int>>(func => { var set = ImmutableHashSet.Create<int>(); var task2TransformEntered = new AutoResetEvent(false); var task1TransformExited = new AutoResetEvent(false); var task1 = Task.Run(delegate { int transform1ExecutionCounter = 0; func( ref set, s => { Assert.Equal(1, ++transform1ExecutionCounter); task2TransformEntered.WaitOne(); return s.Add(1); }); task1TransformExited.Set(); Assert.Equal(1, transform1ExecutionCounter); }); var task2 = Task.Run(delegate { int transform2ExecutionCounter = 0; func( ref set, s => { switch (++transform2ExecutionCounter) { case 1: task2TransformEntered.Set(); task1TransformExited.WaitOne(); Assert.True(s.IsEmpty); break; case 2: Assert.True(s.Contains(1)); Assert.Equal(1, s.Count); break; } return s.Add(2); }); // Verify that this transform had to execute twice. Assert.Equal(2, transform2ExecutionCounter); }); // Wait for all tasks and rethrow any exceptions. Task.WaitAll(task1, task2); Assert.Equal(2, set.Count); Assert.True(set.Contains(1)); Assert.True(set.Contains(2)); }); } [Fact] public void InterlockedExchangeArrayDefault() { ImmutableArray<int> array = default(ImmutableArray<int>); var oldValue = ImmutableInterlocked.InterlockedExchange(ref array, ImmutableArray.Create<int>()); Assert.True(oldValue.IsDefault); Assert.False(array.IsDefault); } [Fact] public void InterlockedExchangeArrayNonDefault() { ImmutableArray<int> array = ImmutableArray.Create(1, 2, 3); var oldValue = ImmutableInterlocked.InterlockedExchange(ref array, ImmutableArray.Create<int>(4, 5, 6)); Assert.Equal(new[] { 1, 2, 3 }, oldValue); Assert.Equal(new[] { 4, 5, 6 }, array); } [Fact] public void InterlockedCompareExchangeArrayDefault() { ImmutableArray<int> array = default(ImmutableArray<int>); var oldValue = ImmutableInterlocked.InterlockedCompareExchange(ref array, ImmutableArray.Create<int>(4, 5, 6), default(ImmutableArray<int>)); } [Fact] public void InterlockedCompareExchangeArray() { ImmutableArray<int> array = ImmutableArray.Create(1, 2, 3); var oldValue = ImmutableInterlocked.InterlockedCompareExchange(ref array, ImmutableArray.Create<int>(4, 5, 6), default(ImmutableArray<int>)); Assert.Equal(array.AsEnumerable(), oldValue); var arrayBefore = array; oldValue = ImmutableInterlocked.InterlockedCompareExchange(ref array, ImmutableArray.Create<int>(4, 5, 6), array); Assert.Equal(oldValue.AsEnumerable(), arrayBefore); Assert.Equal(new[] { 4, 5, 6 }, array); } [Fact] public void InterlockedInitializeArray() { ImmutableArray<int> array = default(ImmutableArray<int>); Assert.True(ImmutableInterlocked.InterlockedInitialize(ref array, ImmutableArray.Create<int>())); Assert.False(array.IsDefault); Assert.False(ImmutableInterlocked.InterlockedInitialize(ref array, ImmutableArray.Create(1, 2, 3))); Assert.True(array.IsEmpty); } [Fact] public void GetOrAddDictionaryValue() { var dictionary = ImmutableDictionary.Create<int, string>(); string value = ImmutableInterlocked.GetOrAdd(ref dictionary, 1, "a"); Assert.Equal("a", value); value = ImmutableInterlocked.GetOrAdd(ref dictionary, 1, "b"); Assert.Equal("a", value); } [Fact] public void GetOrAddDictionaryValueFactory() { var dictionary = ImmutableDictionary.Create<int, string>(); string value = ImmutableInterlocked.GetOrAdd( ref dictionary, 1, key => { Assert.Equal(1, key); return "a"; }); Assert.Equal("a", value); value = ImmutableInterlocked.GetOrAdd( ref dictionary, 1, key => { throw new ShouldNotBeInvokedException(); } ); Assert.Equal("a", value); } [Fact] public void GetOrAddDictionaryValueFactoryWithArg() { var dictionary = ImmutableDictionary.Create<int, string>(); string value = ImmutableInterlocked.GetOrAdd( ref dictionary, 1, (key, arg) => { Assert.True(arg); Assert.Equal(1, key); return "a"; }, true); Assert.Equal("a", value); value = ImmutableInterlocked.GetOrAdd( ref dictionary, 1, (key, arg) => { throw new ShouldNotBeInvokedException(); }, true); Assert.Equal("a", value); } [Fact] public void AddOrUpdateDictionaryAddValue() { var dictionary = ImmutableDictionary.Create<int, string>(); string value = ImmutableInterlocked.AddOrUpdate(ref dictionary, 1, "a", (k, v) => { throw new ShouldNotBeInvokedException(); }); Assert.Equal("a", value); Assert.Equal("a", dictionary[1]); value = ImmutableInterlocked.AddOrUpdate(ref dictionary, 1, "c", (k, v) => { Assert.Equal("a", v); return "b"; }); Assert.Equal("b", value); Assert.Equal("b", dictionary[1]); } [Fact] public void AddOrUpdateDictionaryAddValueFactory() { var dictionary = ImmutableDictionary.Create<int, string>(); string value = ImmutableInterlocked.AddOrUpdate(ref dictionary, 1, k => "a", (k, v) => { throw new ShouldNotBeInvokedException(); }); Assert.Equal("a", value); Assert.Equal("a", dictionary[1]); value = ImmutableInterlocked.AddOrUpdate(ref dictionary, 1, k => { throw new ShouldNotBeInvokedException(); }, (k, v) => { Assert.Equal("a", v); return "b"; }); Assert.Equal("b", value); Assert.Equal("b", dictionary[1]); } [Fact] public void TryAddDictionary() { var dictionary = ImmutableDictionary.Create<int, string>(); Assert.True(ImmutableInterlocked.TryAdd(ref dictionary, 1, "a")); Assert.Equal("a", dictionary[1]); Assert.False(ImmutableInterlocked.TryAdd(ref dictionary, 1, "a")); Assert.False(ImmutableInterlocked.TryAdd(ref dictionary, 1, "b")); Assert.Equal("a", dictionary[1]); } [Fact] public void TryUpdateDictionary() { var dictionary = ImmutableDictionary.Create<int, string>(); // missing var before = dictionary; Assert.False(ImmutableInterlocked.TryUpdate(ref dictionary, 1, "a", "b")); Assert.Same(before, dictionary); // mismatched existing value before = dictionary = dictionary.SetItem(1, "b"); Assert.False(ImmutableInterlocked.TryUpdate(ref dictionary, 1, "a", "c")); Assert.Same(before, dictionary); // match Assert.True(ImmutableInterlocked.TryUpdate(ref dictionary, 1, "c", "b")); Assert.NotSame(before, dictionary); Assert.Equal("c", dictionary[1]); } [Fact] public void TryRemoveDictionary() { var dictionary = ImmutableDictionary.Create<int, string>(); string value; Assert.False(ImmutableInterlocked.TryRemove(ref dictionary, 1, out value)); Assert.Null(value); dictionary = dictionary.Add(1, "a"); Assert.True(ImmutableInterlocked.TryRemove(ref dictionary, 1, out value)); Assert.Equal("a", value); Assert.True(dictionary.IsEmpty); } [Fact] public void PushStack() { var stack = ImmutableStack.Create<int>(); ImmutableInterlocked.Push(ref stack, 5); Assert.False(stack.IsEmpty); Assert.Equal(5, stack.Peek()); Assert.True(stack.Pop().IsEmpty); ImmutableInterlocked.Push(ref stack, 8); Assert.Equal(8, stack.Peek()); Assert.Equal(5, stack.Pop().Peek()); } [Fact] public void TryPopStack() { var stack = ImmutableStack.Create<int>(); int value; Assert.False(ImmutableInterlocked.TryPop(ref stack, out value)); Assert.Equal(0, value); stack = stack.Push(2).Push(3); Assert.True(ImmutableInterlocked.TryPop(ref stack, out value)); Assert.Equal(3, value); Assert.Equal(2, stack.Peek()); Assert.True(stack.Pop().IsEmpty); } [Fact] public void TryDequeueQueue() { var queue = ImmutableQueue.Create<int>(); int value; Assert.False(ImmutableInterlocked.TryDequeue(ref queue, out value)); Assert.Equal(0, value); queue = queue.Enqueue(1).Enqueue(2); Assert.True(ImmutableInterlocked.TryDequeue(ref queue, out value)); Assert.Equal(1, value); Assert.True(ImmutableInterlocked.TryDequeue(ref queue, out value)); Assert.Equal(2, value); Assert.False(ImmutableInterlocked.TryDequeue(ref queue, out value)); Assert.Equal(0, value); } [Fact] public void EnqueueQueue() { var queue = ImmutableQueue.Create<int>(); ImmutableInterlocked.Enqueue(ref queue, 1); Assert.Equal(1, queue.Peek()); Assert.True(queue.Dequeue().IsEmpty); ImmutableInterlocked.Enqueue(ref queue, 2); Assert.Equal(1, queue.Peek()); Assert.Equal(2, queue.Dequeue().Peek()); Assert.True(queue.Dequeue().Dequeue().IsEmpty); } /// <summary> /// Executes a test against both <see cref="ImmutableInterlocked.Update{T}(ref T, Func{T, T})"/> /// and <see cref="ImmutableInterlocked.Update{T, TArg}(ref T, Func{T, TArg, T}, TArg)"/>. /// </summary> /// <typeparam name="T">The type of value under test.</typeparam> /// <param name="test"> /// The test to execute. Invoke the parameter instead of calling /// the ImmutableInterlocked method so that the delegate can test both overloads /// by being executed twice. /// </param> private static void UpdateHelper<T>(Action<UpdateDelegate<T>> test) where T : class { test(ImmutableInterlocked.Update<T>); test(UpdateWrapper<T>); } /// <summary> /// A wrapper that makes one overload look like another so the same test delegate can execute against both. /// </summary> /// <typeparam name="T">The type of value being changed.</typeparam> /// <param name="location">The variable or field to be changed.</param> /// <param name="transformer">The function that transforms the value.</param> /// <returns>The result of the replacement function.</returns> private static bool UpdateWrapper<T>(ref T location, Func<T, T> transformer) where T : class { return ImmutableInterlocked.Update<T, int>( ref location, (t, arg) => { Assert.Equal(1, arg); return transformer(t); }, 1); } } }
using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using IO = System.IO; namespace WixSharp.CommonTasks { /// <summary> /// The utility class implementing the common 'MSI AppSearch' tasks (Directory, File, Registry and Product searches). /// </summary> public static class AppSearch { [DllImport("msi", CharSet = CharSet.Unicode)] static extern Int32 MsiGetProductInfo(string product, string property, [Out] StringBuilder valueBuf, ref Int32 len); [DllImport("msi", CharSet = CharSet.Unicode)] static extern Int32 MsiGetProductInfoEx(string product, string userSid, int context, string property, [Out] StringBuilder valueBuf, ref Int32 len); [DllImport("msi")] static extern int MsiEnumProducts(int iProductIndex, StringBuilder lpProductBuf); [DllImport("msi")] static extern int MsiEnumRelatedProducts(string productCode, int reserved, int iProductIndex, StringBuilder lpProductBuf); /// <summary> /// Gets the 'product code' of the installed product. /// </summary> /// <param name="name">The product name.</param> /// <returns></returns> static public string[] GetProductCode(string name) { var result = new List<string>(); var productCode = new StringBuilder(); int i = 0; while (0 == MsiEnumProducts(i++, productCode)) { var productNameLen = 512; var productName = new StringBuilder(productNameLen); MsiGetProductInfo(productCode.ToString(), "ProductName", productName, ref productNameLen); if (productName.ToString() == name) result.Add(productCode.ToString()); } return result.ToArray(); } /// <summary> /// Gets array of 'product codes' (GUIDs) of all installed products. /// </summary> static public string[] GetProducts() { var result = new List<string>(); var productCode = new StringBuilder(40); int i = 0; while (0 == MsiEnumProducts(i++, productCode)) { result.Add(productCode.ToString()); } return result.ToArray(); } /// <summary> /// Gets the related products (products with the same <c>UpgradeCode</c>). /// </summary> /// <param name="upgradeCode">The upgrade code.</param> /// <returns></returns> static public string[] GetRelatedProducts(string upgradeCode) { var result = new List<string>(); var productCode = new StringBuilder(40); int i = 0; while (0 == MsiEnumRelatedProducts(upgradeCode, 0, i++, productCode)) { result.Add(productCode.ToString()); } return result.ToArray(); } /// <summary> /// Gets the 'product name' of the installed product. /// </summary> /// <param name="productCode">The product code.</param> /// <returns></returns> static public string GetProductName(string productCode) { return GetProductInfo(productCode, "ProductName"); } /// <summary> /// Gets the version of the installed product from its 'upgrade code'. /// <code> /// static void project_BeforeInstall(SetupEventArgs e) /// { /// var detectedVersion = AppSearch.GetProductVersionFromUpgradeCode(e.UpgradeCode); /// } /// </code> /// </summary> /// <param name="upgradeCode">The product Version.</param> /// <returns></returns> static public Version GetProductVersionFromUpgradeCode(string upgradeCode) { try { var productCode = AppSearch.GetRelatedProducts(upgradeCode).FirstOrDefault(); if (productCode != null) return GetProductVersion(productCode); } catch { } return null; } /// <summary> /// Gets the 'product version' of the installed product. /// </summary> /// <param name="productCode">The product code.</param> /// <returns></returns> static public Version GetProductVersion(string productCode) { var versionStr = GetProductInfo(productCode, "Version"); //MMmmBBBB if (versionStr.IsNotEmpty()) { int value; if (int.TryParse(versionStr, out value)) { var major = (int) (value & 0xFF000000) >> 8 * 3; var minor = (int) (value & 0x00FF0000) >> 8 * 2; var build = (int) (value & 0x0000FFFF); return new Version(major, minor, build); } } return null; } static string GetProductInfo(string productCode, string property) { var productNameLen = 512; var productName = new StringBuilder(productNameLen); if (0 == MsiGetProductInfo(productCode, property, productName, ref productNameLen)) return productName.ToString(); else return null; } /// <summary> /// Determines whether the product is installed. /// Caution: if invoked from elevated/deferred action the result is inconclusive. /// </summary> /// <param name="productCode">The product code.</param> /// <returns></returns> static public bool IsProductInstalled(string productCode) { return !string.IsNullOrEmpty(GetProductName(productCode)); } /// <summary> /// Determines whether the file exists. /// </summary> /// <param name="file">The file path.</param> /// <returns></returns> static public bool FileExists(string file) { try { return IO.File.Exists(file); } catch { } return false; } /// <summary> /// Determines whether the dir exists. /// </summary> /// <param name="dir">The directory path.</param> /// <returns></returns> static public bool DirExists(string dir) { try { return IO.Directory.Exists(dir); } catch { } return false; } /// <summary> /// Converts INI file content into dictionary. /// </summary> /// <param name="iniFile">The INI file.</param> /// <param name="encoding">The encoding.</param> /// <returns></returns> static public Dictionary<string, Dictionary<string, string>> IniFileToDictionary(string iniFile, Encoding encoding = null) { return IniToDictionary(IO.File.ReadAllLines(iniFile, encoding ?? Encoding.Default)); } static internal Dictionary<string, Dictionary<string, string>> IniToDictionary(string[] iniFileContent) { var result = new Dictionary<string, Dictionary<string, string>>(); var section = "default"; var entries = iniFileContent.Select(l => l.Trim()) .Where(l => !l.StartsWith(";") && l.IsNotEmpty()); foreach (var line in entries) { if (line.StartsWith("[")) { section = line.Trim('[', ']'); continue; } if (!result.ContainsKey(section)) result[section] = new Dictionary<string, string>(); var pair = line.Split('=').Select(x => x.Trim()); if (pair.Count() < 2) result[section][pair.First()] = null; else result[section][pair.First()] = pair.Last(); } return result; } /// <summary> /// Returns INI file the field value. /// <para>It returns null if file or the field not found.</para> /// </summary> /// <param name="file">The INI file path.</param> /// <param name="section">The section.</param> /// <param name="field">The field.</param> /// <param name="encoding">The encoding.</param> /// <returns></returns> static public string IniFileValue(string file, string section, string field, Encoding encoding = null) { try { return IniFileToDictionary(file)[section][field]; } catch { } return null; } /// <summary> /// Determines whether the registry key exists. /// </summary> /// <param name="root">The root.</param> /// <param name="keyPath">The key path.</param> /// <returns></returns> static public bool RegKeyExists(RegistryKey root, string keyPath) { using (RegistryKey key = root.OpenSubKey(keyPath)) return (key != null); } /// <summary> /// Gets the registry value. /// </summary> /// <param name="root">The root.</param> /// <param name="keyPath">The key path.</param> /// <param name="valueName">Name of the value.</param> /// <returns></returns> static public object GetRegValue(RegistryKey root, string keyPath, string valueName) { using (RegistryKey key = root.OpenSubKey(keyPath)) if (key != null) return key.GetValue(valueName); return null; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.IO; using Encog.App.Quant; using Encog.Util.CSV; using Encog.Util.Logging; namespace Encog.App.Analyst.CSV.Basic { /// <summary> /// Forms the foundation of all of the cached files in Encog Quant. /// </summary> public class BasicCachedFile : BasicFile { /// <summary> /// The column mapping. /// </summary> private readonly IDictionary<String, BaseCachedColumn> _columnMapping; /// <summary> /// The columns. /// </summary> private readonly IList<BaseCachedColumn> _columns; /// <summary> /// Construct the object. /// </summary> public BasicCachedFile() { _columnMapping = new Dictionary<String, BaseCachedColumn>(); _columns = new List<BaseCachedColumn>(); } /// <value>The column mappings.</value> public IDictionary<String, BaseCachedColumn> ColumnMapping { get { return _columnMapping; } } /// <value>The columns.</value> public IList<BaseCachedColumn> Columns { get { return _columns; } } /// <summary> /// Add a new column. /// </summary> /// <param name="column">The column to add.</param> public void AddColumn(BaseCachedColumn column) { _columns.Add(column); _columnMapping[column.Name] = column; } /// <summary> /// Analyze the input file. /// </summary> /// <param name="input">The input file.</param> /// <param name="headers">True, if there are headers.</param> /// <param name="format">The format of the CSV data.</param> public virtual void Analyze(FileInfo input, bool headers, CSVFormat format) { ResetStatus(); InputFilename = input; ExpectInputHeaders = headers; Format = format; _columnMapping.Clear(); _columns.Clear(); // first count the rows TextReader reader = null; try { int recordCount = 0; reader = new StreamReader(InputFilename.OpenRead()); while (reader.ReadLine() != null) { UpdateStatus(true); recordCount++; } if (headers) { recordCount--; } RecordCount = recordCount; } catch (IOException ex) { throw new QuantError(ex); } finally { ReportDone(true); if (reader != null) { try { reader.Close(); } catch (IOException e) { throw new QuantError(e); } } InputFilename = input; ExpectInputHeaders = headers; Format = format; } // now analyze columns ReadCSV csv = null; try { csv = new ReadCSV(input.ToString(), headers, format); if (!csv.Next()) { throw new QuantError("File is empty"); } for (int i = 0; i < csv.ColumnCount; i++) { String name; if (headers) { name = AttemptResolveName(csv.ColumnNames[i]); } else { name = "Column-" + (i + 1); } // determine if it should be an input/output field String str = csv.Get(i); bool io = false; try { Format.Parse(str); io = true; } catch (FormatException ex) { EncogLogging.Log(ex); } AddColumn(new FileData(name, i, io, io)); } } finally { if (csv != null) csv.Close(); Analyzed = true; } } /// <summary> /// Attempt to resolve a column name. /// </summary> /// <param name="name">The unknown column name.</param> /// <returns>The known column name.</returns> private static String AttemptResolveName(String name) { String name2 = name.ToLower(); if (name2.IndexOf("open") != -1) { return FileData.Open; } if (name2.IndexOf("close") != -1) { return FileData.Close; } if (name2.IndexOf("low") != -1) { return FileData.Low; } if (name2.IndexOf("hi") != -1) { return FileData.High; } if (name2.IndexOf("vol") != -1) { return FileData.Volume; } if ((name2.IndexOf("date") != -1) || (name.IndexOf("yyyy") != -1)) { return FileData.Date; } if (name2.IndexOf("time") != -1) { return FileData.Time; } return name; } /// <summary> /// Get the data for a specific column. /// </summary> /// <param name="name">The column to read.</param> /// <param name="csv">The CSV file to read from.</param> /// <returns>The column data.</returns> public String GetColumnData(String name, ReadCSV csv) { if (!_columnMapping.ContainsKey(name)) { return null; } BaseCachedColumn column = _columnMapping[name]; if (!(column is FileData)) { return null; } var fd = (FileData) column; return csv.Get(fd.Index); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Xunit; namespace DiffMatchPatch.Tests { public class PatchTests { [Fact] public void ToString_ReturnsExpectedString() { // Patch Object. var p = new Patch(20, 18, 21, 17, new[] { Diff.Equal("jump"), Diff.Delete("s"), Diff.Insert("ed"), Diff.Equal(" over "), Diff.Delete("the"), Diff.Insert("a"), Diff.Equal("\nlaz") }.ToImmutableList()); var strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0alaz\n"; Assert.Equal(strp, p.ToString()); } [Fact] public void Parse_EmptyString_YieldsEmptyList() { var patches = PatchList.Parse(""); Assert.False(patches.Any()); } [Fact] public void FromTextTest1() { var strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0alaz\n"; Assert.Equal(strp, PatchList.Parse(strp)[0].ToString()); } [Fact] public void FromTextTest2() { Assert.Equal("@@ -1 +1 @@\n-a\n+b\n", PatchList.Parse("@@ -1 +1 @@\n-a\n+b\n")[0].ToString()); } [Fact] public void FromTextTest3() { Assert.Equal("@@ -1,3 +0,0 @@\n-abc\n", PatchList.Parse("@@ -1,3 +0,0 @@\n-abc\n")[0].ToString()); } [Fact] public void FromTextTest4() { Assert.Equal("@@ -0,0 +1,3 @@\n+abc\n", PatchList.Parse("@@ -0,0 +1,3 @@\n+abc\n")[0].ToString()); } [Fact] public void Parse_WhenBadPatch_Throws() { Assert.Throws<ArgumentException>(() => PatchList.Parse("Bad\nPatch\n")); } [Fact] public void ToText_Test1() { var strp = "@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n"; var patches = PatchList.Parse(strp); var result = patches.ToText(); Assert.Equal(strp, result); } [Fact] public void ToText_Test2() { var strp = "@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n"; var patches = PatchList.Parse(strp); var result = patches.ToText(); Assert.Equal(strp, result); } [Fact] public void AddContext_SimpleCase() { var p = PatchList.Parse("@@ -21,4 +21,10 @@\n-jump\n+somersault\n")[0]; var builder = p.Diffs.ToBuilder(); (int s1, int l1, int s2, int l2) = builder.AddContext("The quick brown fox jumps over the lazy dog.", p.Start1, p.Length1, p.Start2, p.Length2); p = new Patch(s1, l1, s2, l2, builder.ToImmutable()); Assert.Equal("@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n", p.ToString()); } [Fact] public void AddContext_NotEnoughTrailingContext() { var p = PatchList.Parse("@@ -21,4 +21,10 @@\n-jump\n+somersault\n")[0]; var builder = p.Diffs.ToBuilder(); (int s1, int l1, int s2, int l2) = builder.AddContext("The quick brown fox jumps.", p.Start1, p.Length1, p.Start2, p.Length2); p = new Patch(s1, l1, s2, l2, builder.ToImmutable()); Assert.Equal("@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n", p.ToString()); } [Fact] public void AddContext_NotEnoughLeadingContext() { var p = PatchList.Parse("@@ -3 +3,2 @@\n-e\n+at\n")[0]; var builder = p.Diffs.ToBuilder(); (int s1, int l1, int s2, int l2) = builder.AddContext("The quick brown fox jumps.", p.Start1, p.Length1, p.Start2, p.Length2); p = new Patch(s1, l1, s2, l2, builder.ToImmutable()); Assert.Equal("@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n", p.ToString()); } [Fact] public void AddContext_Ambiguity() { var p = PatchList.Parse("@@ -3 +3,2 @@\n-e\n+at\n")[0]; var builder = p.Diffs.ToBuilder(); (int s1, int l1, int s2, int l2) = builder.AddContext("The quick brown fox jumps. The quick brown fox crashes.", p.Start1, p.Length1, p.Start2, p.Length2); p = new Patch(s1, l1, s2, l2, builder.ToImmutable()); Assert.Equal("@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n", p.ToString()); } [Fact] public void Compute_FromEmptyString_Succeeds() { var patches = Patch.Compute("", ""); Assert.Equal("", patches.ToText()); } [Fact] public void Compute_FromTwoStrings_Reversed_Succeeds() { var text1 = "The quick brown fox jumps over the lazy dog."; var text2 = "That quick brown fox jumped over a lazy dog."; var expectedPatch = "@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n"; // The second patch must be "-21,17 +21,18", not "-22,17 +21,18" due to rolling context. var patches = Patch.Compute(text2, text1); Assert.Equal(expectedPatch, patches.ToText()); } [Fact] public void Compute_FromTwoStrings_Succeeds() { var text1 = "The quick brown fox jumps over the lazy dog."; var text2 = "That quick brown fox jumped over a lazy dog."; var expectedPatch = "@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n"; var patches = Patch.Compute(text1, text2); Assert.Equal(expectedPatch, patches.ToText()); } [Fact] public void Compute_FromDiffs_Succeeds() { var text1 = "The quick brown fox jumps over the lazy dog."; var text2 = "That quick brown fox jumped over a lazy dog."; var diffs = Diff.Compute(text1, text2, 0, false); var patches = Patch.FromDiffs(diffs); var expectedPatch = "@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n"; Assert.Equal(expectedPatch, patches.ToText()); } [Fact] public void Compute_FromTextAndDiffs_Succeeds() { var text1 = "The quick brown fox jumps over the lazy dog."; var text2 = "That quick brown fox jumped over a lazy dog."; var diffs = Diff.Compute(text1, text2, 0, false); var expectedPatch = "@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n"; var patches = Patch.Compute(text1, diffs).ToList(); Assert.Equal(expectedPatch, patches.ToText()); } [Fact] public void Compute_CharacterEncoding() { var patches = Patch.Compute("`1234567890-=[]\\;',./", "~!@#$%^&*()_+{}|:\"<>?"); Assert.Equal( "@@ -1,21 +1,21 @@\n-%601234567890-=%5b%5d%5c;',./\n+~!@#$%25%5e&*()_+%7b%7d%7c:%22%3c%3e?\n", patches.ToText()); } [Fact] public void Compute_CharacterDecoding() { var diffs = new List<Diff> { Diff.Delete("`1234567890-=[]\\;',./"), Diff.Insert("~!@#$%^&*()_+{}|:\"<>?") }; Assert.Equal(diffs, PatchList.Parse("@@ -1,21 +1,21 @@\n-%601234567890-=%5B%5D%5C;',./\n+~!@#$%25%5E&*()_+%7B%7D%7C:%22%3C%3E?\n")[0] .Diffs); } [Fact] public void Compute_LongStringWithRepeats() { var text1 = ""; for (var x = 0; x < 100; x++) { text1 += "abcdef"; } var text2 = text1 + "123"; var expectedPatch = "@@ -573,28 +573,31 @@\n cdefabcdefabcdefabcdefabcdef\n+123\n"; var patches = Patch.Compute(text1, text2); Assert.Equal(expectedPatch, patches.ToText()); } [Fact] public void SplitMaxTest1() { var patches = Patch .Compute("abcdefghijklmnopqrstuvwxyz01234567890", "XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0") .SplitMax() .ToImmutableList(); Assert.Equal( "@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n", patches.ToText()); } [Fact] public void SplitMaxTest2() { var patches = Patch.Compute("abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz", "abcdefuvwxyz"); var oldToText = patches.ToText(); var patches2 = patches.SplitMax().ToImmutableList(); Assert.Equal(oldToText, patches2.ToText()); } [Fact] public void SplitMaxTest3() { var patches = Patch .Compute("1234567890123456789012345678901234567890123456789012345678901234567890", "abc") .SplitMax() .ToImmutableList(); Assert.Equal( "@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n", patches.ToText()); } [Fact] public void SplitMaxTest4() { var patches = Patch .Compute("abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1 abcdefghij , h : 0 , t : 1", "abcdefghij , h : 1 , t : 1 abcdefghij , h : 1 , t : 1 abcdefghij , h : 0 , t : 1") .SplitMax() .ToImmutableList(); Assert.Equal( "@@ -2,32 +2,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h : \n-0\n+1\n , t : 1 abcdef\n", patches.ToText()); } [Fact] public void AddPadding_Empty() { var patches = Patch.Compute("", ""); Assert.Equal("", patches.ToText()); var patches2 = patches.AddPadding(PatchList.NullPadding()).ToImmutableList(); Assert.Equal("", patches2.ToText()); } [Fact] public void AddPadding_BothEdgesFull() { var patches = Patch.Compute("", "test"); Assert.Equal("@@ -0,0 +1,4 @@\n+test\n", patches.ToText()); var patches2 = patches.AddPadding(PatchList.NullPadding()).ToImmutableList(); Assert.Equal("@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n", patches2.ToText()); } [Fact] public void AddPadding_BothEdgesPartial() { var patches = Patch.Compute("XY", "XtestY"); Assert.Equal("@@ -1,2 +1,6 @@\n X\n+test\n Y\n", patches.ToText()); var patches2 = patches.AddPadding(PatchList.NullPadding()).ToImmutableList(); Assert.Equal("@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n", patches2.ToText()); } [Fact] public void AddPadding_BothEdgesNone() { var patches = Patch.Compute("XXXXYYYY", "XXXXtestYYYY"); Assert.Equal("@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n", patches.ToText()); var patches2 = patches.AddPadding(PatchList.NullPadding()).ToImmutableList(); Assert.Equal("@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n", patches2.ToText()); } [Fact] public void Apply_EmptyString() { var patches = Patch.Compute("", ""); var results = patches.Apply("Hello world."); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray.Length; Assert.Equal("Hello world.\t0", resultStr); } [Fact] public void Apply_ExactMatch() { var patches = Patch.Compute("The quick brown fox jumps over the lazy dog.", "That quick brown fox jumped over a lazy dog."); var results = patches.Apply("The quick brown fox jumps over the lazy dog."); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal("That quick brown fox jumped over a lazy dog.\tTrue\tTrue", resultStr); } [Fact] public void Apply_PartialMatch() { var patches = Patch.Compute("The quick brown fox jumps over the lazy dog.", "That quick brown fox jumped over a lazy dog."); var results = patches.Apply("The quick red rabbit jumps over the tired tiger."); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal("That quick red rabbit jumped over a tired tiger.\tTrue\tTrue", resultStr); } [Fact] public void Apply_FailedMatch() { var patches = Patch.Compute("The quick brown fox jumps over the lazy dog.", "That quick brown fox jumped over a lazy dog."); var results = patches.Apply("I am the very model of a modern major general."); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal("I am the very model of a modern major general.\tFalse\tFalse", resultStr); } [Fact] public void Apply_BigDeleteSmallChange() { var patches = Patch.Compute("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy"); var results = patches.Apply("x123456789012345678901234567890-----++++++++++-----123456789012345678901234567890y"); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal("xabcy\tTrue\tTrue", resultStr); } [Fact] public void Apply_BidgDeleteBigChange1() { var patches = Patch.Compute("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy"); var results = patches.Apply("x12345678901234567890---------------++++++++++---------------12345678901234567890y"); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal( "xabc12345678901234567890---------------++++++++++---------------12345678901234567890y\tFalse\tTrue", resultStr); } [Fact] public void Apply_BigDeleteBigChange2() { var patches = Patch.Compute("x1234567890123456789012345678901234567890123456789012345678901234567890y", "xabcy"); var results = patches.Apply("x12345678901234567890---------------++++++++++---------------12345678901234567890y", MatchSettings.Default, new PatchSettings(0.6f, 4)); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal("xabcy\tTrue\tTrue", resultStr); } [Fact] public void Apply_CompensateForFailedPatch() { var patches = Patch.Compute("abcdefghijklmnopqrstuvwxyz--------------------1234567890", "abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------1234567YYYYYYYYYY890"); var results = patches.Apply("ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890", new MatchSettings(0.0f, 0)); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0] + "\t" + boolArray[1]; Assert.Equal("ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890\tFalse\tTrue", resultStr); } [Fact] public void Apply_NoSideEffects() { var patches = Patch.Compute("", "test"); var patchStr = patches.ToText(); patches.Apply(""); Assert.Equal(patchStr, patches.ToText()); } [Fact] public void Apply_NoSideEffectsWithMajorDelete() { var patches = Patch.Compute("The quick brown fox jumps over the lazy dog.", "Woof"); var patchStr = patches.ToText(); patches.Apply("The quick brown fox jumps over the lazy dog."); Assert.Equal(patchStr, patches.ToText()); } [Fact] public void Apply_EdgeExactMatch() { var patches = Patch.Compute("", "test"); var results = patches.Apply(""); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0]; Assert.Equal("test\tTrue", resultStr); } [Fact] public void Apply_NearEdgeExactMatch() { var patches = Patch.Compute("XY", "XtestY"); var results = patches.Apply("XY"); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0]; Assert.Equal("XtestY\tTrue", resultStr); } [Fact] public void Apply_EdgePartialMatch() { var patches = Patch.Compute("y", "y123"); var results = patches.Apply("x"); var boolArray = results.results; var resultStr = results.newText + "\t" + boolArray[0]; Assert.Equal("x123\tTrue", resultStr); } [Fact] public void LargeEquality() { var diffs = new List<Diff> { Diff.Insert(" "), Diff.Equal("a"), Diff.Insert("nd"), Diff.Equal(" [[Pennsylvania]]"), Diff.Delete(" and [[New") }; var patch = Patch.FromDiffs(diffs); Assert.Equal(diffs, Diff.Compute("a [[Pennsylvania]] and [[New", " and [[Pennsylvania]]", 0, false)); } } }
using System.Collections.Generic; using System.Threading; using System; namespace QarnotSDK { public partial class Connection { #region CreateX /// <summary> /// Create a new bucket. /// </summary> /// <param name="name">The name of the bucket.</param> /// <param name="ct">Optional token to cancel the request.</param> /// <returns>A new Bucket.</returns> [Obsolete("CreateBucket is deprecated, please use CreateBucketAsync instead.")] public virtual QBucket CreateBucket(string name, CancellationToken ct=default(CancellationToken)) { try { return CreateBucketAsync(name, ct).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Submit a list of task as a bulk. /// </summary> /// <param name="tasks">The task list to submit as a bulk.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>void.</returns> [Obsolete("SubmitTasks is deprecated, please use SubmitTasksAsync instead.")] public virtual void SubmitTasks(List<QTask> tasks, CancellationToken cancellationToken = default(CancellationToken)) { try { SubmitTasksAsync(tasks, cancellationToken).Wait(); } catch (AggregateException ex) { throw ex.InnerException; } } #endregion #region RetrieveX /// <summary> /// Retrieve the tasks list. (deprecated) /// </summary> /// <param name="summary">Obsolete params to get a summary version of a task.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of tasks.</returns> [Obsolete("RetrieveTasks is deprecated, please use RetrieveTasksAsync instead.")] public virtual List<QTask> RetrieveTasks(bool summary, CancellationToken cancellationToken = default(CancellationToken)) => RetrieveTasks(cancellationToken); /// <summary> /// Retrieve the list of tasks. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of tasks.</returns> [Obsolete("RetrieveTasks is deprecated, please use RetrieveTasksAsync instead.")] public virtual List<QTask> RetrieveTasks(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTasksAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of tasks summary. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of tasks.</returns> [Obsolete("RetrieveTaskSummaries is deprecated, please use RetrieveTaskSummariesAsync instead.")] public virtual List<QTaskSummary> RetrieveTaskSummaries(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTaskSummariesAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the tasks list with custom filtering. /// </summary> /// <param name="level">the qtask filter object</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of tasks.</returns> [Obsolete("RetrieveTasks is deprecated, please use RetrieveTasksAsync instead.")] public virtual List<QTask> RetrieveTasks(QDataDetail<QTask> level, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTasksAsync(level, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of tasks filtered by tags. /// </summary> /// <param name="tags">list of tags for task filtering.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of tasks.</returns> [Obsolete("RetrieveTasksByTags is deprecated, please use RetrieveTasksByTagsAsync instead.")] public virtual List<QTask> RetrieveTasksByTags(List<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTasksByTagsAsync(tags, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of tasks summary filtered by tags. /// </summary> /// <param name="tags">list of tags for task filtering.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of tasks summary.</returns> [Obsolete("RetrieveTaskSummariesByTags is deprecated, please use RetrieveTaskSummariesByTagsAsync instead.")] public virtual List<QTaskSummary> RetrieveTaskSummariesByTags(List<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTaskSummariesByTagsAsync(tags, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a page of the tasks list summaries. /// </summary> /// <param name="pageDetails">The pagination details, with the result number by page, the filters and the token of the page to reach.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A response page with list of tasks.</returns> [Obsolete("RetrievePaginatedTaskSummaries is deprecated, please use RetrievePaginatedTaskSummariesAsync instead.")] public virtual PaginatedResponse<QTaskSummary> RetrievePaginatedTaskSummaries(PaginatedRequest<QTaskSummary> pageDetails, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePaginatedTaskSummariesAsync(pageDetails, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a page of the tasks list. /// </summary> /// <param name="pageDetails">The pagination details, with the result number by page, the filters and the token of the page to reach.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A page with a list of tasks.</returns> [Obsolete("RetrievePaginatedTask is deprecated, please use RetrievePaginatedTaskAsync instead.")] public virtual PaginatedResponse<QTask> RetrievePaginatedTask(PaginatedRequest<QTask> pageDetails, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePaginatedTaskAsync(pageDetails, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the pools list. (deprecated) /// </summary> /// <param name="summary">Obsolete params to get a summary version of a pool.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of pools.</returns> [Obsolete("RetrievePools is deprecated, please use RetrievePoolsAsync instead.")] public virtual List<QPool> RetrievePools(bool summary, CancellationToken cancellationToken = default(CancellationToken)) => RetrievePools(cancellationToken); /// <summary> /// Retrieve the list of pools. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of pools.</returns> [Obsolete("RetrievePools is deprecated, please use RetrievePoolsAsync instead.")] public virtual List<QPool> RetrievePools(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolsAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of pools summary. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of pools summary.</returns> [Obsolete("RetrievePoolSummaries is deprecated, please use RetrievePoolSummariesAsync instead.")] public virtual List<QPoolSummary> RetrievePoolSummaries(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolSummariesAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a page of the pools list. /// </summary> /// <param name="pageDetails">The pagination details, with the result number by page, the filters and the token of the page to reach.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A page with a list of pools.</returns> [Obsolete("RetrievePaginatedPool is deprecated, please use RetrievePaginatedPoolAsync instead.")] public virtual PaginatedResponse<QPool> RetrievePaginatedPool(PaginatedRequest<QPool> pageDetails, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePaginatedPoolAsync(pageDetails, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a page of the pools list summaries. /// </summary> /// <param name="pageDetails">The pagination details, with the result number by page, the filters and the token of the page to reach.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A response page with list of pools.</returns> [Obsolete("RetrievePaginatedPoolSummaries is deprecated, please use RetrievePaginatedPoolSummariesAsync instead.")] public virtual PaginatedResponse<QPoolSummary> RetrievePaginatedPoolSummaries(PaginatedRequest<QPoolSummary> pageDetails, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePaginatedPoolSummariesAsync(pageDetails, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the pools list with custom filtering. /// </summary> /// <param name="level">the qpool filter object</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of pools.</returns> [Obsolete("RetrievePools is deprecated, please use RetrievePoolsAsync instead.")] public virtual List<QPool> RetrievePools(QDataDetail<QPool> level, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolsAsync(level, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of pools filtered by tags. /// </summary> /// <param name="tags">list of tags for pool filtering.</param> /// <param name="summary">Optional token to choose between full pools and pools summaries.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of pools.</returns> [Obsolete("RetrievePoolsByTags is deprecated, please use RetrievePoolsByTagsAsync instead.")] public virtual List<QPool> RetrievePoolsByTags(List<string> tags, bool summary = true, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolsByTagsAsync(tags, summary, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of jobs. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of jobs.</returns> [Obsolete("RetrieveJobs is deprecated, please use RetrieveJobsAsync instead.")] public virtual List<QJob> RetrieveJobs(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveJobsAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the jobs list with custom filtering. /// </summary> /// <param name="level">the sjob filter object</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of jobs.</returns> [Obsolete("RetrieveJobs is deprecated, please use RetrieveJobsAsync instead.")] public virtual List<QJob> RetrieveJobs(QDataDetail<QJob> level, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveJobsAsync(level, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a page of the jobs list. /// </summary> /// <param name="pageDetails">The pagination details, with the result number by page, the filters and the token of the page to reach.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A page with a list of jobs.</returns> [Obsolete("RetrievePaginatedJob is deprecated, please use RetrievePaginatedJobAsync instead.")] public virtual PaginatedResponse<QJob> RetrievePaginatedJob(PaginatedRequest<QJob> pageDetails, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePaginatedJobAsync(pageDetails, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the bucket /// </summary> /// <param name="bucketName">Unique name of the bucket to retrieve.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <remarks>If the bucket is not found, null is return</remarks> /// <returns>Corresponding bucket.</returns> [Obsolete("RetrieveBucket is deprecated, please use RetrieveBucketAsync instead.")] public virtual QBucket RetrieveBucket(string bucketName, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveBucketAsync(bucketName, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the bucket, if it does not exist, create it /// </summary> /// <param name="bucketName">Unique name of the bucket to retrieve.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>Corresponding bucket.</returns> [Obsolete("RetrieveOrCreateBucket is deprecated, please use RetrieveOrCreateBucketAsync instead.")] public virtual QBucket RetrieveOrCreateBucket(string bucketName, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveOrCreateBucketAsync(bucketName, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the buckets list with each bucket file count and used space. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of buckets.</returns> [Obsolete("RetrieveBuckets is deprecated, please use RetrieveBucketsAsync instead.")] public virtual List<QBucket> RetrieveBuckets(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveBucketsAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the buckets list. /// </summary> /// <param name="retrieveBucketStats">If set to true, the file count and used space of each bucket is also retrieved. If set to false, it is faster but only the bucket names are returned.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of buckets.</returns> [Obsolete("RetrieveBuckets is deprecated, please use RetrieveBucketsAsync instead.")] public virtual List<QBucket> RetrieveBuckets(bool retrieveBucketStats, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveBucketsAsync(retrieveBucketStats, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the user quotas and buckets information for your account. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The quotas and buckets information.</returns> [Obsolete("RetrieveUserInformation is deprecated, please use RetrieveUserInformationAsync instead.")] public virtual UserInformation RetrieveUserInformation(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveUserInformationAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the user quotas and buckets information for your account. /// Note: BucketCount field is retrieved with a second request to the bucket Api. /// </summary> /// <param name="retrieveBucketCount">If set to false, the BucketCount field is not filled but the request is faster.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The quotas and buckets information without BucketCount.</returns> [Obsolete("RetrieveUserInformation is deprecated, please use RetrieveUserInformationAsync instead.")] public virtual UserInformation RetrieveUserInformation(bool retrieveBucketCount, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveUserInformationAsync(retrieveBucketCount, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of profiles available for your account. /// </summary> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of profile names.</returns> [Obsolete("RetrieveProfiles is deprecated, please use RetrieveProfilesAsync instead.")] public virtual List<string> RetrieveProfiles(CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveProfilesAsync(cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve the list of the constants you can override for a specific profile. /// </summary> /// <param name="profile">Name of the profile.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>A list of constants.</returns> [Obsolete("RetrieveConstants is deprecated, please use RetrieveConstantsAsync instead.")] public virtual List<Constant> RetrieveConstants(string profile, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveConstantsAsync(profile, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } #endregion #region RetrieveXByName /// <summary> /// Retrieve a task by its name. /// </summary> /// <param name="name">Name of the task to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The task object for that name or null if it hasn't been found.</returns> [Obsolete("RetrieveTaskByName is deprecated, please use RetrieveTaskByShortnameAsync or RetrieveTasksByNameAsync instead.")] public virtual QTask RetrieveTaskByName(string name, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTaskByNameAsync(name, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a task summary by its name. /// </summary> /// <param name="name">Name of the task to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The task summary object for that name or null if it hasn't been found.</returns> [Obsolete("RetrieveTaskSummaryByName is deprecated, please use RetrieveTaskSummaryByShortnameAsync instead.")] public virtual QTaskSummary RetrieveTaskSummaryByName(string name, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTaskSummaryByNameAsync(name, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a task by its uuid or shortname(unique and dns compliant). /// </summary> /// <param name="uuid">uuid or shortname of the task to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The task object for that uuid or null if it hasn't been found.</returns> [Obsolete("RetrieveTaskByUuid is deprecated, please use RetrieveTaskByUuidAsync instead.")] public virtual QTask RetrieveTaskByUuid(string uuid, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTaskByUuidAsync(uuid, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a task summary by its uuid. /// </summary> /// <param name="uuid">uuid of the task summary to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The task summary object for that uuid or null if it hasn't been found.</returns> [Obsolete("RetrieveTaskSummaryByUuid is deprecated, please use RetrieveTaskSummaryByUuidAsync instead.")] public virtual QTaskSummary RetrieveTaskSummaryByUuid(string uuid, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveTaskSummaryByUuidAsync(uuid, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a job by its uuid or shortname. /// </summary> /// <param name="uuid">uuid or shortname of the job to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The job object for that uuid or null if it hasn't been found.</returns> [Obsolete("RetrieveJobByUuid is deprecated, please use RetrieveJobByUuidAsync instead.")] public virtual QJob RetrieveJobByUuid(string uuid, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrieveJobByUuidAsync(uuid, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a pool by its name. /// </summary> /// <param name="name">Name of the pool to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The pool object for that name or null if it hasn't been found.</returns> [Obsolete("RetrievePoolByName is deprecated, please use RetrievePoolByShortnameAsync or RetrievePoolsByNameAsync instead.")] public virtual QPool RetrievePoolByName(string name, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolByNameAsync(name, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a pool summary by its name. /// </summary> /// <param name="name">Name of the pool to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The pool summary object for that name or null if it hasn't been found.</returns> [Obsolete("RetrievePoolSummaryByName is deprecated, please use RetrievePoolSummaryByShortnameAsync instead.")] public virtual QPoolSummary RetrievePoolSummaryByName(string name, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolSummaryByNameAsync(name, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a pool by its uuid or shortname(unique and dns compliant). /// </summary> /// <param name="uuid">uuid or shortname of the pool to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The pool object for that uuid or null if it hasn't been found.</returns> [Obsolete("RetrievePoolByUuid is deprecated, please use RetrievePoolByUuidAsync instead.")] public virtual QPool RetrievePoolByUuid(string uuid, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolByUuidAsync(uuid, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } /// <summary> /// Retrieve a pool summary by its uuid or shortname. /// </summary> /// <param name="uuid">uuid or shortname of the pool to find.</param> /// <param name="cancellationToken">Optional token to cancel the request.</param> /// <returns>The pool summary object for that uuid or null if it hasn't been found.</returns> [Obsolete("RetrievePoolSummaryByUuid is deprecated, please use RetrievePoolSummaryByUuidAsync instead.")] public virtual QPoolSummary RetrievePoolSummaryByUuid(string uuid, CancellationToken cancellationToken = default(CancellationToken)) { try { return RetrievePoolSummaryByUuidAsync(uuid, cancellationToken).Result; } catch (AggregateException ex) { throw ex.InnerException; } } #endregion } }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B12_CityRoad (editable child object).<br/> /// This is a generated base class of <see cref="B12_CityRoad"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="B11_CityRoadColl"/> collection. /// </remarks> [Serializable] public partial class B12_CityRoad : BusinessBase<B12_CityRoad> { #region Static Fields private static int _lastID; #endregion #region State Fields [NotUndoable] [NonSerialized] internal int parent_City_ID = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="CityRoad_ID"/> property. /// </summary> public static readonly PropertyInfo<int> CityRoad_IDProperty = RegisterProperty<int>(p => p.CityRoad_ID, "City Road ID"); /// <summary> /// Gets the City Road ID. /// </summary> /// <value>The City Road ID.</value> public int CityRoad_ID { get { return GetProperty(CityRoad_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="CityRoad_Name"/> property. /// </summary> public static readonly PropertyInfo<string> CityRoad_NameProperty = RegisterProperty<string>(p => p.CityRoad_Name, "City Road Name"); /// <summary> /// Gets or sets the City Road Name. /// </summary> /// <value>The City Road Name.</value> public string CityRoad_Name { get { return GetProperty(CityRoad_NameProperty); } set { SetProperty(CityRoad_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B12_CityRoad"/> object. /// </summary> /// <returns>A reference to the created <see cref="B12_CityRoad"/> object.</returns> internal static B12_CityRoad NewB12_CityRoad() { return DataPortal.CreateChild<B12_CityRoad>(); } /// <summary> /// Factory method. Loads a <see cref="B12_CityRoad"/> object from the given B12_CityRoadDto. /// </summary> /// <param name="data">The <see cref="B12_CityRoadDto"/>.</param> /// <returns>A reference to the fetched <see cref="B12_CityRoad"/> object.</returns> internal static B12_CityRoad GetB12_CityRoad(B12_CityRoadDto data) { B12_CityRoad obj = new B12_CityRoad(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B12_CityRoad"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B12_CityRoad() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B12_CityRoad"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(CityRoad_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B12_CityRoad"/> object from the given <see cref="B12_CityRoadDto"/>. /// </summary> /// <param name="data">The B12_CityRoadDto to use.</param> private void Fetch(B12_CityRoadDto data) { // Value properties LoadProperty(CityRoad_IDProperty, data.CityRoad_ID); LoadProperty(CityRoad_NameProperty, data.CityRoad_Name); // parent properties parent_City_ID = data.Parent_City_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="B12_CityRoad"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(B10_City parent) { var dto = new B12_CityRoadDto(); dto.Parent_City_ID = parent.City_ID; dto.CityRoad_Name = CityRoad_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IB12_CityRoadDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); LoadProperty(CityRoad_IDProperty, resultDto.CityRoad_ID); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="B12_CityRoad"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; var dto = new B12_CityRoadDto(); dto.CityRoad_ID = CityRoad_ID; dto.CityRoad_Name = CityRoad_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IB12_CityRoadDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="B12_CityRoad"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IB12_CityRoadDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(CityRoad_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeQuality.Analyzers.Maintainability { using static MicrosoftCodeQualityAnalyzersResources; /// <summary> /// CA1806: Do not ignore method results /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class DoNotIgnoreMethodResultsAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1806"; private static readonly ImmutableHashSet<string> s_stringMethodNames = ImmutableHashSet.CreateRange( new[] { "ToUpper", "ToLower", "Trim", "TrimEnd", "TrimStart", "ToUpperInvariant", "ToLowerInvariant", "Clone", "Format", "Concat", "Copy", "Insert", "Join", "Normalize", "Remove", "Replace", "Split", "PadLeft", "PadRight", "Substring", }); private static readonly ImmutableHashSet<string> s_nUnitMethodNames = ImmutableHashSet.CreateRange( new[] { "Throws", "Catch", "DoesNotThrow", "ThrowsAsync", "CatchAsync", "DoesNotThrowAsync" }); private static readonly ImmutableHashSet<string> s_xUnitMethodNames = ImmutableHashSet.Create( new[] { "Throws", "ThrowsAsync", "ThrowsAny", "ThrowsAnyAsync", }); private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsTitle)); private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsDescription)); internal static readonly DiagnosticDescriptor ObjectCreationRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessageObjectCreation)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor StringCreationRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessageStringCreation)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor HResultOrErrorCodeRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessageHResultOrErrorCode)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor PureMethodRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessagePureMethod)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor TryParseRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessageTryParse)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor LinqMethodRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessageLinqMethod)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static readonly DiagnosticDescriptor UserDefinedMethodRule = DiagnosticDescriptorHelper.Create( RuleId, s_localizableTitle, CreateLocalizableResourceString(nameof(DoNotIgnoreMethodResultsMessageUserDefinedMethod)), DiagnosticCategory.Performance, RuleLevel.IdeSuggestion, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(ObjectCreationRule, StringCreationRule, HResultOrErrorCodeRule, TryParseRule, PureMethodRule); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(compilationContext => { INamedTypeSymbol? expectedExceptionType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionAttribute); INamedTypeSymbol? nunitAssertType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkAssert); INamedTypeSymbol? xunitAssertType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.XunitAssert); INamedTypeSymbol? linqEnumerableType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable); compilationContext.RegisterOperationBlockStartAction(osContext => { if (osContext.OwningSymbol is not IMethodSymbol method) { return; } osContext.RegisterOperationAction(opContext => { IOperation expression = ((IExpressionStatementOperation)opContext.Operation).Operation; var userDefinedMethods = compilationContext.Options.GetAdditionalUseResultsMethodsOption(UserDefinedMethodRule, expression.Syntax.SyntaxTree, compilationContext.Compilation); DiagnosticDescriptor? rule = null; string targetMethodName = ""; switch (expression.Kind) { case OperationKind.ObjectCreation: IMethodSymbol ctor = ((IObjectCreationOperation)expression).Constructor; if (ctor != null) { rule = ObjectCreationRule; targetMethodName = ctor.ContainingType.Name; } break; case OperationKind.Invocation: IInvocationOperation invocationExpression = (IInvocationOperation)expression; IMethodSymbol targetMethod = invocationExpression.TargetMethod; if (targetMethod.ReturnsVoid) { break; } if (IsStringCreatingMethod(targetMethod)) { rule = StringCreationRule; } else if (IsTryParseMethod(targetMethod)) { rule = TryParseRule; } else if (IsHResultOrErrorCodeReturningMethod(targetMethod)) { rule = HResultOrErrorCodeRule; } else if (IsPureMethod(targetMethod, opContext.Compilation)) { rule = PureMethodRule; } else if (targetMethod.ContainingType.Equals(linqEnumerableType)) { rule = LinqMethodRule; } else if (userDefinedMethods.Contains(targetMethod.OriginalDefinition)) { rule = UserDefinedMethodRule; } targetMethodName = targetMethod.Name; break; } if (rule != null) { if (ShouldSkipAnalyzing(opContext, expectedExceptionType, xunitAssertType, nunitAssertType)) { return; } Diagnostic diagnostic = expression.CreateDiagnostic(rule, method.Name, targetMethodName); opContext.ReportDiagnostic(diagnostic); } }, OperationKind.ExpressionStatement); }); }); } private static bool ShouldSkipAnalyzing(OperationAnalysisContext operationContext, INamedTypeSymbol? expectedExceptionType, INamedTypeSymbol? xunitAssertType, INamedTypeSymbol? nunitAssertType) { static bool IsThrowsArgument(IParameterSymbol parameterSymbol, string argumentName, ImmutableHashSet<string> methodNames, INamedTypeSymbol? assertSymbol) { return parameterSymbol.Name == argumentName && parameterSymbol.ContainingSymbol is IMethodSymbol methodSymbol && methodNames.Contains(methodSymbol.Name) && Equals(methodSymbol.ContainingSymbol, assertSymbol); } bool IsNUnitThrowsArgument(IParameterSymbol parameterSymbol) { return IsThrowsArgument(parameterSymbol, "code", s_nUnitMethodNames, nunitAssertType); } bool IsXunitThrowsArgument(IParameterSymbol parameterSymbol) { return IsThrowsArgument(parameterSymbol, "testCode", s_xUnitMethodNames, xunitAssertType); } // We skip analysis for the last statement in a lambda passed to Assert.Throws/ThrowsAsync (xUnit and NUnit), or the last // statement in a method annotated with [ExpectedException] (MSTest) if (expectedExceptionType == null && xunitAssertType == null && nunitAssertType == null) { return false; } // Note: We do not attempt to account for a synchronously-running ThrowsAsync with something like return Task.CompletedTask; // as the last line. // We only skip analysis if we're in a method if (operationContext.ContainingSymbol.Kind != SymbolKind.Method) { return false; } // Get the enclosing block. if (operationContext.Operation.Parent is not IBlockOperation enclosingBlock) { return false; } // If enclosing block isn't the topmost IBlockOperation (MSTest case) or its parent isn't an IAnonymousFunctionOperation (xUnit/NUnit), then // we bail immediately var hasTopmostBlockParent = enclosingBlock == operationContext.Operation.GetTopmostParentBlock(); var hasAnonymousFunctionParent = enclosingBlock.Parent?.Kind == OperationKind.AnonymousFunction; if (!hasTopmostBlockParent && !hasAnonymousFunctionParent) { return false; } // Only skip analyzing the last non-implicit statement in the function bool foundBlock = false; foreach (var statement in enclosingBlock.Operations) { if (statement == operationContext.Operation) { foundBlock = true; } else if (foundBlock) { if (!statement.IsImplicit) { return false; } } } // If enclosing block is the topmost block, we're in the MSTest case. Otherwise, we're in the xUnit/NUnit case. if (hasTopmostBlockParent) { if (expectedExceptionType == null) { return false; } IMethodSymbol methodSymbol = (IMethodSymbol)operationContext.ContainingSymbol; return methodSymbol.HasAttribute(expectedExceptionType); } else { IArgumentOperation? argumentOperation = enclosingBlock.GetAncestor<IArgumentOperation>(OperationKind.Argument); if (argumentOperation == null) { return false; } return IsNUnitThrowsArgument(argumentOperation.Parameter) || IsXunitThrowsArgument(argumentOperation.Parameter); } } private static bool IsStringCreatingMethod(IMethodSymbol method) { return method.ContainingType.SpecialType == SpecialType.System_String && s_stringMethodNames.Contains(method.Name); } private static bool IsTryParseMethod(IMethodSymbol method) { return method.Name.StartsWith("TryParse", StringComparison.OrdinalIgnoreCase) && method.ReturnType.SpecialType == SpecialType.System_Boolean && method.Parameters.Length >= 2 && method.Parameters[1].RefKind != RefKind.None; } private static bool IsHResultOrErrorCodeReturningMethod(IMethodSymbol method) { // Tune this method to match the FxCop behavior once https://github.com/dotnet/roslyn/issues/7282 is addressed. return method.GetDllImportData() != null && (method.ReturnType.SpecialType == SpecialType.System_Int32 || method.ReturnType.SpecialType == SpecialType.System_UInt32); } private static bool IsPureMethod(IMethodSymbol method, Compilation compilation) { return method.HasAttribute(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsContractsPureAttribute)); } } }
//----------------------------------------------------------------------- // <copyright file="FanOut.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.Pattern; using Reactive.Streams; namespace Akka.Streams.Implementation { internal class OutputBunch<T> { #region internal classes private sealed class FanoutOutputs : SimpleOutputs { private readonly int _id; public FanoutOutputs(int id, IActorRef actor, IPump pump) : base(actor, pump) { _id = id; } public new ISubscription CreateSubscription() => new FanOut.SubstreamSubscription(Actor, _id); } #endregion private readonly int _outputCount; private bool _bunchCancelled; private readonly FanoutOutputs[] _outputs; private readonly bool[] _marked; private int _markedCount; private readonly bool[] _pending; private int _markedPending; private readonly bool[] _cancelled; private int _markedCanceled; private readonly bool[] _completed; private readonly bool[] _errored; private bool _unmarkCancelled = true; private int _preferredId; public OutputBunch(int outputCount, IActorRef impl, IPump pump) { _outputCount = outputCount; _outputs = new FanoutOutputs[outputCount]; for (var i = 0; i < outputCount; i++) _outputs[i] = new FanoutOutputs(i, impl, pump); _marked = new bool[outputCount]; _pending = new bool[outputCount]; _cancelled = new bool[outputCount]; _completed = new bool[outputCount]; _errored = new bool[outputCount]; AllOfMarkedOutputs = new LambdaTransferState( isCompleted: () => _markedCanceled > 0 || _markedCount == 0, isReady: () => _markedPending == _markedCount); AnyOfMarkedOutputs = new LambdaTransferState( isCompleted: () => _markedCanceled == _markedCount, isReady: () => _markedPending > 0); // FIXME: Eliminate re-wraps SubReceive = new SubReceive(message => message.Match() .With<FanOut.ExposedPublishers<T>>(exposed => { var publishers = exposed.Publishers.GetEnumerator(); var outputs = _outputs.AsEnumerable().GetEnumerator(); while (publishers.MoveNext() && outputs.MoveNext()) outputs.Current.SubReceive.CurrentReceive(new ExposedPublisher(publishers.Current)); }) .With<FanOut.SubstreamRequestMore>(more => { if (more.Demand < 1) // According to Reactive Streams Spec 3.9, with non-positive demand must yield onError Error(more.Id, ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException); else { if (_marked[more.Id] && !_pending[more.Id]) _markedPending += 1; _pending[more.Id] = true; _outputs[more.Id].SubReceive.CurrentReceive(new RequestMore(null, more.Demand)); } }) .With<FanOut.SubstreamCancel>(cancel => { if (_unmarkCancelled) UnmarkOutput(cancel.Id); if (_marked[cancel.Id] && !_cancelled[cancel.Id]) _markedCanceled += 1; _cancelled[cancel.Id] = true; OnCancel(cancel.Id); _outputs[cancel.Id].SubReceive.CurrentReceive(new Cancel(null)); }) .With<FanOut.SubstreamSubscribePending>(pending => _outputs[pending.Id].SubReceive.CurrentReceive(SubscribePending.Instance)) .WasHandled); } /// <summary> /// Will only transfer an element when all marked outputs /// have demand, and will complete as soon as any of the marked /// outputs have canceled. /// </summary> public readonly TransferState AllOfMarkedOutputs; /// <summary> /// Will transfer an element when any of the marked outputs /// have demand, and will complete when all of the marked /// outputs have canceled. /// </summary> public readonly TransferState AnyOfMarkedOutputs; public readonly SubReceive SubReceive; public bool IsPending(int output) => _pending[output]; public bool IsCompleted(int output) => _completed[output]; public bool IsCancelled(int output) => _cancelled[output]; public bool IsErrored(int output) => _errored[output]; public void Complete() { if (!_bunchCancelled) { _bunchCancelled = true; for (var i = 0; i < _outputs.Length; i++) Complete(i); } } public void Complete(int output) { if (!_completed[output] && !_errored[output] && !_cancelled[output]) { _outputs[output].Complete(); _completed[output] = true; UnmarkOutput(output); } } public void Cancel(Exception e) { if (!_bunchCancelled) { _bunchCancelled = true; for (var i = 0; i < _outputs.Length; i++) Error(i, e); } } public void Error(int output, Exception e) { if (!_errored[output] && !_cancelled[output] && !_completed[output]) { _outputs[output].Error(e); _errored[output] = true; UnmarkOutput(output); } } public void MarkOutput(int output) { if (!_marked[output]) { if (_cancelled[output]) _markedCanceled += 1; if (_pending[output]) _markedPending += 1; _marked[output] = true; _markedCount += 1; } } public void UnmarkOutput(int output) { if (_marked[output]) { if (_cancelled[output]) _markedCanceled -= 1; if (_pending[output]) _markedPending -= 1; _marked[output] = false; _markedCount -= 1; } } public void MarkAllOutputs() { for (var i = 0; i < _outputCount; i++) MarkOutput(i); } public void UnmarkAllOutputs() { for (var i = 0; i < _outputCount; i++) UnmarkOutput(i); } public void UnmarkCancelledOutputs(bool enabled) => _unmarkCancelled = enabled; public int IdToEnqueue() { var id = _preferredId; while (!(_marked[id] && _pending[id])) { id += 1; if (id == _outputCount) id = 0; if (id != _preferredId) throw new ArgumentException("Tried to equeue without waiting for any demand"); } return id; } public void Enqueue(int id, T element) { var output = _outputs[id]; output.EnqueueOutputElement(element); if (!output.IsDemandAvailable) { if (_marked[id]) _markedPending -= 1; _pending[id] = false; } } public void EnqueueMarked(T element) { for (var id = 0; id < _outputCount; id++) if (_marked[id]) Enqueue(id, element); } public int IdToEnqueueAndYield() { var id = IdToEnqueue(); _preferredId = id + 1; if (_preferredId == _outputCount) _preferredId = 0; return id; } public void EnqueueAndYield(T element) => Enqueue(IdToEnqueueAndYield(), element); public void EnqueueAndPrefer(T element, int preferred) { var id = IdToEnqueue(); _preferredId = preferred; Enqueue(id, element); } public void OnCancel(int output) { } public TransferState DemandAvailableFor(int id) => new LambdaTransferState(isReady: () => _pending[id], isCompleted: () => _cancelled[id] || _completed[id] || _errored[id]); public TransferState DemandOrCancelAvailableFor(int id) => new LambdaTransferState(isReady: () => _pending[id] || _cancelled[id], isCompleted: () => false); } /// <summary> /// INTERNAL API /// </summary> internal static class FanOut { [Serializable] public struct SubstreamRequestMore : INoSerializationVerificationNeeded, IDeadLetterSuppression { public readonly int Id; public readonly long Demand; public SubstreamRequestMore(int id, long demand) { Id = id; Demand = demand; } } [Serializable] public struct SubstreamCancel : INoSerializationVerificationNeeded, IDeadLetterSuppression { public readonly int Id; public SubstreamCancel(int id) { Id = id; } } [Serializable] public struct SubstreamSubscribePending : INoSerializationVerificationNeeded, IDeadLetterSuppression { public readonly int Id; public SubstreamSubscribePending(int id) { Id = id; } } public class SubstreamSubscription : ISubscription { private readonly IActorRef _parent; private readonly int _id; public SubstreamSubscription(IActorRef parent, int id) { _parent = parent; _id = id; } public void Request(long elements) => _parent.Tell(new SubstreamRequestMore(_id, elements)); public void Cancel() => _parent.Tell(new SubstreamCancel(_id)); public override string ToString() => "SubstreamSubscription" + GetHashCode(); } [Serializable] public struct ExposedPublishers<T> : INoSerializationVerificationNeeded, IDeadLetterSuppression { public readonly ImmutableList<ActorPublisher<T>> Publishers; public ExposedPublishers(ImmutableList<ActorPublisher<T>> publishers) { Publishers = publishers; } } } /// <summary> /// INTERNAL API /// </summary> internal abstract class FanOut<T> : ActorBase, IPump { #region internal classes private sealed class AnonymousBatchingInputBuffer : BatchingInputBuffer { private readonly FanOut<T> _pump; public AnonymousBatchingInputBuffer(int count, FanOut<T> pump) : base(count, pump) { _pump = pump; } protected override void OnError(Exception e) => _pump.Fail(e); } #endregion private readonly ActorMaterializerSettings _settings; protected readonly OutputBunch<T> OutputBunch; protected readonly BatchingInputBuffer PrimaryInputs; protected FanOut(ActorMaterializerSettings settings, int outputCount) { _log = Context.GetLogger(); _settings = settings; OutputBunch = new OutputBunch<T>(outputCount, Self, this); PrimaryInputs = new AnonymousBatchingInputBuffer(settings.MaxInputBufferSize, this); this.Init(); } #region Actor implementation private ILoggingAdapter _log; protected ILoggingAdapter Log => _log ?? (_log = Context.GetLogger()); protected override void PostStop() { PrimaryInputs.Cancel(); OutputBunch.Cancel(new AbruptTerminationException(Self)); } protected override void PostRestart(Exception reason) { base.PostRestart(reason); throw new IllegalStateException("This actor cannot be restarted"); } protected void Fail(Exception e) { if (_settings.IsDebugLogging) Log.Debug($"fail due to: {e.Message}"); PrimaryInputs.Cancel(); OutputBunch.Cancel(e); Pump(); } protected override bool Receive(object message) { return PrimaryInputs.SubReceive.CurrentReceive(message) || OutputBunch.SubReceive.CurrentReceive(message); } #endregion #region Pump implementation public TransferState TransferState { get; set; } public Action CurrentAction { get; set; } public bool IsPumpFinished => this.IsPumpFinished(); public void InitialPhase(int waitForUpstream, TransferPhase andThen) => Pumps.InitialPhase(this, waitForUpstream, andThen); public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream); public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this); public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase); public void Pump() => Pumps.Pump(this); public void PumpFailed(Exception e) => Fail(e); public void PumpFinished() { PrimaryInputs.Cancel(); OutputBunch.Complete(); Context.Stop(Self); } #endregion } /// <summary> /// INTERNAL API /// </summary> internal static class Unzip { public static Props Props<T>(ActorMaterializerSettings settings) => Actor.Props.Create(() => new Unzip<T>(settings, 2)).WithDeploy(Deploy.Local); } /// <summary> /// INTERNAL API /// TODO Find out where this class will be used and check if the type parameter fit /// since we need to cast messages into a tuple and therefore maybe need aditional type parameters /// </summary> internal sealed class Unzip<T> : FanOut<T> { public Unzip(ActorMaterializerSettings settings, int outputCount = 2) : base(settings, outputCount) { OutputBunch.MarkAllOutputs(); InitialPhase(1, new TransferPhase(PrimaryInputs.NeedsInput.And(OutputBunch.AllOfMarkedOutputs), () => { var message = PrimaryInputs.DequeueInputElement(); var tuple = message as Tuple<T, T>; if (tuple == null) throw new ArgumentException($"Unable to unzip elements of type {message.GetType().Name}"); OutputBunch.Enqueue(0, tuple.Item1); OutputBunch.Enqueue(1, tuple.Item2); })); } } }
//////////////////////////////////////////////////////////////////////////////// // The MIT License (MIT) // // Copyright (c) 2015 Tim Stair // // 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.Drawing; using System.Drawing.Text; using System.Reflection; using System.Windows.Forms; using CardMaker.Card; using CardMaker.Card.Shapes; using CardMaker.Data; using CardMaker.Events.Args; using CardMaker.Events.Managers; using CardMaker.XML; using Support.UI; namespace CardMaker.Forms { public partial class MDIElementControl : Form { #warning - this should be in a central spot... not in some random dialog private readonly Dictionary<string, ElementType> m_dictionaryElementTypes = new Dictionary<string, ElementType>(); // mapping controls directly to special functions when a given control is adjusted private readonly Dictionary<Control, Action<ProjectLayoutElement>> m_dictionaryControlActions = new Dictionary<Control, Action<ProjectLayoutElement>>(); // mapping controls directly to properties in the ProjectLayoutElement class private readonly Dictionary<Control, PropertyInfo> m_dictionaryControlField = new Dictionary<Control, PropertyInfo>(); private readonly List<FontFamily> m_listFontFamilies = new List<FontFamily>(); private readonly Dictionary<string, int> dictionaryShapeTypeIndex = new Dictionary<string, int>(); private readonly ContextMenuStrip m_zContextMenu; private bool m_bFireElementChangeEvents = true; private bool m_bFireFontChangeEvents = true; public MDIElementControl() { InitializeComponent(); btnElementBorderColor.Tag = panelBorderColor; btnElementFontColor.Tag = panelFontColor; btnElementShapeColor.Tag = panelShapeColor; btnElementOutlineColor.Tag = panelOutlineColor; // setup the font related items var fonts = new InstalledFontCollection(); foreach (FontFamily zFontFamily in fonts.Families) { m_listFontFamilies.Add(zFontFamily); comboFontName.Items.Add(zFontFamily.Name); } // configure all event handling actions SetupControlActions(); CreateControlFieldDictionary(); comboFontName.SelectedIndex = 0; m_zContextMenu = new ContextMenuStrip { RenderMode = ToolStripRenderMode.System }; LayoutManager.Instance.DeckIndexChanged += DeckIndex_Changed; ElementManager.Instance.ElementSelected += Element_Selected; ElementManager.Instance.ElementBoundsUpdated += ElementBounds_Updated; } #region overrides protected override CreateParams CreateParams { get { const int CP_NOCLOSE_BUTTON = 0x200; CreateParams zParams = base.CreateParams; zParams.ClassStyle = zParams.ClassStyle | CP_NOCLOSE_BUTTON; return zParams; } } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { switch (keyData) { case Keys.Control | Keys.A: txtElementVariable.SelectAll(); break; } return base.ProcessCmdKey(ref msg, keyData); } #endregion #region manager events void DeckIndex_Changed(object sender, DeckChangeEventArgs args) { LayoutManager.Instance.ActiveDeck.PopulateListViewWithElementColumns(listViewElementColumns); if (LayoutManager.Instance.ActiveLayout.Element == null || LayoutManager.Instance.ActiveLayout.Element.Length == 0) { HandleEnableStates(); } } void ElementBounds_Updated(object sender, ElementEventArgs args) { if (null != args && args.Elements.Count > 0) { UpdateElementBoundsControlValues(args.Elements[0]); } } void Element_Selected(object sender, ElementEventArgs args) { HandleEnableStates(); if (args.Elements != null && args.Elements.Count > 0) { UpdateElementValues(args.Elements[0]); HandleTypeEnableStates(); } txtElementVariable.AcceptsTab = ProjectManager.Instance.LoadedProjectTranslatorType == TranslatorType.JavaScript; } #endregion #region form events private void btnElementBrowseImage_Click(object sender, EventArgs e) { FormUtils.FileOpenHandler("All files (*.*)|*.*", txtElementVariable, true); } private void comboElementType_SelectedIndexChanged(object sender, EventArgs e) { HandleElementValueChange(sender, e); HandleTypeEnableStates(); } private void btnColor_Click(object sender, EventArgs e) { var listSelectedElements = ElementManager.Instance.SelectedElements; if (null == listSelectedElements) { MessageBox.Show(this, "Please select at least one enabled Element."); return; } var zRGB = new RGBColorSelectDialog(); var btnClicked = (Button)sender; var zPanel = (Panel)btnClicked.Tag; zRGB.UpdateColorBox(zPanel.BackColor); if (DialogResult.OK != zRGB.ShowDialog()) { return; } var colorRedo = zRGB.Color; var listActions = UserAction.CreateActionList(); foreach (var zElement in listSelectedElements) { var zElementToChange = zElement; var colorUndo = Color.White; if (btnClicked == btnElementBorderColor) { colorUndo = zElement.GetElementBorderColor(); } else if (btnClicked == btnElementOutlineColor) { colorUndo = zElement.GetElementOutlineColor(); } else if (btnClicked == btnElementFontColor || btnClicked == btnElementShapeColor) { colorUndo = zElement.GetElementColor(); } listActions.Add(bRedo => { if (null != LayoutManager.Instance.ActiveDeck) { LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElementToChange.name); } SetColorValue(btnClicked, bRedo ? colorRedo : colorUndo, zElementToChange); UpdatePanelColors(zElementToChange); }); } Action<bool> actionChangeColor = bRedo => { listActions.ForEach(action => action(bRedo)); LayoutManager.Instance.FireLayoutUpdatedEvent(true); }; UserAction.PushAction(actionChangeColor); // perform the action as a redo now actionChangeColor(true); } private void HandleElementValueChange(object sender, EventArgs e) { if (null == ElementManager.Instance.GetSelectedElement() || !m_bFireElementChangeEvents || CardMakerInstance.ProcessingUserAction) { return; } var listSelectedElements = ElementManager.Instance.SelectedElements; if (null != sender && null != listSelectedElements) { var zControl = (Control)sender; var listActions = UserAction.CreateActionList(); foreach (var zElement in listSelectedElements) { object zUndoValue = null; object zRedoValue = null; var zElementToChange = zElement; PopulateUndoRedoValues(zControl, zElementToChange, ref zRedoValue, ref zUndoValue); listActions.Add(bRedo => AssignValueByControl(zControl, zElementToChange, bRedo ? zRedoValue : zUndoValue, false)); } Action<bool> actionElementChange = bRedo => { CardMakerInstance.ProcessingUserAction = true; listActions.ForEach(action => action(bRedo)); CardMakerInstance.ProcessingUserAction = false; LayoutManager.Instance.FireLayoutUpdatedEvent(true); }; UserAction.PushAction(actionElementChange); // perform the action as a redo now actionElementChange(true); } } private void MDIElementControl_Load(object sender, EventArgs e) { foreach (var zShape in ShapeManager.ShapeDictionary.Values) { comboShapeType.Items.Add(zShape); dictionaryShapeTypeIndex.Add(zShape.Name, comboShapeType.Items.Count - 1); } comboShapeType.SelectedIndex = 0; for (int nIdx = 0; nIdx < (int)ElementType.End; nIdx++) { var sType = ((ElementType)nIdx).ToString(); comboElementType.Items.Add(sType); m_dictionaryElementTypes.Add(sType, (ElementType)nIdx); } tabControl.Visible = false; } private void HandleFontSettingChange(object sender, EventArgs e) { if (!m_bFireElementChangeEvents || !m_bFireFontChangeEvents || CardMakerInstance.ProcessingUserAction) { return; } var listElements = ElementManager.Instance.SelectedElements; if (null != listElements) { var listActions = UserAction.CreateActionList(); var zControl = (Control)sender; foreach (var zElement in listElements) { var zElementToChange = zElement; if (!CardMakerInstance.ProcessingUserAction && null != sender) { object zRedoValue = null; object zUndoValue = null; // The current value on the element can be used for an undo if (PopulateUndoRedoValues(zControl, zElementToChange, ref zRedoValue, ref zUndoValue)) { listActions.Add(bRedo => { AssignValueByControl(zControl, zElementToChange, bRedo ? zRedoValue : zUndoValue, false); if (null != LayoutManager.Instance.ActiveDeck) { LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElementToChange.name); } }); } else { FontStyle eFontStyle = (checkBoxBold.Checked ? FontStyle.Bold : FontStyle.Regular) | (checkBoxItalic.Checked ? FontStyle.Italic : FontStyle.Regular) | (checkBoxStrikeout.Checked ? FontStyle.Strikeout : FontStyle.Regular) | (checkBoxUnderline.Checked ? FontStyle.Underline : FontStyle.Regular); var zFont = new Font(m_listFontFamilies[comboFontName.SelectedIndex], (int)numericFontSize.Value, eFontStyle); var fontRedo = zFont; var fontUndo = zElementToChange.GetElementFont(); fontUndo = fontUndo ?? DrawItem.DefaultFont; listActions.Add(bRedo => { var fontValue = bRedo ? fontRedo : fontUndo; zElementToChange.SetElementFont(fontValue); // only affect the controls if the current selected element matches that of the element to change if (zElementToChange == ElementManager.Instance.GetSelectedElement()) { comboFontName.Text = fontValue.Name; SetupElementFont(fontValue); } if (null != LayoutManager.Instance.ActiveDeck) { LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElementToChange.name); } }); } } } Action<bool> actionChangeFont = bRedo => { CardMakerInstance.ProcessingUserAction = true; listActions.ForEach(action => action(bRedo)); CardMakerInstance.ProcessingUserAction = false; if (0 < numericLineSpace.Value) { checkFontAutoScale.Checked = false; } LayoutManager.Instance.FireLayoutUpdatedEvent(true); }; UserAction.PushAction(actionChangeFont); // perform the action as a redo now actionChangeFont(true); } } private void comboFontName_SelectedIndexChanged(object sender, EventArgs e) { SetupElementFont(null); HandleFontSettingChange(sender, e); } private void comboShapeType_SelectedIndexChanged(object sender, EventArgs e) { propertyGridShape.SelectedObject = comboShapeType.SelectedItem; } private void propertyGridShape_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { var zShape = (AbstractShape)propertyGridShape.SelectedObject; txtElementVariable.Text = zShape.ToCardMakerString(); } private void txtElementVariable_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Enter: e.SuppressKeyPress = ProjectManager.Instance.LoadedProjectTranslatorType == TranslatorType.Incept; break; } } private void btnSetSizeToImage_Click(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtElementVariable.Text)) { var zBmp = DrawItem.LoadImageFromCache(txtElementVariable.Text); if (null == zBmp) { var zElement = ElementManager.Instance.GetSelectedElement(); if (null != zElement) { var zElementString = LayoutManager.Instance.ActiveDeck.GetStringFromTranslationCache(zElement.name); if (null != zElementString.String) { zBmp = DrawItem.LoadImageFromCache(zElementString.String); } } } if (null != zBmp) { numericElementW.Value = zBmp.Width; numericElementH.Value = zBmp.Height; } } } private void listViewElementColumns_MouseClick(object sender, MouseEventArgs e) { if (MouseButtons.Right == e.Button) { var info = listViewElementColumns.HitTest(e.Location); if (null != info.Item) { int nColumn = info.Item.SubItems.IndexOf(info.SubItem); if (-1 != nColumn) { string columnText = listViewElementColumns.Columns[nColumn].Text; m_zContextMenu.Items.Clear(); m_zContextMenu.Items.Add("Add Reference to [" + columnText + "] column", null, (osender, ea) => { if (TranslatorType.Incept == ProjectManager.Instance.LoadedProjectTranslatorType) { InsertVariableText("@[" + columnText + "]"); } else if(TranslatorType.JavaScript == ProjectManager.Instance.LoadedProjectTranslatorType) { #warning this is a bit of a hack, this kind of logic should be handled by the translator InsertVariableText(columnText.StartsWith("~") ? columnText.Substring(1) : columnText); } }); m_zContextMenu.Show(listViewElementColumns.PointToScreen(e.Location)); } } } } private void btnAssist_Click(object sender, EventArgs e) { contextMenuStripAssist.Items.Clear(); // NOTE: if there is ever a third scripting language (hopefully not) break this kind of logic out into the Translator classes #warning this is a bit of a hack, this kind of logic should be handled by the translator if (TranslatorType.Incept == ProjectManager.Instance.LoadedProjectTranslatorType) { contextMenuStripAssist.Items.Add("Add Empty", null, (os, ea) => InsertVariableText("#empty")); contextMenuStripAssist.Items.Add("No Draw", null, (os, ea) => InsertVariableText("#nodraw")); contextMenuStripAssist.Items.Add("Add If Statement", null, (os, ea) => InsertVariableText("#(if x == y then a)#")); contextMenuStripAssist.Items.Add("Add If Else Statement", null, (os, ea) => InsertVariableText("#(if x == y then a else b)#")); contextMenuStripAssist.Items.Add("Add Switch Statement", null, (os, ea) => InsertVariableText("#(switch;key;keytocheck1;value1;keytocheck2;value2;#default;#empty)#")); switch ((ElementType) comboElementType.SelectedIndex) { case ElementType.FormattedText: contextMenuStripAssist.Items.Add("Add New Line", null, (os, ea) => InsertVariableText("<br>")); contextMenuStripAssist.Items.Add("Add Quote (\")", null, (os, ea) => InsertVariableText("<q>")); contextMenuStripAssist.Items.Add("Add Comma", null, (os, ea) => InsertVariableText("<c>")); break; case ElementType.Text: contextMenuStripAssist.Items.Add("Add Counter...", null, (os, ea) => { var zQuery = new QueryPanelDialog("Add Counter", 450, false); zQuery.SetIcon(CardMakerInstance.ApplicationIcon); const string INIT_VALUE = "initialValue"; const string MULT_VALUE = "multValue"; const string PAD_VALUE = "padValue"; zQuery.AddNumericBox("Initial Value", 1, int.MinValue, int.MaxValue, INIT_VALUE); zQuery.AddNumericBox("Multiplier Value", 1, int.MinValue, int.MaxValue, MULT_VALUE); zQuery.AddNumericBox("Left 0 Padding", 0, int.MinValue, int.MaxValue, PAD_VALUE); if (DialogResult.OK == zQuery.ShowDialog(this)) { InsertVariableText("##" + zQuery.GetDecimal(INIT_VALUE) + ";" + zQuery.GetDecimal(MULT_VALUE) + ";" + zQuery.GetDecimal(PAD_VALUE) + "#"); } }); contextMenuStripAssist.Items.Add("Add New Line", null, (os, ea) => InsertVariableText("\\n")); contextMenuStripAssist.Items.Add("Add Quote (\")", null, (os, ea) => InsertVariableText("\\q")); contextMenuStripAssist.Items.Add("Add Comma", null, (os, ea) => InsertVariableText("\\c")); break; case ElementType.Graphic: contextMenuStripAssist.Items.Add("Add Draw No Image", null, (os, ea) => InsertVariableText("none")); break; case ElementType.Shape: break; } } else if (TranslatorType.JavaScript == ProjectManager.Instance.LoadedProjectTranslatorType) { contextMenuStripAssist.Items.Add("Add Empty", null, (os, ea) => InsertVariableText("'#empty'")); contextMenuStripAssist.Items.Add("No Draw", null, (os, ea) => InsertVariableText("'#nodraw'")); contextMenuStripAssist.Items.Add("Add If Statement", null, (os, ea) => InsertVariableText(string.Format("if(x == y){0}{{{0}{0}}}", Environment.NewLine))); contextMenuStripAssist.Items.Add("Add If Else Statement", null, (os, ea) => InsertVariableText(string.Format("if(x == y){0}{{{0}{0}}}{0}else{0}{{{0}{0}}}", Environment.NewLine))); contextMenuStripAssist.Items.Add("Add Switch Statement", null, (os, ea) => InsertVariableText(string.Format("switch(key){0}{{{0}case keytocheck1:{0}\tvalue1;{0}}}", Environment.NewLine))); switch ((ElementType)comboElementType.SelectedIndex) { case ElementType.FormattedText: contextMenuStripAssist.Items.Add("Add New Line", null, (os, ea) => InsertVariableText("<br>")); contextMenuStripAssist.Items.Add("Add Quote (\")", null, (os, ea) => InsertVariableText("<q>")); contextMenuStripAssist.Items.Add("Add Comma", null, (os, ea) => InsertVariableText("<c>")); break; case ElementType.Text: contextMenuStripAssist.Items.Add("Add New Line", null, (os, ea) => InsertVariableText("\\\\n")); contextMenuStripAssist.Items.Add("Add Quote (\")", null, (os, ea) => InsertVariableText("\\\\q")); contextMenuStripAssist.Items.Add("Add Comma", null, (os, ea) => InsertVariableText("\\\\c")); break; case ElementType.Graphic: contextMenuStripAssist.Items.Add("Add Draw No Image", null, (os, ea) => InsertVariableText("none")); break; case ElementType.Shape: break; } } contextMenuStripAssist.Show(btnAssist, new Point(btnAssist.Width, 0), ToolStripDropDownDirection.AboveLeft); } #endregion private void SetColorValue(Button btnClicked, Color color, ProjectLayoutElement zElement) { if (btnClicked == btnElementBorderColor) { zElement.SetElementBorderColor(color); } else if (btnClicked == btnElementOutlineColor) { zElement.SetElementOutlineColor(color); } else if (btnClicked == btnElementFontColor || btnClicked == btnElementShapeColor) { zElement.SetElementColor(color); } } private void HandleTypeEnableStates() { tabControl.Visible = true; // update the graphic and text alignment combo boxes ProjectLayoutElement zElement = ElementManager.Instance.GetSelectedElement(); comboTextHorizontalAlign.SelectedIndex = zElement.horizontalalign; comboTextVerticalAlign.SelectedIndex = zElement.verticalalign; comboGraphicHorizontalAlign.SelectedIndex = zElement.horizontalalign; comboGraphicVerticalAlign.SelectedIndex = zElement.verticalalign; tabControl.Enabled = false; #if MONO_BUILD switch ((ElementType)comboElementType.SelectedIndex) { case ElementType.Graphic: tabControl.SelectedTab = tabPageGraphic; break; case ElementType.Shape: tabControl.SelectedTab = tabPageShape; break; case ElementType.Text: tabControl.SelectedTab = tabPageFont; checkFontAutoScale.Visible = true; lblWordSpacing.Visible = false; numericWordSpace.Visible = false; lblLineSpace.Visible = false; numericLineSpace.Visible = false; break; case ElementType.FormattedText: tabControl.SelectedTab = tabPageFont; checkFontAutoScale.Visible = false; lblWordSpacing.Visible = true; numericWordSpace.Visible = true; numericLineSpace.Visible = true; lblLineSpace.Visible = true; break; } #else tabControl.TabPages.Clear(); switch ((ElementType)comboElementType.SelectedIndex) { case ElementType.Graphic: tabControl.TabPages.Add(tabPageGraphic); break; case ElementType.Shape: tabControl.TabPages.Add(tabPageShape); break; case ElementType.Text: tabControl.TabPages.Add(tabPageFont); checkFontAutoScale.Visible = true; lblWordSpacing.Visible = false; numericWordSpace.Visible = false; lblLineSpace.Visible = false; numericLineSpace.Visible = false; checkJustifiedText.Visible = false; break; case ElementType.FormattedText: tabControl.TabPages.Add(tabPageFont); checkFontAutoScale.Visible = false; lblWordSpacing.Visible = true; numericWordSpace.Visible = true; numericLineSpace.Visible = true; lblLineSpace.Visible = true; checkJustifiedText.Visible = true; break; } #endif tabControl.Enabled = true; btnElementBrowseImage.Enabled = (comboElementType.SelectedIndex == (int)ElementType.Graphic); } private void HandleEnableStates() { // TODO: this is duplicated in UpdateElementValues groupBoxElement.Enabled = (null != ElementManager.Instance.GetSelectedElement()); } private void CreateControlFieldDictionary() { Type zType = typeof(ProjectLayoutElement); // HandleElementValueChange related m_dictionaryControlField.Add(txtElementVariable, zType.GetProperty("variable")); m_dictionaryControlField.Add(comboElementType, zType.GetProperty("type")); m_dictionaryControlField.Add(numericElementX, zType.GetProperty("x")); m_dictionaryControlField.Add(numericElementY, zType.GetProperty("y")); m_dictionaryControlField.Add(numericElementW, zType.GetProperty("width")); m_dictionaryControlField.Add(numericElementH, zType.GetProperty("height")); m_dictionaryControlField.Add(numericElementBorderThickness, zType.GetProperty("borderthickness")); m_dictionaryControlField.Add(checkFontAutoScale, zType.GetProperty("autoscalefont")); m_dictionaryControlField.Add(checkLockAspect, zType.GetProperty("lockaspect")); m_dictionaryControlField.Add(checkKeepOriginalSize, zType.GetProperty("keeporiginalsize")); m_dictionaryControlField.Add(numericElementOutLineThickness, zType.GetProperty("outlinethickness")); m_dictionaryControlField.Add(numericElementRotation, zType.GetProperty("rotation")); m_dictionaryControlField.Add(comboGraphicHorizontalAlign, zType.GetProperty("horizontalalign")); m_dictionaryControlField.Add(comboGraphicVerticalAlign, zType.GetProperty("verticalalign")); m_dictionaryControlField.Add(comboTextHorizontalAlign, zType.GetProperty("horizontalalign")); m_dictionaryControlField.Add(comboTextVerticalAlign, zType.GetProperty("verticalalign")); m_dictionaryControlField.Add(numericElementOpacity, zType.GetProperty("opacity")); // HandleFontSettingChange related m_dictionaryControlField.Add(numericLineSpace, zType.GetProperty("lineheight")); m_dictionaryControlField.Add(numericWordSpace, zType.GetProperty("wordspace")); m_dictionaryControlField.Add(checkJustifiedText, zType.GetProperty("justifiedtext")); } private void SetupControlActions() { m_dictionaryControlActions.Add(txtElementVariable, zElement => { LayoutManager.Instance.ActiveDeck.ResetTranslationCache(zElement); LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name); }); m_dictionaryControlActions.Add(numericElementW, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); m_dictionaryControlActions.Add(numericElementH, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); m_dictionaryControlActions.Add(numericElementOutLineThickness, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); m_dictionaryControlActions.Add(comboTextHorizontalAlign, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); m_dictionaryControlActions.Add(comboTextVerticalAlign, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); m_dictionaryControlActions.Add(numericElementOpacity, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); m_dictionaryControlActions.Add(checkJustifiedText, zElement => LayoutManager.Instance.ActiveDeck.ResetMarkupCache(zElement.name)); } private bool PopulateUndoRedoValues(Control zControl, ProjectLayoutElement zElement, ref object zRedoValue, ref object zUndoValue) { PropertyInfo zInfo; if (!m_dictionaryControlField.TryGetValue(zControl, out zInfo)) { return false; } MethodInfo zGetMethodInfo = zInfo.GetGetMethod(); if (zInfo.PropertyType == typeof(int)) { zUndoValue = (int)zGetMethodInfo.Invoke(zElement, null); if (zControl is ComboBox) { zRedoValue = ((ComboBox)zControl).SelectedIndex; } else // assumes numericupdown { zRedoValue = (int)((NumericUpDown)zControl).Value; } } else if (zInfo.PropertyType == typeof(float)) { zUndoValue = (float)zGetMethodInfo.Invoke(zElement, null); zRedoValue = (float)((NumericUpDown)zControl).Value; } else if (zInfo.PropertyType == typeof(string)) { zUndoValue = (string)zGetMethodInfo.Invoke(zElement, null); if (zControl is ComboBox) { zRedoValue = ((ComboBox)zControl).Text; } else // assumes textbox { zRedoValue = ((TextBox)zControl).Text; } } else if (zInfo.PropertyType == typeof(bool)) { zUndoValue = (bool)zGetMethodInfo.Invoke(zElement, null); zRedoValue = ((CheckBox)zControl).Checked; } return true; } private void AssignValueByControl(Control zControl, ProjectLayoutElement zElement, object zNewValue, bool bSkipControlUpdate) { // Assign the element property the new value PropertyInfo zInfo = m_dictionaryControlField[zControl]; // TODO: would caching this call speed anything up? MethodInfo zSetMethodInfo = zInfo.GetSetMethod(); zSetMethodInfo.Invoke(zElement, new object[] { zNewValue }); // execute any control/element property specific functionality Action<ProjectLayoutElement> actionElement; if(m_dictionaryControlActions.TryGetValue(zControl, out actionElement)) { actionElement(zElement); } if (ElementManager.Instance.GetSelectedElement() != zElement || bSkipControlUpdate) { // don't update the controls if they are for a non-selected item return; } // update the element controls if (zInfo.PropertyType == typeof(int)) { if (zControl is ComboBox) { ((ComboBox)zControl).SelectedIndex = (int)zNewValue; } else { ((NumericUpDown)zControl).Value = (int)zNewValue; } } else if (zInfo.PropertyType == typeof(float)) { ((NumericUpDown)zControl).Value = (decimal)(float)zNewValue; } else if (zInfo.PropertyType == typeof(string)) { if (zControl is ComboBox) { ((ComboBox)zControl).Text = (string)zNewValue; } else // assumes textbox { ((TextBox)zControl).Text = (string)zNewValue; } } else if (zInfo.PropertyType == typeof(bool)) { ((CheckBox)zControl).Checked = (bool)zNewValue; } } /// <summary> /// Method for updating the selected element bounds control values externally (no undo/redo processing) /// </summary> /// <param name="zElement"></param> private void UpdateElementBoundsControlValues(ProjectLayoutElement zElement) { if (null != zElement) { m_bFireElementChangeEvents = false; numericElementX.Value = zElement.x; numericElementY.Value = zElement.y; numericElementW.Value = zElement.width; numericElementH.Value = zElement.height; numericElementRotation.Value = (decimal)zElement.rotation; m_bFireElementChangeEvents = true; // TODO: if the value does not actually change this applies an update for no specific reason... (tbd) PerformControlChangeActions(numericElementX, numericElementY, numericElementW, numericElementH, numericElementRotation); } LayoutManager.Instance.FireLayoutUpdatedEvent(true); } private void PerformControlChangeActions(params Control[] arraycontrols) { Action<ProjectLayoutElement> action; foreach(var zControl in arraycontrols) { if (m_dictionaryControlActions.TryGetValue(zControl, out action)) { action(ElementManager.Instance.GetSelectedElement()); } } } private void UpdateElementValues(ProjectLayoutElement zElement) { if (null != zElement) { m_bFireElementChangeEvents = false; numericElementX.Value = zElement.x; numericElementY.Value = zElement.y; numericElementW.Value = zElement.width; numericElementH.Value = zElement.height; numericElementRotation.Value = (decimal)zElement.rotation; numericElementBorderThickness.Value = (decimal)zElement.borderthickness; numericElementOutLineThickness.Value = (decimal)zElement.outlinethickness; numericLineSpace.Value = (decimal)zElement.lineheight; numericWordSpace.Value = (decimal)zElement.wordspace; checkFontAutoScale.Checked = zElement.autoscalefont; checkLockAspect.Checked = zElement.lockaspect; checkKeepOriginalSize.Checked = zElement.keeporiginalsize; numericElementOpacity.Value = (decimal)zElement.opacity; comboTextHorizontalAlign.SelectedIndex = zElement.horizontalalign; comboTextVerticalAlign.SelectedIndex = zElement.verticalalign; comboGraphicHorizontalAlign.SelectedIndex = zElement.horizontalalign; comboGraphicVerticalAlign.SelectedIndex = zElement.verticalalign; checkJustifiedText.Checked = zElement.justifiedtext; txtElementVariable.Text = zElement.variable; txtElementVariable.SelectionStart = zElement.variable.Length; txtElementVariable.SelectionLength = 0; ElementType eType = m_dictionaryElementTypes[zElement.type]; switch (eType) { case ElementType.Shape: // configure the combo box and property grid for the shap string sType = AbstractShape.GetShapeType(zElement.variable); if (null != sType) { int nSelectedIndex; if (dictionaryShapeTypeIndex.TryGetValue(sType, out nSelectedIndex)) { comboShapeType.SelectedIndex = nSelectedIndex; var zShape = (AbstractShape)comboShapeType.SelectedItem; zShape.InitializeItem(zElement.variable); // associated the prop grid with this shape object propertyGridShape.SelectedObject = zShape; } } break; case ElementType.Text: checkFontAutoScale.Visible = true; lblWordSpacing.Visible = false; numericWordSpace.Visible = false; checkJustifiedText.Visible = false; break; case ElementType.FormattedText: checkFontAutoScale.Visible = false; lblWordSpacing.Visible = true; numericWordSpace.Visible = true; checkJustifiedText.Visible = true; break; } // this fires a change event on the combo box... seems like it might be wrong? comboElementType.SelectedIndex = (int)eType; UpdatePanelColors(zElement); groupBoxElement.Enabled = true; Font zFont = zElement.GetElementFont(); zFont = zFont ?? DrawItem.DefaultFont; for (int nFontIndex = 0; nFontIndex < comboFontName.Items.Count; nFontIndex++) { if (zFont.Name.Equals((string)comboFontName.Items[nFontIndex], StringComparison.CurrentCultureIgnoreCase)) { comboFontName.SelectedIndex = nFontIndex; break; } } SetupElementFont(zFont); m_bFireElementChangeEvents = true; } else { groupBoxElement.Enabled = false; } } private void SetupElementFont(Font zElementFont) { m_bFireFontChangeEvents = false; // setup the font settings (unsupported types cause exceptions) var zFamily = m_listFontFamilies[comboFontName.SelectedIndex]; // configure font style controls ConfigureFontStyleControl(zFamily, FontStyle.Bold, checkBoxBold); ConfigureFontStyleControl(zFamily, FontStyle.Italic, checkBoxItalic); ConfigureFontStyleControl(zFamily, FontStyle.Strikeout, checkBoxStrikeout); ConfigureFontStyleControl(zFamily, FontStyle.Underline, checkBoxUnderline); if (null != zElementFont) { checkBoxBold.Checked = zElementFont.Bold; checkBoxItalic.Checked = zElementFont.Italic; checkBoxStrikeout.Checked = zElementFont.Strikeout; checkBoxUnderline.Checked = zElementFont.Underline; numericFontSize.Value = (decimal)zElementFont.SizeInPoints; } m_bFireFontChangeEvents = true; } private void ConfigureFontStyleControl(FontFamily zFamily, FontStyle eStyle, CheckBox checkBox) { checkBox.Enabled = zFamily.IsStyleAvailable(eStyle); if (!checkBox.Enabled) { checkBox.Checked = false; } } private void UpdatePanelColors(ProjectLayoutElement zElement) { if (zElement != ElementManager.Instance.GetSelectedElement()) { return; } panelBorderColor.BackColor = zElement.GetElementBorderColor(); panelOutlineColor.BackColor = zElement.GetElementOutlineColor(); panelShapeColor.BackColor = zElement.GetElementColor(); panelFontColor.BackColor = panelShapeColor.BackColor; } private void InsertVariableText(string textToInsert) { int previousSelectionStart = txtElementVariable.SelectionStart; txtElementVariable.Text = txtElementVariable.Text.Remove(previousSelectionStart, txtElementVariable.SelectionLength).Insert(txtElementVariable.SelectionStart, textToInsert); txtElementVariable.SelectionStart = previousSelectionStart + textToInsert.Length; txtElementVariable.SelectionLength = 0; } } }
//--------------------------------------------------------------------- // <copyright file="JoinElimination.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System; using System.Collections.Generic; //using System.Diagnostics; // Please use PlanCompiler.Assert instead of Debug.Assert in this class... // It is fine to use Debug.Assert in cases where you assert an obvious thing that is supposed // to prevent from simple mistakes during development (e.g. method argument validation // in cases where it was you who created the variables or the variables had already been validated or // in "else" clauses where due to code changes (e.g. adding a new value to an enum type) the default // "else" block is chosen why the new condition should be treated separately). This kind of asserts are // (can be) helpful when developing new code to avoid simple mistakes but have no or little value in // the shipped product. // PlanCompiler.Assert *MUST* be used to verify conditions in the trees. These would be assumptions // about how the tree was built etc. - in these cases we probably want to throw an exception (this is // what PlanCompiler.Assert does when the condition is not met) if either the assumption is not correct // or the tree was built/rewritten not the way we thought it was. // Use your judgment - if you rather remove an assert than ship it use Debug.Assert otherwise use // PlanCompiler.Assert. using System.Globalization; using System.Data.Query.InternalTrees; using System.Data.Metadata.Edm; namespace System.Data.Query.PlanCompiler { /// <summary> /// The JoinElimination module is intended to do just that - eliminate unnecessary joins. /// This module deals with the following kinds of joins /// * Self-joins: The join can be eliminated, and either of the table instances can be /// used instead /// * Implied self-joins: Same as above /// * PK-FK joins: (More generally, UniqueKey-FK joins): Eliminate the join, and use just the FK table, if no /// column of the PK table is used (other than the join condition) /// * PK-PK joins: Eliminate the right side table, if we have a left-outer join /// </summary> internal class JoinElimination : BasicOpVisitorOfNode { #region private constants private const string SqlServerCeNamespaceName = "SqlServerCe"; #endregion #region private state private PlanCompiler m_compilerState; private Command Command { get { return m_compilerState.Command; } } private ConstraintManager ConstraintManager { get { return m_compilerState.ConstraintManager; } } private Dictionary<Node, Node> m_joinGraphUnnecessaryMap = new Dictionary<Node,Node>(); private VarRemapper m_varRemapper; private bool m_treeModified = false; private VarRefManager m_varRefManager; private Nullable<bool> m_isSqlCe = null; #endregion #region constructors private JoinElimination(PlanCompiler compilerState) { m_compilerState = compilerState; m_varRemapper = new VarRemapper(m_compilerState.Command); m_varRefManager = new VarRefManager(m_compilerState.Command); } #endregion #region public surface internal static bool Process(PlanCompiler compilerState) { JoinElimination je = new JoinElimination(compilerState); je.Process(); return je.m_treeModified; } #endregion #region private methods /// <summary> /// Invokes the visitor /// </summary> private void Process() { this.Command.Root = VisitNode(this.Command.Root); } #region JoinHelpers #region Building JoinGraphs /// <summary> /// Do we need to build a join graph for this node - returns false, if we've already /// processed this /// </summary> /// <param name="joinNode"></param> /// <returns></returns> private bool NeedsJoinGraph(Node joinNode) { return !m_joinGraphUnnecessaryMap.ContainsKey(joinNode); } /// <summary> /// Do the real processing of the join graph. /// </summary> /// <param name="joinNode">current join node</param> /// <returns>modified join node</returns> private Node ProcessJoinGraph(Node joinNode) { // Build the join graph JoinGraph joinGraph = new JoinGraph(this.Command, this.ConstraintManager, this.m_varRefManager, joinNode, this.IsSqlCeProvider); // Get the transformed node tree VarMap remappedVars; Dictionary<Node, Node> processedNodes; Node newNode = joinGraph.DoJoinElimination(out remappedVars, out processedNodes); // Get the set of vars that need to be renamed foreach (KeyValuePair<Var, Var> kv in remappedVars) { m_varRemapper.AddMapping(kv.Key, kv.Value); } // get the set of nodes that have already been processed foreach (Node n in processedNodes.Keys) { m_joinGraphUnnecessaryMap[n] = n; } return newNode; } /// <summary> /// Indicates whether we are running against a SQL CE provider or not. /// </summary> private bool IsSqlCeProvider { get { if (!m_isSqlCe.HasValue) { // Figure out if we are using SQL CE by asking the store provider manifest for its namespace name. PlanCompiler.Assert(m_compilerState != null, "Plan compiler cannot be null"); var sspace = (StoreItemCollection)m_compilerState.MetadataWorkspace.GetItemCollection(Metadata.Edm.DataSpace.SSpace); if (sspace != null) { m_isSqlCe = sspace.StoreProviderManifest.NamespaceName == JoinElimination.SqlServerCeNamespaceName; } } // If the sspace was null then m_isSqlCe still doesn't have a value. Use 'false' as default. return m_isSqlCe.HasValue ? m_isSqlCe.Value : false; } } /// <summary> /// Default handler for a node. Simply visits the children, then handles any var /// remapping, and then recomputes the node info /// </summary> /// <param name="n"></param> /// <returns></returns> private Node VisitDefaultForAllNodes(Node n) { VisitChildren(n); m_varRemapper.RemapNode(n); this.Command.RecomputeNodeInfo(n); return n; } #endregion #endregion #region Visitor overrides /// <summary> /// Invokes default handling for a node and adds the child-parent tracking info to the VarRefManager. /// </summary> /// <param name="n"></param> /// <returns></returns> protected override Node VisitDefault(Node n) { m_varRefManager.AddChildren(n); return VisitDefaultForAllNodes(n); } #region RelOps #region JoinOps /// <summary> /// Build a join graph for this node for this node if necessary, and process it /// </summary> /// <param name="op">current join op</param> /// <param name="joinNode">current join node</param> /// <returns></returns> protected override Node VisitJoinOp(JoinBaseOp op, Node joinNode) { Node newNode; // Build and process a join graph if necessary if (NeedsJoinGraph(joinNode)) { newNode = ProcessJoinGraph(joinNode); if (newNode != joinNode) { m_treeModified = true; } } else { newNode = joinNode; } // Now do the default processing (ie) visit the children, compute the nodeinfo etc. return VisitDefaultForAllNodes(newNode); } #endregion #endregion #endregion #endregion } }
using RestSharp; using TwitchCSharp.Enums; using TwitchCSharp.Helpers; using TwitchCSharp.Models; namespace TwitchCSharp.Clients { public class TwitchReadOnlyClient : ITwitchClient { public readonly RestClient restClient; public TwitchReadOnlyClient(string clientID, string url = TwitchHelper.twitchApiUrl) { restClient = new RestClient(url); restClient.AddHandler("application/json", new DynamicJsonDeserializer()); restClient.AddHandler("text/html", new DynamicJsonDeserializer()); restClient.AddDefaultHeader("Accept", TwitchHelper.twitchAcceptHeader); restClient.AddDefaultHeader("Client-ID", clientID); } public Channel GetChannel(string channel) { var request = GetRequest("channels/{channel}", Method.GET); request.AddUrlSegment("channel", channel); var response = restClient.Execute<Channel>(request); return response.Data; } public TwitchList<Team> GetTeams(string channel) { var request = GetRequest("channels/{channel}/teams", Method.GET); request.AddUrlSegment("channel", channel); var response = restClient.Execute<TwitchList<Team>>(request); return response.Data; } public TwitchList<Emoticon> GetEmoticons() { var request = GetRequest("chat/emoticons", Method.GET); var response = restClient.Execute<TwitchList<Emoticon>>(request); return response.Data; } public TwitchList<EmoticonImage> GetEmoticonImages() { var request = GetRequest("chat/emoticon_images", Method.GET); var response = restClient.Execute<TwitchList<EmoticonImage>>(request); return response.Data; } public BadgeResult GetBadges(string channel) { var request = GetRequest("chat/{channel}/badges", Method.GET); request.AddUrlSegment("channel", channel); var response = restClient.Execute<BadgeResult>(request); return response.Data; } public TwitchList<Follower> GetFollowers(string channel, PagingInfo pagingInfo = null) { var request = GetRequest("channels/{channel}/follows", Method.GET); request.AddUrlSegment("channel", channel); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Follower>>(request); return response.Data; } public TwitchList<FollowedChannel> GetFollowedChannels(string user, PagingInfo pagingInfo = null, SortDirection sortDirection = SortDirection.desc, SortType sortType = SortType.created_at) { var request = GetRequest("users/{user}/follows/channels", Method.GET); request.AddUrlSegment("user", user); TwitchHelper.AddPaging(request, pagingInfo); request.AddParameter("direction", sortDirection); request.AddParameter("sortby", sortType); var response = restClient.Execute<TwitchList<FollowedChannel>>(request); return response.Data; } public FollowedChannel GetFollowedChannel(string user, string target) { var request = GetRequest("users/{user}/follows/channels/{target}", Method.GET); request.AddUrlSegment("user", user); request.AddUrlSegment("target", target); var response = restClient.Execute<FollowedChannel>(request); return response.Data; } public bool IsFollowing(string user, string target) { return GetFollowedChannel(user, target).Status != 404; } public TwitchList<TopGame> GetTopGames(PagingInfo pagingInfo = null) { var request = GetRequest("games/top", Method.GET); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<TopGame>>(request); return response.Data; } public TwitchList<Ingest> GetIngests() { var request = GetRequest("ingests/", Method.GET); var response = restClient.Execute<TwitchList<Ingest>>(request); return response.Data; } public RootResult GetRoot() { var request = GetRequest("/", Method.GET); var response = restClient.Execute<RootResult>(request); return response.Data; } public TwitchList<Channel> SearchChannels(string query, PagingInfo pagingInfo = null) { var request = GetRequest("search/channels", Method.GET); request.AddParameter("query", query); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Channel>>(request); return response.Data; } public TwitchList<Stream> SearchStreams(string query, PagingInfo pagingInfo = null) { var request = GetRequest("search/streams", Method.GET); request.AddParameter("query", query); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Stream>>(request); return response.Data; } public TwitchList<Stream> SearchStreams(string query, bool hls, PagingInfo pagingInfo = null) { var request = GetRequest("search/streams", Method.GET); request.AddParameter("query", query); request.AddParameter("hls", hls); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Stream>>(request); return response.Data; } public TwitchList<Game> SearchGames(string query, bool live = false, PagingInfo pagingInfo = null) { var request = GetRequest("search/games", Method.GET); request.AddParameter("query", query); request.AddParameter("type", "suggest"); // currently no other types than "suggest" request.AddParameter("live", live); // if live = true, only returns games that are live on at least one channel. TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Game>>(request); return response.Data; } //stream = null if channel is offline public StreamResult GetStream(string channel) { var request = GetRequest("streams/{channel}", Method.GET); request.AddUrlSegment("channel", channel); var response = restClient.Execute<StreamResult>(request); return response.Data; } public bool IsLive(string channel) { return GetStream(channel).Stream != null; } public TwitchList<Stream> GetStreams(string game = null, string channel = null, string clientId = null, PagingInfo pagingInfo = null) { var request = GetRequest("streams", Method.GET); request.AddSafeParameter("game", game); request.AddSafeParameter("channel", channel); TwitchHelper.AddPaging(request, pagingInfo); request.AddSafeParameter("client_id", clientId); var response = restClient.Execute<TwitchList<Stream>>(request); return response.Data; } public TwitchList<Featured> GetFeaturedStreams(PagingInfo pagingInfo = null) { var request = GetRequest("streams/featured", Method.GET); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Featured>>(request); return response.Data; } public StreamSummary GetStreamSummary(string game = null) { var request = GetRequest("streams/summary", Method.GET); request.AddSafeParameter("game", game); var response = restClient.Execute<StreamSummary>(request); return response.Data; } public TwitchList<Team> GetTeams(PagingInfo pagingInfo = null) { var request = GetRequest("teams", Method.GET); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Team>>(request); return response.Data; } public Team GetTeam(string team) { var request = GetRequest("teams/{team}", Method.GET); request.AddUrlSegment("team", team); var response = restClient.Execute<Team>(request); return response.Data; } public User GetUser(string user) { var request = GetRequest("users/{user}", Method.GET); request.AddUrlSegment("user", user); var response = restClient.Execute<User>(request); return response.Data; } public Video GetVideo(string id) { var request = GetRequest("videos/{id}", Method.GET); request.AddUrlSegment("id", id); var response = restClient.Execute<Video>(request); return response.Data; } public TwitchList<Video> GetTopVideos(string game = null, PeriodType period = PeriodType.week, PagingInfo pagingInfo = null) { var request = GetRequest("videos/top", Method.GET); request.AddSafeParameter("game", game); request.AddParameter("period", period); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Video>>(request); return response.Data; } public TwitchList<Video> GetChannelVideos(string channel, bool broadcasts = false, bool hls = false, PagingInfo pagingInfo = null) { var request = GetRequest("channels/{channel}/videos", Method.GET); request.AddUrlSegment("channel", channel); request.AddParameter("broadcasts", broadcasts); request.AddParameter("hls", hls); TwitchHelper.AddPaging(request, pagingInfo); var response = restClient.Execute<TwitchList<Video>>(request); return response.Data; } public RestRequest GetRequest(string url, Method method) { return new RestRequest(url, method); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using LitS3; using log4net; namespace DataMigration { /// <summary> /// This is a location to put utility functions that don't exist in Mono/.NET, or in our /// source code. If a method becomes globally useful, it should be promoted to a shared /// location for multiple projects to use. It's very MS Sql Server specific, although /// there is some code in here for non-Sql Server things. /// </summary> static public class Utilities { static readonly ILog log = LogManager.GetLogger(typeof(Utilities)); const int maxPasswordLength = 20; /// <summary> /// Tells if an IDataRecord has a column, avoiding exception being thrown when /// looking for it. /// </summary> /// <param name="dr">IDataRecord</param> /// <param name="columnName">Name of column to look for.</param> /// <returns>True if column exists, false otherwise.</returns> public static bool HasColumn(IDataRecord dr, string columnName) { for (int i=0; i < dr.FieldCount; i++) { if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase)) return true; } return false; } /// <summary> /// Given a fully assembly-qualified typename, returns a Mono Type. /// </summary> /// <returns>The desired Mono type.</returns> /// <param name="fullyQualifiedTypeName">Fully assembly-qualified type name.</param> public static Type GetTypeFromFqName(string fullyQualifiedTypeName) { var type = Type.GetType(fullyQualifiedTypeName); if (type == null) { throw new Exception( String.Format("Error creating type {0}", fullyQualifiedTypeName)); } return type; } /// <summary> /// Given a series of uri segments, this method will return a complete Uri. /// </summary> /// <returns>The desired Uri.</returns> /// <param name="paths">Segments of the Uri desired.</param> public static string UriCombine(params string[] paths) { var result = String.Empty; if (paths != null && paths.Length > 0) { foreach (var p in paths) { string temp = p; if (temp.StartsWith("//")) temp = temp.Substring(1, temp.Length - 1); else if (temp.EndsWith ("//")) temp = temp.Substring(0, temp.Length - 1); if (temp.StartsWith("/") && !String.IsNullOrEmpty(result)) result += temp.Substring(1, temp.Length - 1); else { result += temp; } if (!result.EndsWith("/")) { result += "/"; } } if (result.EndsWith("/")) result = result.Substring (0, result.Length - 1); } return result; } /// <summary> /// Helper function that looks in a properties collection for values, throwing an /// exception if not found. /// <returns>The required property value.</returns> /// <param name="key">The key for the property value.</param> /// <param name="properties">The list of properties to look in.</param> /// </summary> public static string GetRequiredProperty (string key, IEnumerable<DescriptorProperty> properties) { return GetProperty(key, properties, true); } /// <summary> /// Helper function that looks in a properties collection for values, throwing an /// exception if not found, although this can be suppressed. It also will throw an /// exception if the property is not parseable as a bool. /// <returns>The boolean property value, if found, and parseable, null if not found and /// the 'required' parameter is false, or throws an exception in remaining cases. /// </returns> /// <param name="key">The key for the property value.</param> /// <param name="properties">The list of properties to look in.</param> /// <param name="required">Is the property required? Defaults to true.</param> /// </summary> public static bool? GetBoolProperty(string key, IEnumerable<DescriptorProperty> properties, bool required = true) { var boolString = GetProperty(key, properties, required); if (String.IsNullOrEmpty(boolString)) { return null; } bool boolValue; if (!Boolean.TryParse(boolString, out boolValue)) { throw new Exception(String.Format("GetRequiredBoolProperty - value for key " + "\"{0}\" = \"{1}\", not parseable as bool", key, boolString)); } return boolValue; } /// <summary> /// This helper is for getting boolean properties that are required to be in the Plan. /// </summary> /// <param name="key">The key for the property value.</param> /// <param name="properties">The list of properties to look in.</param> /// <returns></returns> public static bool GetRequiredBoolProperty(string key, IEnumerable<DescriptorProperty> properties) { // It's OK to use the .Value operator here; this will properly throw a usable // exception if the property is missing in the plan, and otherwise there will be a // valid boolean value. return GetBoolProperty(key, properties).Value; } /// <summary> /// Helper function that looks in a properties collection for values that are expected /// to be parseable to an int. Will throw an exception if required == true and the /// property is not found, or if it is found, but is not parseable as an integer. /// </summary> /// <param name="key">Key for the integer property to look for.</param> /// <param name="properties">The properties collection.</param> /// <param name="required">If true, will throw exception if the property is missing. /// </param> /// <returns>The parsed int value, or null.</returns> public static int? GetIntProperty(string key, IEnumerable<DescriptorProperty> properties, bool required = true) { var intString = GetProperty(key, properties, required); if (String.IsNullOrEmpty(intString)) { return null; } int intValue; if (!Int32.TryParse(intString, out intValue)) { throw new Exception(String.Format("GetIntProperty - {0} property value is not " + "parseable as int", key )); } return intValue; } /// <summary> /// Gets the property. /// </summary> /// <returns>The property.</returns> /// <param name="key">Key.</param> /// <param name="properties">Properties.</param> /// <param name="required">If set to <c>true</c> required. This function will throw an /// exception if 'required' is true and the property doesn't exist or has a blank or /// null value.</param> public static string GetProperty(string key, IEnumerable<DescriptorProperty> properties, bool required) { if (properties == null) { throw new Exception("GetProperty a- properties block is needed to " + "function."); } var property = properties.SingleOrDefault(p => p.Name.Equals(key)); if (property == null) { if (required) { throw new Exception( String.Format("GetRequiredProperty - missing {0} property", key)); } return null; } if (String.IsNullOrWhiteSpace (property.Value)) { if (required) { throw new Exception(String.Format("GetProperty - {0} property " + "value is empty", key)); } return null; } return property.Value; } /// <summary> /// Given a key from the properties for the PostProcessorDescriptor that describes this /// PostProcessor, this will return a matching string in App.Config. /// </summary> /// <param name="keyInProperties"></param> /// <param name="properties">The collection of properties to search through. </param> /// <returns></returns> public static string GetConfigString(string keyInProperties, IEnumerable<DescriptorProperty> properties) { var connectionKey = Utilities.GetRequiredProperty(keyInProperties, properties); try { return ConfigurationManager.AppSettings[connectionKey]; } catch (Exception ex) { throw new Exception( String.Format("GetConfigString - missing App.Config app setting " + "\"{0}\"", keyInProperties), ex); } } /// <summary> /// Instantiates and returns a LitS3 S3 service object. /// </summary> /// <returns>The LitS3 S3Service.</returns> public static S3Service GetS3Service() { var appSettings = ConfigurationManager.AppSettings; var accessKey = appSettings["AWSAccessKey"]; var secretAccessKey = appSettings["AWSSecretAccessKey"]; var service = new S3Service{ AccessKeyID = accessKey, SecretAccessKey = secretAccessKey, UseSsl = true, UseSubdomains = true }; service.BeforeAuthorize += (sender, e) => { e.Request.ServicePoint.ConnectionLimit = int.MaxValue; }; return service; } /// <summary> /// A helper function to encapsulate the creation of integer parameters to stored /// procedures. /// </summary> /// <returns>The SqlParameter object.</returns> /// <param name="command">A SqlCommand object to create the parameter for.</param> /// <param name="direction">Is the parameter In, Out, In/Out, or Return Value?</param> /// <param name="name">Name of the parameter.</param> /// <param name="value">The integer value to set.</param> public static SqlParameter CreateIntParameter(SqlCommand command, ParameterDirection direction, String name, int value) { var parameter = command.Parameters.Add(name, SqlDbType.Int); parameter.Direction = direction; parameter.Value = value; return parameter; } /// <summary> /// Creates an nvarchar variable length string SqlParameter object. /// </summary> /// <returns>The created parameter.</returns> /// <param name="command">A SqlCommand object to create the parameter for.</param> /// <param name="direction">Is the parameter In, Out, In/Out, or Return Value?</param> /// <param name="name">Name of the parameter.</param> /// <param name="value">The string value to set.</param> /// <param name="count">The length of the string</param> public static SqlParameter CreateNVarCharParameter(SqlCommand command, ParameterDirection direction, String name, String value, int count) { var parameter = command.Parameters.Add(name, SqlDbType.NVarChar, count); parameter.Direction = direction; parameter.Value = value; return parameter; } /// <summary> /// Enables the or disable sql trigger. This is 'tui_member', on the 'member' table. /// It enforces historical business logic that is different than what we are permitting /// for the user migration for NAMG. We disable it, run the post-process, then /// re-enable it. /// </summary> /// <param name="connectionString">Database connection string.</param> /// <param name="triggerName">Trigger name.</param> /// <param name="tableName">Table name.</param> /// <param name="enableOrDisable">If set to <c>true</c> enable or disable.</param> public static void EnableOrDisableSqlTrigger(string connectionString, string triggerName, string tableName, bool enableOrDisable) { try { using (var connection = new SqlConnection(connectionString)) { connection.Open(); if (DoesTriggerExist(triggerName, connection)) { var commandString = String.Format(enableOrDisable ? "ALTER TABLE {0} ENABLE TRIGGER {1}" : "ALTER TABLE {0} DISABLE TRIGGER {1}", tableName, triggerName); using (var command = new SqlCommand(commandString, connection)) { command.ExecuteNonQuery(); log.DebugFormat("Successfully executed {0}, commandString", commandString); } } } } catch (Exception ex) { throw new Exception(String.Format("Error {0} sql trigger {1} on table {2}" + " error = {3}", enableOrDisable ? "enabling" : "disabling", triggerName, tableName, ex.Message), ex); } } /// <summary> /// A helper function that piggybacks on an existing open Sql connection, and let us /// know whether a trigger exists or not. /// </summary> /// <returns><c>true</c>, if trigger exists, <c>false</c> otherwise.</returns> /// <param name="triggerName">Trigger name.</param> /// <param name="connection">Connection.</param> static bool DoesTriggerExist(string triggerName, SqlConnection connection) { var commandString = String.Format("if exists (select * from sys.triggers where " + "name = '{0}') select 1 else select 0", triggerName); using (var command = new SqlCommand(commandString, connection)) { var answer = (int)command.ExecuteScalar(); return answer == 1; } } /// Gets a string from an IDataRecord safely, mapping DBNull.Value to null. /// </summary> /// <param name="record">The data record from a query.</param> /// <param name="name">The string value, or null.</param> /// <returns></returns> public static String GetDbString(IDataRecord record, String name) { var objectValue = GetDbValue(record, name); return objectValue == null ? null : (String)objectValue; } /// <summary> /// Gets a value type from an IDataRecord safely, mapping DBNull.Value to null. /// </summary> /// <param name="record">The data record from a query.</param> /// <param name="name">The column name.</param> /// <returns>The value, or null.</returns> public static T? GetDbNullableT<T>(IDataRecord record, String name) where T : struct { var objectValue = GetDbValue(record, name); return objectValue == null ? (T?) null : (T) objectValue; } /// <summary> /// Helper function; turns DBNull.Value into null. /// </summary> /// <param name="record">Data Record returned from query.</param> /// <param name="name">The name of the column.</param> /// <returns></returns> private static object GetDbValue(IDataRecord record, string name) { var objectValue = record[name]; return DBNull.Value == objectValue ? null : objectValue; } /// <summary> /// Writes the bad rows feed file. /// </summary> /// <returns>The bad rows feed file name.</returns> /// <param name="loadNumber">The Loadnumber.</param> /// <param name="phase">The Phase to use for Phase Logging.</param> /// <param name="dataSourcePlan">DataSourcePlan for this processor.</param> /// <param name="description">Description to use for phase logging.</param> /// <param name="badRowsFileName">Name of badRows Feed File.</param> /// <param name="workingDirectory">Directory to write file in.</param> /// <param name="connectionString">Db connection string.</param> /// <param name="logQuantum">How many rows to do before logging.</param> /// <param name="phaseLogger">Phase Logger for logging to Sql</param> /// <param name="logSource">logSource integer that uniquely indentifies who's doing /// the phase logging.</param> public static string WriteBadRowsFeedFile(int loadNumber, DataMigrationPhase phase, DataSourcePlan dataSourcePlan, string description, string badRowsFileName, string workingDirectory, string connectionString, int logQuantum, IPhaseLogger phaseLogger, int logSource) { return WriteFeedFileFromDatabaseQuery( String.Format("select * from dbo.BadRows where loadnum = {0}", loadNumber), badRowsFileName, "LoadNumber\tDataSourceCode\tRowNumber\tDestinationColumn\tReason\t" + "ForeignId\tRowData\t", (reader, textWriter) => { var dataSourceCode = (string)reader["DataSourceCode"]; var rowNumber = (int)reader["RowNumber"]; var destinationColumn = (string)reader["DestColumn"]; var reason = (string)reader["Reason"]; var foreignId = (string)reader["ForeignId"]; // BadRows generated in the PostProcessing stage do not have access to // the original rowdata. string rowData; if (DBNull.Value == reader["RowData"]) { rowData = "null"; } else { rowData = (string)reader["RowData"]; } textWriter.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", loadNumber, dataSourceCode, rowNumber, destinationColumn, reason, foreignId, rowData); textWriter.WriteLine(); }, loadNumber, phase, dataSourcePlan, description, workingDirectory, connectionString, logQuantum, phaseLogger, logSource ); } /// <summary> /// Helper function that factors out the common code for issuing a database query and /// writing a log file to the local file system. /// </summary> /// <returns>The full filepath for the local file produced.</returns> /// <param name="sqlQuery">Text of the sql query to issue.</param> /// <param name="fileName">The local filename to use.</param> /// <param name="tabDelimitedHeaderText">A header row for the file.</param> /// <param name="rowWriter">A delegate that reads from the SqlDataReader and /// writes to the TextWriter passed in. It knows what arguments to pull off the /// DataReader and how they should be written to the TextWriter.</param> /// <param name="loadNumber">The Loadnumber.</param> /// <param name="phase">The Phase to use for Phase Logging.</param> /// <param name="dataSourcePlan">DataSourcePlan for this processor.</param> /// <param name="description">Description to use for phase logging.</param> /// <param name="workingDirectory">Directory to write file in.</param> /// <param name="connectionString">Db connection string.</param> /// <param name="logQuantum">How many rows to do before logging.</param> /// <param name="phaseLogger">Phase Logger for logging to Sql</param> /// <param name="logSource">logSource integer that uniquely indentifies who's doing /// the phase logging.</param> public static string WriteFeedFileFromDatabaseQuery(string sqlQuery, string fileName, string tabDelimitedHeaderText, Action<SqlDataReader, TextWriter> rowWriter, int loadNumber, DataMigrationPhase phase, DataSourcePlan dataSourcePlan, string description, string workingDirectory, string connectionString, int logQuantum, IPhaseLogger phaseLogger, int logSource) { var stopWatch = Stopwatch.StartNew(); var recordCount = 0; var fullFileName = Path.Combine(workingDirectory, fileName); try { // Open up a text file for reading. using (var textWriter = File.CreateText(fullFileName)) { // Write the column name. textWriter.Write(tabDelimitedHeaderText); textWriter.WriteLine(); using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var command = new SqlCommand(sqlQuery, connection)) { var reader = command.ExecuteReader(); while (reader.Read()) { rowWriter(reader, textWriter); recordCount++; if ((recordCount % logQuantum) == 0) { log.DebugFormat("WriteFeedFileFromDatabaseQuery - rows " + "written = {0}", recordCount); } } } } } phaseLogger.Log(new PhaseLogEntry { LogSource = logSource, DataSourceCode = dataSourcePlan.DataSourceCode, LoadNumber = loadNumber, Phase = phase, NumberOfRecords = recordCount, Description = description }); } catch (Exception ex) { throw new Exception( String.Format("WriteFeedFileFromDatabaseQuery - error = {0}", ex.Message), ex); } stopWatch.Stop(); log.DebugFormat("WriteFeedFileFromDictionary - wrote {0} rows in {1} seconds", recordCount, stopWatch.Elapsed.TotalSeconds); return fullFileName; } /// <summary> /// Copies to s3, using the LitS3 library, and the internal S3Parts class. /// </summary> /// <param name="s3Location">Full S3 url where we want this to live.</param> /// <param name="localFilePath">Local file path to the file to upload.</param> /// <param name="baseFileName">The name of the file without path.</param> /// <param name="loadNumber">The Load Number.</param> /// <param name="phase">The phase to use for phase logging.</param> /// <param name="dataSourcePlan">DataSourcePlan for this processor.</param> /// <param name="description">Description to use for phase logging.</param> /// <param name="phaseLogger">PhaseLogger to use to talk about progress.</param> /// <param name="logSource">logSource to use when logging.</param> public static void CopyToS3(string s3Location, string localFilePath, string baseFileName, int loadNumber, DataMigrationPhase phase, DataSourcePlan dataSourcePlan, string description, IPhaseLogger phaseLogger, int logSource) { log.DebugFormat("CopyToS3 - attempting upload from {0} to {1}", baseFileName, s3Location); var stopWatch = Stopwatch.StartNew(); var s3DestinationFile = Utilities.UriCombine(s3Location, baseFileName); var s3Parts = S3Parts.FromUrl(s3DestinationFile); var s3Service = Utilities.GetS3Service(); EventHandler<S3ProgressEventArgs> progressHandler = (source, eventArguments) => { var percentDone = eventArguments.ProgressPercentage; if ((percentDone % 10) == 0) { // Throttle the log messages. log.DebugFormat("Uploading {0}, progress = {1}%", baseFileName, percentDone); } }; s3Service.AddObjectProgress += progressHandler; try { s3Service.AddObject(localFilePath, s3Parts.Bucket, s3Parts.File); phaseLogger.Log(new PhaseLogEntry { LogSource = logSource, DataSourceCode = dataSourcePlan.DataSourceCode, LoadNumber = loadNumber, Phase = phase, Description = description }); } catch (Exception ex) { throw new Exception(String.Format("CopyToS3 - error uploading file {0} = {1}", localFilePath, ex.Message), ex); } finally { s3Service.AddObjectProgress -= progressHandler; } stopWatch.Stop(); log.DebugFormat("CopyToS3 - uploaded file {0} in {1} seconds.", baseFileName, stopWatch.Elapsed.TotalSeconds); } /// <summary> /// This function makes every effort to remove the temporary working directory, but /// on error will just log a warning and continue on. /// </summary> public static void DeleteWorkingDirectory(string workingDirectory) { try { if (String.IsNullOrWhiteSpace(workingDirectory)) { return; } var directoryInfo = new DirectoryInfo(workingDirectory); if (!directoryInfo.Exists) { return; } Directory.Delete(workingDirectory); } catch (Exception ex) { // Log a warning and continue. This is not a fatal error. log.WarnFormat("DeleteWorkingDirectory - error deleting {0} = {1}", workingDirectory, ex.Message); } } /// <summary> /// This function makes every effort to remove the local feed file, but on error will /// just log a warning and continue on. /// </summary> /// <param name="feedFileFullPath">Full path to the file to delete.</param> public static void DeleteLocalFeedFile(string feedFileFullPath) { try { if (String.IsNullOrWhiteSpace(feedFileFullPath)) { return; } var fileInfo = new FileInfo(feedFileFullPath); if (!fileInfo.Exists) { return; } File.Delete(feedFileFullPath); } catch (Exception ex) { // Just log a warning and continue; this is not a fatal error. log.WarnFormat("DeleteLocalFeedFile - error deleting file {0} = {1}", feedFileFullPath, ex.Message); } } } }
// <copyright file="FisherSnedecorTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2014 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> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Continuous { /// <summary> /// Fisher-Snedecor distribution tests. /// </summary> [TestFixture, Category("Distributions")] public class FisherSnedecorTests { /// <summary> /// Can create fisher snedecor. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(0.1, 0.1)] [TestCase(1.0, 0.1)] [TestCase(10.0, 0.1)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(0.1, 1.0)] [TestCase(1.0, 1.0)] [TestCase(10.0, 1.0)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(0.1, Double.PositiveInfinity)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(10.0, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void CanCreateFisherSnedecor(double d1, double d2) { var n = new FisherSnedecor(d1, d2); Assert.AreEqual(d1, n.DegreesOfFreedom1); Assert.AreEqual(d2, n.DegreesOfFreedom2); } /// <summary> /// <c>FisherSnedecor</c> create fails with bad parameters. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(Double.NaN, Double.NaN)] [TestCase(0.0, Double.NaN)] [TestCase(-1.0, Double.NaN)] [TestCase(-10.0, Double.NaN)] [TestCase(Double.NaN, 0.0)] [TestCase(0.0, 0.0)] [TestCase(-1.0, 0.0)] [TestCase(-10.0, 0.0)] [TestCase(Double.NaN, -1.0)] [TestCase(0.0, -1.0)] [TestCase(-1.0, -1.0)] [TestCase(-10.0, -1.0)] [TestCase(Double.NaN, -10.0)] [TestCase(0.0, -10.0)] [TestCase(-1.0, -10.0)] [TestCase(-10.0, -10.0)] public void FisherSnedecorCreateFailsWithBadParameters(double d1, double d2) { Assert.That(() => new FisherSnedecor(d1, d2), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var n = new FisherSnedecor(2d, 1d); Assert.AreEqual("FisherSnedecor(d1 = 2, d2 = 1)", n.ToString()); } /// <summary> /// Validate mean. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(0.1, 0.1)] [TestCase(1.0, 0.1)] [TestCase(10.0, 0.1)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(0.1, 1.0)] [TestCase(1.0, 1.0)] [TestCase(10.0, 1.0)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(0.1, Double.PositiveInfinity)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(10.0, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateMean(double d1, double d2) { var n = new FisherSnedecor(d1, d2); if (d2 > 2) { Assert.AreEqual(d2 / (d2 - 2.0), n.Mean); } } /// <summary> /// Validate variance. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(0.1, 0.1)] [TestCase(1.0, 0.1)] [TestCase(10.0, 0.1)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(0.1, 1.0)] [TestCase(1.0, 1.0)] [TestCase(10.0, 1.0)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(0.1, Double.PositiveInfinity)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(10.0, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateVariance(double d1, double d2) { var n = new FisherSnedecor(d1, d2); if (d2 > 4) { Assert.AreEqual((2.0 * d2 * d2 * (d1 + d2 - 2.0)) / (d1 * (d2 - 2.0) * (d2 - 2.0) * (d2 - 4.0)), n.Variance); } } /// <summary> /// Validate standard deviation. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(0.1, 0.1)] [TestCase(1.0, 0.1)] [TestCase(10.0, 0.1)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(0.1, 1.0)] [TestCase(1.0, 1.0)] [TestCase(10.0, 1.0)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(0.1, Double.PositiveInfinity)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(10.0, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateStdDev(double d1, double d2) { var n = new FisherSnedecor(d1, d2); if (d2 > 4) { Assert.AreEqual(Math.Sqrt(n.Variance), n.StdDev); } } /// <summary> /// Validate entropy throws <c>NotSupportedException</c>. /// </summary> [Test] public void ValidateEntropyThrowsNotSupportedException() { var n = new FisherSnedecor(1.0, 2.0); Assert.Throws<NotSupportedException>(() => { var ent = n.Entropy; }); } /// <summary> /// Validate skewness. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(0.1, 0.1)] [TestCase(1.0, 0.1)] [TestCase(10.0, 0.1)] [TestCase(Double.PositiveInfinity, 0.1)] [TestCase(0.1, 1.0)] [TestCase(1.0, 1.0)] [TestCase(10.0, 1.0)] [TestCase(Double.PositiveInfinity, 1.0)] [TestCase(0.1, Double.PositiveInfinity)] [TestCase(1.0, Double.PositiveInfinity)] [TestCase(10.0, Double.PositiveInfinity)] [TestCase(Double.PositiveInfinity, Double.PositiveInfinity)] public void ValidateSkewness(double d1, double d2) { var n = new FisherSnedecor(d1, d2); if (d2 > 6) { Assert.AreEqual((((2.0 * d1) + d2 - 2.0) * Math.Sqrt(8.0 * (d2 - 4.0))) / ((d2 - 6.0) * Math.Sqrt(d1 * (d1 + d2 - 2.0))), n.Skewness); } } /// <summary> /// Validate mode. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> [TestCase(0.1, 0.1)] [TestCase(1.0, 0.1)] [TestCase(10.0, 0.1)] [TestCase(100.0, 0.1)] [TestCase(0.1, 1.0)] [TestCase(1.0, 1.0)] [TestCase(10.0, 1.0)] [TestCase(100.0, 1.0)] [TestCase(0.1, 100.0)] [TestCase(1.0, 100.0)] [TestCase(10.0, 100.0)] [TestCase(100.0, 100.0)] public void ValidateMode(double d1, double d2) { var n = new FisherSnedecor(d1, d2); if (d1 > 2) { Assert.AreEqual((d2 * (d1 - 2.0)) / (d1 * (d2 + 2.0)), n.Mode); } } /// <summary> /// Validate median throws <c>NotSupportedException</c>. /// </summary> [Test] public void ValidateMedianThrowsNotSupportedException() { var n = new FisherSnedecor(1.0, 2.0); Assert.Throws<NotSupportedException>(() => { var m = n.Median; }); } /// <summary> /// Validate minimum. /// </summary> [Test] public void ValidateMinimum() { var n = new FisherSnedecor(1.0, 2.0); Assert.AreEqual(0.0, n.Minimum); } /// <summary> /// Validate maximum. /// </summary> [Test] public void ValidateMaximum() { var n = new FisherSnedecor(1.0, 2.0); Assert.AreEqual(Double.PositiveInfinity, n.Maximum); } /// <summary> /// Validate density. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> /// <param name="x">Input X value</param> [TestCase(0.1, 0.1, 1.0)] [TestCase(1.0, 0.1, 1.0)] [TestCase(10.0, 0.1, 1.0)] [TestCase(100.0, 0.1, 1.0)] [TestCase(0.1, 1.0, 1.0)] [TestCase(1.0, 1.0, 1.0)] [TestCase(10.0, 1.0, 1.0)] [TestCase(100.0, 1.0, 1.0)] [TestCase(0.1, 100.0, 1.0)] [TestCase(1.0, 100.0, 1.0)] [TestCase(10.0, 100.0, 1.0)] [TestCase(100.0, 100.0, 1.0)] [TestCase(0.1, 0.1, 10.0)] [TestCase(1.0, 0.1, 10.0)] [TestCase(10.0, 0.1, 10.0)] [TestCase(100.0, 0.1, 10.0)] [TestCase(0.1, 1.0, 10.0)] [TestCase(1.0, 1.0, 10.0)] [TestCase(10.0, 1.0, 10.0)] [TestCase(100.0, 1.0, 10.0)] [TestCase(0.1, 100.0, 10.0)] [TestCase(1.0, 100.0, 10.0)] [TestCase(10.0, 100.0, 10.0)] [TestCase(100.0, 100.0, 10.0)] public void ValidateDensity(double d1, double d2, double x) { var n = new FisherSnedecor(d1, d2); double expected = Math.Sqrt(Math.Pow(d1*x, d1)*Math.Pow(d2, d2)/Math.Pow((d1*x) + d2, d1 + d2))/(x*SpecialFunctions.Beta(d1/2.0, d2/2.0)); Assert.AreEqual(expected, n.Density(x)); Assert.AreEqual(expected, FisherSnedecor.PDF(d1, d2, x)); } /// <summary> /// Validate density log. /// </summary> /// <param name="d1">Degrees of freedom 1</param> /// <param name="d2">Degrees of freedom 2</param> /// <param name="x">Input X value</param> [TestCase(0.1, 0.1, 1.0)] [TestCase(1.0, 0.1, 1.0)] [TestCase(10.0, 0.1, 1.0)] [TestCase(100.0, 0.1, 1.0)] [TestCase(0.1, 1.0, 1.0)] [TestCase(1.0, 1.0, 1.0)] [TestCase(10.0, 1.0, 1.0)] [TestCase(100.0, 1.0, 1.0)] [TestCase(0.1, 100.0, 1.0)] [TestCase(1.0, 100.0, 1.0)] [TestCase(10.0, 100.0, 1.0)] [TestCase(100.0, 100.0, 1.0)] [TestCase(0.1, 0.1, 10.0)] [TestCase(1.0, 0.1, 10.0)] [TestCase(10.0, 0.1, 10.0)] [TestCase(100.0, 0.1, 10.0)] [TestCase(0.1, 1.0, 10.0)] [TestCase(1.0, 1.0, 10.0)] [TestCase(10.0, 1.0, 10.0)] [TestCase(100.0, 1.0, 10.0)] [TestCase(0.1, 100.0, 10.0)] [TestCase(1.0, 100.0, 10.0)] [TestCase(10.0, 100.0, 10.0)] [TestCase(100.0, 100.0, 10.0)] public void ValidateDensityLn(double d1, double d2, double x) { var n = new FisherSnedecor(d1, d2); double expected = Math.Log(Math.Sqrt(Math.Pow(d1*x, d1)*Math.Pow(d2, d2)/Math.Pow((d1*x) + d2, d1 + d2))/(x*SpecialFunctions.Beta(d1/2.0, d2/2.0))); Assert.AreEqual(expected, n.DensityLn(x)); Assert.AreEqual(expected, FisherSnedecor.PDFLn(d1, d2, x)); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new FisherSnedecor(1.0, 2.0); n.Sample(); } /// <summary> /// Can sample sequence. /// </summary> [Test] public void CanSampleSequence() { var n = new FisherSnedecor(1.0, 2.0); var ied = n.Samples(); GC.KeepAlive(ied.Take(5).ToArray()); } [TestCase(0.1, 0.1, 1.0)] [TestCase(1.0, 0.1, 1.0)] [TestCase(10.0, 0.1, 1.0)] [TestCase(0.1, 1.0, 1.0)] [TestCase(1.0, 1.0, 1.0)] [TestCase(10.0, 1.0, 1.0)] [TestCase(0.1, 0.1, 10.0)] [TestCase(1.0, 0.1, 10.0)] [TestCase(10.0, 0.1, 10.0)] [TestCase(0.1, 1.0, 10.0)] [TestCase(1.0, 1.0, 10.0)] [TestCase(10.0, 1.0, 10.0)] public void ValidateCumulativeDistribution(double d1, double d2, double x) { var n = new FisherSnedecor(d1, d2); double expected = SpecialFunctions.BetaRegularized(d1/2.0, d2/2.0, d1*x/(d2 + (x*d1))); Assert.That(n.CumulativeDistribution(x), Is.EqualTo(expected)); Assert.That(FisherSnedecor.CDF(d1, d2, x), Is.EqualTo(expected)); } [TestCase(0.1, 0.1, 1.0)] [TestCase(1.0, 0.1, 1.0)] [TestCase(10.0, 0.1, 1.0)] [TestCase(0.1, 1.0, 1.0)] [TestCase(1.0, 1.0, 1.0)] [TestCase(10.0, 1.0, 1.0)] [TestCase(0.1, 0.1, 10.0)] [TestCase(1.0, 0.1, 10.0)] [TestCase(10.0, 0.1, 10.0)] [TestCase(0.1, 1.0, 10.0)] [TestCase(1.0, 1.0, 10.0)] [TestCase(10.0, 1.0, 10.0)] public void ValidateInverseCumulativeDistribution(double d1, double d2, double x) { var n = new FisherSnedecor(d1, d2); double p = SpecialFunctions.BetaRegularized(d1/2.0, d2/2.0, d1*x/(d2 + (x*d1))); Assert.That(n.InverseCumulativeDistribution(p), Is.EqualTo(x).Within(1e-8)); Assert.That(FisherSnedecor.InvCDF(d1, d2, p), Is.EqualTo(x).Within(1e-8)); } } }
using System.Diagnostics; namespace CocosSharp { class CCTransitionSceneContainerNode: CCNode { public CCScene InnerScene { get; private set; } public CCTransitionSceneContainerNode(CCScene scene, CCSize contentSize) : base(contentSize) { InnerScene = scene; } protected override void Draw() { base.Draw(); CCDrawManager drawManager = CCDrawManager.SharedDrawManager; if(this.Visible) InnerScene.Visit(); } } class CCTransitionSceneContainerLayer : CCLayer { CCTransitionSceneContainerNode inSceneNodeContainer; CCTransitionSceneContainerNode outSceneNodeContainer; internal CCNode InSceneNodeContainer { get { return inSceneNodeContainer; } } internal CCNode OutSceneNodeContainer { get { return outSceneNodeContainer; } } internal CCScene InScene { get { return inSceneNodeContainer.InnerScene; } } internal CCScene OutScene { get { return outSceneNodeContainer.InnerScene; } } internal bool IsInSceneOnTop { get; set; } public CCTransitionSceneContainerLayer(CCScene inScene, CCScene outScene) : base(new CCCamera(outScene.VisibleBoundsScreenspace.Size)) { CCSize contentSize = outScene.VisibleBoundsScreenspace.Size; AnchorPoint = new CCPoint(0.5f, 0.5f); inSceneNodeContainer = new CCTransitionSceneContainerNode(inScene, contentSize); outSceneNodeContainer = new CCTransitionSceneContainerNode(outScene, contentSize); // The trick here is that we're not actually adding the InScene/OutScene as children // This keeps the scenes' original parents (if they have one) intact, so that there's no cleanup afterwards AddChild(InSceneNodeContainer); AddChild(OutSceneNodeContainer); } public override void Visit() { bool outSceneVisible = OutSceneNodeContainer.Visible; bool inSceneVisible = InSceneNodeContainer.Visible; CCDrawManager drawManager = CCDrawManager.SharedDrawManager; base.Visit(); if (IsInSceneOnTop) { outSceneNodeContainer.Visit(); inSceneNodeContainer.Visit(); } else { inSceneNodeContainer.Visit(); outSceneNodeContainer.Visit(); } } } public class CCTransitionScene : CCScene { CCTransitionSceneContainerLayer transitionSceneContainerLayer; #region Properties protected bool IsSendCleanupToScene { get; set; } protected float Duration { get; set; } public override bool IsTransition { get { return true; } } protected bool IsInSceneOnTop { get { return transitionSceneContainerLayer.IsInSceneOnTop; } set { transitionSceneContainerLayer.IsInSceneOnTop = value; } } public override CCLayer Layer { get { return transitionSceneContainerLayer; } internal set { } } protected CCNode InSceneNodeContainer { get { return transitionSceneContainerLayer.InSceneNodeContainer; } } protected CCNode OutSceneNodeContainer { get { return transitionSceneContainerLayer.OutSceneNodeContainer; } } protected virtual CCFiniteTimeAction InSceneAction { get { return null; } } protected virtual CCFiniteTimeAction OutSceneAction { get { return null; } } // Don't want subclasses do access scene - use node container instead CCScene InScene { get; set; } CCScene OutScene { get; set; } #endregion Properties #region Constructors public CCTransitionScene (float duration, CCScene scene) : base(scene.Window, scene.Viewport) { InitCCTransitionScene(duration, scene); } void InitCCTransitionScene(float duration, CCScene scene) { Debug.Assert(scene != null, "Argument scene must be non-nil"); Duration = duration; InScene = scene; CCScene outScene = Director.RunningScene; if (outScene == null) { // Creating an empty scene. outScene = new CCScene(Window, Viewport, Director); } Debug.Assert(InScene != outScene, "Incoming scene must be different from the outgoing scene"); OutScene = outScene; transitionSceneContainerLayer = new CCTransitionSceneContainerLayer(InScene, OutScene); AddChild(transitionSceneContainerLayer); SceneOrder(); } #endregion Constructors protected virtual void InitialiseScenes() { } public override void OnEnter() { base.OnEnter(); // Disable events while transitioning EventDispatcherIsEnabled = false; InScene.OnEnter(); InitialiseScenes(); OutSceneNodeContainer.OnEnter(); InSceneNodeContainer.OnEnter(); if(InSceneAction != null) InSceneNodeContainer.RunAction(InSceneAction); if (OutSceneAction != null) OutSceneNodeContainer.RunAction(new CCSequence(OutSceneAction, new CCCallFunc(Finish))); else OutSceneNodeContainer.RunAction(new CCSequence(new CCDelayTime(Duration), new CCCallFunc(Finish))); } public override void OnExit() { base.OnExit(); // Enable event after transitioning EventDispatcherIsEnabled = true; } public virtual void Reset(float t, CCScene scene) { InitCCTransitionScene(t, scene); } public void Finish() { Schedule(SetNewScene, 0); } public void HideOutShowIn() { InSceneNodeContainer.Visible = true; OutSceneNodeContainer.Visible = false; } protected virtual void SceneOrder() { IsInSceneOnTop = true; } void SetNewScene(float dt) { Unschedule(SetNewScene); // Before replacing, save the "send cleanup to scene" IsSendCleanupToScene = Director.IsSendCleanupToScene; Director.ReplaceScene(transitionSceneContainerLayer.InScene); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Tests task result. /// </summary> public class TaskResultTest : AbstractTaskTest { /** Grid name. */ private static volatile string _gridName; /// <summary> /// Constructor. /// </summary> public TaskResultTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="forked">Fork flag.</param> protected TaskResultTest(bool forked) : base(forked) { } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultInt() { TestTask<int> task = new TestTask<int>(); int res = Grid1.GetCompute().Execute(task, new Tuple<bool, int>(true, 10)); Assert.AreEqual(10, res); res = Grid1.GetCompute().Execute(task, new Tuple<bool, int>(false, 11)); Assert.AreEqual(11, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultLong() { TestTask<long> task = new TestTask<long>(); long res = Grid1.GetCompute().Execute(task, new Tuple<bool, long>(true, 10000000000)); Assert.AreEqual(10000000000, res); res = Grid1.GetCompute().Execute(task, new Tuple<bool, long>(false, 10000000001)); Assert.AreEqual(10000000001, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultFloat() { TestTask<float> task = new TestTask<float>(); float res = Grid1.GetCompute().Execute(task, new Tuple<bool, float>(true, 1.1f)); Assert.AreEqual(1.1f, res); res = Grid1.GetCompute().Execute(task, new Tuple<bool, float>(false, -1.1f)); Assert.AreEqual(-1.1f, res); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultBinarizable() { TestTask<BinarizableResult> task = new TestTask<BinarizableResult>(); BinarizableResult val = new BinarizableResult(100); BinarizableResult res = Grid1.GetCompute().Execute(task, new Tuple<bool, BinarizableResult>(true, val)); Assert.AreEqual(val.Val, res.Val); val.Val = 101; res = Grid1.GetCompute().Execute(task, new Tuple<bool, BinarizableResult>(false, val)); Assert.AreEqual(val.Val, res.Val); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultSerializable() { TestTask<SerializableResult> task = new TestTask<SerializableResult>(); SerializableResult val = new SerializableResult(100); SerializableResult res = Grid1.GetCompute().Execute(task, new Tuple<bool, SerializableResult>(true, val)); Assert.AreEqual(val.Val, res.Val); val.Val = 101; res = Grid1.GetCompute().Execute(task, new Tuple<bool, SerializableResult>(false, val)); Assert.AreEqual(val.Val, res.Val); } /// <summary> /// Test for task result. /// </summary> [Test] public void TestTaskResultLarge() { TestTask<byte[]> task = new TestTask<byte[]>(); byte[] res = Grid1.GetCompute().Execute(task, new Tuple<bool, byte[]>(true, new byte[100 * 1024])); Assert.AreEqual(100 * 1024, res.Length); res = Grid1.GetCompute().Execute(task, new Tuple<bool, byte[]>(false, new byte[101 * 1024])); Assert.AreEqual(101 * 1024, res.Length); } /** <inheritDoc /> */ override protected void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs) { portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableResult))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(TestBinarizableJob))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableOutFunc))); portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(BinarizableFunc))); } [Test] public void TestOutFuncResultPrimitive1() { ICollection<int> res = Grid1.GetCompute().Broadcast(new BinarizableOutFunc()); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(10, r); } [Test] public void TestOutFuncResultPrimitive2() { ICollection<int> res = Grid1.GetCompute().Broadcast(new SerializableOutFunc()); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(10, r); } [Test] public void TestFuncResultPrimitive1() { ICollection<int> res = Grid1.GetCompute().Broadcast(new BinarizableFunc(), 10); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(11, r); } [Test] public void TestFuncResultPrimitive2() { ICollection<int> res = Grid1.GetCompute().Broadcast(new SerializableFunc(), 10); Assert.AreEqual(2, res.Count); foreach (int r in res) Assert.AreEqual(11, r); } interface IUserInterface<in T, out TR> { TR Invoke(T arg); } /// <summary> /// Test function. /// </summary> public class BinarizableFunc : IComputeFunc<int, int>, IUserInterface<int, int> { int IComputeFunc<int, int>.Invoke(int arg) { return arg + 1; } int IUserInterface<int, int>.Invoke(int arg) { // Same signature as IComputeFunc<int, int>, but from different interface throw new Exception("Invalid method"); } public int Invoke(int arg) { // Same signature as IComputeFunc<int, int>, // but due to explicit interface implementation this is a wrong method throw new Exception("Invalid method"); } } /// <summary> /// Test function. /// </summary> [Serializable] public class SerializableFunc : IComputeFunc<int, int> { public int Invoke(int arg) { return arg + 1; } } /// <summary> /// Test function. /// </summary> public class BinarizableOutFunc : IComputeFunc<int> { public int Invoke() { return 10; } } /// <summary> /// Test function. /// </summary> [Serializable] public class SerializableOutFunc : IComputeFunc<int> { public int Invoke() { return 10; } } /// <summary> /// Test task. /// </summary> public class TestTask<T> : ComputeTaskAdapter<Tuple<bool, T>, T, T> { /** <inheritDoc /> */ override public IDictionary<IComputeJob<T>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, T> arg) { _gridName = null; Assert.AreEqual(2, subgrid.Count); bool local = arg.Item1; T res = arg.Item2; var jobs = new Dictionary<IComputeJob<T>, IClusterNode>(); IComputeJob<T> job; if (res is BinarizableResult) { TestBinarizableJob job0 = new TestBinarizableJob(); job0.SetArguments(res); job = (IComputeJob<T>) job0; } else { TestJob<T> job0 = new TestJob<T>(); job0.SetArguments(res); job = job0; } foreach (IClusterNode node in subgrid) { bool add = local ? node.IsLocal : !node.IsLocal; if (add) { jobs.Add(job, node); break; } } Assert.AreEqual(1, jobs.Count); return jobs; } /** <inheritDoc /> */ override public T Reduce(IList<IComputeJobResult<T>> results) { Assert.AreEqual(1, results.Count); var res = results[0]; Assert.IsNull(res.Exception); Assert.IsFalse(res.Cancelled); Assert.IsNotNull(_gridName); Assert.AreEqual(GridId(_gridName), res.NodeId); var job = res.Job; Assert.IsNotNull(job); return res.Data; } } private static Guid GridId(string gridName) { if (gridName.Equals(Grid1Name)) return Ignition.GetIgnite(Grid1Name).GetCluster().GetLocalNode().Id; if (gridName.Equals(Grid2Name)) return Ignition.GetIgnite(Grid2Name).GetCluster().GetLocalNode().Id; if (gridName.Equals(Grid3Name)) return Ignition.GetIgnite(Grid3Name).GetCluster().GetLocalNode().Id; Assert.Fail("Failed to find grid " + gridName); return new Guid(); } /// <summary> /// /// </summary> class BinarizableResult { /** */ public int Val; public BinarizableResult(int val) { Val = val; } } /// <summary> /// /// </summary> [Serializable] class SerializableResult { /** */ public int Val; public SerializableResult(int val) { Val = val; } } /// <summary> /// /// </summary> [Serializable] class TestJob<T> : ComputeJobAdapter<T> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ override public T Execute() { Assert.IsNotNull(_grid); _gridName = _grid.Name; T res = GetArgument<T>(0); return res; } } /// <summary> /// /// </summary> class TestBinarizableJob : ComputeJobAdapter<BinarizableResult> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ override public BinarizableResult Execute() { Assert.IsNotNull(_grid); _gridName = _grid.Name; BinarizableResult res = GetArgument<BinarizableResult>(0); return res; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // AsynchronousOneToOneChannel.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This is a bounded channel meant for single-producer/single-consumer scenarios. /// </summary> /// <typeparam name="T">Specifies the type of data in the channel.</typeparam> internal sealed class AsynchronousChannel<T> : IDisposable { // The producer will be blocked once the channel reaches a capacity, and unblocked // as soon as a consumer makes room. A consumer can block waiting until a producer // enqueues a new element. We use a chunking scheme to adjust the granularity and // frequency of synchronization, e.g. by enqueueing/dequeueing N elements at a time. // Because there is only ever a single producer and consumer, we are able to achieve // efficient and low-overhead synchronization. // // In general, the buffer has four logical states: // FULL <--> OPEN <--> EMPTY <--> DONE // // Here is a summary of the state transitions and what they mean: // * OPEN: // A buffer starts in the OPEN state. When the buffer is in the READY state, // a consumer and producer can dequeue and enqueue new elements. // * OPEN->FULL: // A producer transitions the buffer from OPEN->FULL when it enqueues a chunk // that causes the buffer to reach capacity; a producer can no longer enqueue // new chunks when this happens, causing it to block. // * FULL->OPEN: // When the consumer takes a chunk from a FULL buffer, it transitions back from // FULL->OPEN and the producer is woken up. // * OPEN->EMPTY: // When the consumer takes the last chunk from a buffer, the buffer is // transitioned from OPEN->EMPTY; a consumer can no longer take new chunks, // causing it to block. // * EMPTY->OPEN: // Lastly, when the producer enqueues an item into an EMPTY buffer, it // transitions to the OPEN state. This causes any waiting consumers to wake up. // * EMPTY->DONE: // If the buffer is empty, and the producer is done enqueueing new // items, the buffer is DONE. There will be no more consumption or production. // // Assumptions: // There is only ever one producer and one consumer operating on this channel // concurrently. The internal synchronization cannot handle anything else. // // ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** WARNING ** // VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV // // There... got your attention now... just in case you didn't read the comments // very carefully above, this channel will deadlock, become corrupt, and generally // make you an unhappy camper if you try to use more than 1 producer or more than // 1 consumer thread to access this thing concurrently. It's been carefully designed // to avoid locking, but only because of this restriction... private T[][] _buffer; // The buffer of chunks. private readonly int _index; // Index of this channel private volatile int _producerBufferIndex; // Producer's current index, i.e. where to put the next chunk. private volatile int _consumerBufferIndex; // Consumer's current index, i.e. where to get the next chunk. private volatile bool _done; // Set to true once the producer is done. private T[] _producerChunk; // The temporary chunk being generated by the producer. private int _producerChunkIndex; // A producer's index into its temporary chunk. private T[] _consumerChunk; // The temporary chunk being enumerated by the consumer. private int _consumerChunkIndex; // A consumer's index into its temporary chunk. private int _chunkSize; // The number of elements that comprise a chunk. // These events are used to signal a waiting producer when the consumer dequeues, and to signal a // waiting consumer when the producer enqueues. private ManualResetEventSlim _producerEvent; private IntValueEvent _consumerEvent; // These two-valued ints track whether a producer or consumer _might_ be waiting. They are marked // volatile because they are used in synchronization critical regions of code (see usage below). private volatile int _producerIsWaiting; private volatile int _consumerIsWaiting; private CancellationToken _cancellationToken; //----------------------------------------------------------------------------------- // Initializes a new channel with the specific capacity and chunk size. // // Arguments: // orderingHelper - the ordering helper to use for order preservation // capacity - the maximum number of elements before a producer blocks // chunkSize - the granularity of chunking on enqueue/dequeue. 0 means default size. // // Notes: // The capacity represents the maximum number of chunks a channel can hold. That // means producers will actually block after enqueueing capacity*chunkSize // individual elements. // internal AsynchronousChannel(int index, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) : this(index, Scheduling.DEFAULT_BOUNDED_BUFFER_CAPACITY, chunkSize, cancellationToken, consumerEvent) { } internal AsynchronousChannel(int index, int capacity, int chunkSize, CancellationToken cancellationToken, IntValueEvent consumerEvent) { if (chunkSize == 0) chunkSize = Scheduling.GetDefaultChunkSize<T>(); Debug.Assert(chunkSize > 0, "chunk size must be greater than 0"); Debug.Assert(capacity > 1, "this impl doesn't support capacity of 1 or 0"); // Initialize a buffer with enough space to hold 'capacity' elements. // We need one extra unused element as a sentinel to detect a full buffer, // thus we add one to the capacity requested. _index = index; _buffer = new T[capacity + 1][]; _producerBufferIndex = 0; _consumerBufferIndex = 0; _producerEvent = new ManualResetEventSlim(); _consumerEvent = consumerEvent; _chunkSize = chunkSize; _producerChunk = new T[chunkSize]; _producerChunkIndex = 0; _cancellationToken = cancellationToken; } //----------------------------------------------------------------------------------- // Checks whether the buffer is full. If the consumer is calling this, they can be // assured that a true value won't change before the consumer has a chance to dequeue // elements. That's because only one consumer can run at once. A producer might see // a true value, however, and then a consumer might transition to non-full, so it's // not stable for them. Lastly, it's of course possible to see a false value when // there really is a full queue, it's all dependent on small race conditions. // internal bool IsFull { get { // Read the fields once. One of these is always stable, since the only threads // that call this are the 1 producer/1 consumer threads. int producerIndex = _producerBufferIndex; int consumerIndex = _consumerBufferIndex; // Two cases: // 1) Is the producer index one less than the consumer? // 2) The producer is at the end of the buffer and the consumer at the beginning. return (producerIndex == consumerIndex - 1) || (consumerIndex == 0 && producerIndex == _buffer.Length - 1); // Note to readers: you might have expected us to consider the case where // _producerBufferIndex == _buffer.Length && _consumerBufferIndex == 1. // That is, a producer has gone off the end of the array, but is about to // wrap around to the 0th element again. We don't need this for a subtle // reason. It is SAFE for a consumer to think we are non-full when we // actually are full; it is NOT for a producer; but thankfully, there is // only one producer, and hence the producer will never see this seemingly // invalid state. Hence, we're fine producing a false negative. It's all // based on a race condition we have to deal with anyway. } } //----------------------------------------------------------------------------------- // Checks whether the buffer is empty. If the producer is calling this, they can be // assured that a true value won't change before the producer has a chance to enqueue // an item. That's because only one producer can run at once. A consumer might see // a true value, however, and then a producer might transition to non-empty. // internal bool IsChunkBufferEmpty { get { // The queue is empty when the producer and consumer are at the same index. return _producerBufferIndex == _consumerBufferIndex; } } //----------------------------------------------------------------------------------- // Checks whether the producer is done enqueueing new elements. // internal bool IsDone { get { return _done; } } //----------------------------------------------------------------------------------- // Used by a producer to flush out any internal buffers that have been accumulating // data, but which hasn't yet been published to the consumer. internal void FlushBuffers() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::FlushBuffers() called", Environment.CurrentManagedThreadId); // Ensure that a partially filled chunk is made available to the consumer. FlushCachedChunk(); } //----------------------------------------------------------------------------------- // Used by a producer to signal that it is done producing new elements. This will // also wake up any consumers that have gone to sleep. // internal void SetDone() { TraceHelpers.TraceInfo("tid {0}: AsynchronousChannel<T>::SetDone() called", Environment.CurrentManagedThreadId); // This is set with a volatile write to ensure that, after the consumer // sees done, they can re-read the enqueued chunks and see the last one we // enqueued just above. _done = true; // We set the event to ensure consumers that may have waited or are // considering waiting will notice that the producer is done. This is done // after setting the done flag to facilitate a Dekker-style check/recheck. // // Because we can race with threads trying to Dispose of the event, we must // acquire a lock around our setting, and double-check that the event isn't null. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { if (_consumerEvent != null) { _consumerEvent.Set(_index); } } } //----------------------------------------------------------------------------------- // Enqueues a new element to the buffer, possibly blocking in the process. // // Arguments: // item - the new element to enqueue // timeoutMilliseconds - a timeout (or -1 for no timeout) used in case the buffer // is full; we return false if it expires // // Notes: // This API will block until the buffer is non-full. This internally buffers // elements up into chunks, so elements are not immediately available to consumers. // internal void Enqueue(T item) { // Store the element into our current chunk. int producerChunkIndex = _producerChunkIndex; _producerChunk[producerChunkIndex] = item; // And lastly, if we have filled a chunk, make it visible to consumers. if (producerChunkIndex == _chunkSize - 1) { EnqueueChunk(_producerChunk); _producerChunk = new T[_chunkSize]; } _producerChunkIndex = (producerChunkIndex + 1) % _chunkSize; } //----------------------------------------------------------------------------------- // Internal helper to queue a real chunk, not just an element. // // Arguments: // chunk - the chunk to make visible to consumers // timeoutMilliseconds - an optional timeout; we return false if it expires // // Notes: // This API will block if the buffer is full. A chunk must contain only valid // elements; if the chunk wasn't filled, it should be trimmed to size before // enqueueing it for consumers to observe. // private void EnqueueChunk(T[] chunk) { Debug.Assert(chunk != null); Debug.Assert(!_done, "can't continue producing after the production is over"); if (IsFull) WaitUntilNonFull(); Debug.Assert(!IsFull, "expected a non-full buffer"); // We can safely store into the current producer index because we know no consumers // will be reading from it concurrently. int bufferIndex = _producerBufferIndex; _buffer[bufferIndex] = chunk; // Increment the producer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. #pragma warning disable 0420 Interlocked.Exchange(ref _producerBufferIndex, (bufferIndex + 1) % _buffer.Length); #pragma warning restore 0420 // (If there is a consumer waiting, we have to ensure to signal the event. Unfortunately, // this requires that we issue a memory barrier: We need to guarantee that the write to // our producer index doesn't pass the read of the consumer waiting flags; the CLR memory // model unfortunately permits this reordering. That is handled by using a CAS above.) if (_consumerIsWaiting == 1 && !IsChunkBufferEmpty) { TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waking consumer"); _consumerIsWaiting = 0; _consumerEvent.Set(_index); } } //----------------------------------------------------------------------------------- // Just waits until the queue is non-full. // private void WaitUntilNonFull() { // We must loop; sometimes the producer event will have been set // prematurely due to the way waiting flags are managed. By looping, // we will only return from this method when space is truly available. do { // If the queue is full, we have to wait for a consumer to make room. // Reset the event to unsignaled state before waiting. _producerEvent.Reset(); // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a producer might see a full queue (by // reading IsFull just above), but meanwhile a consumer might drain the queue // very quickly, suddenly seeing an empty queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. #pragma warning disable 0420 Interlocked.Exchange(ref _producerIsWaiting, 1); #pragma warning restore 0420 // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a consumer that is transitioning the // buffer from full to non-full, we must check that the queue is full once // more. Otherwise, we might decide to wait and never be woken up (since // we just reset the event). if (IsFull) { // Assuming a consumer didn't make room for us, we can wait on the event. TraceHelpers.TraceInfo("AsynchronousChannel::EnqueueChunk - producer waiting, buffer full"); _producerEvent.Wait(_cancellationToken); } else { // Reset the flags, we don't actually have to wait after all. _producerIsWaiting = 0; } } while (IsFull); } //----------------------------------------------------------------------------------- // Flushes any built up elements that haven't been made available to a consumer yet. // Only safe to be called by a producer. // // Notes: // This API can block if the channel is currently full. // private void FlushCachedChunk() { // If the producer didn't fill their temporary working chunk, flushing forces an enqueue // so that a consumer will see the partially filled chunk of elements. if (_producerChunk != null && _producerChunkIndex != 0) { // Trim the partially-full chunk to an array just big enough to hold it. Debug.Assert(1 <= _producerChunkIndex && _producerChunkIndex <= _chunkSize); T[] leftOverChunk = new T[_producerChunkIndex]; Array.Copy(_producerChunk, 0, leftOverChunk, 0, _producerChunkIndex); // And enqueue the right-sized temporary chunk, possibly blocking if it's full. EnqueueChunk(leftOverChunk); _producerChunk = null; } } //----------------------------------------------------------------------------------- // Dequeues the next element in the queue. // // Arguments: // item - a byref to the location into which we'll store the dequeued element // // Return Value: // True if an item was found, false otherwise. // internal bool TryDequeue(ref T item) { // Ensure we have a chunk to work with. if (_consumerChunk == null) { if (!TryDequeueChunk(ref _consumerChunk)) { Debug.Assert(_consumerChunk == null); return false; } _consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Debug.Assert(_consumerChunk != null, "consumer chunk is null"); Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds"); item = _consumerChunk[_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out so we'll get the // next one when dequeue is called again. ++_consumerChunkIndex; if (_consumerChunkIndex == _consumerChunk.Length) { _consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. // // Arguments: // chunk - a byref to the location into which we'll store the chunk // // Return Value: // True if a chunk was found, false otherwise. // private bool TryDequeueChunk(ref T[] chunk) { // This is the non-blocking version of dequeue. We first check to see // if the queue is empty. If the caller chooses to wait later, they can // call the overload with an event. if (IsChunkBufferEmpty) { return false; } chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Blocking dequeue for the next element. This version of the API is used when the // caller will possibly wait for a new chunk to be enqueued. // // Arguments: // item - a byref for the returned element // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if an element was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // internal bool TryDequeue(ref T item, ref bool isDone) { isDone = false; // Ensure we have a buffer to work with. if (_consumerChunk == null) { if (!TryDequeueChunk(ref _consumerChunk, ref isDone)) { Debug.Assert(_consumerChunk == null); return false; } _consumerChunkIndex = 0; } // Retrieve the current item in the chunk. Debug.Assert(_consumerChunk != null, "consumer chunk is null"); Debug.Assert(0 <= _consumerChunkIndex && _consumerChunkIndex < _consumerChunk.Length, "chunk index out of bounds"); item = _consumerChunk[_consumerChunkIndex]; // And lastly, if we have consumed the chunk, null it out. ++_consumerChunkIndex; if (_consumerChunkIndex == _consumerChunk.Length) { _consumerChunk = null; } return true; } //----------------------------------------------------------------------------------- // Internal helper method to dequeue a whole chunk. This version of the API is used // when the caller will wait for a new chunk to be enqueued. // // Arguments: // chunk - a byref for the dequeued chunk // waitEvent - a byref for the event used to signal blocked consumers // // Return Value: // True if a chunk was found, false otherwise. // // Notes: // If the return value is false, it doesn't always mean waitEvent will be non- // null. If the producer is done enqueueing, the return will be false and the // event will remain null. A caller must check for this condition. // // If the return value is false and an event is returned, there have been // side-effects on the channel. Namely, the flag telling producers a consumer // might be waiting will have been set. DequeueEndAfterWait _must_ be called // eventually regardless of whether the caller actually waits or not. // private bool TryDequeueChunk(ref T[] chunk, ref bool isDone) { isDone = false; // We will register our interest in waiting, and then return an event // that the caller can use to wait. while (IsChunkBufferEmpty) { // If the producer is done and we've drained the queue, we can bail right away. if (IsDone) { // We have to see if the buffer is empty AFTER we've seen that it's done. // Otherwise, we would possibly miss the elements enqueued before the // producer signaled that it's done. This is done with a volatile load so // that the read of empty doesn't move before the read of done. if (IsChunkBufferEmpty) { // Return isDone=true so callers know not to wait isDone = true; return false; } } // We have to handle the case where a producer and consumer are racing to // wait simultaneously. For instance, a consumer might see an empty queue (by // reading IsChunkBufferEmpty just above), but meanwhile a producer might fill the queue // very quickly, suddenly seeing a full queue. This would lead to deadlock // if we aren't careful. Therefore we check the empty/full state AGAIN after // setting our flag to see if a real wait is warranted. #pragma warning disable 0420 Interlocked.Exchange(ref _consumerIsWaiting, 1); #pragma warning restore 0420 // (We have to prevent the reads that go into determining whether the buffer // is full from moving before the write to the producer-wait flag. Hence the CAS.) // Because we might be racing with a producer that is transitioning the // buffer from empty to non-full, we must check that the queue is empty once // more. Similarly, if the queue has been marked as done, we must not wait // because we just reset the event, possibly losing as signal. In both cases, // we would otherwise decide to wait and never be woken up (i.e. deadlock). if (IsChunkBufferEmpty && !IsDone) { // Note that the caller must eventually call DequeueEndAfterWait to set the // flags back to a state where no consumer is waiting, whether they choose // to wait or not. TraceHelpers.TraceInfo("AsynchronousChannel::DequeueChunk - consumer possibly waiting"); return false; } else { // Reset the wait flags, we don't need to wait after all. We loop back around // and recheck that the queue isn't empty, done, etc. _consumerIsWaiting = 0; } } Debug.Assert(!IsChunkBufferEmpty, "single-consumer should never witness an empty queue here"); chunk = InternalDequeueChunk(); return true; } //----------------------------------------------------------------------------------- // Internal helper method that dequeues a chunk after we've verified that there is // a chunk available to dequeue. // // Return Value: // The dequeued chunk. // // Assumptions: // The caller has verified that a chunk is available, i.e. the queue is non-empty. // private T[] InternalDequeueChunk() { Debug.Assert(!IsChunkBufferEmpty); // We can safely read from the consumer index because we know no producers // will write concurrently. int consumerBufferIndex = _consumerBufferIndex; T[] chunk = _buffer[consumerBufferIndex]; // Zero out contents to avoid holding on to memory for longer than necessary. This // ensures the entire chunk is eligible for GC sooner. (More important for big chunks.) _buffer[consumerBufferIndex] = null; // Increment the consumer index, taking into count wrapping back to 0. This is a shared // write; the CLR 2.0 memory model ensures the write won't move before the write to the // corresponding element, so a consumer won't see the new index but the corresponding // element in the array as empty. #pragma warning disable 0420 Interlocked.Exchange(ref _consumerBufferIndex, (consumerBufferIndex + 1) % _buffer.Length); #pragma warning restore 0420 // (Unfortunately, this whole sequence requires a memory barrier: We need to guarantee // that the write to _consumerBufferIndex doesn't pass the read of the wait-flags; the CLR memory // model sadly permits this reordering. Hence the CAS above.) if (_producerIsWaiting == 1 && !IsFull) { TraceHelpers.TraceInfo("BoundedSingleLockFreeChannel::DequeueChunk - consumer waking producer"); _producerIsWaiting = 0; _producerEvent.Set(); } return chunk; } //----------------------------------------------------------------------------------- // Clears the flag set when a blocking Dequeue is called, letting producers know // the consumer is no longer waiting. // internal void DoneWithDequeueWait() { // On our way out, be sure to reset the flags. _consumerIsWaiting = 0; } //----------------------------------------------------------------------------------- // Closes Win32 events possibly allocated during execution. // public void Dispose() { // We need to take a lock to deal with consumer threads racing to call Dispose // and producer threads racing inside of SetDone. // // Update 8/2/2011: Dispose() should never be called with SetDone() concurrently, // but in order to reduce churn late in the product cycle, we decided not to // remove the lock. lock (this) { Debug.Assert(_done, "Expected channel to be done before disposing"); Debug.Assert(_producerEvent != null); Debug.Assert(_consumerEvent != null); _producerEvent.Dispose(); _producerEvent = null; _consumerEvent = null; } } } }
//------------------------------------------------------------------------------ // <copyright file="StyleReferenceConverter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls.Converters { using System.Diagnostics; using System.Collections; using System.Globalization; using System.ComponentModel; using System.Web.UI.MobileControls; using System.Web.UI.Design.MobileControls.Adapters; using System.Web.UI.Design.MobileControls.Util; /// <summary> /// <para> /// Can filter and retrieve several types of values from controls. /// </para> /// </summary> [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class StyleReferenceConverter: StringConverter { protected virtual Object [] GetStyles(Object instance) { StyleSheet styleSheet = null; Style instanceStyle = null; // Remember, ChoicePropertyFilter is a MobileControl, so we must // check for ChoicePropertyFilter first... if (instance is IDeviceSpecificChoiceDesigner) { instance = ((IDeviceSpecificChoiceDesigner)instance).UnderlyingObject; } if (instance is System.Web.UI.MobileControls.Style) { instanceStyle = (Style) instance; if (instanceStyle.Control is StyleSheet) { styleSheet = (StyleSheet) instanceStyle.Control; } else if ((instanceStyle.Control is Form && instanceStyle is PagerStyle) || (instanceStyle.Control is ObjectList)) { if (instanceStyle.Control.MobilePage != null) { styleSheet = instanceStyle.Control.MobilePage.StyleSheet; } else { return null; } } else { Debug.Fail("Unsupported objects passed in"); } } else if (instance is System.Web.UI.MobileControls.MobileControl) { MobileControl control = (MobileControl)instance; if (control.MobilePage == null) { return null; } styleSheet = control.MobilePage.StyleSheet; } else if (instance is Array) { Array array = (Array)instance; Debug.Assert(array.Length > 0); return GetStyles(array.GetValue(0)); } else { Debug.Fail("Unsupported type passed in"); return null; } Debug.Assert(null != styleSheet); ICollection styles = styleSheet.Styles; ArrayList styleArray = new ArrayList(); foreach (String key in styles) { System.Web.UI.MobileControls.Style style = styleSheet[key]; if (style.Name != null && style.Name.Length > 0) { if (null == instanceStyle || 0 != String.Compare(instanceStyle.Name, style.Name, StringComparison.Ordinal)) { styleArray.Add(style.Name); } } } if (styleSheet == StyleSheet.Default) { styleArray.Sort(); return styleArray.ToArray(); } styles = StyleSheet.Default.Styles; foreach (String key in styles) { System.Web.UI.MobileControls.Style style = StyleSheet.Default[key]; if (style.Name != null && style.Name.Length > 0) { if (null == instanceStyle || 0 != String.Compare(instanceStyle.Name, style.Name, StringComparison.Ordinal)) { styleArray.Add(style.Name); } } } if (styleArray.Count <= 1) { return styleArray.ToArray(); } styleArray.Sort(); String preID = ((String)styleArray[0]).ToLower(CultureInfo.InvariantCulture); int i = 1; while (i < styleArray.Count) { if (String.Equals((String)styleArray[i], preID, StringComparison.OrdinalIgnoreCase)) { styleArray.RemoveAt(i); } else { preID = ((String)styleArray[i]).ToLower(CultureInfo.InvariantCulture); i++; } } return styleArray.ToArray(); } /// <summary> /// <para> /// Returns a collection of standard values retrieved from the context specified /// by the specified type descriptor. /// </para> /// </summary> /// <param name='context'> /// A type descriptor that specifies the location of the context to convert from. /// </param> /// <returns> /// <para> /// A StandardValuesCollection that represents the standard values collected from /// the specified context. /// </para> /// </returns> public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { if (context == null || context.Instance == null) { return null; } Object [] objValues = GetStyles(context.Instance); if (objValues != null) { return new StandardValuesCollection(objValues); } else { return null; } } /// <summary> /// <para> /// Gets whether /// or not the context specified contains exclusive standard values. /// </para> /// </summary> /// <param name='context'> /// A type descriptor that indicates the context to convert from. /// </param> /// <returns> /// <para> /// <see langword='true'/> if the specified context contains exclusive standard /// values, otherwise <see langword='false'/>. /// </para> /// </returns> public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { return false; } /// <summary> /// <para> /// Gets whether or not the specified context contains supported standard /// values. /// </para> /// </summary> /// <param name='context'> /// A type descriptor that indicates the context to convert from. /// </param> /// <returns> /// <para> /// <see langword='true'/> if the specified context conatins supported standard /// values, otherwise <see langword='false'/>. /// </para> /// </returns> public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data; namespace Glass.Mapper.Sc.Tests.DataMappers { [TestFixture] public class SitecoreFieldEnumMapperFixture : AbstractMapperFixture { #region Method - GetField [Test] public void GetField_FieldContainsValidEnum_ReturnsEnum() { //Assign string fieldValue = "Value1"; StubEnum expected = StubEnum.Value1; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsValidEnumInLowercase_ReturnsEnum() { //Assign string fieldValue = "value1"; StubEnum expected = StubEnum.Value1; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsValidEnumInteger_ReturnsEnum() { //Assign string fieldValue = "2"; StubEnum expected = StubEnum.Value2; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(expected, result); } [Test] public void GetField_FieldContainsEmptyString_ReturnsDefaultEnum() { //Assign string fieldValue = string.Empty; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert Assert.AreEqual(StubEnum.Value1, result); } [Test] [ExpectedException(typeof (MapperException))] public void GetField_FieldContainsInvalidValidEnum_ThrowsException() { //Assign string fieldValue = "hello world"; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, fieldValue); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = (StubEnum)mapper.GetField(field, config, null); //Assert } #endregion #region Method - SetField [Test] public void SetField_ObjectisValidEnum_SetsFieldValue() { //Assign string expected = "Value2"; StubEnum objectValue = StubEnum.Value2; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); item.Editing.BeginEdit(); //Act mapper.SetField(field, objectValue, config, null); //Assert Assert.AreEqual(expected, field.Value); } [Test] [ExpectedException(typeof (ArgumentException))] public void SetField_ObjectIsInt_ThrowsException() { //Assign string objectValue = "hello world"; var fieldId = Guid.NewGuid(); var item = Helpers.CreateFakeItem(fieldId, string.Empty); var field = item.Fields[new ID(fieldId)]; var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act mapper.SetField(field, objectValue, config, null); //Assert } #endregion #region Method - CanHandle [Test] public void CanHandle_PropertyIsEnum_ReturnsTrue() { //Assign var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (Stub).GetProperty("Property"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } [Test] public void CanHandle_PropertyIsNotEnum_ReturnsTrue() { //Assign var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof(Stub).GetProperty("PropertyNotEnum"); var mapper = new SitecoreFieldEnumMapper(); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsFalse(result); } #endregion #region Stub public enum StubEnum { Value1 =1, Value2 = 2 } public class Stub { public StubEnum Property { get; set; } public string PropertyNotEnum { get; set; } } #endregion } }
// // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // namespace OpenTK.Input { /// <summary> /// The available keyboard keys. /// </summary> public enum Key : int { /// <summary>A key outside the known keys.</summary> Unknown = 0, // Modifiers /// <summary>The left shift key.</summary> ShiftLeft, /// <summary>The left shift key (equivalent to ShiftLeft).</summary> LShift = ShiftLeft, /// <summary>The right shift key.</summary> ShiftRight, /// <summary>The right shift key (equivalent to ShiftRight).</summary> RShift = ShiftRight, /// <summary>The left control key.</summary> ControlLeft, /// <summary>The left control key (equivalent to ControlLeft).</summary> LControl = ControlLeft, /// <summary>The right control key.</summary> ControlRight, /// <summary>The right control key (equivalent to ControlRight).</summary> RControl = ControlRight, /// <summary>The left alt key.</summary> AltLeft, /// <summary>The left alt key (equivalent to AltLeft.</summary> LAlt = AltLeft, /// <summary>The right alt key.</summary> AltRight, /// <summary>The right alt key (equivalent to AltRight).</summary> RAlt = AltRight, /// <summary>The left win key.</summary> WinLeft, /// <summary>The left win key (equivalent to WinLeft).</summary> LWin = WinLeft, /// <summary>The right win key.</summary> WinRight, /// <summary>The right win key (equivalent to WinRight).</summary> RWin = WinRight, /// <summary>The menu key.</summary> Menu, // Function keys (hopefully enough for most keyboards - mine has 26) // <keysymdef.h> on X11 reports up to 35 function keys. /// <summary>The F1 key.</summary> F1, /// <summary>The F2 key.</summary> F2, /// <summary>The F3 key.</summary> F3, /// <summary>The F4 key.</summary> F4, /// <summary>The F5 key.</summary> F5, /// <summary>The F6 key.</summary> F6, /// <summary>The F7 key.</summary> F7, /// <summary>The F8 key.</summary> F8, /// <summary>The F9 key.</summary> F9, /// <summary>The F10 key.</summary> F10, /// <summary>The F11 key.</summary> F11, /// <summary>The F12 key.</summary> F12, /// <summary>The F13 key.</summary> F13, /// <summary>The F14 key.</summary> F14, /// <summary>The F15 key.</summary> F15, /// <summary>The F16 key.</summary> F16, /// <summary>The F17 key.</summary> F17, /// <summary>The F18 key.</summary> F18, /// <summary>The F19 key.</summary> F19, /// <summary>The F20 key.</summary> F20, /// <summary>The F21 key.</summary> F21, /// <summary>The F22 key.</summary> F22, /// <summary>The F23 key.</summary> F23, /// <summary>The F24 key.</summary> F24, /// <summary>The F25 key.</summary> F25, /// <summary>The F26 key.</summary> F26, /// <summary>The F27 key.</summary> F27, /// <summary>The F28 key.</summary> F28, /// <summary>The F29 key.</summary> F29, /// <summary>The F30 key.</summary> F30, /// <summary>The F31 key.</summary> F31, /// <summary>The F32 key.</summary> F32, /// <summary>The F33 key.</summary> F33, /// <summary>The F34 key.</summary> F34, /// <summary>The F35 key.</summary> F35, // Direction arrows /// <summary>The up arrow key.</summary> Up, /// <summary>The down arrow key.</summary> Down, /// <summary>The left arrow key.</summary> Left, /// <summary>The right arrow key.</summary> Right, /// <summary>The enter key.</summary> Enter, /// <summary>The escape key.</summary> Escape, /// <summary>The space key.</summary> Space, /// <summary>The tab key.</summary> Tab, /// <summary>The backspace key.</summary> BackSpace, /// <summary>The backspace key (equivalent to BackSpace).</summary> Back = BackSpace, /// <summary>The insert key.</summary> Insert, /// <summary>The delete key.</summary> Delete, /// <summary>The page up key.</summary> PageUp, /// <summary>The page down key.</summary> PageDown, /// <summary>The home key.</summary> Home, /// <summary>The end key.</summary> End, /// <summary>The caps lock key.</summary> CapsLock, /// <summary>The scroll lock key.</summary> ScrollLock, /// <summary>The print screen key.</summary> PrintScreen, /// <summary>The pause key.</summary> Pause, /// <summary>The num lock key.</summary> NumLock, // Special keys /// <summary>The clear key (Keypad5 with NumLock disabled, on typical keyboards).</summary> Clear, /// <summary>The sleep key.</summary> Sleep, /*LogOff, Help, Undo, Redo, New, Open, Close, Reply, Forward, Send, Spell, Save, Calculator, // Folders and applications Documents, Pictures, Music, MediaPlayer, Mail, Browser, Messenger, // Multimedia keys Mute, PlayPause, Stop, VolumeUp, VolumeDown, TrackPrevious, TrackNext,*/ // Keypad keys /// <summary>The keypad 0 key.</summary> Keypad0, /// <summary>The keypad 1 key.</summary> Keypad1, /// <summary>The keypad 2 key.</summary> Keypad2, /// <summary>The keypad 3 key.</summary> Keypad3, /// <summary>The keypad 4 key.</summary> Keypad4, /// <summary>The keypad 5 key.</summary> Keypad5, /// <summary>The keypad 6 key.</summary> Keypad6, /// <summary>The keypad 7 key.</summary> Keypad7, /// <summary>The keypad 8 key.</summary> Keypad8, /// <summary>The keypad 9 key.</summary> Keypad9, /// <summary>The keypad divide key.</summary> KeypadDivide, /// <summary>The keypad multiply key.</summary> KeypadMultiply, /// <summary>The keypad subtract key.</summary> KeypadSubtract, /// <summary>The keypad minus key (equivalent to KeypadSubtract).</summary> KeypadMinus = KeypadSubtract, /// <summary>The keypad add key.</summary> KeypadAdd, /// <summary>The keypad plus key (equivalent to KeypadAdd).</summary> KeypadPlus = KeypadAdd, /// <summary>The keypad decimal key.</summary> KeypadDecimal, /// <summary>The keypad period key (equivalent to KeypadDecimal).</summary> KeypadPeriod = KeypadDecimal, /// <summary>The keypad enter key.</summary> KeypadEnter, // Letters /// <summary>The A key.</summary> A, /// <summary>The B key.</summary> B, /// <summary>The C key.</summary> C, /// <summary>The D key.</summary> D, /// <summary>The E key.</summary> E, /// <summary>The F key.</summary> F, /// <summary>The G key.</summary> G, /// <summary>The H key.</summary> H, /// <summary>The I key.</summary> I, /// <summary>The J key.</summary> J, /// <summary>The K key.</summary> K, /// <summary>The L key.</summary> L, /// <summary>The M key.</summary> M, /// <summary>The N key.</summary> N, /// <summary>The O key.</summary> O, /// <summary>The P key.</summary> P, /// <summary>The Q key.</summary> Q, /// <summary>The R key.</summary> R, /// <summary>The S key.</summary> S, /// <summary>The T key.</summary> T, /// <summary>The U key.</summary> U, /// <summary>The V key.</summary> V, /// <summary>The W key.</summary> W, /// <summary>The X key.</summary> X, /// <summary>The Y key.</summary> Y, /// <summary>The Z key.</summary> Z, // Numbers /// <summary>The number 0 key.</summary> Number0, /// <summary>The number 1 key.</summary> Number1, /// <summary>The number 2 key.</summary> Number2, /// <summary>The number 3 key.</summary> Number3, /// <summary>The number 4 key.</summary> Number4, /// <summary>The number 5 key.</summary> Number5, /// <summary>The number 6 key.</summary> Number6, /// <summary>The number 7 key.</summary> Number7, /// <summary>The number 8 key.</summary> Number8, /// <summary>The number 9 key.</summary> Number9, // Symbols /// <summary>The tilde key.</summary> Tilde, /// <summary>The grave key (equivaent to Tilde).</summary> Grave = Tilde, /// <summary>The minus key.</summary> Minus, //Equal, /// <summary>The plus key.</summary> Plus, /// <summary>The left bracket key.</summary> BracketLeft, /// <summary>The left bracket key (equivalent to BracketLeft).</summary> LBracket = BracketLeft, /// <summary>The right bracket key.</summary> BracketRight, /// <summary>The right bracket key (equivalent to BracketRight).</summary> RBracket = BracketRight, /// <summary>The semicolon key.</summary> Semicolon, /// <summary>The quote key.</summary> Quote, /// <summary>The comma key.</summary> Comma, /// <summary>The period key.</summary> Period, /// <summary>The slash key.</summary> Slash, /// <summary>The backslash key.</summary> BackSlash, /// <summary>The secondary backslash key.</summary> NonUSBackSlash, /// <summary>Indicates the last available keyboard key.</summary> LastKey } }
// 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. // // RunBenchmark - .NET Benchmark Performance Harness // // Note: This harness is currently built as a CoreCLR test case for ease of running // against test CORE_ROOT assemblies. As such, when run with out any parameters, // it will do nothing and simply return 100. Use "-run" to actually run tests cases. // // Usage: RunBenchmarks [options] // // options: // // -f <xmlFile> specify benchmark xml control file (default benchmarks.xml) // -n <number> specify number of runs for each benchmark (default is 1) // -w specify that warmup run should be done first // -v run in verbose mode // -r <rootDir> specify root directory to run from // -s <suite> specify a single benchmark suite to run (by name) // -i <benchmark> specify benchmark to include by name (multiple -i's allowed) // -e <benchmark> specify benchmark to exclude by name (multiple -e's allowed) // -list prints a list of the benchmark names and does nothing else // -listsuites prints a list of the suite names and does nothing else // -listtags prints a list of the tag names and does nothing else // -listexes prints a list of full path names to executables in benchmarks // -runner run benchmarks on using runner(e.g. corerun, default is DesktopCLR) // -complus_version <version> run benchmarks on particular DesktopCLR version // -run run benchmarks // -testcase run as CoreCLR test case (default) // -norun prints what would be run, but don't run benchmarks // -tags <tags> specify benchmarks with tags to include // -notags <tags> specify benchmarks with tags to exclude // -csvfile specify name of Comma Seperated Value output file (default console) // // Benchmark .XML Control File format: // // <?xml version="1.0" encoding="UTF-8"?> // <benchmark-system> // <benchmark-root-directory>ROOT_DIRECTORY</benchmark-root-directory> // optional, can be on command line // <benchmark-suite> // <name>SUITE_NAME</name> // <benchmark> // <name>BENCHMARK_NAME</name> // <directory>BENCHMARK_DIRECTORY</directory> // <executable>EXECUTABLE_PATH</executable> // <args>EXECUTABLE_ARGUMENTS</args> // optional args, can redirect output: &gt; > out // <run-in-shell>true</run-in-shell> // optional // <useSSE>true</useSSE> // optional use SSE // <useAVX>true</useAVX> // optional use AVX // <tags>SIMD,SSE</tags> // optional tags for inclusion/exclusion // </benchmark> // ... // LIST_OF_BENCHMARKS // ... // </benchmark-suite> // ... // LIST_OF_BENCHMARK_SUITES // ... // </benchmark-system> // // Where: // // ROOT_DIRECTORY = root directory for all benchmarks described in this file // SUITE_NAME = suite name that benchmark belongs to // BENCHMARK_NAME = benchmark name // BENCHMARK_DIRECTORY = benchmark directory, relative to root (becomes working directory for benchmark) // EXECUTABLE_PATH = relative path (to working directory) for benchmark (simplest form foo.exe) // EXECUTABLE_ARGUMENTS = argument for benchmark if any // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Xml; using System.Xml.XPath; using System.IO; namespace BenchmarkConsoleApplication { // Benchmark Suite - includes suite name an list of benchmarks included in suite. internal class BenchmarkSuite { public string SuiteName; public List<Benchmark> BenchmarkList; public BenchmarkSuite ( string suiteName ) { SuiteName = suiteName; BenchmarkList = new List<Benchmark>(); } } // Benchmark Tag Set - includes tag name an list of benchmarks that have been tagged with this tag. internal class BenchmarkTagSet { public string TagName; public List<Benchmark> BenchmarkList; public BenchmarkTagSet ( string tagName ) { TagName = tagName; BenchmarkList = new List<Benchmark>(); } } // Benchmark - includes benchmark name, suite name, tags, working directory, executable name, // executable argurments, whether to run in a shell, whether to use SSE, whether to use // AVX and expected results (exit code). internal class Benchmark { public string Name; public string SuiteName; public string Tags; public string WorkingDirectory; public string ExeName; public string ExeArgs; public bool DoRunInShell; public bool UseSSE; public bool UseAVX; public int ExpectedResults; public Benchmark ( string name, string suiteName, string tags, string workingDirectory, string exeName, string exeArgs, bool doRunInShell, bool useSSE, bool useAVX, int expectedResults ) { Name = name; SuiteName = suiteName; Tags = tags; WorkingDirectory = workingDirectory; ExeName = exeName; ExeArgs = exeArgs; DoRunInShell = doRunInShell; UseSSE = useSSE; UseAVX = useAVX; ExpectedResults = expectedResults; } } // Benchmark Results - includes benchmark, array of times for each iteration of the benchmark // minimum time, maximum time, average time, standard deviation and number // of failures. internal class Results { public Benchmark Benchmark; public long[] Times; public long Minimum; public long Maximum; public long Average; public double StandardDeviation; public int Failures; public Results ( Benchmark benchmark, int numberOfRuns ) { Benchmark = benchmark; Times = new long[numberOfRuns + 1]; // leave empty slot at index 0, not used. Minimum = 0; Maximum = 0; Average = 0; StandardDeviation = 0.0; Failures = 0; } } // Controls - command line controls used to internal class Controls { public bool DoRun; // Actually execute the benchmarks public bool DoWarmUpRun; // Do a warmup run first. public bool DoVerbose; // Run in verbose mode. public bool DoPrintResults; // Print results of runs. public bool DoRunAsTestCase; // Run as test case (default) public string Runner; // Use the runner to execute benchmarks (e.g. corerun.exe) public bool DoDebugBenchmark; // Execute benchmark under debugger (Windows). public bool DoListBenchmarks; // List out the benchmarks from .XML file public bool DoListBenchmarkSuites; // List out the benchmark suites from .XML file public bool DoListBenchmarkTagSets; // List out the benchmark tag sets from the .XML file public bool DoListBenchmarkExecutables; // List out the benchmark exectubles from the .XML file public int NumberOfRunsPerBenchmark; // Number of runs/iterations each benchmark should be run public string ComplusVersion; // COMPlus_VERSION for desktop CLR hosted runs (optional). public string BenchmarksRootDirectory; // Root directory for benchmark tree specified in .XML file. public string BenchmarkXmlFileName; // Benchmark .XML filename (default coreclr_benchmarks.xml) public string BenchmarkCsvFileName; // Benchmark output .CSV filename (default coreclr_benchmarks.csv) public string SuiteName; // Specific benchmark suite name to be executed (optional). public List<string> IncludeBenchmarkList; // List of specific benchmarks to be included (optional) public List<string> ExcludeBenchmarkList; // List of specific benchmarks to be excluded (optional) public List<string> IncludeTagList; //List of specific benchmark tags to be included (optional) public List<string> ExcludeTagList; //List of specific benchmark tags to be excluded (optional) } // Benchmark System - actual benchmark system. Includes the controls, the command processer, main // execution engine, benchmarks lists, selected benchmark lists, // benchmark suite dictionary, benchmark tag dictionary, and results table. internal class BenchmarkSystem { public const bool OptionalField = true; public Controls Controls = new Controls() { NumberOfRunsPerBenchmark = 1, DoWarmUpRun = false, DoVerbose = false, Runner = "", DoDebugBenchmark = false, DoListBenchmarks = false, DoListBenchmarkSuites = false, DoListBenchmarkTagSets = false, DoListBenchmarkExecutables = false, DoRun = false, DoRunAsTestCase = true, DoPrintResults = false, ComplusVersion = "", SuiteName = "", BenchmarksRootDirectory = "", BenchmarkXmlFileName = "coreclr_benchmarks.xml", BenchmarkCsvFileName = "coreclr_benchmarks.csv", IncludeBenchmarkList = new List<string>(), ExcludeBenchmarkList = new List<string>(), IncludeTagList = new List<string>(), ExcludeTagList = new List<string>() }; public Dictionary<string, BenchmarkSuite> BenchmarkSuiteTable = new Dictionary<string, BenchmarkSuite>(); public Dictionary<string, BenchmarkTagSet> BenchmarkTagSetTable = new Dictionary<string, BenchmarkTagSet>(); public List<Benchmark> BenchmarkList = new List<Benchmark>(); public List<Benchmark> SelectedBenchmarkList = new List<Benchmark>(); public List<Results> ResultsList = new List<Results>(); public int NumberOfBenchmarksRun; public int Failures = 0; public char[] ListSeparatorCharSet = new char[] { ',', ' ' }; public char[] DirectorySeparatorCharSet = new char[] { '/', '\\' }; // Main driver for benchmark system. public static int Main(string[] args) { int exitCode = 0; Console.WriteLine("RyuJIT Benchmark System"); try { BenchmarkSystem benchmarkSystem = new BenchmarkSystem(); benchmarkSystem.ProcessCommandLine(args); benchmarkSystem.BuildBenchmarksList(); benchmarkSystem.SelectBenchmarks(); benchmarkSystem.RunBenchmarks(); benchmarkSystem.ReportResults(); bool doRunAsTestCase = benchmarkSystem.Controls.DoRunAsTestCase; if (doRunAsTestCase) { exitCode = 100; } } catch (Exception exception) { // Need to find portable Environment.Exit() if (exception.Message == "Exit") { exitCode = 0; } else { Console.WriteLine("{0}", exception.ToString()); exitCode = -1; } } return exitCode; } // Command line processor. public void ProcessCommandLine(string[] args) { Controls controls = Controls; try { for (int i = 0; i < args.Length;) { string arg = args[i++]; string benchmark; string[] tags; string runner; switch (arg) { case "-n": arg = args[i++]; controls.NumberOfRunsPerBenchmark = Int32.Parse(arg); break; case "-testcase": controls.DoRun = false; controls.DoPrintResults = false; controls.DoRunAsTestCase = true; break; case "-run": controls.DoRun = true; controls.DoPrintResults = true; controls.DoRunAsTestCase = false; break; case "-norun": controls.DoRun = false; controls.DoPrintResults = true; controls.DoRunAsTestCase = false; break; case "-w": controls.DoWarmUpRun = true; break; case "-v": controls.DoVerbose = true; break; case "-r": arg = args[i++]; controls.BenchmarksRootDirectory = PlatformSpecificDirectoryName(arg); break; case "-f": arg = args[i++]; controls.BenchmarkXmlFileName = arg; break; case "-csvfile": arg = args[i++]; controls.BenchmarkCsvFileName = arg; break; case "-s": arg = args[i++]; controls.SuiteName = arg; break; case "-i": arg = args[i++]; benchmark = arg; controls.IncludeBenchmarkList.Add(benchmark); break; case "-e": arg = args[i++]; benchmark = arg; controls.ExcludeBenchmarkList.Add(benchmark); break; case "-list": controls.DoListBenchmarks = true; controls.DoRunAsTestCase = false; break; case "-listsuites": controls.DoListBenchmarkSuites = true; controls.DoRunAsTestCase = false; break; case "-listtags": controls.DoListBenchmarkTagSets = true; controls.DoRunAsTestCase = false; break; case "-listexes": controls.DoListBenchmarkExecutables = true; controls.DoRunAsTestCase = false; break; case "-tags": arg = args[i++]; tags = arg.Split(ListSeparatorCharSet, StringSplitOptions.RemoveEmptyEntries); controls.IncludeTagList.AddRange(tags); break; case "-notags": arg = args[i++]; tags = arg.Split(ListSeparatorCharSet, StringSplitOptions.RemoveEmptyEntries); controls.ExcludeTagList.AddRange(tags); break; case "-runner": arg = args[i++]; runner = arg; controls.Runner = runner; break; case "-debug": controls.DoDebugBenchmark = true; break; case "-complus_version": arg = args[i++]; controls.ComplusVersion = arg; break; default: throw new Exception("invalid argument: " + arg); } } } catch (Exception exception) { Console.WriteLine("Exception: {0}", exception); Usage(); } } // Print out usage and exit. public void Usage() { Console.WriteLine(""); Console.WriteLine("Usage: RunBenchmarks [options]"); Console.WriteLine(""); Console.WriteLine(" options: "); Console.WriteLine(""); Console.WriteLine(" -f <xmlFile> specify benchmark xml file (default coreclr_benchmarks.xml)"); Console.WriteLine(" -n <number> specify number of runs for each benchmark (default is 1)"); Console.WriteLine(" -w specify that warmup run should be done first"); Console.WriteLine(" -v run in verbose mode"); Console.WriteLine(" -r <rootDir> specify root directory to run from"); Console.WriteLine(" -s <suite> specify a single benchmark suite to run (by name)"); Console.WriteLine(" -i <benchmark> specify benchmark to include by name (multiple -i's allowed)"); Console.WriteLine(" -e <benchmark> specify benchmark to exclude by name (multiple -e's allowed)"); Console.WriteLine(" -list prints a list of the benchmark names and does nothing else"); Console.WriteLine(" -listsuites prints a list of the suite names and does nothing else"); Console.WriteLine(" -listtags prints a list of the tag names and does nothing else"); Console.WriteLine(" -listexes prints a list of the benchmark executables and does nothing else"); Console.WriteLine(" -coreclr run benchmarks on CoreCLR (default DesktopCLR)"); Console.WriteLine(" -complus_version <version> run benchmarks on particular DesktopCLR version"); Console.WriteLine(" -run run benchmarks"); Console.WriteLine(" -norun prints what would be run, but nothing is executed"); Console.WriteLine(" -testcase run as CoreCLR test case (default)"); Console.WriteLine(" -norun prints what would be run, but don't run benchmarks"); Console.WriteLine(" -tags <tags> specify benchmarks with tags to include"); Console.WriteLine(" -notags <tags> specify benchmarks with tags to exclude"); Console.WriteLine(" -csvfile specify name of Comma Seperated Value output file (default coreclr_benchmarks.csv)"); Exit(-1); } // Add a benchmark to the list of benchmarks read in from the .XML file. public void AddBenchmark ( string name, string suiteName, string tags, string workingDirectory, string exeName, string exeArgs, bool doRunInShell, bool useSSE, bool useAVX, int expectedResults ) { BenchmarkSuite benchmarkSuite; BenchmarkTagSet benchmarkTagSet; Benchmark benchmark; benchmark = new Benchmark(name, suiteName, tags, workingDirectory, exeName, exeArgs, doRunInShell, useSSE, useAVX, expectedResults); BenchmarkList.Add(benchmark); if (!BenchmarkSuiteTable.TryGetValue(suiteName, out benchmarkSuite)) { benchmarkSuite = new BenchmarkSuite(suiteName); BenchmarkSuiteTable.Add(suiteName, benchmarkSuite); } benchmarkSuite.BenchmarkList.Add(benchmark); string[] tagList = tags.Split(ListSeparatorCharSet, StringSplitOptions.RemoveEmptyEntries); foreach (string tag in tagList) { if (!BenchmarkTagSetTable.TryGetValue(tag, out benchmarkTagSet)) { benchmarkTagSet = new BenchmarkTagSet(tag); BenchmarkTagSetTable.Add(tag, benchmarkTagSet); } benchmarkTagSet.BenchmarkList.Add(benchmark); } } // XML processing, select a single node given root node and xpath field name. public XmlNode SelectSingleNode ( XmlNode node, string xpath ) { #if DESKTOP return node.SelectSingleNode(xpath); #else return XmlDocumentXPathExtensions.SelectSingleNode(node, xpath); #endif } // XML processing, get a string field value given a node and xpath field name. // Can be optional field. public string GetField ( XmlNode node, string xpath, bool optional = false ) { XmlNode fieldNode = SelectSingleNode(node, xpath); if (fieldNode == null) { if (optional) { return ""; } throw new Exception("missing field: " + xpath); } return fieldNode.InnerText; } // XML processing, get a boolean field value given a node and xpath field name. // Can be optional field. public bool GetBooleanField ( XmlNode node, string xpath, bool optional = false ) { string value = GetField(node, xpath, optional); if (value == "true") return true; if (value == "false") return false; if (optional) return false; throw new Exception("bad boolean value: " + value); } // XML processing, get an integer field value given a node and xpath field name. // Can be optional field. public int GetIntegerField ( XmlNode node, string xpath, bool optional = false ) { string value = GetField(node, xpath, optional); if (value != "") { int number = Int32.Parse(value); return number; } if (optional) return 0; throw new Exception("bad integer value: " + value); } // XML processing, select a list of nodes given root node and xpath field name. public XmlNodeList SelectNodes ( XmlNode node, string xpath ) { #if DESKTOP return node.SelectNodes(xpath); #else return XmlDocumentXPathExtensions.SelectNodes(node, xpath); #endif } // XML processing, get a list of nodes given root node and xpath field name. public XmlNodeList GetList ( XmlNode node, string xpath ) { return SelectNodes(node, xpath); } // Exit benchmark system with specified exit code. public int Exit(int exitCode) { // Need to find portable Environment.Exit() switch (exitCode) { case 0: case -1: case -2: throw new Exception("Exit"); default: throw new Exception("BadExit"); } } // Constructed platform specific field name given either Unix style or Windows style // directory name. public string PlatformSpecificDirectoryName ( string directoryName ) { if (directoryName == "") return ""; string[] path = directoryName.Split(DirectorySeparatorCharSet, StringSplitOptions.RemoveEmptyEntries); string platformSpecificDirectoryName = System.IO.Path.Combine(path); bool absolutePath = false; char firstChar = directoryName[0]; for (int i = 0; i < DirectorySeparatorCharSet.Length; i++) { if (firstChar == DirectorySeparatorCharSet[i]) { absolutePath = true; break; } } if (absolutePath) { platformSpecificDirectoryName = (Path.DirectorySeparatorChar + platformSpecificDirectoryName); } return platformSpecificDirectoryName; } // Build list of benchmarks by reading in and processing .XML file. public void BuildBenchmarksList() { bool doRunAsTestCase = Controls.DoRunAsTestCase; string benchmarksRootDirectory = Controls.BenchmarksRootDirectory; string benchmarkXmlFileName = Controls.BenchmarkXmlFileName; string benchmarkXmlFullFileName; string benchmarkRootDirectoryName; string benchmarkSuiteName; string benchmarkDirectoryName; string benchmarkName; string benchmarkExecutableName; string benchmarkArgs; bool doRunInShell; bool useSSE; bool useAVX; int expectedResults; string tags; // If we aren't being asked to run benchmarks or print results // then we must be being executed as a simple CoreCLR test case. // Don't bother reading XML file. if (doRunAsTestCase) { return; } benchmarkXmlFullFileName = benchmarkXmlFileName; // Load XML description of benchmarks. XmlDocument benchmarkXml = new XmlDocument(); var xmlFile = new FileStream(benchmarkXmlFullFileName, FileMode.Open, FileAccess.Read); benchmarkXml.Load(xmlFile); // Get root directory for benchmark system. Command line argument overrides // specification in benchmark control file. benchmarkRootDirectoryName = Controls.BenchmarksRootDirectory; if (benchmarkRootDirectoryName == "") { benchmarkRootDirectoryName = GetField(benchmarkXml.DocumentElement, "benchmark-root-directory"); Controls.BenchmarksRootDirectory = benchmarkRootDirectoryName; } benchmarkRootDirectoryName = PlatformSpecificDirectoryName(benchmarkRootDirectoryName); Controls.BenchmarksRootDirectory = benchmarkRootDirectoryName; // Process each benchmark suite in the list of benchmark suites. XmlNodeList benchmarkSuiteList = GetList(benchmarkXml.DocumentElement, "benchmark-suite"); foreach (XmlNode benchmarkSuite in benchmarkSuiteList) { benchmarkSuiteName = GetField(benchmarkSuite, "name"); //Process each benchmark in benchmark suite. XmlNodeList benchmarkList = GetList(benchmarkSuite, "benchmark"); foreach (XmlNode benchmark in benchmarkList) { benchmarkName = GetField(benchmark, "name"); benchmarkDirectoryName = GetField(benchmark, "directory", OptionalField); benchmarkDirectoryName = PlatformSpecificDirectoryName(benchmarkDirectoryName); benchmarkExecutableName = GetField(benchmark, "executable"); benchmarkArgs = GetField(benchmark, "args", OptionalField); useSSE = GetBooleanField(benchmark, "useSSE", OptionalField); useAVX = GetBooleanField(benchmark, "useAVX", OptionalField); expectedResults = GetIntegerField(benchmark, "expected-results", OptionalField); doRunInShell = GetBooleanField(benchmark, "run-in-shell", OptionalField); tags = GetField(benchmark, "tags", OptionalField); AddBenchmark(benchmarkName, benchmarkSuiteName, tags, benchmarkDirectoryName, benchmarkExecutableName, benchmarkArgs, doRunInShell, useSSE, useAVX, expectedResults); } } // Process early out controls that just do listing. if (Controls.DoListBenchmarks) { ListBenchmarks(); Exit(-2); } if (Controls.DoListBenchmarkSuites) { ListBenchmarkSuites(); Exit(-2); } if (Controls.DoListBenchmarkTagSets) { ListBenchmarkTagSets(); Exit(-2); } if (Controls.DoListBenchmarkExecutables) { ListBenchmarkExecutables(); Exit(-2); } } // Print out list of benchmarks read in. public void ListBenchmarks() { Console.WriteLine("Benchmark List"); foreach (Benchmark benchmark in BenchmarkList) { Console.WriteLine("{0}", benchmark.Name); Console.WriteLine(" Suite: {0}", benchmark.SuiteName); Console.WriteLine(" WorkingDirectory: {0}", benchmark.WorkingDirectory); Console.WriteLine(" ExeName: {0}", benchmark.ExeName); Console.WriteLine(" ExeArgs: {0}", benchmark.ExeArgs); Console.WriteLine(" RunInShell: {0}", benchmark.DoRunInShell); Console.WriteLine(" UseSSE: {0}", benchmark.UseSSE); Console.WriteLine(" UseAVX: {0}", benchmark.UseAVX); Console.WriteLine(" Tags: {0}", benchmark.Tags); } } // Print out list of benchmark suites read in. public void ListBenchmarkSuites() { Console.WriteLine("Benchmark Suite List"); var benchmarkSuiteList = BenchmarkSuiteTable.Keys; foreach (var suiteName in benchmarkSuiteList) { Console.WriteLine("{0}", suiteName); } } // Print out list of benchmark tags read in. public void ListBenchmarkTagSets() { Console.WriteLine("Benchmark TagSet List"); var benchmarkTagSetList = BenchmarkTagSetTable.Keys; foreach (var tagName in benchmarkTagSetList) { Console.WriteLine("{0}", tagName); } } // Print out list of benchmark executables read in. public void ListBenchmarkExecutables() { Console.WriteLine("Benchmark Executable List"); var benchmarkList = BenchmarkList; foreach (var benchmark in benchmarkList) { string benchmarksRootDirectory = Controls.BenchmarksRootDirectory; string benchmarkDirectory = System.IO.Path.Combine(benchmarksRootDirectory, benchmark.WorkingDirectory); string workingDirectory = benchmarkDirectory; string executableName = System.IO.Path.Combine(workingDirectory, benchmark.ExeName); Console.WriteLine("{0}", executableName); } } // Select benchmarks to run based on controls for suite, tag, or specfic // benchmark inclusion/exclusion. public void SelectBenchmarks() { List<Benchmark> benchmarkList = BenchmarkList; List<string> includeBenchmarkList = Controls.IncludeBenchmarkList; List<string> excludeBenchmarkList = Controls.ExcludeBenchmarkList; List<string> includeTagList = Controls.IncludeTagList; List<string> excludeTagList = Controls.ExcludeTagList; string suiteName = Controls.SuiteName; if (suiteName != "") { BenchmarkSuite benchmarkSuite = null; if (!BenchmarkSuiteTable.TryGetValue(suiteName, out benchmarkSuite)) { throw new Exception("bad suite name: " + suiteName); } benchmarkList = benchmarkSuite.BenchmarkList; } foreach (Benchmark benchmark in benchmarkList) { string benchmarkName = benchmark.Name; bool include = true; if (includeBenchmarkList.Count > 0) { include = false; if (includeBenchmarkList.Contains(benchmarkName)) { include = true; } } if (include && (excludeBenchmarkList.Count > 0)) { if (excludeBenchmarkList.Contains(benchmarkName)) { include = false; } } if (include && (excludeTagList.Count > 0)) { foreach (string tag in excludeTagList) { BenchmarkTagSet benchmarkTagSet = null; if (!BenchmarkTagSetTable.TryGetValue(tag, out benchmarkTagSet)) { throw new Exception("bad tag: " + tag); } List<Benchmark> excludeTagBenchmarkList = benchmarkTagSet.BenchmarkList; if (excludeTagBenchmarkList.Contains(benchmark)) { include = false; } } } if (include) { SelectedBenchmarkList.Add(benchmark); } } } // Run benchmark - actually run benchmark the specified number of times and using the specified // controls and return results. public Results RunBenchmark(Benchmark benchmark) { bool doRun = Controls.DoRun; int numberOfRuns = Controls.NumberOfRunsPerBenchmark; bool doWarmUpRun = Controls.DoWarmUpRun; string runner = Controls.Runner; bool doDebugBenchmark = Controls.DoDebugBenchmark; bool doVerbose = Controls.DoVerbose; string complusVersion = Controls.ComplusVersion; string benchmarksRootDirectory = Controls.BenchmarksRootDirectory; string benchmarkDirectory = System.IO.Path.Combine(benchmarksRootDirectory, benchmark.WorkingDirectory); bool doRunInShell = benchmark.DoRunInShell; bool useSSE = benchmark.UseSSE; bool useAVX = benchmark.UseAVX; int expectedResults = benchmark.ExpectedResults; int failureResults = ~expectedResults; int actualResults; int failures = 0; Results results = new Results(benchmark, numberOfRuns); if (!doRun) { return results; } string workingDirectory = benchmarkDirectory; string fileName = System.IO.Path.Combine(workingDirectory, benchmark.ExeName); string args = benchmark.ExeArgs; if (runner != "") { args = fileName + " " + args; fileName = runner; } if (doDebugBenchmark) { args = "/debugexe " + fileName + " " + args; fileName = "devenv.exe"; } if (doRunInShell) { args = "/C " + fileName + " " + args; fileName = "cmd.exe"; } if (doVerbose) { Console.WriteLine("Running benchmark {0} ...", benchmark.Name); Console.WriteLine("Invoking: {0} {1}", fileName, args); } for (int run = (doWarmUpRun) ? 0 : 1; run <= numberOfRuns; run++) { ProcessStartInfo startInfo = new ProcessStartInfo() { FileName = fileName, Arguments = args, WorkingDirectory = workingDirectory, UseShellExecute = false }; if (complusVersion != "") { startInfo.Environment["COMPlus_Version"] = complusVersion; startInfo.Environment["COMPlus_DefaultVersion"] = complusVersion; } if (useSSE) { startInfo.Environment["COMPlus_FeatureSIMD"] = "1"; startInfo.Environment["COMPlus_EnableAVX"] = "0"; } if (useAVX) { startInfo.Environment["COMPlus_FeatureSIMD"] = "1"; startInfo.Environment["COMPlus_EnableAVX"] = "1"; } startInfo.Environment["COMPlus_gcConcurrent"] = "0"; startInfo.Environment["COMPlus_gcServer"] = "0"; startInfo.Environment["COMPlus_NoGuiOnAssert"] = "1"; startInfo.Environment["COMPlus_BreakOnUncaughtException"] = "0"; var clockTime = Stopwatch.StartNew(); int exitCode = 0; try { using (var proc = Process.Start(startInfo)) { proc.EnableRaisingEvents = true; proc.WaitForExit(); exitCode = proc.ExitCode; } this.NumberOfBenchmarksRun++; } catch (Exception exception) { Console.WriteLine("Could not launch test {0} exception: {1}", startInfo.FileName, exception); exitCode = failureResults; } clockTime.Stop(); actualResults = exitCode; long time = clockTime.ElapsedMilliseconds; if (actualResults != expectedResults) { failures++; time = 0; } results.Times[run] = time; if (doVerbose) { Console.Write("Iteration benchmark {0} ", benchmark.Name); if (actualResults == expectedResults) { Console.Write("elapsed time {0}ms", time); } else { Console.Write("FAILED(expected={0}, actual={1})", expectedResults, actualResults); } if (run == 0) { Console.Write(" (warmup)"); } Console.WriteLine(""); } } // Calculate min, max, avg, and std devation. long sum = 0; long minimum = results.Times[1]; long maximum = minimum; for (int run = 1; run <= numberOfRuns; run++) { long time = results.Times[run]; sum += time; minimum = Math.Min(minimum, time); maximum = Math.Max(maximum, time); } long average = sum / (long)numberOfRuns; double standardDeviation = 0.0; if (numberOfRuns > 1) { double s = 0.0; double a = (double)average; double n = (double)numberOfRuns; for (int run = 1; run <= numberOfRuns; run++) { double time = (double)results.Times[run]; double t = (time - a); s += (t * t); } double variance = s / n; if (a == 0.0) { standardDeviation = 0.0; } else { standardDeviation = 100.0 * (Math.Sqrt(variance) / a); // stddev as a percentage standardDeviation = Math.Round(standardDeviation, 2, MidpointRounding.AwayFromZero); } } // Record results and return. results.Average = average; results.Minimum = minimum; results.Maximum = maximum; results.StandardDeviation = standardDeviation; results.Failures = failures; return results; } // Run the list of selected benchmarks. public void RunBenchmarks() { bool doVerbose = Controls.DoVerbose; if (doVerbose) { Console.WriteLine("Run benchmarks ..."); } foreach (Benchmark benchmark in SelectedBenchmarkList) { Results results = RunBenchmark(benchmark); Failures += results.Failures; ResultsList.Add(results); } } // Report the results of the benchmark run. public void ReportResults() { bool doVerbose = Controls.DoVerbose; bool doPrintResults = Controls.DoPrintResults; string benchmarkCsvFileName = Controls.BenchmarkCsvFileName; int numberOfBenchmarksRun = this.NumberOfBenchmarksRun; int numberOfFailures = this.Failures; int numberOfPasses = numberOfBenchmarksRun - numberOfFailures; int numberOfRunsPerBenchmark = Controls.NumberOfRunsPerBenchmark; int numberOfFailuresPerBenchmark = 0; if (!doPrintResults) { return; } if (doVerbose) { Console.WriteLine("Generating benchmark report on {0}", benchmarkCsvFileName); } using (TextWriter outputFile = File.CreateText(benchmarkCsvFileName)) { outputFile.WriteLine("Benchmark,Minimum(ms),Maximum(ms),Average(ms),StdDev(%),Passed/Failed(#)"); foreach (Results results in ResultsList) { string name = results.Benchmark.Name; outputFile.Write("{0},", name); long minimum = results.Minimum; long maximum = results.Maximum; long average = results.Average; double standardDeviation = results.StandardDeviation; outputFile.Write("{0},{1},{2},{3}", minimum, maximum, average, standardDeviation); numberOfFailuresPerBenchmark = results.Failures; numberOfPasses = (numberOfPasses < 0) ? 0 : numberOfPasses; if (numberOfFailuresPerBenchmark > 0) { outputFile.Write(",FAILED({0})", numberOfFailuresPerBenchmark); } else { outputFile.Write(",PASSED({0})", numberOfRunsPerBenchmark); } outputFile.WriteLine(""); } outputFile.WriteLine("TOTAL BENCHMARKS({0}), PASSED({1}), FAILED({2})", numberOfBenchmarksRun, numberOfPasses, numberOfFailures); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Text; namespace System.Management.Automation { /// <summary> /// The parameter binder for native commands. /// </summary> /// internal class NativeCommandParameterBinder : ParameterBinderBase { #region ctor /// <summary> /// Constructs a NativeCommandParameterBinder /// </summary> /// /// <param name="command"> /// The NativeCommand to bind to. /// </param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="command"/>.Context is null /// </exception> internal NativeCommandParameterBinder( NativeCommand command) : base(command.MyInvocation, command.Context, command) { _nativeCommand = command; } #endregion ctor #region internal members #region Parameter binding /// <summary> /// Binds a parameter for a native command (application). /// </summary> /// <param name="name"> /// The name of the parameter to bind the value to. For applications /// this just becomes another parameter... /// </param> /// <param name="value"> /// The value to bind to the parameter. It should be assumed by /// derived classes that the proper type coercion has already taken /// place and that any prerequisite metadata has been satisfied. /// </param> /// <param name="parameterMetadata"></param> internal override void BindParameter(string name, object value, CompiledCommandParameter parameterMetadata) { Diagnostics.Assert(false, "Unreachable code"); throw new NotSupportedException(); } // BindParameter internal override object GetDefaultParameterValue(string name) { return null; } internal void BindParameters(Collection<CommandParameterInternal> parameters) { bool sawVerbatimArgumentMarker = false; bool first = true; foreach (CommandParameterInternal parameter in parameters) { if (!first) { _arguments.Append(' '); } first = false; if (parameter.ParameterNameSpecified) { Diagnostics.Assert(parameter.ParameterText.IndexOf(' ') == -1, "Parameters cannot have whitespace"); _arguments.Append(parameter.ParameterText); if (parameter.SpaceAfterParameter) { _arguments.Append(' '); } } if (parameter.ArgumentSpecified) { // If this is the verbatim argument marker, we don't pass it on to the native command. // We do need to remember it though - we'll expand environment variables in subsequent args. object argValue = parameter.ArgumentValue; if (string.Equals("--%", argValue as string, StringComparison.OrdinalIgnoreCase)) { sawVerbatimArgumentMarker = true; continue; } if (argValue != AutomationNull.Value && argValue != UnboundParameter.Value) { // ArrayIsSingleArgumentForNativeCommand is true when a comma is used in the // command line, e.g. // windbg -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect // The parser produced an array of strings but marked the parameter so we // can properly reconstruct the correct command line. appendOneNativeArgument(Context, argValue, parameter.ArrayIsSingleArgumentForNativeCommand ? ',' : ' ', sawVerbatimArgumentMarker); } } } } #endregion Parameter binding /// <summary> /// Gets the command arguments in string form /// </summary> /// internal String Arguments { get { return _arguments.ToString(); } } // Arguments private readonly StringBuilder _arguments = new StringBuilder(); #endregion internal members #region private members /// <summary> /// Stringize a non-IEnum argument to a native command, adding quotes /// and trailing spaces as appropriate. An array gets added as multiple arguments /// each of which will be stringized. /// </summary> /// <param name="context">Execution context instance</param> /// <param name="obj">The object to append</param> /// <param name="separator">A space or comma used when obj is enumerable</param> /// <param name="sawVerbatimArgumentMarker">true if the argument occurs after --%</param> private void appendOneNativeArgument(ExecutionContext context, object obj, char separator, bool sawVerbatimArgumentMarker) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); bool needSeparator = false; do { string arg; if (list == null) { arg = PSObject.ToStringParser(context, obj); } else { if (!ParserOps.MoveNext(context, null, list)) { break; } arg = PSObject.ToStringParser(context, ParserOps.Current(null, list)); } if (!String.IsNullOrEmpty(arg)) { if (needSeparator) { _arguments.Append(separator); } else { needSeparator = true; } if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); } else { // We need to add quotes if the argument has unquoted spaces. The // quotes could appear anywhere inside the string, not just at the start, // e.g. // $a = 'a"b c"d' // echoargs $a 'a"b c"d' a"b c"d // // The above should see 3 identical arguments in argv (the command line will // actually have quotes in different places, but the Win32 command line=>argv parser // erases those differences. // // We need to check quotes that the win32 arugment parser checks which is currently // just the normal double quotes, no other special quotes. Also note that mismatched // quotes are supported. bool needQuotes = false; int quoteCount = 0; for (int i = 0; i < arg.Length; i++) { if (arg[i] == '"') { quoteCount += 1; } else if (char.IsWhiteSpace(arg[i]) && (quoteCount % 2 == 0)) { needQuotes = true; } } if (needQuotes) { _arguments.Append('"'); _arguments.Append(arg); _arguments.Append('"'); } else { _arguments.Append(arg); } } } } while (list != null); } /// <summary> /// The native command to bind to /// </summary> private NativeCommand _nativeCommand; #endregion private members } } // namespace System.Management.Automation
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; namespace NGIC.CHAP.Diagnostics { public abstract class BindingListBase<TItem> : IList<TItem>, IBindingList where TItem : class { [Serializable] public class OrderedItem : IEquatable<OrderedItem>, IComparable<OrderedItem> { public int OriginalIndex { get; private set; } public TItem Item { get; private set; } public OrderedItem(TItem item, int index) { this.OriginalIndex = index; this.Item = item; } public bool Equals(OrderedItem other) { return other != null && (Object.ReferenceEquals(this, other) || this.OriginalIndex == other.OriginalIndex); } public override bool Equals(object obj) { return this.Equals(obj as OrderedItem); } public override int GetHashCode() { return this.OriginalIndex; } public override string ToString() { return this.OriginalIndex.ToString(); } public int CompareTo(OrderedItem other) { if (other == null) return 1; return (Object.ReferenceEquals(this, other)) ? 0 : this.OriginalIndex.CompareTo(other.OriginalIndex); } } public abstract class ItemPropertyComparer : IEqualityComparer<OrderedItem>, IComparer<OrderedItem>, IEquatable<ItemPropertyComparer> { public PropertyDescriptor Property { get; private set; } public static ItemPropertyComparer Create(PropertyDescriptor property) { if (property == null || !typeof(TItem).IsAssignableFrom(property.ComponentType)) return null; ItemPropertyComparer result = Activator.CreateInstance((typeof(ItemPropertyComparer<>)).MakeGenericType(property.PropertyType)) as ItemPropertyComparer; result.Property = property; return result; } public abstract bool ItemHasProperty(TItem item); public abstract bool PropertiesAreEqual(TItem x, TItem y); public abstract int GetPropertyHashCode(TItem item); public abstract int ComparePropertyValues(TItem x, TItem y); public bool Equals(OrderedItem x, OrderedItem y) { return (x == null) ? y == null : (y != null && (Object.ReferenceEquals(x, y) || ((this.ItemHasProperty(x.Item)) ? this.ItemHasProperty(y.Item) : this.ItemHasProperty(y.Item) && this.PropertiesAreEqual(x.Item, y.Item)))); } public int GetHashCode(OrderedItem obj) { return (obj == null || !this.ItemHasProperty(obj.Item)) ? 0 : this.GetPropertyHashCode(obj.Item); } public int Compare(OrderedItem x, OrderedItem y) { if (x == null) return (y == null) ? 0 : -1; if (y == null) return 1; if (Object.ReferenceEquals(x, y) || Object.ReferenceEquals(x.Item, y.Item)) return 0; if (!this.ItemHasProperty(x.Item)) return (this.ItemHasProperty(y.Item)) ? -1 : 0; if (!this.ItemHasProperty(y.Item)) return 1; return this.ComparePropertyValues(x.Item, y.Item); } public bool Equals(ItemPropertyComparer other) { return other != null && (Object.ReferenceEquals(this, other) || (this.Property.ComponentType.Equals(other.Property.ComponentType) && this.Property.PropertyType.Equals(other.Property.PropertyType) && String.Compare(this.Property.Name, other.Property.Name, true) == 0)); } public override bool Equals(object obj) { return this.Equals(obj as ItemPropertyComparer); } public override int GetHashCode() { return this.Property.Name.GetHashCode(); } public override string ToString() { return String.Format("{0} => {1} {2}", this.Property.ComponentType.ToString(), this.Property.PropertyType.ToString(), this.Property.Name); } } [Serializable] public class ItemPropertyComparer<TValue> : ItemPropertyComparer { private EqualityComparer<TValue> _equalityComparer; private Comparer<TValue> _comparer; private Func<TValue, TValue, bool> _valuesEqual; private Func<TValue, int> _gethashCode; private Func<TValue, TValue, int> _compreTo; public ItemPropertyComparer() { Type type = typeof(TValue); if (type.Equals(typeof(string))) { this._equalityComparer = StringComparer.Ordinal as EqualityComparer<TValue>; this._comparer = this._equalityComparer as Comparer<TValue>; } else { this._equalityComparer = EqualityComparer<TValue>.Default; this._comparer = Comparer<TValue>.Default; if (type.IsValueType) { this._valuesEqual = (TValue x, TValue y) => this._equalityComparer.Equals(x, y); this._gethashCode = (TValue value) => this._equalityComparer.GetHashCode(value); this._compreTo = (TValue x, TValue y) => this._comparer.Compare(x, y); return; } } this._valuesEqual = (TValue x, TValue y) => ((object)x == null) ? (object)y == null : ((object)y != null && (Object.ReferenceEquals(x, y) || this._equalityComparer.Equals(x, y))); this._gethashCode = (TValue value) => ((object)value == null) ? 0 : this._equalityComparer.GetHashCode(value); this._compreTo = (TValue x, TValue y) => { if ((object)x == null) return ((object)y == null) ? 0 : -1; if ((object)y == null) return 1; if (Object.ReferenceEquals(x, y)) return 0; return this._comparer.Compare(x, y); }; } private bool TryGetValue(TItem item, out TValue value) { bool result; try { value = (TValue)(this.Property.GetValue(item)); result = true; } catch { value = default(TValue); result = false; } return result; } public override bool ItemHasProperty(TItem item) { return item != null && this.Property.ComponentType.IsInstanceOfType(item); } public override bool PropertiesAreEqual(TItem itemX, TItem itemY) { TValue valueX, valueY; if (!this.TryGetValue(itemX, out valueX)) return !this.TryGetValue(itemY, out valueY); if (!this.TryGetValue(itemY, out valueY)) return false; return this._valuesEqual(valueX, valueY); } public override int GetPropertyHashCode(TItem item) { TValue value; if (!this.TryGetValue(item, out value)) return 0; return this._gethashCode(value); } public override int ComparePropertyValues(TItem itemX, TItem itemY) { TValue valueX, valueY; if (!this.TryGetValue(itemX, out valueX)) return (this.TryGetValue(itemY, out valueY)) ? -1 : 0; if (!this.TryGetValue(itemY, out valueY)) return 1; return this._compreTo(valueX, valueY); } } private object _syncRoot = new object(); private OrderedItem[] _items; private Dictionary<Type, bool> _validatedPropertyDescriptors = new Dictionary<Type, bool>(); private LinkedList<Tuple<ItemPropertyComparer, ListSortDirection>> _sortStack = new LinkedList<Tuple<ItemPropertyComparer,ListSortDirection>>(); private int _sortIndex = 0; public BindingListBase(params TItem[] items) : this(items as IEnumerable<TItem>) { } public BindingListBase(IEnumerable<TItem> items) { int index = 0; this._items = (items == null) ? new OrderedItem[0] : items.Where(i => i != null).Select(i => new OrderedItem(i, index++)).ToArray(); } protected void RunWithLock(System.Action action) { lock (this._syncRoot) action(); } protected T GetWithLock<T>(Func<T> func) { T result; lock (this._syncRoot) result = func(); return result; } private void _ResetInnerSort() { this._items = this._items.OrderBy(i => i.OriginalIndex).ToArray(); this._sortIndex = 0; } private void _EnsureSort() { if (this._items.Length < 2 || this._sortStack.Count == 0 || this._sortIndex >= this._sortStack.Count) return; foreach (Tuple<ItemPropertyComparer, ListSortDirection> sort in this._sortStack.Skip(this._sortIndex)) { if (sort.Item2 == ListSortDirection.Ascending) this._items = this._items.OrderBy(i => i, sort.Item1).ToArray(); else this._items = this._items.OrderByDescending(i => i, sort.Item1).ToArray(); } this._sortIndex = this._items.Length; } public void EnsureSort() { this.RunWithLock(this._EnsureSort); } protected bool ValidatePropertyDescriptor(PropertyDescriptor property) { if (property == null) throw new ArgumentNullException("property"); if (!this._validatedPropertyDescriptors.ContainsKey(property.ComponentType)) this._validatedPropertyDescriptors.Add(property.ComponentType, (typeof(TItem)).IsAssignableFrom(property.ComponentType)); return this._validatedPropertyDescriptors[property.ComponentType]; } private OrderedItem[] _GetItems() { this._EnsureSort(); return this._items; } public List<TItem> GetAllItems() { return this.GetWithLock<List<TItem>>(() => this._GetItems().Select(i => i.Item).ToList()); } public List<TItem> GetItems(int startIndex, int maxResults, string orderBy) { throw new NotImplementedException(); } #region IList<TItem> Members public int IndexOf(TItem item) { return this.GetWithLock<int>(() => { if (item == null || this._items.Length == 0) return -1; int index = this._GetItems().TakeWhile(i => !Object.ReferenceEquals(i.Item, item)).Count(); return (index == this._items.Length) ? -1 : index; }); } public TItem this[int index] { get { return this.GetWithLock<TItem>(() => this._GetItems()[index].Item); } } #endregion #region ICollection<TItem> Members public bool Contains(TItem item) { return this.GetWithLock<bool>(() => item != null && this._GetItems().Any(i => Object.ReferenceEquals(i, item))); } public void CopyTo(TItem[] array, int arrayIndex) { this.RunWithLock(() => this._GetItems().Select(i => i.Item).ToList().CopyTo(array, arrayIndex)); } public int Count { get { return this.GetWithLock<int>(() => this._items.Length); } } bool ICollection<TItem>.IsReadOnly { get { return true; } } #endregion #region IEnumerator<TItem> Members public IEnumerator<TItem> GetEnumerator() { return this.GetWithLock<IEnumerator<TItem>>(() => this._GetItems().Select(i => i.Item).ToList().GetEnumerator()); } #endregion #region System.Collections.IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetWithLock<System.Collections.IEnumerator>(() => this._GetItems().Select(i => i.Item).ToArray().GetEnumerator()); } #endregion #region IBindingList Members bool IBindingList.AllowEdit { get { return false; } } bool IBindingList.AllowNew { get { return false; } } bool IBindingList.AllowRemove { get { return false; } } public void _ApplySort(PropertyDescriptor property, ListSortDirection direction) { if (this._items.Length < 2) return; if (this._sortStack.Count > 0) { if (String.Compare(property.Name, this._sortStack.Last.Value.Item1.Property.Name, true) == 0) { if (direction == this._sortStack.Last.Value.Item2) return; this._sortStack.RemoveLast(); this._sortStack.AddLast(new Tuple<ItemPropertyComparer, ListSortDirection>(ItemPropertyComparer.Create(property), direction)); if (this._sortIndex >= this._items.Length) this._items = this._items.Reverse().ToArray(); return; } Tuple<ItemPropertyComparer, ListSortDirection> toRemove = this._sortStack.FirstOrDefault(i => String.Compare(i.Item1.Property.Name, property.Name, true) == 0); if (toRemove != null) { this._sortStack.Remove(toRemove); this._ResetInnerSort(); } } this._sortStack.AddLast(new Tuple<ItemPropertyComparer, ListSortDirection>(ItemPropertyComparer.Create(property), direction)); } public void ApplySort(PropertyDescriptor property, ListSortDirection direction) { if (!this.ValidatePropertyDescriptor(property)) throw new ArgumentOutOfRangeException("property", String.Format("Property descriptor's component object is not of type {0}.", typeof(TItem).FullName)); this.RunWithLock(() => this._ApplySort(property, direction)); } public bool IsSorted { get { return this.GetWithLock<bool>(() => this._sortStack.Count > 0); } } public void RemoveSort() { this.RunWithLock(() => { if (this._sortStack.Count == 0) return; this._sortStack.RemoveLast(); this._ResetInnerSort(); }); } public ListSortDirection SortDirection { get { return this.GetWithLock<ListSortDirection>(() => (this._sortStack.Count == 0) ? ListSortDirection.Ascending : this._sortStack.Last.Value.Item2); } } public PropertyDescriptor SortProperty { get { return this.GetWithLock<PropertyDescriptor>(() => (this._sortStack.Count == 0) ? null : this._sortStack.Last.Value.Item1.Property); } } bool IBindingList.SupportsChangeNotification { get { return false; } } bool IBindingList.SupportsSearching { get { return false; } } bool IBindingList.SupportsSorting { get { return true; } } #endregion #region System.Collections.IList Members bool System.Collections.IList.Contains(object value) { return this.Contains(value as TItem); } int System.Collections.IList.IndexOf(object value) { return this.IndexOf(value as TItem); } bool System.Collections.IList.IsFixedSize { get { return true; } } bool System.Collections.IList.IsReadOnly { get { return true; } } #endregion #region System.Collections.ICollection Members void System.Collections.ICollection.CopyTo(Array array, int index) { this.RunWithLock(() => this._GetItems().Select(i => i.Item).ToArray().CopyTo(array, index)); } bool System.Collections.ICollection.IsSynchronized { get { return true; } } public object SyncRoot { get { return this._syncRoot; } } #endregion #region Unsupported Members #region IList<TItem> Members void IList<TItem>.Insert(int index, TItem item) { throw new NotSupportedException(); } void IList<TItem>.RemoveAt(int index) { throw new NotSupportedException(); } TItem IList<TItem>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } #endregion #region ICollection<TItem> Members void ICollection<TItem>.Add(TItem item) { throw new NotSupportedException(); } void ICollection<TItem>.Clear() { throw new NotSupportedException(); } bool ICollection<TItem>.Remove(TItem item) { throw new NotSupportedException(); } #endregion #region IBindingList Members void IBindingList.AddIndex(PropertyDescriptor property) { throw new NotSupportedException(); } object IBindingList.AddNew() { throw new NotSupportedException(); } int IBindingList.Find(PropertyDescriptor property, object key) { throw new NotSupportedException(); } private event ListChangedEventHandler _listChanged; event ListChangedEventHandler IBindingList.ListChanged { add { this._listChanged += value; } remove { this._listChanged -= value; } } void IBindingList.RemoveIndex(PropertyDescriptor property) { throw new NotSupportedException(); } #endregion #region System.Collections.IList Members int System.Collections.IList.Add(object value) { throw new NotSupportedException(); } void System.Collections.IList.Clear() { throw new NotSupportedException(); } void System.Collections.IList.Insert(int index, object value) { throw new NotSupportedException(); } void System.Collections.IList.Remove(object value) { throw new NotSupportedException(); } void System.Collections.IList.RemoveAt(int index) { throw new NotSupportedException(); } object System.Collections.IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } #endregion #endregion } }
#if NET20 || NET40 || NET45 // Taken and adapted from Microsoft.Bcl.HashCode NuGet package // 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. /* The xxHash32 implementation is based on the code published by Yann Collet: https://raw.githubusercontent.com/Cyan4973/xxHash/5c174cfa4e45a42f94082dc0d4539b39696afea1/xxhash.c xxHash - Fast Hash algorithm Copyright (C) 2012-2016, Yann Collet BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You can contact the author at : - xxHash homepage: http://www.xxhash.com - xxHash source repository : https://github.com/Cyan4973/xxHash */ using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace System { // xxHash32 is used for the hash code. // https://github.com/Cyan4973/xxHash public struct HashCode { private static readonly uint s_seed = GenerateGlobalSeed(); private const uint Prime1 = 2654435761U; private const uint Prime2 = 2246822519U; private const uint Prime3 = 3266489917U; private const uint Prime4 = 668265263U; private const uint Prime5 = 374761393U; private uint _v1, _v2, _v3, _v4; private uint _queue1, _queue2, _queue3; private uint _length; private static uint GenerateGlobalSeed() { var random = new Random(); return (uint)(random.Next(1 << 30)) << 2 | (uint)(random.Next(1 << 2)); } public static int Combine<T1>(T1 value1) { // Provide a way of diffusing bits from something with a limited // input hash space. For example, many enums only have a few // possible hashes, only using the bottom few bits of the code. Some // collections are built on the assumption that hashes are spread // over a larger space, so diffusing the bits may help the // collection work more efficiently. var hc1 = (uint)(value1?.GetHashCode() ?? 0); uint hash = MixEmptyState(); hash += 4; hash = QueueRound(hash, hc1); hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2>(T1 value1, T2 value2) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); uint hash = MixEmptyState(); hash += 8; hash = QueueRound(hash, hc1); hash = QueueRound(hash, hc2); hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2, T3>(T1 value1, T2 value2, T3 value3) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); var hc3 = (uint)(value3?.GetHashCode() ?? 0); uint hash = MixEmptyState(); hash += 12; hash = QueueRound(hash, hc1); hash = QueueRound(hash, hc2); hash = QueueRound(hash, hc3); hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2, T3, T4>(T1 value1, T2 value2, T3 value3, T4 value4) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); var hc3 = (uint)(value3?.GetHashCode() ?? 0); var hc4 = (uint)(value4?.GetHashCode() ?? 0); Initialize(out uint v1, out uint v2, out uint v3, out uint v4); v1 = Round(v1, hc1); v2 = Round(v2, hc2); v3 = Round(v3, hc3); v4 = Round(v4, hc4); uint hash = MixState(v1, v2, v3, v4); hash += 16; hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2, T3, T4, T5>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); var hc3 = (uint)(value3?.GetHashCode() ?? 0); var hc4 = (uint)(value4?.GetHashCode() ?? 0); var hc5 = (uint)(value5?.GetHashCode() ?? 0); Initialize(out uint v1, out uint v2, out uint v3, out uint v4); v1 = Round(v1, hc1); v2 = Round(v2, hc2); v3 = Round(v3, hc3); v4 = Round(v4, hc4); uint hash = MixState(v1, v2, v3, v4); hash += 20; hash = QueueRound(hash, hc5); hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2, T3, T4, T5, T6>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); var hc3 = (uint)(value3?.GetHashCode() ?? 0); var hc4 = (uint)(value4?.GetHashCode() ?? 0); var hc5 = (uint)(value5?.GetHashCode() ?? 0); var hc6 = (uint)(value6?.GetHashCode() ?? 0); Initialize(out uint v1, out uint v2, out uint v3, out uint v4); v1 = Round(v1, hc1); v2 = Round(v2, hc2); v3 = Round(v3, hc3); v4 = Round(v4, hc4); uint hash = MixState(v1, v2, v3, v4); hash += 24; hash = QueueRound(hash, hc5); hash = QueueRound(hash, hc6); hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2, T3, T4, T5, T6, T7>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); var hc3 = (uint)(value3?.GetHashCode() ?? 0); var hc4 = (uint)(value4?.GetHashCode() ?? 0); var hc5 = (uint)(value5?.GetHashCode() ?? 0); var hc6 = (uint)(value6?.GetHashCode() ?? 0); var hc7 = (uint)(value7?.GetHashCode() ?? 0); Initialize(out uint v1, out uint v2, out uint v3, out uint v4); v1 = Round(v1, hc1); v2 = Round(v2, hc2); v3 = Round(v3, hc3); v4 = Round(v4, hc4); uint hash = MixState(v1, v2, v3, v4); hash += 28; hash = QueueRound(hash, hc5); hash = QueueRound(hash, hc6); hash = QueueRound(hash, hc7); hash = MixFinal(hash); return (int)hash; } public static int Combine<T1, T2, T3, T4, T5, T6, T7, T8>(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) { var hc1 = (uint)(value1?.GetHashCode() ?? 0); var hc2 = (uint)(value2?.GetHashCode() ?? 0); var hc3 = (uint)(value3?.GetHashCode() ?? 0); var hc4 = (uint)(value4?.GetHashCode() ?? 0); var hc5 = (uint)(value5?.GetHashCode() ?? 0); var hc6 = (uint)(value6?.GetHashCode() ?? 0); var hc7 = (uint)(value7?.GetHashCode() ?? 0); var hc8 = (uint)(value8?.GetHashCode() ?? 0); Initialize(out uint v1, out uint v2, out uint v3, out uint v4); v1 = Round(v1, hc1); v2 = Round(v2, hc2); v3 = Round(v3, hc3); v4 = Round(v4, hc4); v1 = Round(v1, hc5); v2 = Round(v2, hc6); v3 = Round(v3, hc7); v4 = Round(v4, hc8); uint hash = MixState(v1, v2, v3, v4); hash += 32; hash = MixFinal(hash); return (int)hash; } private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) { v1 = s_seed + Prime1 + Prime2; v2 = s_seed + Prime2; v3 = s_seed; v4 = s_seed - Prime1; } private static uint Round(uint hash, uint input) { return RotateLeft(hash + input * Prime2, 13) * Prime1; } private static uint QueueRound(uint hash, uint queuedValue) { return RotateLeft(hash + queuedValue * Prime3, 17) * Prime4; } private static uint MixState(uint v1, uint v2, uint v3, uint v4) { return RotateLeft(v1, 1) + RotateLeft(v2, 7) + RotateLeft(v3, 12) + RotateLeft(v4, 18); } private static uint RotateLeft(uint value, int offset) => (value << offset) | (value >> (32 - offset)); private static uint MixEmptyState() { return s_seed + Prime5; } private static uint MixFinal(uint hash) { hash ^= hash >> 15; hash *= Prime2; hash ^= hash >> 13; hash *= Prime3; hash ^= hash >> 16; return hash; } public void Add<T>(T value) { Add(value?.GetHashCode() ?? 0); } public void Add<T>(T value, IEqualityComparer<T>? comparer) { Add(comparer != null && value != null ? comparer.GetHashCode(value) : (value?.GetHashCode() ?? 0)); } private void Add(int value) { // The original xxHash works as follows: // 0. Initialize immediately. We can't do this in a struct (no // default ctor). // 1. Accumulate blocks of length 16 (4 uints) into 4 accumulators. // 2. Accumulate remaining blocks of length 4 (1 uint) into the // hash. // 3. Accumulate remaining blocks of length 1 into the hash. // There is no need for #3 as this type only accepts ints. _queue1, // _queue2 and _queue3 are basically a buffer so that when // ToHashCode is called we can execute #2 correctly. // We need to initialize the xxHash32 state (_v1 to _v4) lazily (see // #0) nd the last place that can be done if you look at the // original code is just before the first block of 16 bytes is mixed // in. The xxHash32 state is never used for streams containing fewer // than 16 bytes. // To see what's really going on here, have a look at the Combine // methods. var val = (uint)value; // Storing the value of _length locally shaves of quite a few bytes // in the resulting machine code. uint previousLength = _length++; uint position = previousLength % 4; // Switch can't be inlined. if (position == 0) _queue1 = val; else if (position == 1) _queue2 = val; else if (position == 2) _queue3 = val; else // position == 3 { if (previousLength == 3) Initialize(out _v1, out _v2, out _v3, out _v4); _v1 = Round(_v1, _queue1); _v2 = Round(_v2, _queue2); _v3 = Round(_v3, _queue3); _v4 = Round(_v4, val); } } public int ToHashCode() { // Storing the value of _length locally shaves of quite a few bytes // in the resulting machine code. uint length = _length; // position refers to the *next* queue position in this method, so // position == 1 means that _queue1 is populated; _queue2 would have // been populated on the next call to Add. uint position = length % 4; // If the length is less than 4, _v1 to _v4 don't contain anything // yet. xxHash32 treats this differently. uint hash = length < 4 ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4); // _length is incremented once per Add(Int32) and is therefore 4 // times too small (xxHash length is in bytes, not ints). hash += length * 4; // Mix what remains in the queue // Switch can't be inlined right now, so use as few branches as // possible by manually excluding impossible scenarios (position > 1 // is always false if position is not > 0). if (position > 0) { hash = QueueRound(hash, _queue1); if (position > 1) { hash = QueueRound(hash, _queue2); if (position > 2) hash = QueueRound(hash, _queue3); } } hash = MixFinal(hash); return (int)hash; } #pragma warning disable 0809 // Obsolete member 'memberA' overrides non-obsolete member 'memberB'. // Disallowing GetHashCode and Equals is by design // * We decided to not override GetHashCode() to produce the hash code // as this would be weird, both naming-wise as well as from a // behavioral standpoint (GetHashCode() should return the object's // hash code, not the one being computed). // * Even though ToHashCode() can be called safely multiple times on // this implementation, it is not part of the contract. If the // implementation has to change in the future we don't want to worry // about people who might have incorrectly used this type. [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => throw new NotSupportedException("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code."); [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) => throw new NotSupportedException("HashCode is a mutable struct and should not be compared with other HashCodes."); #pragma warning restore 0809 } } #else [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.HashCode))] #endif
using System; using PublicApiGeneratorTests.Examples; using Xunit; namespace PublicApiGeneratorTests { public class Class_constructors : ApiGeneratorTestsBase { [Fact] public void Should_output_default_constructor() { AssertPublicApi<ClassWithDefaultConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithDefaultConstructor { public ClassWithDefaultConstructor() { } } }"); } [Fact] public void Should_output_protected_default_constructor_in_abstract_class() { AssertPublicApi<AbstractClass>( @"namespace PublicApiGeneratorTests.Examples { public abstract class AbstractClass { protected AbstractClass() { } } }"); } [Fact] public void Should_not_output_protected_default_constructor_in_abstract_class_with_other_constructors() { AssertPublicApi<AbstractClassWithCtors>( @"namespace PublicApiGeneratorTests.Examples { public abstract class AbstractClassWithCtors { public AbstractClassWithCtors(int i) { } protected AbstractClassWithCtors(string j) { } } }"); } [Fact] public void Should_not_output_private_constructor_from_abstract_class() { AssertPublicApi<AbstractClassWithPrivateCtor>( @"namespace PublicApiGeneratorTests.Examples { public abstract class AbstractClassWithPrivateCtor { } }"); } [Fact] public void Should_not_output_internal_constructor() { AssertPublicApi<ClassWithInternalConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithInternalConstructor { } }"); } [Fact] public void Should_not_output_private_constructor() { AssertPublicApi<ClassWithPrivateConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPrivateConstructor { } }"); } [Fact] public void Should_not_output_private_protected_constructor() { AssertPublicApi<ClassWithPrivateProtectedConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPrivateProtectedConstructor { } }"); } [Fact] public void Should_output_public_constructor() { AssertPublicApi<ClassWithPublicConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithPublicConstructor { public ClassWithPublicConstructor() { } } }"); } [Fact] public void Should_output_protected_constructor() { AssertPublicApi<ClassWithProtectedConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedConstructor { protected ClassWithProtectedConstructor() { } } }"); } [Fact] public void Should_output_protected_internal_constructor() { AssertPublicApi<ClassWithProtectedInternalConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithProtectedInternalConstructor { protected ClassWithProtectedInternalConstructor() { } } }"); } [Fact] public void Should_output_constructor_parameters() { AssertPublicApi<ClassWithConstructorWithParameters>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithConstructorWithParameters { public ClassWithConstructorWithParameters(int intValue, string stringValue, PublicApiGeneratorTests.Examples.ComplexType complexType, PublicApiGeneratorTests.Examples.GenericType<int> genericType, ref int intValueByRef, in int intValueByIn) { } } }"); } [Fact] public void Should_output_multiple_constructors() { // TODO: Not sure about ordering here AssertPublicApi<ClassWithMultipleConstructors>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithMultipleConstructors { public ClassWithMultipleConstructors() { } protected ClassWithMultipleConstructors(int value) { } } }"); } [Fact] public void Should_output_constructor_default_parameter_values() { AssertPublicApi<ClassWithConstructorWithDefaultValues>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithConstructorWithDefaultValues { public ClassWithConstructorWithDefaultValues(int intValue = 42, string stringValue = ""hello world"", System.Type typeValue = null) { } } }"); } [Fact] public void Should_not_output_static_constructor_of_class() { AssertPublicApi<ClassWithStaticConstructor>( @"namespace PublicApiGeneratorTests.Examples { public class ClassWithStaticConstructor { public ClassWithStaticConstructor() { } } }"); } [Fact] public void Should_not_output_static_constructor_of_static_class() { AssertPublicApi(typeof(StaticClassWithStaticConstructor), @"namespace PublicApiGeneratorTests.Examples { public static class StaticClassWithStaticConstructor { } }"); } } // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable UnusedParameter.Local // ReSharper disable UnusedMember.Global namespace Examples { public class ClassWithDefaultConstructor { } public class ClassWithInternalConstructor { internal ClassWithInternalConstructor() { } } public class ClassWithPrivateConstructor { private ClassWithPrivateConstructor() { } } public class ClassWithPrivateProtectedConstructor { private protected ClassWithPrivateProtectedConstructor() { } } public class ClassWithProtectedConstructor { protected ClassWithProtectedConstructor() { } } public class ClassWithProtectedInternalConstructor { protected internal ClassWithProtectedInternalConstructor() { } } public class ClassWithPublicConstructor { public ClassWithPublicConstructor() { Console.WriteLine(); } } public class ClassWithConstructorWithParameters { public ClassWithConstructorWithParameters(int intValue, string stringValue, ComplexType complexType, GenericType<int> genericType, ref int intValueByRef, in int intValueByIn) { } } public class ClassWithMultipleConstructors { public ClassWithMultipleConstructors() { } protected ClassWithMultipleConstructors(int value) { } } public class ClassWithConstructorWithDefaultValues { public ClassWithConstructorWithDefaultValues(int intValue = 42, string stringValue = "hello world", Type typeValue = null!) { } } public class ClassWithStaticConstructor { static ClassWithStaticConstructor() { } } public static class StaticClassWithStaticConstructor { static StaticClassWithStaticConstructor() { } } public abstract class AbstractClassWithCtors { public AbstractClassWithCtors(int i) { } protected AbstractClassWithCtors(string j) { } } public abstract class AbstractClassWithPrivateCtor { private AbstractClassWithPrivateCtor(int i) { } } } // ReSharper restore UnusedMember.Global // ReSharper restore UnusedParameter.Local // ReSharper restore ClassNeverInstantiated.Global }
// 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.Abstractions; using System; using System.Globalization; using System.Xml; public class CustomUrlResolver : XmlUrlResolver { private ITestOutputHelper _output; public CustomUrlResolver(ITestOutputHelper output) { _output = output; } public override Object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { _output.WriteLine("Getting {0}", absoluteUri); return base.GetEntity(absoluteUri, role, ofObjectToReturn); } } public class CustomNullResolver : XmlUrlResolver { private ITestOutputHelper _output; public CustomNullResolver(ITestOutputHelper output) { _output = output; } public override Object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { _output.WriteLine("Getting {0}", absoluteUri); return null; } } // These two classes are for bug 78587 repro public class Id { private string _id; public Id(string id) { _id = id; } public string GetId() { return _id; } } public class Capitalizer { public string Capitalize(string str) { return str.ToUpper(); } } public class MyObject { private int _iUniqueVal; private double _dNotUsed; private String _strTestTmp; private ITestOutputHelper _output; // State Tests public MyObject(int n, ITestOutputHelper output) { _iUniqueVal = n; _output = output; } public MyObject(double n, ITestOutputHelper output) { _dNotUsed = n; _output = output; } public void DecreaseCounter() { _iUniqueVal--; } public String ReduceCount(double n) { _iUniqueVal -= (int)n; return _iUniqueVal.ToString(); } public String AddToString(String str) { _strTestTmp = String.Concat(_strTestTmp, str); return _strTestTmp; } public override String ToString() { String S = String.Format("My Custom Object has a value of {0}", _iUniqueVal); return S; } public String PublicFunction() { return "Inside Public Function"; } private String PrivateFunction() { return "Inside Private Function"; } protected String ProtectedFunction() { return "Inside Protected Function"; } private String DefaultFunction() { return "Default Function"; } // Return types tests public int MyValue() { return _iUniqueVal; } public double GetUnitialized() { return _dNotUsed; } public String GetNull() { return null; } // Basic Tests public String Fn1() { return "Test1"; } public String Fn2() { return "Test2"; } public String Fn3() { return "Test3"; } //Output Tests public void ConsoleWrite() { _output.WriteLine("\r\r\n\n> Where did I see this"); } public String MessMeUp() { return ">\" $tmp >;\'\t \n&"; } public String MessMeUp2() { return "<xsl:variable name=\"tmp\"/>"; } public String MessMeUp3() { return "</xsl:stylesheet>"; } //Recursion Tests public String RecursionSample() { return (Factorial(5)).ToString(); } public int Factorial(int n) { if (n < 1) return 1; return (n * Factorial(n - 1)); } //Overload by type public String OverloadType(String str) { return "String Overlaod"; } public String OverloadType(int i) { return "Int Overlaod"; } public String OverloadType(double d) { return "Double Overload"; } //Overload by arg public String OverloadArgTest(string s1) { return "String"; } public String OverloadArgTest(string s1, string s2) { return "String, String"; } public String OverloadArgTest(string s1, double d, string s2) { return "String, Double, String"; } public String OverloadArgTest(string s1, string s2, double d) { return "String, String, Double"; } // Overload conversion tests public String IntArg(int i) { return "Int"; } public String BoolArg(Boolean i) { return "Boolean"; } // Arg Tests public String ArgBoolTest(Boolean bFlag) { if (bFlag) return "Statement is True"; return "Statement is False"; } public String ArgDoubleTest(double d) { String s = String.Format("Received a double with value {0}", Convert.ToString(d, NumberFormatInfo.InvariantInfo)); return s; } public String ArgStringTest(String s) { String s1 = String.Format("Received a string with value: {0}", s); return s1; } //Return tests public String ReturnString() { return "Hello world"; } public int ReturnInt() { return 10; } public double ReturnDouble() { return 022.4127600; } public Boolean ReturnBooleanTrue() { return true; } public Boolean ReturnBooleanFalse() { return false; } public MyObject ReturnOther() { return this; } public void DoNothing() { } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Billing.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Cloud.Iam.V1; using Google.Protobuf.WellKnownTypes; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedCloudBillingClientSnippets { /// <summary>Snippet for GetBillingAccount</summary> public void GetBillingAccountRequestObject() { // Snippet: GetBillingAccount(GetBillingAccountRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) GetBillingAccountRequest request = new GetBillingAccountRequest { BillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), }; // Make the request BillingAccount response = cloudBillingClient.GetBillingAccount(request); // End snippet } /// <summary>Snippet for GetBillingAccountAsync</summary> public async Task GetBillingAccountRequestObjectAsync() { // Snippet: GetBillingAccountAsync(GetBillingAccountRequest, CallSettings) // Additional: GetBillingAccountAsync(GetBillingAccountRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) GetBillingAccountRequest request = new GetBillingAccountRequest { BillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), }; // Make the request BillingAccount response = await cloudBillingClient.GetBillingAccountAsync(request); // End snippet } /// <summary>Snippet for GetBillingAccount</summary> public void GetBillingAccount() { // Snippet: GetBillingAccount(string, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string name = "billingAccounts/[BILLING_ACCOUNT]"; // Make the request BillingAccount response = cloudBillingClient.GetBillingAccount(name); // End snippet } /// <summary>Snippet for GetBillingAccountAsync</summary> public async Task GetBillingAccountAsync() { // Snippet: GetBillingAccountAsync(string, CallSettings) // Additional: GetBillingAccountAsync(string, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string name = "billingAccounts/[BILLING_ACCOUNT]"; // Make the request BillingAccount response = await cloudBillingClient.GetBillingAccountAsync(name); // End snippet } /// <summary>Snippet for GetBillingAccount</summary> public void GetBillingAccountResourceNames() { // Snippet: GetBillingAccount(BillingAccountName, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) BillingAccountName name = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"); // Make the request BillingAccount response = cloudBillingClient.GetBillingAccount(name); // End snippet } /// <summary>Snippet for GetBillingAccountAsync</summary> public async Task GetBillingAccountResourceNamesAsync() { // Snippet: GetBillingAccountAsync(BillingAccountName, CallSettings) // Additional: GetBillingAccountAsync(BillingAccountName, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) BillingAccountName name = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"); // Make the request BillingAccount response = await cloudBillingClient.GetBillingAccountAsync(name); // End snippet } /// <summary>Snippet for ListBillingAccounts</summary> public void ListBillingAccountsRequestObject() { // Snippet: ListBillingAccounts(ListBillingAccountsRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) ListBillingAccountsRequest request = new ListBillingAccountsRequest { Filter = "", }; // Make the request PagedEnumerable<ListBillingAccountsResponse, BillingAccount> response = cloudBillingClient.ListBillingAccounts(request); // Iterate over all response items, lazily performing RPCs as required foreach (BillingAccount item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBillingAccountsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (BillingAccount item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<BillingAccount> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (BillingAccount item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBillingAccountsAsync</summary> public async Task ListBillingAccountsRequestObjectAsync() { // Snippet: ListBillingAccountsAsync(ListBillingAccountsRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) ListBillingAccountsRequest request = new ListBillingAccountsRequest { Filter = "", }; // Make the request PagedAsyncEnumerable<ListBillingAccountsResponse, BillingAccount> response = cloudBillingClient.ListBillingAccountsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((BillingAccount item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBillingAccountsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (BillingAccount item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<BillingAccount> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (BillingAccount item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBillingAccounts</summary> public void ListBillingAccounts() { // Snippet: ListBillingAccounts(string, int?, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Make the request PagedEnumerable<ListBillingAccountsResponse, BillingAccount> response = cloudBillingClient.ListBillingAccounts(); // Iterate over all response items, lazily performing RPCs as required foreach (BillingAccount item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListBillingAccountsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (BillingAccount item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<BillingAccount> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (BillingAccount item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListBillingAccountsAsync</summary> public async Task ListBillingAccountsAsync() { // Snippet: ListBillingAccountsAsync(string, int?, CallSettings) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Make the request PagedAsyncEnumerable<ListBillingAccountsResponse, BillingAccount> response = cloudBillingClient.ListBillingAccountsAsync(); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((BillingAccount item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListBillingAccountsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (BillingAccount item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<BillingAccount> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (BillingAccount item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for UpdateBillingAccount</summary> public void UpdateBillingAccountRequestObject() { // Snippet: UpdateBillingAccount(UpdateBillingAccountRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) UpdateBillingAccountRequest request = new UpdateBillingAccountRequest { BillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), Account = new BillingAccount(), UpdateMask = new FieldMask(), }; // Make the request BillingAccount response = cloudBillingClient.UpdateBillingAccount(request); // End snippet } /// <summary>Snippet for UpdateBillingAccountAsync</summary> public async Task UpdateBillingAccountRequestObjectAsync() { // Snippet: UpdateBillingAccountAsync(UpdateBillingAccountRequest, CallSettings) // Additional: UpdateBillingAccountAsync(UpdateBillingAccountRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) UpdateBillingAccountRequest request = new UpdateBillingAccountRequest { BillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), Account = new BillingAccount(), UpdateMask = new FieldMask(), }; // Make the request BillingAccount response = await cloudBillingClient.UpdateBillingAccountAsync(request); // End snippet } /// <summary>Snippet for UpdateBillingAccount</summary> public void UpdateBillingAccount() { // Snippet: UpdateBillingAccount(string, BillingAccount, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string name = "billingAccounts/[BILLING_ACCOUNT]"; BillingAccount account = new BillingAccount(); // Make the request BillingAccount response = cloudBillingClient.UpdateBillingAccount(name, account); // End snippet } /// <summary>Snippet for UpdateBillingAccountAsync</summary> public async Task UpdateBillingAccountAsync() { // Snippet: UpdateBillingAccountAsync(string, BillingAccount, CallSettings) // Additional: UpdateBillingAccountAsync(string, BillingAccount, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string name = "billingAccounts/[BILLING_ACCOUNT]"; BillingAccount account = new BillingAccount(); // Make the request BillingAccount response = await cloudBillingClient.UpdateBillingAccountAsync(name, account); // End snippet } /// <summary>Snippet for UpdateBillingAccount</summary> public void UpdateBillingAccountResourceNames() { // Snippet: UpdateBillingAccount(BillingAccountName, BillingAccount, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) BillingAccountName name = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"); BillingAccount account = new BillingAccount(); // Make the request BillingAccount response = cloudBillingClient.UpdateBillingAccount(name, account); // End snippet } /// <summary>Snippet for UpdateBillingAccountAsync</summary> public async Task UpdateBillingAccountResourceNamesAsync() { // Snippet: UpdateBillingAccountAsync(BillingAccountName, BillingAccount, CallSettings) // Additional: UpdateBillingAccountAsync(BillingAccountName, BillingAccount, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) BillingAccountName name = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"); BillingAccount account = new BillingAccount(); // Make the request BillingAccount response = await cloudBillingClient.UpdateBillingAccountAsync(name, account); // End snippet } /// <summary>Snippet for CreateBillingAccount</summary> public void CreateBillingAccountRequestObject() { // Snippet: CreateBillingAccount(CreateBillingAccountRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) CreateBillingAccountRequest request = new CreateBillingAccountRequest { BillingAccount = new BillingAccount(), }; // Make the request BillingAccount response = cloudBillingClient.CreateBillingAccount(request); // End snippet } /// <summary>Snippet for CreateBillingAccountAsync</summary> public async Task CreateBillingAccountRequestObjectAsync() { // Snippet: CreateBillingAccountAsync(CreateBillingAccountRequest, CallSettings) // Additional: CreateBillingAccountAsync(CreateBillingAccountRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) CreateBillingAccountRequest request = new CreateBillingAccountRequest { BillingAccount = new BillingAccount(), }; // Make the request BillingAccount response = await cloudBillingClient.CreateBillingAccountAsync(request); // End snippet } /// <summary>Snippet for CreateBillingAccount</summary> public void CreateBillingAccount() { // Snippet: CreateBillingAccount(BillingAccount, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) BillingAccount billingAccount = new BillingAccount(); // Make the request BillingAccount response = cloudBillingClient.CreateBillingAccount(billingAccount); // End snippet } /// <summary>Snippet for CreateBillingAccountAsync</summary> public async Task CreateBillingAccountAsync() { // Snippet: CreateBillingAccountAsync(BillingAccount, CallSettings) // Additional: CreateBillingAccountAsync(BillingAccount, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) BillingAccount billingAccount = new BillingAccount(); // Make the request BillingAccount response = await cloudBillingClient.CreateBillingAccountAsync(billingAccount); // End snippet } /// <summary>Snippet for ListProjectBillingInfo</summary> public void ListProjectBillingInfoRequestObject() { // Snippet: ListProjectBillingInfo(ListProjectBillingInfoRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) ListProjectBillingInfoRequest request = new ListProjectBillingInfoRequest { BillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), }; // Make the request PagedEnumerable<ListProjectBillingInfoResponse, ProjectBillingInfo> response = cloudBillingClient.ListProjectBillingInfo(request); // Iterate over all response items, lazily performing RPCs as required foreach (ProjectBillingInfo item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListProjectBillingInfoResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProjectBillingInfo item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProjectBillingInfo> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProjectBillingInfo item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProjectBillingInfoAsync</summary> public async Task ListProjectBillingInfoRequestObjectAsync() { // Snippet: ListProjectBillingInfoAsync(ListProjectBillingInfoRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) ListProjectBillingInfoRequest request = new ListProjectBillingInfoRequest { BillingAccountName = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"), }; // Make the request PagedAsyncEnumerable<ListProjectBillingInfoResponse, ProjectBillingInfo> response = cloudBillingClient.ListProjectBillingInfoAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ProjectBillingInfo item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProjectBillingInfoResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProjectBillingInfo item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProjectBillingInfo> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProjectBillingInfo item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProjectBillingInfo</summary> public void ListProjectBillingInfo() { // Snippet: ListProjectBillingInfo(string, string, int?, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string name = "billingAccounts/[BILLING_ACCOUNT]"; // Make the request PagedEnumerable<ListProjectBillingInfoResponse, ProjectBillingInfo> response = cloudBillingClient.ListProjectBillingInfo(name); // Iterate over all response items, lazily performing RPCs as required foreach (ProjectBillingInfo item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListProjectBillingInfoResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProjectBillingInfo item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProjectBillingInfo> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProjectBillingInfo item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProjectBillingInfoAsync</summary> public async Task ListProjectBillingInfoAsync() { // Snippet: ListProjectBillingInfoAsync(string, string, int?, CallSettings) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string name = "billingAccounts/[BILLING_ACCOUNT]"; // Make the request PagedAsyncEnumerable<ListProjectBillingInfoResponse, ProjectBillingInfo> response = cloudBillingClient.ListProjectBillingInfoAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ProjectBillingInfo item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProjectBillingInfoResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProjectBillingInfo item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProjectBillingInfo> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProjectBillingInfo item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProjectBillingInfo</summary> public void ListProjectBillingInfoResourceNames() { // Snippet: ListProjectBillingInfo(BillingAccountName, string, int?, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) BillingAccountName name = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"); // Make the request PagedEnumerable<ListProjectBillingInfoResponse, ProjectBillingInfo> response = cloudBillingClient.ListProjectBillingInfo(name); // Iterate over all response items, lazily performing RPCs as required foreach (ProjectBillingInfo item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListProjectBillingInfoResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProjectBillingInfo item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProjectBillingInfo> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProjectBillingInfo item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListProjectBillingInfoAsync</summary> public async Task ListProjectBillingInfoResourceNamesAsync() { // Snippet: ListProjectBillingInfoAsync(BillingAccountName, string, int?, CallSettings) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) BillingAccountName name = BillingAccountName.FromBillingAccount("[BILLING_ACCOUNT]"); // Make the request PagedAsyncEnumerable<ListProjectBillingInfoResponse, ProjectBillingInfo> response = cloudBillingClient.ListProjectBillingInfoAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((ProjectBillingInfo item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListProjectBillingInfoResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ProjectBillingInfo item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ProjectBillingInfo> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ProjectBillingInfo item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetProjectBillingInfo</summary> public void GetProjectBillingInfoRequestObject() { // Snippet: GetProjectBillingInfo(GetProjectBillingInfoRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) GetProjectBillingInfoRequest request = new GetProjectBillingInfoRequest { Name = "", }; // Make the request ProjectBillingInfo response = cloudBillingClient.GetProjectBillingInfo(request); // End snippet } /// <summary>Snippet for GetProjectBillingInfoAsync</summary> public async Task GetProjectBillingInfoRequestObjectAsync() { // Snippet: GetProjectBillingInfoAsync(GetProjectBillingInfoRequest, CallSettings) // Additional: GetProjectBillingInfoAsync(GetProjectBillingInfoRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) GetProjectBillingInfoRequest request = new GetProjectBillingInfoRequest { Name = "", }; // Make the request ProjectBillingInfo response = await cloudBillingClient.GetProjectBillingInfoAsync(request); // End snippet } /// <summary>Snippet for GetProjectBillingInfo</summary> public void GetProjectBillingInfo() { // Snippet: GetProjectBillingInfo(string, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string name = ""; // Make the request ProjectBillingInfo response = cloudBillingClient.GetProjectBillingInfo(name); // End snippet } /// <summary>Snippet for GetProjectBillingInfoAsync</summary> public async Task GetProjectBillingInfoAsync() { // Snippet: GetProjectBillingInfoAsync(string, CallSettings) // Additional: GetProjectBillingInfoAsync(string, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string name = ""; // Make the request ProjectBillingInfo response = await cloudBillingClient.GetProjectBillingInfoAsync(name); // End snippet } /// <summary>Snippet for UpdateProjectBillingInfo</summary> public void UpdateProjectBillingInfoRequestObject() { // Snippet: UpdateProjectBillingInfo(UpdateProjectBillingInfoRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) UpdateProjectBillingInfoRequest request = new UpdateProjectBillingInfoRequest { Name = "", ProjectBillingInfo = new ProjectBillingInfo(), }; // Make the request ProjectBillingInfo response = cloudBillingClient.UpdateProjectBillingInfo(request); // End snippet } /// <summary>Snippet for UpdateProjectBillingInfoAsync</summary> public async Task UpdateProjectBillingInfoRequestObjectAsync() { // Snippet: UpdateProjectBillingInfoAsync(UpdateProjectBillingInfoRequest, CallSettings) // Additional: UpdateProjectBillingInfoAsync(UpdateProjectBillingInfoRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) UpdateProjectBillingInfoRequest request = new UpdateProjectBillingInfoRequest { Name = "", ProjectBillingInfo = new ProjectBillingInfo(), }; // Make the request ProjectBillingInfo response = await cloudBillingClient.UpdateProjectBillingInfoAsync(request); // End snippet } /// <summary>Snippet for UpdateProjectBillingInfo</summary> public void UpdateProjectBillingInfo() { // Snippet: UpdateProjectBillingInfo(string, ProjectBillingInfo, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string name = ""; ProjectBillingInfo projectBillingInfo = new ProjectBillingInfo(); // Make the request ProjectBillingInfo response = cloudBillingClient.UpdateProjectBillingInfo(name, projectBillingInfo); // End snippet } /// <summary>Snippet for UpdateProjectBillingInfoAsync</summary> public async Task UpdateProjectBillingInfoAsync() { // Snippet: UpdateProjectBillingInfoAsync(string, ProjectBillingInfo, CallSettings) // Additional: UpdateProjectBillingInfoAsync(string, ProjectBillingInfo, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string name = ""; ProjectBillingInfo projectBillingInfo = new ProjectBillingInfo(); // Make the request ProjectBillingInfo response = await cloudBillingClient.UpdateProjectBillingInfoAsync(name, projectBillingInfo); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicyRequestObject() { // Snippet: GetIamPolicy(GetIamPolicyRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Options = new GetPolicyOptions(), }; // Make the request Policy response = cloudBillingClient.GetIamPolicy(request); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyRequestObjectAsync() { // Snippet: GetIamPolicyAsync(GetIamPolicyRequest, CallSettings) // Additional: GetIamPolicyAsync(GetIamPolicyRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) GetIamPolicyRequest request = new GetIamPolicyRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Options = new GetPolicyOptions(), }; // Make the request Policy response = await cloudBillingClient.GetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicy() { // Snippet: GetIamPolicy(string, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string resource = "a/wildcard/resource"; // Make the request Policy response = cloudBillingClient.GetIamPolicy(resource); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyAsync() { // Snippet: GetIamPolicyAsync(string, CallSettings) // Additional: GetIamPolicyAsync(string, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; // Make the request Policy response = await cloudBillingClient.GetIamPolicyAsync(resource); // End snippet } /// <summary>Snippet for GetIamPolicy</summary> public void GetIamPolicyResourceNames() { // Snippet: GetIamPolicy(IResourceName, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) IResourceName resource = new UnparsedResourceName("a/wildcard/resource"); // Make the request Policy response = cloudBillingClient.GetIamPolicy(resource); // End snippet } /// <summary>Snippet for GetIamPolicyAsync</summary> public async Task GetIamPolicyResourceNamesAsync() { // Snippet: GetIamPolicyAsync(IResourceName, CallSettings) // Additional: GetIamPolicyAsync(IResourceName, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) IResourceName resource = new UnparsedResourceName("a/wildcard/resource"); // Make the request Policy response = await cloudBillingClient.GetIamPolicyAsync(resource); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicyRequestObject() { // Snippet: SetIamPolicy(SetIamPolicyRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Policy = new Policy(), }; // Make the request Policy response = cloudBillingClient.SetIamPolicy(request); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyRequestObjectAsync() { // Snippet: SetIamPolicyAsync(SetIamPolicyRequest, CallSettings) // Additional: SetIamPolicyAsync(SetIamPolicyRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Policy = new Policy(), }; // Make the request Policy response = await cloudBillingClient.SetIamPolicyAsync(request); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicy() { // Snippet: SetIamPolicy(string, Policy, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string resource = "a/wildcard/resource"; Policy policy = new Policy(); // Make the request Policy response = cloudBillingClient.SetIamPolicy(resource, policy); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyAsync() { // Snippet: SetIamPolicyAsync(string, Policy, CallSettings) // Additional: SetIamPolicyAsync(string, Policy, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; Policy policy = new Policy(); // Make the request Policy response = await cloudBillingClient.SetIamPolicyAsync(resource, policy); // End snippet } /// <summary>Snippet for SetIamPolicy</summary> public void SetIamPolicyResourceNames() { // Snippet: SetIamPolicy(IResourceName, Policy, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) IResourceName resource = new UnparsedResourceName("a/wildcard/resource"); Policy policy = new Policy(); // Make the request Policy response = cloudBillingClient.SetIamPolicy(resource, policy); // End snippet } /// <summary>Snippet for SetIamPolicyAsync</summary> public async Task SetIamPolicyResourceNamesAsync() { // Snippet: SetIamPolicyAsync(IResourceName, Policy, CallSettings) // Additional: SetIamPolicyAsync(IResourceName, Policy, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) IResourceName resource = new UnparsedResourceName("a/wildcard/resource"); Policy policy = new Policy(); // Make the request Policy response = await cloudBillingClient.SetIamPolicyAsync(resource, policy); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissionsRequestObject() { // Snippet: TestIamPermissions(TestIamPermissionsRequest, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Permissions = { "", }, }; // Make the request TestIamPermissionsResponse response = cloudBillingClient.TestIamPermissions(request); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsRequestObjectAsync() { // Snippet: TestIamPermissionsAsync(TestIamPermissionsRequest, CallSettings) // Additional: TestIamPermissionsAsync(TestIamPermissionsRequest, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) TestIamPermissionsRequest request = new TestIamPermissionsRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Permissions = { "", }, }; // Make the request TestIamPermissionsResponse response = await cloudBillingClient.TestIamPermissionsAsync(request); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissions() { // Snippet: TestIamPermissions(string, IEnumerable<string>, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) string resource = "a/wildcard/resource"; IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = cloudBillingClient.TestIamPermissions(resource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsAsync() { // Snippet: TestIamPermissionsAsync(string, IEnumerable<string>, CallSettings) // Additional: TestIamPermissionsAsync(string, IEnumerable<string>, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) string resource = "a/wildcard/resource"; IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = await cloudBillingClient.TestIamPermissionsAsync(resource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissions</summary> public void TestIamPermissionsResourceNames() { // Snippet: TestIamPermissions(IResourceName, IEnumerable<string>, CallSettings) // Create client CloudBillingClient cloudBillingClient = CloudBillingClient.Create(); // Initialize request argument(s) IResourceName resource = new UnparsedResourceName("a/wildcard/resource"); IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = cloudBillingClient.TestIamPermissions(resource, permissions); // End snippet } /// <summary>Snippet for TestIamPermissionsAsync</summary> public async Task TestIamPermissionsResourceNamesAsync() { // Snippet: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CallSettings) // Additional: TestIamPermissionsAsync(IResourceName, IEnumerable<string>, CancellationToken) // Create client CloudBillingClient cloudBillingClient = await CloudBillingClient.CreateAsync(); // Initialize request argument(s) IResourceName resource = new UnparsedResourceName("a/wildcard/resource"); IEnumerable<string> permissions = new string[] { "", }; // Make the request TestIamPermissionsResponse response = await cloudBillingClient.TestIamPermissionsAsync(resource, permissions); // End snippet } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using Microsoft.Azure; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Protocol; using Newtonsoft.Json; using System.Linq; /// <summary> /// Contains information about the execution of a Job Preparation task on a /// compute node. /// </summary> public partial class JobPreparationTaskExecutionInformation { /// <summary> /// Initializes a new instance of the /// JobPreparationTaskExecutionInformation class. /// </summary> public JobPreparationTaskExecutionInformation() { CustomInit(); } /// <summary> /// Initializes a new instance of the /// JobPreparationTaskExecutionInformation class. /// </summary> /// <param name="startTime">The time at which the task started /// running.</param> /// <param name="state">The current state of the Job Preparation task /// on the compute node.</param> /// <param name="retryCount">The number of times the task has been /// retried by the Batch service. Task application failures (non-zero /// exit code) are retried, pre-processing errors (the task could not /// be run) and file upload errors are not retried. The Batch service /// will retry the task up to the limit specified by the /// constraints.</param> /// <param name="endTime">The time at which the Job Preparation task /// completed.</param> /// <param name="taskRootDirectory">The root directory of the Job /// Preparation task on the compute node. You can use this path to /// retrieve files created by the task, such as log files.</param> /// <param name="taskRootDirectoryUrl">The URL to the root directory of /// the Job Preparation task on the compute node.</param> /// <param name="exitCode">The exit code of the program specified on /// the task command line.</param> /// <param name="failureInfo">Information describing the task failure, /// if any.</param> /// <param name="lastRetryTime">The most recent time at which a retry /// of the Job Preparation task started running.</param> /// <param name="result">The result of the task execution.</param> public JobPreparationTaskExecutionInformation(System.DateTime startTime, JobPreparationTaskState state, int retryCount, System.DateTime? endTime = default(System.DateTime?), string taskRootDirectory = default(string), string taskRootDirectoryUrl = default(string), int? exitCode = default(int?), TaskFailureInformation failureInfo = default(TaskFailureInformation), System.DateTime? lastRetryTime = default(System.DateTime?), TaskExecutionResult? result = default(TaskExecutionResult?)) { StartTime = startTime; EndTime = endTime; State = state; TaskRootDirectory = taskRootDirectory; TaskRootDirectoryUrl = taskRootDirectoryUrl; ExitCode = exitCode; FailureInfo = failureInfo; RetryCount = retryCount; LastRetryTime = lastRetryTime; Result = result; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets the time at which the task started running. /// </summary> /// <remarks> /// If the task has been restarted or retried, this is the most recent /// time at which the task started running. /// </remarks> [JsonProperty(PropertyName = "startTime")] public System.DateTime StartTime { get; set; } /// <summary> /// Gets or sets the time at which the Job Preparation task completed. /// </summary> /// <remarks> /// This property is set only if the task is in the Completed state. /// </remarks> [JsonProperty(PropertyName = "endTime")] public System.DateTime? EndTime { get; set; } /// <summary> /// Gets or sets the current state of the Job Preparation task on the /// compute node. /// </summary> /// <remarks> /// Values are: /// /// running - the task is currently running (including retrying). /// completed - the task has exited with exit code 0, or the task has /// exhausted its retry limit, or the Batch service was unable to start /// the task due to task preparation errors (such as resource file /// download failures). Possible values include: 'running', 'completed' /// </remarks> [JsonProperty(PropertyName = "state")] public JobPreparationTaskState State { get; set; } /// <summary> /// Gets or sets the root directory of the Job Preparation task on the /// compute node. You can use this path to retrieve files created by /// the task, such as log files. /// </summary> [JsonProperty(PropertyName = "taskRootDirectory")] public string TaskRootDirectory { get; set; } /// <summary> /// Gets or sets the URL to the root directory of the Job Preparation /// task on the compute node. /// </summary> [JsonProperty(PropertyName = "taskRootDirectoryUrl")] public string TaskRootDirectoryUrl { get; set; } /// <summary> /// Gets or sets the exit code of the program specified on the task /// command line. /// </summary> /// <remarks> /// This parameter is returned only if the task is in the completed /// state. The exit code for a process reflects the specific convention /// implemented by the application developer for that process. If you /// use the exit code value to make decisions in your code, be sure /// that you know the exit code convention used by the application /// process. Note that the exit code may also be generated by the /// compute node operating system, such as when a process is forcibly /// terminated. /// </remarks> [JsonProperty(PropertyName = "exitCode")] public int? ExitCode { get; set; } /// <summary> /// Gets or sets information describing the task failure, if any. /// </summary> /// <remarks> /// This property is set only if the task is in the completed state and /// encountered a failure. /// </remarks> [JsonProperty(PropertyName = "failureInfo")] public TaskFailureInformation FailureInfo { get; set; } /// <summary> /// Gets or sets the number of times the task has been retried by the /// Batch service. Task application failures (non-zero exit code) are /// retried, pre-processing errors (the task could not be run) and file /// upload errors are not retried. The Batch service will retry the /// task up to the limit specified by the constraints. /// </summary> /// <remarks> /// Task application failures (non-zero exit code) are retried, /// pre-processing errors (the task could not be run) and file upload /// errors are not retried. The Batch service will retry the task up to /// the limit specified by the constraints. /// </remarks> [JsonProperty(PropertyName = "retryCount")] public int RetryCount { get; set; } /// <summary> /// Gets or sets the most recent time at which a retry of the Job /// Preparation task started running. /// </summary> /// <remarks> /// This property is set only if the task was retried (i.e. retryCount /// is nonzero). If present, this is typically the same as startTime, /// but may be different if the task has been restarted for reasons /// other than retry; for example, if the compute node was rebooted /// during a retry, then the startTime is updated but the lastRetryTime /// is not. /// </remarks> [JsonProperty(PropertyName = "lastRetryTime")] public System.DateTime? LastRetryTime { get; set; } /// <summary> /// Gets or sets the result of the task execution. /// </summary> /// <remarks> /// If the value is 'failed', then the details of the failure can be /// found in the failureInfo property. Possible values include: /// 'success', 'failure' /// </remarks> [JsonProperty(PropertyName = "result")] public TaskExecutionResult? Result { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (FailureInfo != null) { FailureInfo.Validate(); } } } }
using System; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using System.Threading; /* * Copyright 2011-2013 Mario Vernari (http://www.netmftoolbox.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. */ namespace WindInstrumentToNMEA { /// <summary> /// Represent an extension over an input port, with embedded auto-repeat capabilities. /// This kind of class is well suited for pushbuttons input managements /// </summary> public class AutoRepeatInputPort : InputPort { /// <summary> /// Enumeration of the possible states issued by the <see cref="AutoRepeatInputPort.StateChanged"/> event /// </summary> /// <remarks> /// Each state is better depicted considering a pushbutton acting on the input port /// </remarks> public enum AutoRepeatState { /// <summary> /// The button has just been pressed. This state is always issued, but once only /// </summary> Press, /// <summary> /// The button has been hold down enough to begin the auto-repeat cycle. /// This state can be issued periodically /// </summary> Tick, /// <summary> /// The button has just been depressed. This state is always issued, but once only /// </summary> Release, } /// <summary> /// Indicates the duration of the quantum for the input port sampling, /// and all the related calculations /// </summary> /// <remarks>It is recommended to leave this value as is</remarks> private const int QuantumDuration = 100; //ms /// <summary> /// The initial delay used as default. /// </summary> private const int DefaultInitialDelay = 1000 / QuantumDuration; /// <summary> /// The auto-repeat period used as default /// </summary> private const int DefaultAutoRepeatPeriod = 500 / QuantumDuration; /// <summary> /// Create and open an instance of an input port, /// with embedded auto-repeat capabilities /// </summary> /// <param name="port">The I/O pin selected for the input</param> /// <param name="resistor">The resistor wired-logic easing</param> /// <param name="activeLevel">The level on which the input has to be considered active</param> public AutoRepeatInputPort( Cpu.Pin port, Port.ResistorMode resistor, bool activeLevel) : base(port, false, resistor) { this.ActiveLevel = activeLevel; //create, then start the working thread this._workingThread = new Thread(this.Worker); this._workingThread.Start(); } private Thread _workingThread; private int _initialDelayCount = DefaultInitialDelay; private int _autoRepeatPeriodCount = DefaultAutoRepeatPeriod; private bool _shutdown; /// <summary> /// Gets the active level defined for this instance /// </summary> public bool ActiveLevel { get; private set; } /// <summary> /// Get/set the initial delay before the auto-repeat starts. /// The value is expressed in milliseconds, and is rounded accordingly to the quantum /// </summary> /// <remarks> /// The minimum allowed value is zero, that is an immediate starting of the auto-repeat /// </remarks> public int InitialDelay { get { return this._initialDelayCount * QuantumDuration; } set { this._initialDelayCount = value >= 0 ? value / QuantumDuration : 0; } } /// <summary> /// Get/set the interval period of the auto-repeat. /// The value is expressed in milliseconds, and is rounded accordingly to the quantum /// </summary> /// <remarks> /// The minimum value is equal to the quantum (i.e. 100ms) /// </remarks> public int AutoRepeatPeriod { get { return this._autoRepeatPeriodCount * QuantumDuration; } set { this._autoRepeatPeriodCount = value >= QuantumDuration ? value / QuantumDuration : QuantumDuration; } } /// <summary> /// the working thread handler, as the manager of the auto-repeat /// </summary> private void Worker() { bool prevActivity = false; int counter = 0; while (this._shutdown == false) { //check the current level at the input port if (this.Read() == this.ActiveLevel) { //activity if (prevActivity) { //activity in progress if (--counter <= 0) { Debug.Print("tick"); this.OnStateChanged(AutoRepeatState.Tick); counter = this._autoRepeatPeriodCount; } Debug.Print("autorepeat counter: " + counter); } else { //just pressed this.OnStateChanged(AutoRepeatState.Press); prevActivity = true; counter = (this._initialDelayCount > 0) ? this._initialDelayCount : this._autoRepeatPeriodCount; } } else if (prevActivity) { //just dropped into the inactivity this.OnStateChanged(AutoRepeatState.Release); counter = 0; prevActivity = false; } //pause for the quantum duration Thread.Sleep(QuantumDuration); } } /// <summary> /// Disposes the object /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { //shut-down the thread gracefully this._shutdown = true; this._workingThread.Join(); //dispose the underlying stuffs base.Dispose(disposing); } #region EVT StateChanged /// <summary> /// Notify any change occurring in the auto-repeat life-cycle /// </summary> public event AutoRepeatEventHandler StateChanged; /// <summary> /// /// </summary> /// <param name="state"></param> protected virtual void OnStateChanged(AutoRepeatState state) { var handler = this.StateChanged; if (handler != null) { handler( this, new AutoRepeatEventArgs(state)); } } #endregion } /// <summary> /// The delegate behind the <see cref="AutoRepeatInputPort.StateChanged"/> event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void AutoRepeatEventHandler(object sender, AutoRepeatEventArgs e); /// <summary> /// Extension wrapper to the standard <see cref="Microsoft.SPOT.EventArgs"/> object, thus the state of the auto-repeat may be carried out to the host /// </summary> public class AutoRepeatEventArgs : EventArgs { /// <summary> /// Extension wrapper to the standard <see cref="Microsoft.SPOT.EventArgs"/> object, thus the state of the auto-repeat may be carried out to the host /// </summary> /// <param name="state"></param> public AutoRepeatEventArgs(AutoRepeatInputPort.AutoRepeatState state) { this.State = state; } /// <summary> /// /// </summary> public AutoRepeatInputPort.AutoRepeatState State { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; namespace System.ComponentModel.Composition.ReflectionModel { internal static class GenericServices { internal static IList<Type> GetPureGenericParameters(this Type type) { if(type == null) { throw new ArgumentNullException(nameof(type)); } if (type.IsGenericType && type.ContainsGenericParameters) { List<Type> pureGenericParameters = new List<Type>(); TraverseGenericType(type, (Type t) => { if (t.IsGenericParameter) { pureGenericParameters.Add(t); } }); return pureGenericParameters; } else { return Type.EmptyTypes; } } internal static int GetPureGenericArity(this Type type) { if(type == null) { throw new ArgumentNullException(nameof(type)); } int genericArity = 0; if (type.IsGenericType && type.ContainsGenericParameters) { List<Type> pureGenericParameters = new List<Type>(); TraverseGenericType(type, (Type t) => { if (t.IsGenericParameter) { genericArity++; } }); } return genericArity; } private static void TraverseGenericType(Type type, Action<Type> onType) { if (type.IsGenericType) { foreach (Type genericArgument in type.GetGenericArguments()) { TraverseGenericType(genericArgument, onType); } } onType(type); } public static int[] GetGenericParametersOrder(Type type) { return type.GetPureGenericParameters().Select(parameter => parameter.GenericParameterPosition).ToArray(); } public static string GetGenericName(string originalGenericName, int[] genericParametersOrder, int genericArity) { string[] genericFormatArgs = new string[genericArity]; for (int i = 0; i < genericParametersOrder.Length; i++) { genericFormatArgs[genericParametersOrder[i]] = string.Format(CultureInfo.InvariantCulture, "{{{0}}}", i); } return string.Format(CultureInfo.InvariantCulture, originalGenericName, genericFormatArgs); } public static T[] Reorder<T>(T[] original, int[] genericParametersOrder) { T[] genericSpecialization = new T[genericParametersOrder.Length]; for (int i = 0; i < genericParametersOrder.Length; i++) { genericSpecialization[i] = original[genericParametersOrder[i]]; } return genericSpecialization; } public static IEnumerable<Type> CreateTypeSpecializations(this Type[] types, Type[] specializationTypes) { if (types == null) { return null; } else { return types.Select(type => type.CreateTypeSpecialization(specializationTypes)); } } public static Type CreateTypeSpecialization(this Type type, Type[] specializationTypes) { if (!type.ContainsGenericParameters) { return type; } if (type.IsGenericParameter) { // the only case when MakeGenericType won't work is when the 'type' represents a "naked" generic type // in this case we simply grab the type with the proper index from the specializtion return specializationTypes[type.GenericParameterPosition]; } else { Type[] typeGenericArguments = type.GetGenericArguments(); Type[] subSpecialization = new Type[typeGenericArguments.Length]; for (int i = 0; i < typeGenericArguments.Length; i++) { Type typeGenericArgument = typeGenericArguments[i]; subSpecialization[i] = typeGenericArgument.IsGenericParameter ? specializationTypes[typeGenericArgument.GenericParameterPosition] : typeGenericArgument; } // and "close" the generic return type.GetGenericTypeDefinition().MakeGenericType(subSpecialization); } } public static bool CanSpecialize(Type type, IEnumerable<Type> constraints, GenericParameterAttributes attributes) { return CanSpecialize(type, constraints) && CanSpecialize(type, attributes); } public static bool CanSpecialize(Type type, IEnumerable<Type> constraintTypes) { if (constraintTypes == null) { return true; } // where T : IFoo // a part of where T : struct is also handled here as T : ValueType foreach (Type constraintType in constraintTypes) { if ((constraintType != null) && !constraintType.IsAssignableFrom(type)) { return false; } } return true; } public static bool CanSpecialize(Type type, GenericParameterAttributes attributes) { if (attributes == GenericParameterAttributes.None) { return true; } // where T : class if ((attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0) { if (type.IsValueType) { return false; } } // where T : new if ((attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0) { // value types always have default constructors if (!type.IsValueType && (type.GetConstructor(Type.EmptyTypes) == null)) { return false; } } // where T : struct if ((attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { // must be a value type if (!type.IsValueType) { return false; } // Make sure that the type is not nullable // this is salways guaranteed in C#, but other languages may be different if (Nullable.GetUnderlyingType(type) != null) { return false; } } // all other fals indicate variance and don't place any actual restrictions on the generic parameters // but rather how they should be used by the compiler return true; } } }
using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Threading.Tasks; using FluentAssertions; using Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.Interfaces; using NSubstitute; using Toggl.Core.Analytics; using Toggl.Core.Calendar; using Toggl.Core.DTOs; using Toggl.Core.Interactors; using Toggl.Core.Models; using Toggl.Core.Models.Interfaces; using Toggl.Core.Tests.Generators; using Toggl.Core.Tests.Mocks; using Toggl.Core.Tests.TestExtensions; using Toggl.Core.UI.Parameters; using Toggl.Core.UI.ViewModels; using Toggl.Core.UI.ViewModels.Calendar.ContextualMenu; using Toggl.Core.UI.Views; using Toggl.Shared; using Xunit; using ColorHelper = Toggl.Core.Helper.Colors; using Task = System.Threading.Tasks.Task; namespace Toggl.Core.Tests.UI.ViewModels { public sealed class CalendarContextualMenuViewModelTests { public abstract class CalendarContextualMenuViewModelTest : BaseViewModelTests<CalendarContextualMenuViewModel> { protected override CalendarContextualMenuViewModel CreateViewModel() => new CalendarContextualMenuViewModel(InteractorFactory, SchedulerProvider, AnalyticsService, RxActionFactory, TimeService, NavigationService); protected CalendarItem CreateEmptyCalendarItem() => new CalendarItem(); protected CalendarItem CreateDummyTimeEntryCalendarItem(bool isRunning = false, long timeEntryId = 1, DateTimeOffset? startTime = null, TimeSpan? duration = null) { TimeSpan? nullTimespan = null; return new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, startTime ?? DateTimeOffset.Now, isRunning ? nullTimespan : (duration ?? TimeSpan.FromMinutes(30)), "", CalendarIconKind.None, timeEntryId: timeEntryId); } protected CalendarItem CreateDummyCalendarEventCalendarItem( string description = "", DateTimeOffset? startTime = null, TimeSpan? duration = null) => new CalendarItem( "Id", "Id", CalendarItemSource.Calendar, startTime ?? DateTimeOffset.Now, duration, description, CalendarIconKind.Event, calendarId: "Id"); } public sealed class TheConstructor : CalendarContextualMenuViewModelTest { [Theory, LogIfTooSlow] [ConstructorData] public void ThrowsIfAnyOfTheArgumentsIsNull( bool useInteractorFactory, bool useSchedulerProvider, bool useAnalyticsService, bool useRxActionFactory, bool useTimeService, bool useNavigationService) { Action tryingToConstructWithEmptyParameters = () => new CalendarContextualMenuViewModel( useInteractorFactory ? InteractorFactory : null, useSchedulerProvider ? SchedulerProvider : null, useAnalyticsService ? AnalyticsService : null, useRxActionFactory ? RxActionFactory : null, useTimeService ? TimeService : null, useNavigationService ? NavigationService : null ); tryingToConstructWithEmptyParameters.Should().Throw<ArgumentNullException>(); } } public sealed class TheCurrentMenuObservable : CalendarContextualMenuViewModelTest { [Fact] public void ShouldStartEmpty() { var menuObserver = TestScheduler.CreateObserver<CalendarContextualMenu>(); var visibilityObserver = TestScheduler.CreateObserver<bool>(); ViewModel.CurrentMenu.Subscribe(menuObserver); ViewModel.MenuVisible.Subscribe(visibilityObserver); TestScheduler.Start(); menuObserver.Messages.Should().HaveCount(1); menuObserver.Messages.First().Value.Value.Actions.Should().BeEmpty(); visibilityObserver.Messages.Should().HaveCount(1); visibilityObserver.Messages.First().Value.Value.Should().BeFalse(); } [Fact] public void EmitsDiscardEditSaveActionsWhenNewCalendarItemIsBeingEdited() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var calendarItem = CreateEmptyCalendarItem(); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(2); var kinds = observer.Messages[1].Value.Value.Actions.Select(action => action.ActionKind); kinds.Should().ContainInOrder( CalendarMenuActionKind.Discard, CalendarMenuActionKind.Edit, CalendarMenuActionKind.Save); } [Fact] public void EmitsDeleteEditSaveContinueActionsWhenExistingTimeEntryCalendarItemIsBeingEdited() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var calendarItem = CreateDummyTimeEntryCalendarItem(isRunning: false); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(2); var kinds = observer.Messages[1].Value.Value.Actions.Select(action => action.ActionKind); kinds.Should().ContainInOrder( CalendarMenuActionKind.Delete, CalendarMenuActionKind.Edit, CalendarMenuActionKind.Save, CalendarMenuActionKind.Continue); } [Fact] public void EmitsDiscardEditSaveStopWhenItemIsBeingEdited() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var calendarItem = CreateDummyTimeEntryCalendarItem(isRunning: true); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(2); var kinds = observer.Messages[1].Value.Value.Actions.Select(action => action.ActionKind); kinds.Should().ContainInOrder( CalendarMenuActionKind.Discard, CalendarMenuActionKind.Edit, CalendarMenuActionKind.Save, CalendarMenuActionKind.Stop); } [Fact] public void EmitsCopyStartActionsWhenCalendarEventCalendarItemIsBeingEdited() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var calendarItem = CreateDummyCalendarEventCalendarItem(duration: TimeSpan.FromMinutes(30)); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(2); var kinds = observer.Messages[1].Value.Value.Actions.Select(action => action.ActionKind); kinds.Should().ContainInOrder( CalendarMenuActionKind.Copy, CalendarMenuActionKind.Start); } [Fact] public void DoesNotEmitWhenTheCalendarItemBeingUpdatedIsntDifferent() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var calendarItem = CreateDummyTimeEntryCalendarItem(duration: TimeSpan.FromMinutes(30), startTime: startTime); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem.WithStartTime(DateTimeOffset.Now)); TestScheduler.Start(); observer.Messages.Should().HaveCount(2); } [Fact] public void EmitsClosedMenuWhenItemIsUpdatedWithNull() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var calendarItem = CreateDummyTimeEntryCalendarItem(duration: TimeSpan.FromMinutes(30), startTime: startTime); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(null); TestScheduler.Start(); observer.Messages.Should().HaveCount(2); observer.Messages.Last().Value.Value.Type.Should().Be(ContextualMenuType.Closed); } } public abstract class TheMenuActionTests : CalendarContextualMenuViewModelTest { protected CalendarContextualMenu ContextualMenu { get; } public TheMenuActionTests() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var calendarItem = CreateMenuTypeCalendarItemTrigger(); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarItem); TestScheduler.Start(); ContextualMenu = observer.Messages.Last().Value.Value; } public abstract CalendarItem CreateMenuTypeCalendarItemTrigger(); public virtual void TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange() => ClosesTheMenuWithoutMakingChanges(() => ContextualMenu.Dismiss.Inputs.OnNext(Unit.Default)); public virtual void TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu() => ConfirmsBeforeDiscardingChanges(() => ContextualMenu.Dismiss.Inputs.OnNext(Unit.Default)); public void ExecutesActionAndClosesMenu(Action action, int discardCount = 0) { var menuVisibilityObserver = TestScheduler.CreateObserver<bool>(); var discardsObserver = TestScheduler.CreateObserver<Unit>(); var menuObserver = TestScheduler.CreateObserver<CalendarContextualMenu>(); ViewModel.MenuVisible.Subscribe(menuVisibilityObserver); ViewModel.DiscardChanges.Subscribe(discardsObserver); ViewModel.CurrentMenu.Subscribe(menuObserver); TestScheduler.Start(); action(); TestScheduler.Start(); discardsObserver.Messages.Should().HaveCount(discardCount); menuVisibilityObserver.LastEmittedValue().Should().BeFalse(); menuObserver.LastEmittedValue().Actions.Should().BeEmpty(); } public void ClosesTheMenuWithoutMakingChanges(Action action) { var menuVisibilityObserver = TestScheduler.CreateObserver<bool>(); var discardsObserver = TestScheduler.CreateObserver<Unit>(); var menuObserver = TestScheduler.CreateObserver<CalendarContextualMenu>(); var view = Substitute.For<IView>(); ViewModel.MenuVisible.Subscribe(menuVisibilityObserver); ViewModel.DiscardChanges.Subscribe(discardsObserver); ViewModel.CurrentMenu.Subscribe(menuObserver); ViewModel.AttachView(view); discardsObserver.Messages.Should().HaveCount(0); TestScheduler.Start(); action(); TestScheduler.Start(); view.DidNotReceiveWithAnyArgs().ConfirmDestructiveAction(Arg.Any<ActionType>()); menuVisibilityObserver.LastEmittedValue().Should().BeFalse(); menuObserver.LastEmittedValue().Actions.Should().BeEmpty(); discardsObserver.Messages.Should().HaveCount(1); } public void ConfirmsBeforeDiscardingChanges(Action action) { var menuVisibilityObserver = TestScheduler.CreateObserver<bool>(); var discardsObserver = TestScheduler.CreateObserver<Unit>(); var menuObserver = TestScheduler.CreateObserver<CalendarContextualMenu>(); var view = Substitute.For<IView>(); view.ConfirmDestructiveAction(Arg.Any<ActionType>()).Returns(Observable.Return(false)); ViewModel.MenuVisible.Subscribe(menuVisibilityObserver); ViewModel.DiscardChanges.Subscribe(discardsObserver); ViewModel.AttachView(view); menuVisibilityObserver.Messages.Clear(); ViewModel.CurrentMenu.Subscribe(menuObserver); discardsObserver.Messages.Should().HaveCount(0); var updatedCalendarItem = CreateMenuTypeCalendarItemTrigger().WithDuration(TimeSpan.FromMinutes(7)); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(updatedCalendarItem); TestScheduler.Start(); action(); TestScheduler.Start(); view.Received().ConfirmDestructiveAction(Arg.Is<ActionType>(type => type == ActionType.DiscardEditingChanges)); } public void ClosesTheMenuAndDiscardChangesAfterConfirmingDestructiveAction() { } public void DoesNotCloseTheMenuAndDoesNotDiscardChangesAfterCancellingDestructiveAction() { } } public sealed class TheMenuActionForCalendarEvents : TheMenuActionTests { public override CalendarItem CreateMenuTypeCalendarItemTrigger() => CreateDummyCalendarEventCalendarItem(); [Fact] public void TheCopyActionCreatesATimeEntryWithTheDetailsFromTheCalendarEvent() { var copyAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Copy); var expectedDescription = "X"; var expectedStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var expectedDuration = TimeSpan.FromHours(1); var calendarEventBeingEdited = CreateDummyCalendarEventCalendarItem(expectedDescription, expectedStartTime, expectedDuration); InteractorFactory.GetDefaultWorkspace().Execute().Returns(Observable.Return(new MockWorkspace(1))); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarEventBeingEdited); TestScheduler.Start(); copyAction.MenuItemAction.Execute(); var prototypeArg = Arg.Is<ITimeEntryPrototype>(te => te.Description == expectedDescription && te.StartTime == expectedStartTime && te.Duration == expectedDuration && te.WorkspaceId == 1 ); TestScheduler.Start(); InteractorFactory.Received().CreateTimeEntry(prototypeArg, TimeEntryStartOrigin.CalendarEvent); } [Fact] public void TheCopyActionClosesTheMenuAfterItsExecution() => ExecutesActionAndClosesMenu(TheCopyActionCreatesATimeEntryWithTheDetailsFromTheCalendarEvent); [Fact] public void TheStartActionCreatesARunningTimeEntryWithTheDetailsFromTheCalendarEvent() { var startAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Start); var expectedDescription = "X"; var originalStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var calendarEventBeingEdited = CreateDummyCalendarEventCalendarItem(expectedDescription, originalStartTime); var now = DateTimeOffset.Now; TimeService.CurrentDateTime.Returns(now); InteractorFactory.GetDefaultWorkspace().Execute().Returns(Observable.Return(new MockWorkspace(1))); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(calendarEventBeingEdited); TestScheduler.Start(); startAction.MenuItemAction.Execute(); var prototypeArg = Arg.Is<ITimeEntryPrototype>(te => te.Description == expectedDescription && te.StartTime == now && te.StartTime != originalStartTime && te.Duration == null && te.WorkspaceId == 1 ); InteractorFactory.Received().CreateTimeEntry(prototypeArg, TimeEntryStartOrigin.CalendarEvent); } [Fact] public void TheStartActionClosesTheMenuAfterItsExecution() => ExecutesActionAndClosesMenu(TheStartActionCreatesARunningTimeEntryWithTheDetailsFromTheCalendarEvent); [Fact] public override void TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange() { base.TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange(); } } public sealed class TheMenuForNewTimeEntries : TheMenuActionTests { public override CalendarItem CreateMenuTypeCalendarItemTrigger() => CreateEmptyCalendarItem(); [Fact] public void TheDiscardActionTriggersTheDiscardChangesObservable() { var observer = TestScheduler.CreateObserver<Unit>(); ViewModel.DiscardChanges.Subscribe(observer); var discardAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Discard); var expectedStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var expectedDuration = TimeSpan.FromMinutes(30); var expectedDescription = "whatever"; var newCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, expectedStartTime, expectedDuration, expectedDescription, CalendarIconKind.None); InteractorFactory.GetDefaultWorkspace().Execute().Returns(Observable.Return(new MockWorkspace(1))); TestScheduler.Start(); observer.Messages.Should().HaveCount(0); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(newCalendarItem); TestScheduler.Start(); discardAction.MenuItemAction.Execute(); TestScheduler.Start(); observer.Messages.Should().HaveCount(1); } [Fact] public void TheDiscardActionExecutesActionAndClosesMenu() => ClosesTheMenuWithoutMakingChanges(TheDiscardActionTriggersTheDiscardChangesObservable); [Fact] public void TheEditActionNavigatesToTheStartTimeEntryViewModelWithProperParameters() { var editAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Edit); var expectedStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var expectedDuration = TimeSpan.FromMinutes(30); var newCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, expectedStartTime, expectedDuration, string.Empty, CalendarIconKind.None); InteractorFactory.GetDefaultWorkspace().Execute().Returns(Observable.Return(new MockWorkspace(1))); var view = Substitute.For<IView>(); ViewModel.AttachView(view); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(newCalendarItem); TestScheduler.Start(); editAction.MenuItemAction.Execute(); var startTimeEntryArg = Arg.Is<StartTimeEntryParameters>(param => param.StartTime == expectedStartTime && param.Duration == expectedDuration && param.EntryDescription == string.Empty && param.WorkspaceId == 1 ); TestScheduler.Start(); NavigationService.Received().Navigate<StartTimeEntryViewModel, StartTimeEntryParameters, IThreadSafeTimeEntry>(startTimeEntryArg, view); } [Fact] public void TheEditActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheEditActionNavigatesToTheStartTimeEntryViewModelWithProperParameters); [Fact] public void TheSaveActionCreatesATimeEntryWithNoDescriptionWithTheRightStartTimeAndDuration() { var saveAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Save); var expectedStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var expectedDuration = TimeSpan.FromMinutes(30); var expectedDescription = "whatever"; var newCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, expectedStartTime, expectedDuration, expectedDescription, CalendarIconKind.None); InteractorFactory.GetDefaultWorkspace().Execute().Returns(Observable.Return(new MockWorkspace(1))); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(newCalendarItem); TestScheduler.Start(); saveAction.MenuItemAction.Execute(); var prototypeArg = Arg.Is<ITimeEntryPrototype>(te => te.Description == expectedDescription && te.StartTime == expectedStartTime && te.Duration == expectedDuration && te.WorkspaceId == 1 ); TestScheduler.Start(); InteractorFactory.Received().CreateTimeEntry(prototypeArg, TimeEntryStartOrigin.CalendarEvent); } [Fact] public void TheSaveActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheSaveActionCreatesATimeEntryWithNoDescriptionWithTheRightStartTimeAndDuration); [Fact] public override void TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange() { base.TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange(); } [Fact] public override void TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu() { base.TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu(); } } public sealed class TheMenuForRunningEntries : TheMenuActionTests { public override CalendarItem CreateMenuTypeCalendarItemTrigger() => CreateDummyTimeEntryCalendarItem(isRunning: true); [Fact] public void TheDiscardActionDeletesTheRunningTimeEntryIfTheUsersConfirmsTheDialog() { View.ConfirmDestructiveAction(Arg.Any<ActionType>()).ReturnsObservableOf(true); var discardAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Discard); var runningTimeEntryId = 10; var runningTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: true, timeEntryId: runningTimeEntryId); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(runningTimeEntry); TestScheduler.Start(); discardAction.MenuItemAction.Execute(); TestScheduler.Start(); InteractorFactory.Received().DeleteTimeEntry(runningTimeEntryId); } [Fact] public void TheDiscardActionDoesNotDeleteTheRunningTimeEntryIfTheUsersDoesNotConfirmTheDialog() { View.ConfirmDestructiveAction(Arg.Any<ActionType>()).ReturnsObservableOf(false); var discardAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Discard); var runningTimeEntryId = 10; var runningTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: true, timeEntryId: runningTimeEntryId); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(runningTimeEntry); TestScheduler.Start(); discardAction.MenuItemAction.Execute(); TestScheduler.Start(); InteractorFactory.DidNotReceive().DeleteTimeEntry(runningTimeEntryId); } [Fact] public void TheDiscardActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheDiscardActionDeletesTheRunningTimeEntryIfTheUsersConfirmsTheDialog, 1); [Fact] public void TheEditActionNavigatesToTheEditTimeEntryViewModelWithTheRightId() { var editAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Edit); var runningTimeEntryId = 10L; var runningTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: true, timeEntryId: runningTimeEntryId); var view = Substitute.For<IView>(); ViewModel.AttachView(view); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(runningTimeEntry); TestScheduler.Start(); editAction.MenuItemAction.Execute(); var idArg = Arg.Is<long[]>(ids => ids[0] == runningTimeEntryId); TestScheduler.Start(); NavigationService.Received().Navigate<EditTimeEntryViewModel, long[], Unit>(idArg, view); } [Fact] public void TheEditActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheEditActionNavigatesToTheEditTimeEntryViewModelWithTheRightId, 1); [Fact] public void TheSaveActionUpdatesTheRunningTimeEntry() { var saveAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Save); var runningTimeEntryId = 10L; var newStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var runningTimeEntry = CreateDummyTimeEntryCalendarItem(true, runningTimeEntryId, newStartTime); var originalStartTime = new DateTimeOffset(2019, 10, 10, 11, 10, 10, TimeSpan.Zero); var mockWorkspace = new MockWorkspace(1); var timeEntryMock = new MockTimeEntry(runningTimeEntryId, mockWorkspace, originalStartTime); InteractorFactory.GetTimeEntryById(runningTimeEntryId).Execute().Returns(Observable.Return(timeEntryMock)); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(runningTimeEntry); TestScheduler.Start(); saveAction.MenuItemAction.Execute(); var dtoArg = Arg.Is<EditTimeEntryDto>(dto => dto.Id == runningTimeEntryId && dto.StartTime == newStartTime && dto.StartTime != originalStartTime && dto.WorkspaceId == mockWorkspace.Id && !dto.StopTime.HasValue); TestScheduler.Start(); InteractorFactory.Received().UpdateTimeEntry(dtoArg); } [Fact] public void TheSaveActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheSaveActionUpdatesTheRunningTimeEntry, 1); [Fact] public void TheStopActionStopsTheRunningTimeEntry() { var stopAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Stop); var runningTimeEntryId = 10L; var runningTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: true, timeEntryId: runningTimeEntryId); var now = DateTimeOffset.Now; TimeService.CurrentDateTime.Returns(now); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(runningTimeEntry); TestScheduler.Start(); stopAction.MenuItemAction.Execute(); TestScheduler.Start(); InteractorFactory.Received().StopTimeEntry(now, TimeEntryStopOrigin.CalendarContextualMenu); } [Fact] public void TheStopActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheStopActionStopsTheRunningTimeEntry, 1); [Fact] public override void TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange() { base.TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange(); } [Fact] public override void TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu() { base.TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu(); } } public sealed class TheMenuForStoppedEntries : TheMenuActionTests { public override CalendarItem CreateMenuTypeCalendarItemTrigger() => CreateDummyTimeEntryCalendarItem(isRunning: false); [Fact] public void TheDeleteActionDeletesTheTimeEntryIfTheUserConfirmsTheDialog() { View.ConfirmDestructiveAction(ActionType.DeleteExistingTimeEntry).ReturnsObservableOf(true); var deleteAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Delete); var stoppedTimeEntryId = 10; var stoppedTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: false, timeEntryId: stoppedTimeEntryId); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(stoppedTimeEntry); TestScheduler.Start(); deleteAction.MenuItemAction.Execute(); TestScheduler.Start(); InteractorFactory.Received().DeleteTimeEntry(stoppedTimeEntryId); } [Fact] public void TheDeleteActionDoesNotDeleteTheTimeEntryIfTheUserConfirmsDoesNotConfirmTheDialog() { View.ConfirmDestructiveAction(ActionType.DeleteExistingTimeEntry).ReturnsObservableOf(false); var deleteAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Delete); var stoppedTimeEntryId = 10; var stoppedTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: false, timeEntryId: stoppedTimeEntryId); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(stoppedTimeEntry); TestScheduler.Start(); deleteAction.MenuItemAction.Execute(); TestScheduler.Start(); InteractorFactory.DidNotReceive().DeleteTimeEntry(stoppedTimeEntryId); } [Fact] public void TheDeleteActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheDeleteActionDeletesTheTimeEntryIfTheUserConfirmsTheDialog, 1); [Fact] public void TheEditActionNavigatesToTheEditTimeEntryViewModelWithTheRightId() { var editAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Edit); var stoppedTimeEntryId = 10L; var stoppedTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: false, timeEntryId: stoppedTimeEntryId); var view = Substitute.For<IView>(); ViewModel.AttachView(view); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(stoppedTimeEntry); TestScheduler.Start(); editAction.MenuItemAction.Execute(); TestScheduler.Start(); var idArg = Arg.Is<long[]>(ids => ids[0] == stoppedTimeEntryId); NavigationService.Received().Navigate<EditTimeEntryViewModel, long[], Unit>(idArg, view); } [Fact] public void TheEditActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheEditActionNavigatesToTheEditTimeEntryViewModelWithTheRightId, 1); [Fact] public void TheSaveActionUpdatesTheRunningTimeEntry() { var saveAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Save); var stoppedTimeEntryId = 10L; var newStartTime = new DateTimeOffset(2019, 10, 10, 10, 10, 10, TimeSpan.Zero); var newEndTime = new DateTimeOffset(2019, 10, 10, 10, 30, 10, TimeSpan.Zero); var stoppedTimeEntry = CreateDummyTimeEntryCalendarItem(false, stoppedTimeEntryId, newStartTime, newEndTime - newStartTime); var originalStartTime = new DateTimeOffset(2019, 10, 10, 11, 10, 10, TimeSpan.Zero); var originalEndTime = new DateTimeOffset(2019, 10, 10, 11, 30, 10, TimeSpan.Zero); var mockWorkspace = new MockWorkspace(1); var timeEntryMock = new MockTimeEntry(stoppedTimeEntryId, mockWorkspace, originalStartTime, (long)(originalEndTime - originalStartTime).TotalSeconds); InteractorFactory.GetTimeEntryById(stoppedTimeEntryId).Execute().Returns(Observable.Return(timeEntryMock)); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(stoppedTimeEntry); TestScheduler.Start(); saveAction.MenuItemAction.Execute(); var dtoArg = Arg.Is<EditTimeEntryDto>(dto => dto.Id == stoppedTimeEntryId && dto.StartTime == newStartTime && dto.StartTime != originalStartTime && dto.WorkspaceId == mockWorkspace.Id && dto.StopTime.HasValue && dto.StopTime.Value == newEndTime && dto.StopTime.Value != originalEndTime); TestScheduler.Start(); InteractorFactory.Received().UpdateTimeEntry(dtoArg); } [Fact] public void TheSaveActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheSaveActionUpdatesTheRunningTimeEntry, 1); [Fact] public void TheContinueActionStartsANewTheRunningTimeEntryWithTheDetailsFromTheCalendarItemCalledFromTheMenuAction() { var continueAction = ContextualMenu.Actions.First(action => action.ActionKind == CalendarMenuActionKind.Continue); var stoppedTimeEntryId = 10L; var stoppedTimeEntry = CreateDummyTimeEntryCalendarItem(isRunning: false, timeEntryId: stoppedTimeEntryId); var mockWorkspace = new MockWorkspace(1); var mockProject = new MockProject(1, mockWorkspace); var mockTask = new MockTask(1, mockWorkspace, mockProject); var expectedTimeEntryToContinue = Substitute.For<IThreadSafeTimeEntry>(); expectedTimeEntryToContinue.WorkspaceId.Returns(1); expectedTimeEntryToContinue.Description.Returns(""); expectedTimeEntryToContinue.Duration.Returns(100); expectedTimeEntryToContinue.Start.Returns(stoppedTimeEntry.StartTime); expectedTimeEntryToContinue.Project.Returns(mockProject); expectedTimeEntryToContinue.Task.Returns(mockTask); expectedTimeEntryToContinue.TagIds.Returns(Array.Empty<long>()); expectedTimeEntryToContinue.Billable.Returns(false); InteractorFactory.GetTimeEntryById(stoppedTimeEntryId).Execute().Returns(Observable.Return(expectedTimeEntryToContinue)); ViewModel.OnCalendarItemUpdated.Inputs.OnNext(stoppedTimeEntry); TestScheduler.Start(); continueAction.MenuItemAction.Execute(); var continuePrototype = Arg.Is(stoppedTimeEntryId); TestScheduler.Start(); InteractorFactory.Received().ContinueTimeEntry(continuePrototype, ContinueTimeEntryMode.CalendarContextualMenu); } [Fact] public void TheContinueActionExecutesActionAndClosesMenu() => ExecutesActionAndClosesMenu(TheContinueActionStartsANewTheRunningTimeEntryWithTheDetailsFromTheCalendarItemCalledFromTheMenuAction, 1); [Fact] public override void TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange() { base.TheDismissActionClosesTheMenuWhenTheCalendarItemDidNotChange(); } [Fact] public override void TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu() { base.TheDismissActionConfirmsBeforeDiscardingAndClosingTheMenu(); } } public sealed class TheOnCalendarItemUpdatedInputEntry : CalendarContextualMenuViewModelTest { [Fact] public void UpdatesTheCurrentItemInEditModeWhenTheContextualMenuIsClosed() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(1); observer.Messages.First().Value.Value.Should() .Match<CalendarItem?>(ci => ci.HasValue && ci.Value.Id == "" && ci.Value.Source == CalendarItemSource.TimeEntry && ci.Value.StartTime == now && ci.Value.Duration == TimeSpan.FromMinutes(30) ); } [Fact] public void UpdatesTheCurrentItemInEditModeWithoutConfirmationsWhenAnewItemIsInputtedAndCurrentItemInEditModeHasNotChanged() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 1); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); var newCalendarItem = new CalendarItem( "2", "2", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 2); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); view.DidNotReceiveWithAnyArgs().ConfirmDestructiveAction(Arg.Any<ActionType>()); observer.Messages.Should().HaveCount(2); observer.Messages.Last().Value.Value.Should() .Match<CalendarItem?>(ci => ci.HasValue && ci.Value.Id == "2" ); } [Fact] public void UpdatesTheCurrentItemInEditModeWhenAnewItemIsInputtedAndCurrentMenuIsFromACalendarEventItem() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.Calendar, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.Event, "#c2c2c2", calendarId: "X"); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); var newCalendarItem = new CalendarItem( "2", "2", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 2); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); view.DidNotReceiveWithAnyArgs().ConfirmDestructiveAction(Arg.Any<ActionType>()); observer.Messages.Should().HaveCount(2); observer.Messages.Last().Value.Value.Should() .Match<CalendarItem?>(ci => ci.HasValue && ci.Value.Id == "2" ); } [Fact] public void ConfirmsBeforeUpdatingTheCurrentItemInEditModeWhenANewItemIsInputtedAndTheCurrentItemInEditModeHasChanged() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); view.ConfirmDestructiveAction(Arg.Any<ActionType>()).Returns(Observable.Return(true)); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 1); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem.WithDuration(TimeSpan.FromMinutes(15))); TestScheduler.Start(); var newCalendarItem = new CalendarItem( "2", "2", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 2); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); view.Received().ConfirmDestructiveAction(Arg.Is(ActionType.DiscardEditingChanges)); observer.Messages.Should().HaveCount(2); } [Fact] public void ConfirmsBeforeClosingTheMenuWhenANullCalendarItemIsInputtedAndChangesWereMadeToTheCurrentItemInEditMode() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); view.ConfirmDestructiveAction(Arg.Any<ActionType>()).Returns(Observable.Return(true)); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 1); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem.WithDuration(TimeSpan.FromMinutes(15))); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(null); TestScheduler.Start(); view.Received().ConfirmDestructiveAction(Arg.Is(ActionType.DiscardEditingChanges)); observer.Messages.Should().HaveCount(2); } [Fact] public void DoesNotUpdateTheCurrentItemInEditModeWhenANewItemIsInputtedAndTheCurrentItemInEditModeHasChangedButConfirmationIsDenied() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); view.ConfirmDestructiveAction(Arg.Any<ActionType>()).Returns(Observable.Return(false)); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 1); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem.WithDuration(TimeSpan.FromMinutes(15))); TestScheduler.Start(); var newCalendarItem = new CalendarItem( "2", "2", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 2); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); view.Received().ConfirmDestructiveAction(Arg.Is(ActionType.DiscardEditingChanges)); observer.Messages.Should().HaveCount(1); } [Fact] public void DoesNotCloseTheMenuWhenANullCalendarItemIsInputtedAndChangesWereMadeToTheCurrentItemInEditModeAndConfirmationIsDenied() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); view.ConfirmDestructiveAction(Arg.Any<ActionType>()).Returns(Observable.Return(false)); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 1); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem.WithDuration(TimeSpan.FromMinutes(15))); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(null); TestScheduler.Start(); view.Received().ConfirmDestructiveAction(Arg.Is(ActionType.DiscardEditingChanges)); observer.Messages.Should().HaveCount(1); } [Fact] public void ClosesTheMenuWhenANullCalendarItemIsInputtedAndNoChangesWereMadeToTheCurrentItemInEditMode() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.TimeEntry, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client", timeEntryId: 1); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(null); TestScheduler.Start(); view.DidNotReceiveWithAnyArgs().ConfirmDestructiveAction(Arg.Any<ActionType>()); observer.Messages.Should().HaveCount(2); observer.Messages.Last().Value.Value.Should().BeNull(); } [Fact] public void ClosesTheMenuWhenANullCalendarItemIsInputtedAndTheCurrentMenuIsFromACalendarEventItem() { var observer = TestScheduler.CreateObserver<CalendarItem?>(); var now = DateTimeOffset.Now; var view = Substitute.For<IView>(); ViewModel.AttachView(view); var startingCalendarItem = new CalendarItem( "1", "1", CalendarItemSource.Calendar, now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.Event, "#c2c2c2", calendarId: "X"); ViewModel.CalendarItemInEditMode.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(null); TestScheduler.Start(); view.DidNotReceiveWithAnyArgs().ConfirmDestructiveAction(Arg.Any<ActionType>()); observer.Messages.Should().HaveCount(2); observer.Messages.Last().Value.Value.Should().BeNull(); } } public sealed class TheTimeEntryInfoObservable : CalendarContextualMenuViewModelTest { [Fact] public void StartsWithTheTimeEntryInfoFromPassedFirstThroughOnCalendarItemUpdated() { var observer = TestScheduler.CreateObserver<TimeEntryDisplayInfo>(); var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now, TimeSpan.FromMinutes(30), "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); ViewModel.TimeEntryInfo.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); TestScheduler.Start(); observer.Messages.First().Value.Value .Should() .Match<TimeEntryDisplayInfo>(e => e.Description == "Such description" && e.ProjectTaskColor == "#c2c2c2" && e.Project == "Such Project" && e.Task == "Such Task" && e.Client == "Such Client"); } [Fact] public void EmitsWhenItemIsUpdatedWithNewDetails() { var observer = TestScheduler.CreateObserver<TimeEntryDisplayInfo>(); var startingCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now, TimeSpan.FromMinutes(30), "Old description", CalendarIconKind.None, "#c2c2c2", project: "Old Project", task: "Old Task", client: "Old Client"); var updatedCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now, TimeSpan.FromMinutes(30), "New description", CalendarIconKind.None, "#f2f2f2", project: "New Project", task: "New Task", client: "New Client"); ViewModel.TimeEntryInfo.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(updatedCalendarItem); TestScheduler.Start(); observer.Messages[0].Value.Value .Should() .Match<TimeEntryDisplayInfo>(e => e.Description == "Old description" && e.ProjectTaskColor == "#c2c2c2" && e.Project == "Old Project" && e.Task == "Old Task" && e.Client == "Old Client"); observer.Messages[1].Value.Value .Should() .Match<TimeEntryDisplayInfo>(e => e.Description == "New description" && e.ProjectTaskColor == "#f2f2f2" && e.Project == "New Project" && e.Task == "New Task" && e.Client == "New Client"); } [Fact] public void DoesNotEmitWhenItemIsUpdatedWithTheSameDetailsEvenIfStartTimeAndDurationAreDifferent() { var observer = TestScheduler.CreateObserver<TimeEntryDisplayInfo>(); var startingCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now, TimeSpan.FromMinutes(30), "description", CalendarIconKind.None, "#c2c2c2", project: "project", task: "task", client: "client"); var updatedCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now.AddHours(1), TimeSpan.FromMinutes(25), "description", CalendarIconKind.None, "#c2c2c2", project: "project", task: "task", client: "client"); ViewModel.TimeEntryInfo.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(updatedCalendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(1); observer.Messages[0].Value.Value .Should() .Match<TimeEntryDisplayInfo>(e => e.Description == "description" && e.ProjectTaskColor == "#c2c2c2" && e.Project == "project" && e.Task == "task" && e.Client == "client"); } [Fact] public void DoesNotEmitAnotherContextualMenuWhenTheItemIsUpdated() { var observer = TestScheduler.CreateObserver<CalendarContextualMenu>(); var startingCalendarItem = new CalendarItem(string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now, TimeSpan.FromMinutes(30), "Old description", CalendarIconKind.None, "#c2c2c2", project: "Old Project", task: "Old Task", client: "Old Client"); var updatedCalendarItem = new CalendarItem(string.Empty, string.Empty, CalendarItemSource.TimeEntry, DateTimeOffset.Now, TimeSpan.FromMinutes(30), "New description", CalendarIconKind.None, "#f2f2f2", project: "New Project", task: "New Task", client: "New Client"); ViewModel.OnCalendarItemUpdated.Execute(startingCalendarItem); TestScheduler.Start(); ViewModel.CurrentMenu.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Execute(updatedCalendarItem); TestScheduler.Start(); observer.Messages.Should().HaveCount(1); } } public sealed class TheTimeEntryPeriodObservable : CalendarContextualMenuViewModelTest { public TheTimeEntryPeriodObservable() { var preferences = new MockPreferences { TimeOfDayFormat = TimeFormat.TwelveHoursFormat }; var interactor = Substitute.For<IInteractor<IObservable<IThreadSafePreferences>>>(); interactor.Execute().ReturnsObservableOf(preferences); InteractorFactory.ObserveCurrentPreferences().Returns(interactor); } [Fact] public void StartsWithThePeriodFromCalendarItemPassedFirstOnCalendarItemUpdated() { var observer = TestScheduler.CreateObserver<string>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 0, TimeSpan.Zero); var duration = TimeSpan.FromMinutes(30); var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, startTime, duration, "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); ViewModel.TimeEntryPeriod.Subscribe(observer); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); TestScheduler.Start(); observer.LastEmittedValue() .ToLower() .Should() .Be($"{calendarItem.StartTime.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)} - {calendarItem.EndTime.Value.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)}".ToLower()); } [Fact] public void EmitsWhenItemIsUpdatedWithADifferentStartTime() { var observer = TestScheduler.CreateObserver<string>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 0, TimeSpan.Zero); var duration = TimeSpan.FromMinutes(30); var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, startTime, duration, "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); ViewModel.TimeEntryPeriod.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); var newStartTime = startTime.AddHours(1); var newCalendarItem = calendarItem.WithStartTime(newStartTime); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); observer.LastEmittedValue() .ToLower() .Should() .Be($"{newCalendarItem.StartTime.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)} - {newCalendarItem.EndTime.Value.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)}".ToLower()); } [Fact] public void EmitsWhenItemIsUpdatedWithADifferentDuration() { var observer = TestScheduler.CreateObserver<string>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 0, TimeSpan.Zero); var duration = TimeSpan.FromMinutes(30); var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, startTime, duration, "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); ViewModel.TimeEntryPeriod.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); var newDuration = TimeSpan.FromMinutes(10); var newCalendarItem = calendarItem.WithDuration(newDuration); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); observer.LastEmittedValue() .ToLower() .Should() .Be($"{newCalendarItem.StartTime.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)} - {newCalendarItem.EndTime.Value.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)}".ToLower()); } [Fact] public void DoesNotEmitWhenItemIsUpdatedWithSameStartTimeAndDuration() { var observer = TestScheduler.CreateObserver<string>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 0, TimeSpan.Zero); var duration = TimeSpan.FromMinutes(30); var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, startTime, duration, "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); var newCalendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, startTime, duration, "New description", CalendarIconKind.None, "#c2c2c2", project: "New Project", task: "New Task", client: "New Client"); ViewModel.TimeEntryPeriod.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); TestScheduler.Start(); var beforeCount = observer.Messages.Count(); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); var afterCount = observer.Messages.Count(); beforeCount.Should().Be(afterCount); } [Fact] public void EmitsEndTimeAsNowWhenItemIsUpdatedWithNullDuration() { var observer = TestScheduler.CreateObserver<string>(); var startTime = new DateTimeOffset(2019, 10, 10, 10, 10, 0, TimeSpan.Zero); var duration = TimeSpan.FromMinutes(30); var calendarItem = new CalendarItem( string.Empty, string.Empty, CalendarItemSource.TimeEntry, startTime, duration, "Such description", CalendarIconKind.None, "#c2c2c2", project: "Such Project", task: "Such Task", client: "Such Client"); ViewModel.TimeEntryPeriod.Subscribe(observer); ViewModel.OnCalendarItemUpdated.Execute(calendarItem); var newCalendarItem = calendarItem.WithDuration(null); TestScheduler.Start(); ViewModel.OnCalendarItemUpdated.Execute(newCalendarItem); TestScheduler.Start(); observer.LastEmittedValue() .ToLower() .Should() .Be($"{newCalendarItem.StartTime.ToLocalTime().ToString(Resources.EditingTwelveHoursFormat)} - {Shared.Resources.Now}".ToLower()); } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API includes operations for managing the service /// and virtual machine extension images in your publisher subscription. /// </summary> internal partial class ExtensionImageOperations : IServiceOperations<ComputeManagementClient>, IExtensionImageOperations { /// <summary> /// Initializes a new instance of the ExtensionImageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ExtensionImageOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// Register a new extension. An extension is identified by the /// combination of its ProviderNamespace and Type (case-sensitive /// string). It is not allowed to register an extension with the same /// identity (i.e. combination of ProviderNamespace and Type) of an /// already-registered extension. To register new version of an /// existing extension, the Update Extension API should be used. /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Register Virtual Machine /// Extension Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginRegisteringAsync(ExtensionImageRegisterParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Certificate != null) { if (parameters.Certificate.StoreLocation == null) { throw new ArgumentNullException("parameters.Certificate.StoreLocation"); } } if (parameters.ExtensionEndpoints != null) { if (parameters.ExtensionEndpoints.InputEndpoints != null) { foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem in parameters.ExtensionEndpoints.InputEndpoints) { if (inputEndpointsParameterItem.LocalPort == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort"); } if (inputEndpointsParameterItem.Name == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Name"); } if (inputEndpointsParameterItem.Protocol == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Protocol"); } } } if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null) { foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem in parameters.ExtensionEndpoints.InstanceInputEndpoints) { if (instanceInputEndpointsParameterItem.LocalPort == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort"); } if (instanceInputEndpointsParameterItem.Name == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name"); } if (instanceInputEndpointsParameterItem.Protocol == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol"); } } } if (parameters.ExtensionEndpoints.InternalEndpoints != null) { foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem in parameters.ExtensionEndpoints.InternalEndpoints) { if (internalEndpointsParameterItem.Name == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Name"); } if (internalEndpointsParameterItem.Protocol == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol"); } } } } if (parameters.LocalResources != null) { foreach (ExtensionLocalResourceConfiguration localResourcesParameterItem in parameters.LocalResources) { if (localResourcesParameterItem.Name == null) { throw new ArgumentNullException("parameters.LocalResources.Name"); } } } if (parameters.ProviderNameSpace == null) { throw new ArgumentNullException("parameters.ProviderNameSpace"); } if (parameters.Type == null) { throw new ArgumentNullException("parameters.Type"); } if (parameters.Version == null) { throw new ArgumentNullException("parameters.Version"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginRegisteringAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/extensions"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-09-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement extensionImageElement = new XElement(XName.Get("ExtensionImage", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(extensionImageElement); XElement providerNameSpaceElement = new XElement(XName.Get("ProviderNameSpace", "http://schemas.microsoft.com/windowsazure")); providerNameSpaceElement.Value = parameters.ProviderNameSpace; extensionImageElement.Add(providerNameSpaceElement); XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); typeElement.Value = parameters.Type; extensionImageElement.Add(typeElement); XElement versionElement = new XElement(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); versionElement.Value = parameters.Version; extensionImageElement.Add(versionElement); if (parameters.Label != null) { XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = parameters.Label; extensionImageElement.Add(labelElement); } if (parameters.HostingResources != null) { XElement hostingResourcesElement = new XElement(XName.Get("HostingResources", "http://schemas.microsoft.com/windowsazure")); hostingResourcesElement.Value = parameters.HostingResources; extensionImageElement.Add(hostingResourcesElement); } if (parameters.MediaLink != null) { XElement mediaLinkElement = new XElement(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); mediaLinkElement.Value = parameters.MediaLink.AbsoluteUri; extensionImageElement.Add(mediaLinkElement); } if (parameters.Certificate != null) { XElement certificateElement = new XElement(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")); extensionImageElement.Add(certificateElement); XElement storeLocationElement = new XElement(XName.Get("StoreLocation", "http://schemas.microsoft.com/windowsazure")); storeLocationElement.Value = parameters.Certificate.StoreLocation; certificateElement.Add(storeLocationElement); if (parameters.Certificate.StoreName != null) { XElement storeNameElement = new XElement(XName.Get("StoreName", "http://schemas.microsoft.com/windowsazure")); storeNameElement.Value = parameters.Certificate.StoreName; certificateElement.Add(storeNameElement); } if (parameters.Certificate.ThumbprintRequired != null) { XElement thumbprintRequiredElement = new XElement(XName.Get("ThumbprintRequired", "http://schemas.microsoft.com/windowsazure")); thumbprintRequiredElement.Value = parameters.Certificate.ThumbprintRequired.ToString().ToLower(); certificateElement.Add(thumbprintRequiredElement); } if (parameters.Certificate.ThumbprintAlgorithm != null) { XElement thumbprintAlgorithmElement = new XElement(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure")); thumbprintAlgorithmElement.Value = parameters.Certificate.ThumbprintAlgorithm; certificateElement.Add(thumbprintAlgorithmElement); } } if (parameters.ExtensionEndpoints != null) { XElement endpointsElement = new XElement(XName.Get("Endpoints", "http://schemas.microsoft.com/windowsazure")); extensionImageElement.Add(endpointsElement); if (parameters.ExtensionEndpoints.InputEndpoints != null) { if (parameters.ExtensionEndpoints.InputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InputEndpoints).IsInitialized) { XElement inputEndpointsSequenceElement = new XElement(XName.Get("InputEndpoints", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem in parameters.ExtensionEndpoints.InputEndpoints) { XElement inputEndpointElement = new XElement(XName.Get("InputEndpoint", "http://schemas.microsoft.com/windowsazure")); inputEndpointsSequenceElement.Add(inputEndpointElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = inputEndpointsItem.Name; inputEndpointElement.Add(nameElement); XElement protocolElement = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure")); protocolElement.Value = inputEndpointsItem.Protocol; inputEndpointElement.Add(protocolElement); XElement portElement = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure")); portElement.Value = inputEndpointsItem.Port.ToString(); inputEndpointElement.Add(portElement); XElement localPortElement = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure")); localPortElement.Value = inputEndpointsItem.LocalPort; inputEndpointElement.Add(localPortElement); } endpointsElement.Add(inputEndpointsSequenceElement); } } if (parameters.ExtensionEndpoints.InternalEndpoints != null) { if (parameters.ExtensionEndpoints.InternalEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InternalEndpoints).IsInitialized) { XElement internalEndpointsSequenceElement = new XElement(XName.Get("InternalEndpoints", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem in parameters.ExtensionEndpoints.InternalEndpoints) { XElement internalEndpointElement = new XElement(XName.Get("InternalEndpoint", "http://schemas.microsoft.com/windowsazure")); internalEndpointsSequenceElement.Add(internalEndpointElement); XElement nameElement2 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement2.Value = internalEndpointsItem.Name; internalEndpointElement.Add(nameElement2); XElement protocolElement2 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure")); protocolElement2.Value = internalEndpointsItem.Protocol; internalEndpointElement.Add(protocolElement2); XElement portElement2 = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure")); portElement2.Value = internalEndpointsItem.Port.ToString(); internalEndpointElement.Add(portElement2); } endpointsElement.Add(internalEndpointsSequenceElement); } } if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null) { if (parameters.ExtensionEndpoints.InstanceInputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InstanceInputEndpoints).IsInitialized) { XElement instanceInputEndpointsSequenceElement = new XElement(XName.Get("InstanceInputEndpoints", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem in parameters.ExtensionEndpoints.InstanceInputEndpoints) { XElement instanceInputEndpointElement = new XElement(XName.Get("InstanceInputEndpoint", "http://schemas.microsoft.com/windowsazure")); instanceInputEndpointsSequenceElement.Add(instanceInputEndpointElement); XElement nameElement3 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement3.Value = instanceInputEndpointsItem.Name; instanceInputEndpointElement.Add(nameElement3); XElement protocolElement3 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure")); protocolElement3.Value = instanceInputEndpointsItem.Protocol; instanceInputEndpointElement.Add(protocolElement3); XElement localPortElement2 = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure")); localPortElement2.Value = instanceInputEndpointsItem.LocalPort; instanceInputEndpointElement.Add(localPortElement2); XElement fixedPortMinElement = new XElement(XName.Get("FixedPortMin", "http://schemas.microsoft.com/windowsazure")); fixedPortMinElement.Value = instanceInputEndpointsItem.FixedPortMin.ToString(); instanceInputEndpointElement.Add(fixedPortMinElement); XElement fixedPortMaxElement = new XElement(XName.Get("FixedPortMax", "http://schemas.microsoft.com/windowsazure")); fixedPortMaxElement.Value = instanceInputEndpointsItem.FixedPortMax.ToString(); instanceInputEndpointElement.Add(fixedPortMaxElement); } endpointsElement.Add(instanceInputEndpointsSequenceElement); } } } if (parameters.PublicConfigurationSchema != null) { XElement publicConfigurationSchemaElement = new XElement(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); publicConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PublicConfigurationSchema); extensionImageElement.Add(publicConfigurationSchemaElement); } if (parameters.PrivateConfigurationSchema != null) { XElement privateConfigurationSchemaElement = new XElement(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); privateConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PrivateConfigurationSchema); extensionImageElement.Add(privateConfigurationSchemaElement); } if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; extensionImageElement.Add(descriptionElement); } if (parameters.PublisherName != null) { XElement publisherNameElement = new XElement(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure")); publisherNameElement.Value = parameters.PublisherName; extensionImageElement.Add(publisherNameElement); } if (parameters.PublishedDate != null) { XElement publishedDateElement = new XElement(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); publishedDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PublishedDate.Value.ToUniversalTime()); extensionImageElement.Add(publishedDateElement); } if (parameters.LocalResources != null) { XElement localResourcesSequenceElement = new XElement(XName.Get("LocalResources", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionLocalResourceConfiguration localResourcesItem in parameters.LocalResources) { XElement localResourceElement = new XElement(XName.Get("LocalResource", "http://schemas.microsoft.com/windowsazure")); localResourcesSequenceElement.Add(localResourceElement); XElement nameElement4 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement4.Value = localResourcesItem.Name; localResourceElement.Add(nameElement4); if (localResourcesItem.SizeInMB != null) { XElement sizeInMBElement = new XElement(XName.Get("SizeInMB", "http://schemas.microsoft.com/windowsazure")); sizeInMBElement.Value = localResourcesItem.SizeInMB.ToString(); localResourceElement.Add(sizeInMBElement); } } extensionImageElement.Add(localResourcesSequenceElement); } if (parameters.BlockRoleUponFailure != null) { XElement blockRoleUponFailureElement = new XElement(XName.Get("BlockRoleUponFailure", "http://schemas.microsoft.com/windowsazure")); blockRoleUponFailureElement.Value = parameters.BlockRoleUponFailure.ToString().ToLower(); extensionImageElement.Add(blockRoleUponFailureElement); } if (parameters.IsInternalExtension != null) { XElement isInternalExtensionElement = new XElement(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure")); isInternalExtensionElement.Value = parameters.IsInternalExtension.ToString().ToLower(); extensionImageElement.Add(isInternalExtensionElement); } if (parameters.SampleConfig != null) { XElement sampleConfigElement = new XElement(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure")); sampleConfigElement.Value = TypeConversion.ToBase64String(parameters.SampleConfig); extensionImageElement.Add(sampleConfigElement); } if (parameters.ReplicationCompleted != null) { XElement replicationCompletedElement = new XElement(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure")); replicationCompletedElement.Value = parameters.ReplicationCompleted.ToString().ToLower(); extensionImageElement.Add(replicationCompletedElement); } if (parameters.Eula != null) { XElement eulaElement = new XElement(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); eulaElement.Value = parameters.Eula.AbsoluteUri; extensionImageElement.Add(eulaElement); } if (parameters.PrivacyUri != null) { XElement privacyUriElement = new XElement(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); privacyUriElement.Value = parameters.PrivacyUri.AbsoluteUri; extensionImageElement.Add(privacyUriElement); } if (parameters.HomepageUri != null) { XElement homepageUriElement = new XElement(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure")); homepageUriElement.Value = parameters.HomepageUri.AbsoluteUri; extensionImageElement.Add(homepageUriElement); } if (parameters.IsJsonExtension != null) { XElement isJsonExtensionElement = new XElement(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure")); isJsonExtensionElement.Value = parameters.IsJsonExtension.ToString().ToLower(); extensionImageElement.Add(isJsonExtensionElement); } if (parameters.DisallowMajorVersionUpgrade != null) { XElement disallowMajorVersionUpgradeElement = new XElement(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure")); disallowMajorVersionUpgradeElement.Value = parameters.DisallowMajorVersionUpgrade.ToString().ToLower(); extensionImageElement.Add(disallowMajorVersionUpgradeElement); } if (parameters.SupportedOS != null) { XElement supportedOSElement = new XElement(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure")); supportedOSElement.Value = parameters.SupportedOS; extensionImageElement.Add(supportedOSElement); } if (parameters.CompanyName != null) { XElement companyNameElement = new XElement(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure")); companyNameElement.Value = parameters.CompanyName; extensionImageElement.Add(companyNameElement); } if (parameters.Regions != null) { XElement regionsElement = new XElement(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure")); regionsElement.Value = parameters.Regions; extensionImageElement.Add(regionsElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Unregister a version of an extension that was previously registered /// using either the Register Extension or Update Extension APIs. An /// extension version is identified by the combination of its /// ProviderNamespace, Type and Version which are specified when /// registering the extension. Unregistering is only allowed for /// internal extensions, that is, the extensions for which the /// IsInternalExtension field is set to 'true' during registration or /// during an update. There is a quota (15) on the number of /// extensions that can be registered per subscription. If your /// subscription runs out of quota, you will wither need to unregister /// some of the internal extensions or contact Azure (same email used /// to become a publisher) to increase the quota. /// </summary> /// <param name='providerNamespace'> /// Required. The provider namespace of the extension image to /// unregister. /// </param> /// <param name='type'> /// Required. The type of the extension image to unregister. /// </param> /// <param name='version'> /// Required. The version of the extension image to unregister. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginUnregisteringAsync(string providerNamespace, string type, string version, CancellationToken cancellationToken) { // Validate if (providerNamespace == null) { throw new ArgumentNullException("providerNamespace"); } if (type == null) { throw new ArgumentNullException("type"); } if (version == null) { throw new ArgumentNullException("version"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("providerNamespace", providerNamespace); tracingParameters.Add("type", type); tracingParameters.Add("version", version); TracingAdapter.Enter(invocationId, this, "BeginUnregisteringAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/extensions/"; url = url + Uri.EscapeDataString(providerNamespace); url = url + "/"; url = url + Uri.EscapeDataString(type); url = url + "/"; url = url + Uri.EscapeDataString(version); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-09-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a new extension. It is allowed to update an extension which /// had already been registered with the same identity (i.e. /// combination of ProviderNamespace and Type) but with different /// version. It will fail if the extension to update has an identity /// that has not been registered before, or there is already an /// extension with the same identity and same version. /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Update Virtual Machine /// Extension Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginUpdatingAsync(ExtensionImageUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Certificate != null) { if (parameters.Certificate.StoreLocation == null) { throw new ArgumentNullException("parameters.Certificate.StoreLocation"); } } if (parameters.ExtensionEndpoints != null) { if (parameters.ExtensionEndpoints.InputEndpoints != null) { foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem in parameters.ExtensionEndpoints.InputEndpoints) { if (inputEndpointsParameterItem.LocalPort == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort"); } if (inputEndpointsParameterItem.Name == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Name"); } if (inputEndpointsParameterItem.Protocol == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InputEndpoints.Protocol"); } } } if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null) { foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem in parameters.ExtensionEndpoints.InstanceInputEndpoints) { if (instanceInputEndpointsParameterItem.LocalPort == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort"); } if (instanceInputEndpointsParameterItem.Name == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name"); } if (instanceInputEndpointsParameterItem.Protocol == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol"); } } } if (parameters.ExtensionEndpoints.InternalEndpoints != null) { foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem in parameters.ExtensionEndpoints.InternalEndpoints) { if (internalEndpointsParameterItem.Name == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Name"); } if (internalEndpointsParameterItem.Protocol == null) { throw new ArgumentNullException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol"); } } } } if (parameters.LocalResources != null) { foreach (ExtensionLocalResourceConfiguration localResourcesParameterItem in parameters.LocalResources) { if (localResourcesParameterItem.Name == null) { throw new ArgumentNullException("parameters.LocalResources.Name"); } } } if (parameters.ProviderNameSpace == null) { throw new ArgumentNullException("parameters.ProviderNameSpace"); } if (parameters.Type == null) { throw new ArgumentNullException("parameters.Type"); } if (parameters.Version == null) { throw new ArgumentNullException("parameters.Version"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/extensions"; List<string> queryParameters = new List<string>(); queryParameters.Add("action=update"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-09-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement extensionImageElement = new XElement(XName.Get("ExtensionImage", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(extensionImageElement); XElement providerNameSpaceElement = new XElement(XName.Get("ProviderNameSpace", "http://schemas.microsoft.com/windowsazure")); providerNameSpaceElement.Value = parameters.ProviderNameSpace; extensionImageElement.Add(providerNameSpaceElement); XElement typeElement = new XElement(XName.Get("Type", "http://schemas.microsoft.com/windowsazure")); typeElement.Value = parameters.Type; extensionImageElement.Add(typeElement); XElement versionElement = new XElement(XName.Get("Version", "http://schemas.microsoft.com/windowsazure")); versionElement.Value = parameters.Version; extensionImageElement.Add(versionElement); if (parameters.Label != null) { XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = parameters.Label; extensionImageElement.Add(labelElement); } if (parameters.HostingResources != null) { XElement hostingResourcesElement = new XElement(XName.Get("HostingResources", "http://schemas.microsoft.com/windowsazure")); hostingResourcesElement.Value = parameters.HostingResources; extensionImageElement.Add(hostingResourcesElement); } if (parameters.MediaLink != null) { XElement mediaLinkElement = new XElement(XName.Get("MediaLink", "http://schemas.microsoft.com/windowsazure")); mediaLinkElement.Value = parameters.MediaLink.AbsoluteUri; extensionImageElement.Add(mediaLinkElement); } if (parameters.Certificate != null) { XElement certificateElement = new XElement(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")); extensionImageElement.Add(certificateElement); XElement storeLocationElement = new XElement(XName.Get("StoreLocation", "http://schemas.microsoft.com/windowsazure")); storeLocationElement.Value = parameters.Certificate.StoreLocation; certificateElement.Add(storeLocationElement); if (parameters.Certificate.StoreName != null) { XElement storeNameElement = new XElement(XName.Get("StoreName", "http://schemas.microsoft.com/windowsazure")); storeNameElement.Value = parameters.Certificate.StoreName; certificateElement.Add(storeNameElement); } if (parameters.Certificate.ThumbprintRequired != null) { XElement thumbprintRequiredElement = new XElement(XName.Get("ThumbprintRequired", "http://schemas.microsoft.com/windowsazure")); thumbprintRequiredElement.Value = parameters.Certificate.ThumbprintRequired.ToString().ToLower(); certificateElement.Add(thumbprintRequiredElement); } if (parameters.Certificate.ThumbprintAlgorithm != null) { XElement thumbprintAlgorithmElement = new XElement(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure")); thumbprintAlgorithmElement.Value = parameters.Certificate.ThumbprintAlgorithm; certificateElement.Add(thumbprintAlgorithmElement); } } if (parameters.ExtensionEndpoints != null) { XElement endpointsElement = new XElement(XName.Get("Endpoints", "http://schemas.microsoft.com/windowsazure")); extensionImageElement.Add(endpointsElement); if (parameters.ExtensionEndpoints.InputEndpoints != null) { if (parameters.ExtensionEndpoints.InputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InputEndpoints).IsInitialized) { XElement inputEndpointsSequenceElement = new XElement(XName.Get("InputEndpoints", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem in parameters.ExtensionEndpoints.InputEndpoints) { XElement inputEndpointElement = new XElement(XName.Get("InputEndpoint", "http://schemas.microsoft.com/windowsazure")); inputEndpointsSequenceElement.Add(inputEndpointElement); XElement nameElement = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement.Value = inputEndpointsItem.Name; inputEndpointElement.Add(nameElement); XElement protocolElement = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure")); protocolElement.Value = inputEndpointsItem.Protocol; inputEndpointElement.Add(protocolElement); XElement portElement = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure")); portElement.Value = inputEndpointsItem.Port.ToString(); inputEndpointElement.Add(portElement); XElement localPortElement = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure")); localPortElement.Value = inputEndpointsItem.LocalPort; inputEndpointElement.Add(localPortElement); } endpointsElement.Add(inputEndpointsSequenceElement); } } if (parameters.ExtensionEndpoints.InternalEndpoints != null) { if (parameters.ExtensionEndpoints.InternalEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InternalEndpoints).IsInitialized) { XElement internalEndpointsSequenceElement = new XElement(XName.Get("InternalEndpoints", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem in parameters.ExtensionEndpoints.InternalEndpoints) { XElement internalEndpointElement = new XElement(XName.Get("InternalEndpoint", "http://schemas.microsoft.com/windowsazure")); internalEndpointsSequenceElement.Add(internalEndpointElement); XElement nameElement2 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement2.Value = internalEndpointsItem.Name; internalEndpointElement.Add(nameElement2); XElement protocolElement2 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure")); protocolElement2.Value = internalEndpointsItem.Protocol; internalEndpointElement.Add(protocolElement2); XElement portElement2 = new XElement(XName.Get("Port", "http://schemas.microsoft.com/windowsazure")); portElement2.Value = internalEndpointsItem.Port.ToString(); internalEndpointElement.Add(portElement2); } endpointsElement.Add(internalEndpointsSequenceElement); } } if (parameters.ExtensionEndpoints.InstanceInputEndpoints != null) { if (parameters.ExtensionEndpoints.InstanceInputEndpoints is ILazyCollection == false || ((ILazyCollection)parameters.ExtensionEndpoints.InstanceInputEndpoints).IsInitialized) { XElement instanceInputEndpointsSequenceElement = new XElement(XName.Get("InstanceInputEndpoints", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem in parameters.ExtensionEndpoints.InstanceInputEndpoints) { XElement instanceInputEndpointElement = new XElement(XName.Get("InstanceInputEndpoint", "http://schemas.microsoft.com/windowsazure")); instanceInputEndpointsSequenceElement.Add(instanceInputEndpointElement); XElement nameElement3 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement3.Value = instanceInputEndpointsItem.Name; instanceInputEndpointElement.Add(nameElement3); XElement protocolElement3 = new XElement(XName.Get("Protocol", "http://schemas.microsoft.com/windowsazure")); protocolElement3.Value = instanceInputEndpointsItem.Protocol; instanceInputEndpointElement.Add(protocolElement3); XElement localPortElement2 = new XElement(XName.Get("LocalPort", "http://schemas.microsoft.com/windowsazure")); localPortElement2.Value = instanceInputEndpointsItem.LocalPort; instanceInputEndpointElement.Add(localPortElement2); XElement fixedPortMinElement = new XElement(XName.Get("FixedPortMin", "http://schemas.microsoft.com/windowsazure")); fixedPortMinElement.Value = instanceInputEndpointsItem.FixedPortMin.ToString(); instanceInputEndpointElement.Add(fixedPortMinElement); XElement fixedPortMaxElement = new XElement(XName.Get("FixedPortMax", "http://schemas.microsoft.com/windowsazure")); fixedPortMaxElement.Value = instanceInputEndpointsItem.FixedPortMax.ToString(); instanceInputEndpointElement.Add(fixedPortMaxElement); } endpointsElement.Add(instanceInputEndpointsSequenceElement); } } } if (parameters.PublicConfigurationSchema != null) { XElement publicConfigurationSchemaElement = new XElement(XName.Get("PublicConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); publicConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PublicConfigurationSchema); extensionImageElement.Add(publicConfigurationSchemaElement); } if (parameters.PrivateConfigurationSchema != null) { XElement privateConfigurationSchemaElement = new XElement(XName.Get("PrivateConfigurationSchema", "http://schemas.microsoft.com/windowsazure")); privateConfigurationSchemaElement.Value = TypeConversion.ToBase64String(parameters.PrivateConfigurationSchema); extensionImageElement.Add(privateConfigurationSchemaElement); } if (parameters.Description != null) { XElement descriptionElement = new XElement(XName.Get("Description", "http://schemas.microsoft.com/windowsazure")); descriptionElement.Value = parameters.Description; extensionImageElement.Add(descriptionElement); } if (parameters.PublisherName != null) { XElement publisherNameElement = new XElement(XName.Get("PublisherName", "http://schemas.microsoft.com/windowsazure")); publisherNameElement.Value = parameters.PublisherName; extensionImageElement.Add(publisherNameElement); } if (parameters.PublishedDate != null) { XElement publishedDateElement = new XElement(XName.Get("PublishedDate", "http://schemas.microsoft.com/windowsazure")); publishedDateElement.Value = string.Format(CultureInfo.InvariantCulture, "{0:O}", parameters.PublishedDate.Value.ToUniversalTime()); extensionImageElement.Add(publishedDateElement); } if (parameters.LocalResources != null) { XElement localResourcesSequenceElement = new XElement(XName.Get("LocalResources", "http://schemas.microsoft.com/windowsazure")); foreach (ExtensionLocalResourceConfiguration localResourcesItem in parameters.LocalResources) { XElement localResourceElement = new XElement(XName.Get("LocalResource", "http://schemas.microsoft.com/windowsazure")); localResourcesSequenceElement.Add(localResourceElement); XElement nameElement4 = new XElement(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); nameElement4.Value = localResourcesItem.Name; localResourceElement.Add(nameElement4); if (localResourcesItem.SizeInMB != null) { XElement sizeInMBElement = new XElement(XName.Get("SizeInMB", "http://schemas.microsoft.com/windowsazure")); sizeInMBElement.Value = localResourcesItem.SizeInMB.ToString(); localResourceElement.Add(sizeInMBElement); } } extensionImageElement.Add(localResourcesSequenceElement); } if (parameters.BlockRoleUponFailure != null) { XElement blockRoleUponFailureElement = new XElement(XName.Get("BlockRoleUponFailure", "http://schemas.microsoft.com/windowsazure")); blockRoleUponFailureElement.Value = parameters.BlockRoleUponFailure.ToString().ToLower(); extensionImageElement.Add(blockRoleUponFailureElement); } if (parameters.IsInternalExtension != null) { XElement isInternalExtensionElement = new XElement(XName.Get("IsInternalExtension", "http://schemas.microsoft.com/windowsazure")); isInternalExtensionElement.Value = parameters.IsInternalExtension.ToString().ToLower(); extensionImageElement.Add(isInternalExtensionElement); } if (parameters.SampleConfig != null) { XElement sampleConfigElement = new XElement(XName.Get("SampleConfig", "http://schemas.microsoft.com/windowsazure")); sampleConfigElement.Value = TypeConversion.ToBase64String(parameters.SampleConfig); extensionImageElement.Add(sampleConfigElement); } if (parameters.ReplicationCompleted != null) { XElement replicationCompletedElement = new XElement(XName.Get("ReplicationCompleted", "http://schemas.microsoft.com/windowsazure")); replicationCompletedElement.Value = parameters.ReplicationCompleted.ToString().ToLower(); extensionImageElement.Add(replicationCompletedElement); } if (parameters.Eula != null) { XElement eulaElement = new XElement(XName.Get("Eula", "http://schemas.microsoft.com/windowsazure")); eulaElement.Value = parameters.Eula.AbsoluteUri; extensionImageElement.Add(eulaElement); } if (parameters.PrivacyUri != null) { XElement privacyUriElement = new XElement(XName.Get("PrivacyUri", "http://schemas.microsoft.com/windowsazure")); privacyUriElement.Value = parameters.PrivacyUri.AbsoluteUri; extensionImageElement.Add(privacyUriElement); } if (parameters.HomepageUri != null) { XElement homepageUriElement = new XElement(XName.Get("HomepageUri", "http://schemas.microsoft.com/windowsazure")); homepageUriElement.Value = parameters.HomepageUri.AbsoluteUri; extensionImageElement.Add(homepageUriElement); } if (parameters.IsJsonExtension != null) { XElement isJsonExtensionElement = new XElement(XName.Get("IsJsonExtension", "http://schemas.microsoft.com/windowsazure")); isJsonExtensionElement.Value = parameters.IsJsonExtension.ToString().ToLower(); extensionImageElement.Add(isJsonExtensionElement); } if (parameters.DisallowMajorVersionUpgrade != null) { XElement disallowMajorVersionUpgradeElement = new XElement(XName.Get("DisallowMajorVersionUpgrade", "http://schemas.microsoft.com/windowsazure")); disallowMajorVersionUpgradeElement.Value = parameters.DisallowMajorVersionUpgrade.ToString().ToLower(); extensionImageElement.Add(disallowMajorVersionUpgradeElement); } if (parameters.SupportedOS != null) { XElement supportedOSElement = new XElement(XName.Get("SupportedOS", "http://schemas.microsoft.com/windowsazure")); supportedOSElement.Value = parameters.SupportedOS; extensionImageElement.Add(supportedOSElement); } if (parameters.CompanyName != null) { XElement companyNameElement = new XElement(XName.Get("CompanyName", "http://schemas.microsoft.com/windowsazure")); companyNameElement.Value = parameters.CompanyName; extensionImageElement.Add(companyNameElement); } if (parameters.Regions != null) { XElement regionsElement = new XElement(XName.Get("Regions", "http://schemas.microsoft.com/windowsazure")); regionsElement.Value = parameters.Regions; extensionImageElement.Add(regionsElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Register a new extension. An extension is identified by the /// combination of its ProviderNamespace and Type (case-sensitive /// string). It is not allowed to register an extension with the same /// identity (i.e. combination of ProviderNamespace and Type) of an /// already-registered extension. To register new version of an /// existing extension, the Update Extension API should be used. /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Register Virtual Machine /// Extension Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> RegisterAsync(ExtensionImageRegisterParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ExtensionImages.BeginRegisteringAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// Unregister a version of an extension that was previously registered /// using either the Register Extension or Update Extension APIs. An /// extension version is identified by the combination of its /// ProviderNamespace, Type and Version which are specified when /// registering the extension. Unregistering is only allowed for /// internal extensions, that is, the extensions for which the /// IsInternalExtension field is set to 'true' during registration or /// during an update. There is a quota (15) on the number of /// extensions that can be registered per subscription. If your /// subscription runs out of quota, you will wither need to unregister /// some of the internal extensions or contact Azure (same email used /// to become a publisher) to increase the quota. /// </summary> /// <param name='providerNamespace'> /// Required. The provider namespace of the extension image to /// unregister. /// </param> /// <param name='type'> /// Required. The type of the extension image to unregister. /// </param> /// <param name='version'> /// Required. The version of the extension image to unregister. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> UnregisterAsync(string providerNamespace, string type, string version, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("providerNamespace", providerNamespace); tracingParameters.Add("type", type); tracingParameters.Add("version", version); TracingAdapter.Enter(invocationId, this, "UnregisterAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ExtensionImages.BeginUnregisteringAsync(providerNamespace, type, version, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// Update a new extension. It is allowed to update an extension which /// had already been registered with the same identity (i.e. /// combination of ProviderNamespace and Type) but with different /// version. It will fail if the extension to update has an identity /// that has not been registered before, or there is already an /// extension with the same identity and same version. /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Update Virtual Machine /// Extension Image operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> UpdateAsync(ExtensionImageUpdateParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ExtensionImages.BeginUpdatingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace SampleWebAPIApp.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); } } } }
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Globalization; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Schema { internal class JsonSchemaBuilder { private JsonReader _reader; private readonly IList<JsonSchema> _stack; private readonly JsonSchemaResolver _resolver; private JsonSchema _currentSchema; private void Push(JsonSchema value) { _currentSchema = value; _stack.Add(value); _resolver.LoadedSchemas.Add(value); } private JsonSchema Pop() { JsonSchema poppedSchema = _currentSchema; _stack.RemoveAt(_stack.Count - 1); _currentSchema = _stack.LastOrDefault(); return poppedSchema; } private JsonSchema CurrentSchema { get { return _currentSchema; } } public JsonSchemaBuilder(JsonSchemaResolver resolver) { _stack = new List<JsonSchema>(); _resolver = resolver; } internal JsonSchema Parse(JsonReader reader) { _reader = reader; if (reader.TokenType == JsonToken.None) _reader.Read(); return BuildSchema(); } private JsonSchema BuildSchema() { if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); _reader.Read(); // empty schema object if (_reader.TokenType == JsonToken.EndObject) { Push(new JsonSchema()); return Pop(); } string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); // schema reference if (propertyName == JsonSchemaConstants.ReferencePropertyName) { string id = (string)_reader.Value; // skip to the end of the current object while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { if (_reader.TokenType == JsonToken.StartObject) throw new Exception("Found StartObject within the schema reference with the Id '{0}'" .FormatWith(CultureInfo.InvariantCulture, id)); } JsonSchema referencedSchema = _resolver.GetSchema(id); if (referencedSchema == null) throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id)); return referencedSchema; } // regular ol' schema object Push(new JsonSchema()); ProcessSchemaProperty(propertyName); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); ProcessSchemaProperty(propertyName); } return Pop(); } private void ProcessSchemaProperty(string propertyName) { switch (propertyName) { case JsonSchemaConstants.TypePropertyName: CurrentSchema.Type = ProcessType(); break; case JsonSchemaConstants.IdPropertyName: CurrentSchema.Id = (string) _reader.Value; break; case JsonSchemaConstants.TitlePropertyName: CurrentSchema.Title = (string) _reader.Value; break; case JsonSchemaConstants.DescriptionPropertyName: CurrentSchema.Description = (string)_reader.Value; break; case JsonSchemaConstants.PropertiesPropertyName: ProcessProperties(); break; case JsonSchemaConstants.ItemsPropertyName: ProcessItems(); break; case JsonSchemaConstants.AdditionalPropertiesPropertyName: ProcessAdditionalProperties(); break; case JsonSchemaConstants.PatternPropertiesPropertyName: ProcessPatternProperties(); break; case JsonSchemaConstants.RequiredPropertyName: CurrentSchema.Required = (bool)_reader.Value; break; case JsonSchemaConstants.RequiresPropertyName: CurrentSchema.Requires = (string) _reader.Value; break; case JsonSchemaConstants.IdentityPropertyName: ProcessIdentity(); break; case JsonSchemaConstants.MinimumPropertyName: CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MaximumPropertyName: CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.ExclusiveMinimumPropertyName: CurrentSchema.ExclusiveMinimum = (bool)_reader.Value; break; case JsonSchemaConstants.ExclusiveMaximumPropertyName: CurrentSchema.ExclusiveMaximum = (bool)_reader.Value; break; case JsonSchemaConstants.MaximumLengthPropertyName: CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MinimumLengthPropertyName: CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MaximumItemsPropertyName: CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.MinimumItemsPropertyName: CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.DivisibleByPropertyName: CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); break; case JsonSchemaConstants.DisallowPropertyName: CurrentSchema.Disallow = ProcessType(); break; case JsonSchemaConstants.DefaultPropertyName: ProcessDefault(); break; case JsonSchemaConstants.HiddenPropertyName: CurrentSchema.Hidden = (bool) _reader.Value; break; case JsonSchemaConstants.ReadOnlyPropertyName: CurrentSchema.ReadOnly = (bool) _reader.Value; break; case JsonSchemaConstants.FormatPropertyName: CurrentSchema.Format = (string) _reader.Value; break; case JsonSchemaConstants.PatternPropertyName: CurrentSchema.Pattern = (string) _reader.Value; break; case JsonSchemaConstants.OptionsPropertyName: ProcessOptions(); break; case JsonSchemaConstants.EnumPropertyName: ProcessEnum(); break; case JsonSchemaConstants.ExtendsPropertyName: ProcessExtends(); break; default: _reader.Skip(); break; } } private void ProcessExtends() { CurrentSchema.Extends = BuildSchema(); } private void ProcessEnum() { if (_reader.TokenType != JsonToken.StartArray) throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); CurrentSchema.Enum = new List<JToken>(); while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { JToken value = JToken.ReadFrom(_reader); CurrentSchema.Enum.Add(value); } } private void ProcessOptions() { CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer()); switch (_reader.TokenType) { case JsonToken.StartArray: while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); string label = null; JToken value = null; while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); switch (propertyName) { case JsonSchemaConstants.OptionValuePropertyName: value = JToken.ReadFrom(_reader); break; case JsonSchemaConstants.OptionLabelPropertyName: label = (string) _reader.Value; break; default: throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } } if (value == null) throw new Exception("No value specified for JSON schema option."); if (CurrentSchema.Options.ContainsKey(value)) throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value)); CurrentSchema.Options.Add(value, label); } break; default: throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } private void ProcessDefault() { CurrentSchema.Default = JToken.ReadFrom(_reader); } private void ProcessIdentity() { CurrentSchema.Identity = new List<string>(); switch (_reader.TokenType) { case JsonToken.String: CurrentSchema.Identity.Add(_reader.Value.ToString()); break; case JsonToken.StartArray: while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.String) throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); CurrentSchema.Identity.Add(_reader.Value.ToString()); } break; default: throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } private void ProcessAdditionalProperties() { if (_reader.TokenType == JsonToken.Boolean) CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value; else CurrentSchema.AdditionalProperties = BuildSchema(); } private void ProcessPatternProperties() { Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>(); if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expected start object token."); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); if (patternProperties.ContainsKey(propertyName)) throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); patternProperties.Add(propertyName, BuildSchema()); } CurrentSchema.PatternProperties = patternProperties; } private void ProcessItems() { CurrentSchema.Items = new List<JsonSchema>(); switch (_reader.TokenType) { case JsonToken.StartObject: CurrentSchema.Items.Add(BuildSchema()); break; case JsonToken.StartArray: while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { CurrentSchema.Items.Add(BuildSchema()); } break; default: throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } private void ProcessProperties() { IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>(); if (_reader.TokenType != JsonToken.StartObject) throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); _reader.Read(); if (properties.ContainsKey(propertyName)) throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); properties.Add(propertyName, BuildSchema()); } CurrentSchema.Properties = properties; } private JsonSchemaType? ProcessType() { switch (_reader.TokenType) { case JsonToken.String: return MapType(_reader.Value.ToString()); case JsonToken.StartArray: // ensure type is in blank state before ORing values JsonSchemaType? type = JsonSchemaType.None; while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.String) throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); type = type | MapType(_reader.Value.ToString()); } return type; default: throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } internal static JsonSchemaType MapType(string type) { JsonSchemaType mappedType; if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType)) throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); return mappedType; } internal static string MapType(JsonSchemaType type) { return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key; } } } #endif
// ============================================================================ // FileName: SIPProxyCore.cs // // Description: // A SIP proxy core that routes SIP requests and responses to and from other SIP servers. // // Author(s): // Aaron Clauson // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2006-2008 Aaron Clauson (aaronc@blueface.ie), Blue Face Ltd, Dublin, Ireland (www.blueface.ie) // 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 Blue Face Ltd. // nor the names of its contributors may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, // BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using SIPSorcery.Net; using SIPSorcery.SIP; using SIPSorcery.SIP.App; using SIPSorcery.Sys; using log4net; using Microsoft.Scripting.Hosting; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.Servers { public delegate SIPEndPoint GetAppServerDelegate(); public class SIPProxyCore { private static ILog logger = log4net.LogManager.GetLogger("sipproxy"); //private static string m_branchIdSuffix = Crypto.GetRandomString(6); // A string that will be appended to Via branch ID's used by thsi proxy, used for Loop identification private SIPMonitorLogDelegate m_proxyLogger = (e) => { }; private SIPTransport m_sipTransport; private CompiledCode m_compiledScript; private string m_scriptPath; private ScriptLoader m_scriptLoader; private SIPProxyScriptFacade m_proxyScriptFacade; private SIPProxyDispatcher m_proxyDispatcher; private SIPCallDispatcherFile m_sipCallDispatcherFile; private DateTime m_lastScriptChange = DateTime.MinValue; public IPAddress PublicIPAddress; // Can be set if there is an object somewhere that knows the public IP. The address wil be available in the proxy runtime script. public SIPProxyCore( SIPMonitorLogDelegate proxyLogger, SIPTransport sipTransport, string scriptPath, string appServerEndPointsPath) { try { m_proxyLogger = proxyLogger ?? m_proxyLogger; m_scriptPath = scriptPath; m_sipTransport = sipTransport; if (!appServerEndPointsPath.IsNullOrBlank() && File.Exists(appServerEndPointsPath)) { m_sipCallDispatcherFile = new SIPCallDispatcherFile(SendMonitorEvent, appServerEndPointsPath); m_sipCallDispatcherFile.LoadAndWatch(); } else { logger.Warn("No call dispatcher file specified for SIP Proxy."); } m_proxyDispatcher = new SIPProxyDispatcher(new SIPMonitorLogDelegate(SendMonitorEvent)); GetAppServerDelegate getAppServer = (m_sipCallDispatcherFile != null) ? new GetAppServerDelegate(m_sipCallDispatcherFile.GetAppServer) : null; m_proxyScriptFacade = new SIPProxyScriptFacade( new SIPMonitorLogDelegate(SendMonitorEvent), // Don't use the m_proxyLogger delegate directly here as doing so caused stack overflow exceptions in the IronRuby engine. sipTransport, m_proxyDispatcher, getAppServer); m_scriptLoader = new ScriptLoader(SendMonitorEvent, m_scriptPath); m_scriptLoader.ScriptFileChanged += (s, e) => { m_compiledScript = m_scriptLoader.GetCompiledScript(); }; m_compiledScript = m_scriptLoader.GetCompiledScript(); // Events that pass the SIP requests and responses onto the Stateless Proxy Core. m_sipTransport.SIPTransportRequestReceived += GotRequest; m_sipTransport.SIPTransportResponseReceived += GotResponse; } catch (Exception excp) { logger.Error("Exception SIPProxyCore (ctor). " + excp.Message); throw excp; } } /// <summary> /// From RFC3261: Stateless Proxy Request Processing: /// /// For each target, the proxy forwards the request following these /// 1. Make a copy of the received request /// 2. Update the Request-URI /// 3. Update the Max-Forwards header field /// 4. Optionally add a Record-route header field value /// 5. Optionally add additional header fields /// 6. Postprocess routing information /// 7. Determine the next-hop address, port, and transport /// 8. Add a Via header field value /// 9. Add a Content-Length header field if necessary /// 10. Forward the new request /// /// See sections 12.2.1.1 and 16.12.1.2 in the SIP RFC for the best explanation on the way the Route header works. /// </summary> /// <param name="sipRequest"></param> /// <param name="inEndPoint">End point the request was received on.</param> /// <param name="sipChannel"></param> private void GotRequest(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPRequest sipRequest) { try { // Calculate the proxy branch parameter for this request. The branch parameter has to be calculated so that INVITE's and CANCEL's generate the same branchid. //string toTag = (sipRequest.Header.To != null) ? sipRequest.Header.To.ToTag : null; //string fromTag = (sipRequest.Header.From != null) ? sipRequest.Header.From.FromTag : null; string route = (sipRequest.Header.Routes != null) ? sipRequest.Header.Routes.ToString() : null; //string authHeader = (sipRequest.Header.AuthenticationHeader != null) ? sipRequest.Header.AuthenticationHeader.ToString() : null; string proxyBranch = CallProperties.CreateBranchId(SIPConstants.SIP_BRANCH_MAGICCOOKIE, null, null, sipRequest.Header.CallId, sipRequest.URI.ToString(), null, sipRequest.Header.CSeq, route, null, null); // Check whether the branch parameter already exists in the Via list. One instance of an already added Via header will be allowed to support a single spiral. int loopedViaCount = 0; foreach (SIPViaHeader viaHeader in sipRequest.Header.Vias.Via) { //if (viaHeader.Branch == proxyBranch) SIPEndPoint sentFromEndPoint = SIPEndPoint.TryParse(viaHeader.Transport + ":" + viaHeader.ContactAddress); if (sentFromEndPoint != null && m_sipTransport.IsLocalSIPEndPoint(sentFromEndPoint)) { loopedViaCount++; } if (loopedViaCount >= 2) { SendMonitorEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.SIPProxy, SIPMonitorEventTypesEnum.Warn, "Loop detected on request from " + remoteEndPoint + " to " + sipRequest.URI.ToString() + ".", null)); m_sipTransport.SendResponse(SIPTransport.GetResponse(sipRequest, SIPResponseStatusCodesEnum.LoopDetected, null)); return; } } // Used in the proxy monitor messages only, plays no part in request routing. string fromUser = (sipRequest.Header.From != null) ? sipRequest.Header.From.FromURI.User : null; string toUser = (sipRequest.Header.To != null) ? sipRequest.Header.To.ToURI.User : null; string summaryStr = "req " + sipRequest.Method + " from=" + fromUser + ", to=" + toUser + ", " + remoteEndPoint.ToString(); bool isFromAppServer = (m_sipCallDispatcherFile != null) ? m_sipCallDispatcherFile.IsAppServerEndPoint(remoteEndPoint) : false; lock (this) { m_compiledScript.DefaultScope.RemoveVariable("sys"); m_compiledScript.DefaultScope.RemoveVariable("localEndPoint"); m_compiledScript.DefaultScope.RemoveVariable("isreq"); m_compiledScript.DefaultScope.RemoveVariable("req"); m_compiledScript.DefaultScope.RemoveVariable("remoteEndPoint"); m_compiledScript.DefaultScope.RemoveVariable("summary"); m_compiledScript.DefaultScope.RemoveVariable("proxyBranch"); m_compiledScript.DefaultScope.RemoveVariable("sipMethod"); m_compiledScript.DefaultScope.RemoveVariable("publicip"); m_compiledScript.DefaultScope.RemoveVariable("IsFromAppServer"); m_compiledScript.DefaultScope.SetVariable("sys", m_proxyScriptFacade); m_compiledScript.DefaultScope.SetVariable("localEndPoint", localSIPEndPoint); m_compiledScript.DefaultScope.SetVariable("isreq", true); m_compiledScript.DefaultScope.SetVariable("req", sipRequest); m_compiledScript.DefaultScope.SetVariable("remoteEndPoint", remoteEndPoint); m_compiledScript.DefaultScope.SetVariable("summary", summaryStr); m_compiledScript.DefaultScope.SetVariable("proxyBranch", proxyBranch); m_compiledScript.DefaultScope.SetVariable("sipMethod", sipRequest.Method.ToString()); m_compiledScript.DefaultScope.SetVariable("publicip", PublicIPAddress); m_compiledScript.DefaultScope.SetVariable("IsFromAppServer", isFromAppServer); m_compiledScript.Execute(); } //if (requestStopwatch.ElapsedMilliseconds > 20) //{ // logger.Debug("GotRequest processing time=" + requestStopwatch.ElapsedMilliseconds + "ms, script time=" + scriptStopwatch.ElapsedMilliseconds + "ms."); //} } catch (SIPValidationException) { throw; } catch (Exception excp) { string remoteEndPointStr = (remoteEndPoint != null) ? remoteEndPoint.ToString() : null; string reqExcpError = "Exception SIPProxyCore GotRequest (from " + remoteEndPointStr + "). " + excp.Message; logger.Error(reqExcpError); SIPMonitorEvent reqExcpEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.SIPProxy, SIPMonitorEventTypesEnum.Error, reqExcpError, localSIPEndPoint, remoteEndPoint, null); SendMonitorEvent(reqExcpEvent); throw excp; } } /// <summary> /// From RFC3261: Stateless Proxy Response Processing: /// /// When a response arrives at a stateless proxy, the proxy MUST inspect the sent-by value in the first /// (topmost) Via header field value. If that address matches the proxy, (it equals a value this proxy has /// inserted into previous requests) the proxy MUST remove that header field value from the response and /// forward the result to the location indicated in the next Via header field value. The proxy MUST NOT add /// to, modify, or remove the message body. Unless specified otherwise, the proxy MUST NOT remove /// any other header field values. If the address does not match the proxy, the message MUST be silently discarded. /// </summary> private void GotResponse(SIPEndPoint localSIPEndPoint, SIPEndPoint remoteEndPoint, SIPResponse sipResponse) { try { // Used in the proxy monitor messages only, plays no part in response processing. string fromUser = (sipResponse.Header.From != null) ? sipResponse.Header.From.FromURI.User : null; string toUser = (sipResponse.Header.To != null) ? sipResponse.Header.To.ToURI.User : null; string summaryStr = "resp " + sipResponse.Header.CSeqMethod + " from=" + fromUser + ", to=" + toUser + ", " + remoteEndPoint.ToString(); SIPViaHeader topVia = sipResponse.Header.Vias.PopTopViaHeader(); SIPEndPoint outSocket = localSIPEndPoint; // If the second Via header on the response was also set by this proxy it means the request was originally received and forwarded // on different sockets. To get the response to travel the same path in reverse it must be forwarded from the proxy socket indicated // by the second top Via. if (sipResponse.Header.Vias.Length > 1) { SIPViaHeader nextTopVia = sipResponse.Header.Vias.TopViaHeader; SIPEndPoint nextTopViaSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(nextTopVia.Transport + ":" + nextTopVia.ReceivedFromAddress); //if (!(PublicIPAddress != null && nextTopVia.ReceivedFromIPAddress != null && nextTopVia.ReceivedFromIPAddress != PublicIPAddress.ToString()) // && // (m_sipTransport.IsLocalSIPEndPoint(nextTopViaSIPEndPoint) || (PublicIPAddress != null && nextTopVia.ReceivedFromIPAddress == PublicIPAddress.ToString()))) if(m_sipTransport.IsLocalSIPEndPoint(nextTopViaSIPEndPoint)) { sipResponse.Header.Vias.PopTopViaHeader(); outSocket = nextTopViaSIPEndPoint; } } bool isFromAppServer = (m_sipCallDispatcherFile != null) ? m_sipCallDispatcherFile.IsAppServerEndPoint(remoteEndPoint) : false; lock (this) { m_compiledScript.DefaultScope.RemoveVariable("sys"); m_compiledScript.DefaultScope.RemoveVariable("isreq"); m_compiledScript.DefaultScope.RemoveVariable("localEndPoint"); m_compiledScript.DefaultScope.RemoveVariable("outSocket"); m_compiledScript.DefaultScope.RemoveVariable("resp"); m_compiledScript.DefaultScope.RemoveVariable("remoteEndPoint"); m_compiledScript.DefaultScope.RemoveVariable("summary"); m_compiledScript.DefaultScope.RemoveVariable("sipMethod"); m_compiledScript.DefaultScope.RemoveVariable("topVia"); m_compiledScript.DefaultScope.RemoveVariable("IsFromAppServer"); m_compiledScript.DefaultScope.SetVariable("sys", m_proxyScriptFacade); m_compiledScript.DefaultScope.SetVariable("isreq", false); m_compiledScript.DefaultScope.SetVariable("localEndPoint", localSIPEndPoint); m_compiledScript.DefaultScope.SetVariable("outSocket", outSocket); m_compiledScript.DefaultScope.SetVariable("resp", sipResponse); m_compiledScript.DefaultScope.SetVariable("remoteEndPoint", remoteEndPoint); m_compiledScript.DefaultScope.SetVariable("summary", summaryStr); m_compiledScript.DefaultScope.SetVariable("sipMethod", sipResponse.Header.CSeqMethod.ToString()); m_compiledScript.DefaultScope.SetVariable("topVia", topVia); m_compiledScript.DefaultScope.SetVariable("IsFromAppServer", isFromAppServer); m_compiledScript.Execute(); } //if (responseStopwatch.ElapsedMilliseconds > 20) //{ // logger.Debug("GotResponse processing time=" + responseStopwatch.ElapsedMilliseconds + "ms, script time=" + scriptStopwatch.ElapsedMilliseconds + "ms."); //} } catch (Exception excp) { string respExcpError = "Exception SIPProxyCore GotResponse. " + excp.Message; logger.Error(respExcpError + "\n" + sipResponse.ToString()); SIPMonitorEvent respExcpEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.SIPProxy, SIPMonitorEventTypesEnum.Error, respExcpError, localSIPEndPoint, remoteEndPoint, null); SendMonitorEvent(respExcpEvent); throw excp; } } private void SendMonitorEvent(SIPMonitorEventTypesEnum eventType, string message, SIPEndPoint localEndPoint, SIPEndPoint remoteEndPoint, SIPEndPoint dstEndPoint) { SIPMonitorEvent proxyEvent = new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.SIPProxy, eventType, message, localEndPoint, remoteEndPoint, dstEndPoint); SendMonitorEvent(proxyEvent); } private void SendMonitorEvent(SIPMonitorEvent monitorEvent) { if (m_proxyLogger != null) { m_proxyLogger(monitorEvent); } } #region Unit testing. #if UNITTEST #region Mock Objects /*public class ProxySIPChannel { public IPEndPoint m_unitTestEndPoint; // Used so that tests using this mock object can see the end point a message was sent to. public ProxySIPChannel() { } public ProxySIPChannel(IPEndPoint endPoint) { } public void Send(IPEndPoint endPoint, SIPResponse sipResponse) { m_unitTestEndPoint = endPoint; Console.WriteLine("Dummy Channel: Sending to: " + endPoint.Address.ToString() + ":" + endPoint.Port + "\r\n" + sipResponse.ToString()); } public void Send(IPEndPoint endPoint, SIPRequest sipRequest) { m_unitTestEndPoint = endPoint; Console.WriteLine("Dummy Channel: Sending to: " + endPoint.Address.ToString() + ":" + endPoint.Port + "\r\n" + sipRequest.ToString()); } }*/ #endregion /* [TestFixture] public class StatelessProxyCoreUnitTest { private static string m_CRLF = SIPConstants.CRLF; private static XmlDocument m_sipRoutes = new XmlDocument(); [TestFixtureSetUp] public void Init() { string sipRoutesXML = "<siproutes>" + " <inexsipserversocket>192.168.1.28:5061</inexsipserversocket>" + " <sipserversocket>192.168.1.28:5061</sipserversocket>" + "</siproutes>"; m_sipRoutes.LoadXml(sipRoutesXML); } [TestFixtureTearDown] public void Dispose() { } [Test] public void SampleTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); Assert.IsTrue(true, "True was false."); Console.WriteLine("---------------------------------"); } [Test] //[Ignore("Next hop tests only.")] public void ResponseAddViaHeaderTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); Assert.IsTrue(true, "True was false."); Console.WriteLine("---------------------------------"); } [Test] //[Ignore("Next hop tests only.")] public void ParseRouteNotForThisProxyBYEUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); string sipRequest = "BYE sip:bluesipd@192.168.1.2:5065 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK74ab714b;rport" + m_CRLF + "From: <sip:303@bluesipd>;tag=as6a65fae3" + m_CRLF + "To: bluesipd <sip:bluesipd@bluesipd:5065>;tag=1898247079" + m_CRLF + "Contact: <sip:303@213.168.225.133>" + m_CRLF + "Call-ID: 80B34165-8C89-4623-B862-40AFB1884071@192.168.1.2" + m_CRLF + "CSeq: 102 BYE" + m_CRLF + "Route: <sip:bluesipd@12.12.12.12:5065;lr>" + m_CRLF + "Content-Length: 0" + m_CRLF+ m_CRLF; SIPMessage sipMsg = SIPMessage.ParseSIPMessage(Encoding.ASCII.GetBytes(sipRequest), new IPEndPoint(IPAddress.Loopback, 9998)); SIPRequest byeReq = SIPRequest.ParseSIPRequest(sipMsg); IPEndPoint proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 19998); ProxySIPChannel dummySIPChannel = new ProxySIPChannel(proxyEndPoint, null); StatelessProxyCore proxyCore = new StatelessProxyCore(dummySIPChannel, proxyEndPoint, null, null, true, null, null); IPEndPoint dummyRcvdEndPoint = new IPEndPoint(IPAddress.Loopback, 19999); proxyCore.GotRequest(proxyEndPoint, dummyRcvdEndPoint, byeReq); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Address.ToString() == "12.12.12.12", "The IP address for the UA end point was not correctly extracted, extracted address " + IPSocketAddress.GetSocketString(dummySIPChannel.m_unitTestEndPoint) + "."); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Port == 5065, "The IP port for the UA end point was not correctly extracted."); Assert.IsTrue(byeReq.URI.ToString() == "sip:bluesipd@192.168.1.2:5065", "The SIP URI was incorrect."); Assert.IsTrue(byeReq.Header.Routes.TopRoute.ToString() == "<sip:bluesipd@12.12.12.12:5065;lr>", "The top route was incorrect."); Console.WriteLine("-----------------------------------------"); } [Test] //[Ignore("Next hop tests only.")] public void ParseStrictRouteNotForThisProxyBYEUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); string sipRequest = "BYE sip:bluesipd@192.168.1.2:5065 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK74ab714b;rport" + m_CRLF + "From: <sip:303@bluesipd>;tag=as6a65fae3" + m_CRLF + "To: bluesipd <sip:bluesipd@bluesipd:5065>;tag=1898247079" + m_CRLF + "Contact: <sip:303@213.168.225.133>" + m_CRLF + "Call-ID: 80B34165-8C89-4623-B862-40AFB1884071@192.168.1.2" + m_CRLF + "CSeq: 102 BYE" + m_CRLF + "Route: <sip:bluesipd@12.12.12.12:5065>" + m_CRLF + "Content-Length: 0" + m_CRLF+ m_CRLF; SIPMessage sipMsg = SIPMessage.ParseSIPMessage(Encoding.ASCII.GetBytes(sipRequest), new IPEndPoint(IPAddress.Loopback, 9998)); SIPRequest byeReq = SIPRequest.ParseSIPRequest(sipMsg); IPEndPoint proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 19998); ProxySIPChannel dummySIPChannel = new ProxySIPChannel(proxyEndPoint); StatelessProxyCore proxyCore = new StatelessProxyCore(dummySIPChannel, proxyEndPoint, null, null, true, null, null); IPEndPoint dummyRcvdEndPoint = new IPEndPoint(IPAddress.Loopback, 19999); proxyCore.GotRequest(proxyEndPoint, dummyRcvdEndPoint, byeReq); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Address.ToString() == "12.12.12.12", "The IP address for the UA end point was not correctly extracted, extracted address " + IPSocketAddress.GetSocketString(dummySIPChannel.m_unitTestEndPoint) + "."); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Port == 5065, "The IP port for the UA end point was not correctly extracted."); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Address.ToString() == "12.12.12.12", "The IP address for the UA end point was not correctly extracted, extracted address " + IPSocketAddress.GetSocketString(dummySIPChannel.m_unitTestEndPoint) + "."); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Port == 5065, "The IP port for the UA end point was not correctly extracted."); Assert.IsTrue(byeReq.Header.Routes.TopRoute.ToString() == "sip:bluesipd@192.168.1.2:5065", "The SIP URI was incorrect."); Assert.IsTrue(byeReq.URI.ToString() == "<sip:bluesipd@12.12.12.12:5065;lr>", "The top route was incorrect."); Console.WriteLine("-----------------------------------------"); } [Test] //[Ignore("Next hop tests only.")] public void ParseRouteForThisProxyBYEUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); IPEndPoint proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 19998); string sipRequest = "BYE sip:bluesipd@192.168.1.2:5065 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK74ab714b;rport" + m_CRLF + "From: <sip:303@bluesipd>;tag=as6a65fae3" + m_CRLF + "To: bluesipd <sip:bluesipd@bluesipd:5065>;tag=1898247079" + m_CRLF + "Contact: <sip:303@213.168.225.133>" + m_CRLF + "Call-ID: 80B34165-8C89-4623-B862-40AFB1884071@192.168.1.2" + m_CRLF + "CSeq: 102 BYE" + m_CRLF + "Route: <sip:" + IPSocketAddress.GetSocketString(proxyEndPoint) + ";lr>" + m_CRLF + "Content-Length: 0" + m_CRLF+ m_CRLF; SIPMessage sipMsg = SIPMessage.ParseSIPMessage(Encoding.ASCII.GetBytes(sipRequest), new IPEndPoint(IPAddress.Loopback, 9998)); SIPRequest byeReq = SIPRequest.ParseSIPRequest(sipMsg); ProxySIPChannel dummySIPChannel = new ProxySIPChannel(proxyEndPoint); StatelessProxyCore proxyCore = new StatelessProxyCore(dummySIPChannel, proxyEndPoint, null, null, true, null, null); IPEndPoint dummyRcvdEndPoint = new IPEndPoint(IPAddress.Loopback, 19999); proxyCore.GotRequest(proxyEndPoint, dummyRcvdEndPoint, byeReq); Assert.IsTrue(byeReq.URI.ToString() == "sip:bluesipd@192.168.1.2:5065", "The SIP URI was incorrect."); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Address.ToString() == "12.12.12.12", "The IP address for the UA end point was not correctly extracted, extracted address " + IPSocketAddress.GetSocketString(dummySIPChannel.m_unitTestEndPoint) + "."); //Assert.IsTrue(dummySIPChannel.m_unitTestEndPoint.Port == 5065, "The IP port for the UA end point was not correctly extracted."); Console.WriteLine("-----------------------------------------"); } [Test] //[Ignore("Next hop tests only.")] public void TooManyHopsUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); string sipRequest = "BYE sip:bluesipd@192.168.1.2:5065 SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK74ab714b;rport" + m_CRLF + "Route: <sip:bluesipd@12.12.12.12:5065>" + m_CRLF + "From: <sip:303@bluesipd>;tag=as6a65fae3" + m_CRLF + "To: bluesipd <sip:bluesipd@bluesipd:5065>;tag=1898247079" + m_CRLF + "Contact: <sip:303@213.168.225.133>" + m_CRLF + "Call-ID: 80B34165-8C89-4623-B862-40AFB1884071@192.168.1.2" + m_CRLF + "CSeq: 102 BYE" + m_CRLF + "Max-Forwards: 0" + m_CRLF + "User-Agent: asterisk" + m_CRLF + "Content-Length: 0" + m_CRLF+ m_CRLF; SIPMessage sipMsg = SIPMessage.ParseSIPMessage(Encoding.ASCII.GetBytes(sipRequest), new IPEndPoint(IPAddress.Loopback, 9998)); SIPRequest byeReq = SIPRequest.ParseSIPRequest(sipMsg); IPEndPoint proxyEndPoint = new IPEndPoint(IPAddress.Loopback, 19998); ProxySIPChannel dummySIPChannel = new ProxySIPChannel(proxyEndPoint); StatelessProxyCore proxyCore = new StatelessProxyCore(dummySIPChannel, proxyEndPoint, null, null, true, null, null); IPEndPoint dummyRcvdEndPoint = new IPEndPoint(IPAddress.Loopback, 19999); proxyCore.GotRequest(proxyEndPoint, dummyRcvdEndPoint, byeReq); //Assert.IsTrue(dummyChannel.m_unitTestEndPoint.Address.ToString() == "12.12.12.12", "The IP address for the UA end point was not correctly extracted, extracted address " + dummyChannel.m_unitTestEndPoint.Address.ToString() + "."); //ssert.IsTrue(dummyChannel.m_unitTestEndPoint.Port == 5065, "The IP port for the UA end point was not correctly extracted."); Console.WriteLine("-----------------------------------------"); } [Test] public void DetermineHextHopUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); StatelessProxyCore proxy = new StatelessProxyCore(null, 0); string uri = "sip:303@213.168.225.133"; IPEndPoint nextHop = proxy.DetermineNextHop(uri); Console.WriteLine("The next hop for uri = " + uri + " is " + nextHop.Address.ToString() + ":" + nextHop.Port + "."); Assert.IsTrue(nextHop.Address.ToString() == "213.168.225.133", "The next hop IP address was not correctly determined from the request URI."); Assert.IsTrue(nextHop.Port == 5060, "The next hop port was not correctly determined from the request URI."); } [Test] public void DetermineHextHopDifferentServerUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); StatelessProxyCore proxy = new StatelessProxyCore(null, 0); string uri = "sip:303@213.168.225.135"; IPEndPoint nextHop = proxy.DetermineNextHop(uri); Console.WriteLine("The next hop for uri = " + uri + " is " + nextHop.Address.ToString() + ":" + nextHop.Port + "."); Assert.IsTrue(nextHop.Address.ToString() == "213.168.225.135", "The next hop IP address was not correctly determined from the request URI."); Assert.IsTrue(nextHop.Port == 5060, "The next hop port was not correctly determined from the request URI."); } [Test] public void DetermineHextHopWithPortUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); StatelessProxyCore proxy = new StatelessProxyCore(null, 0); string uri = "sip:303@213.168.225.133:5066"; IPEndPoint nextHop = proxy.DetermineNextHop(uri); Console.WriteLine("The next hop for uri = " + uri + " is " + nextHop.Address.ToString() + ":" + nextHop.Port + "."); Assert.IsTrue(nextHop.Address.ToString() == "213.168.225.133", "The next hop IP address was not correctly determined from the request URI."); Assert.IsTrue(nextHop.Port== 5066, "The next hop port was not correctly determined from the request URI."); } [Test] public void DetermineHextHopWithInvalidURIUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); StatelessProxyCore proxy = new StatelessProxyCore(null, 0); string uri = "sip:303@myserver"; IPEndPoint nextHop = proxy.DetermineNextHop(uri); Console.WriteLine("The next hop for uri = " + uri + " is " + nextHop.Address.ToString() + ":" + nextHop.Port + "."); Assert.IsTrue(nextHop.Address.ToString() == "213.168.225.133", "The next hop IP address was not correctly determined from the request URI."); Assert.IsTrue(nextHop.Port== 5060, "The next hop port was not correctly determined from the request URI."); } [Test] public void CredentialsPassThruUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); string registerMsg = "REGISTER sip:blueface SIP/2.0" + m_CRLF + "Via: SIP/2.0/UDP 192.168.1.2:5066;branch=z9hG4bK60341d2470" + m_CRLF + "From: \"aaron\" <sip:aaron@blueface>;tag=632743740325493750" + m_CRLF + "To: \"aaron\" <sip:aaron@blueface>" + m_CRLF + "Contact: <sip:aaron@220.240.255.198:50652>" + m_CRLF + "Call-ID: 1540e4c48d3b447@192.168.1.2" + m_CRLF + "CSeq: 550 REGISTER" + m_CRLF + "Max-Forwards: 70" + m_CRLF + "Expires: 600" + m_CRLF + "Authorization: Digest username=\"aaron\",realm=\"asterisk\",nonce=\"422e215b\",response=\"af05b4f63e3593c449ad9eac9f0443e4\",uri=\"sip:blueface\"" + m_CRLF + m_CRLF; StatelessProxyCore proxy = new StatelessProxyCore(null, 0); SIPRequest registerReq = SIPRequest.ParseSIPRequest(registerMsg); StatelessProxyCore proxyCore = new StatelessProxyCore("213.168.225.135", 5060); SIPChannel dummyChannel = new SIPChannel(); proxyCore.GotRequest(registerReq, new IPEndPoint(IPAddress.Parse("12.12.12.12"), 5060), dummyChannel); Console.WriteLine("-----------------------------------------"); } [Test] public void CredentialsPassThruNonceAndRealmResposeUnitTest() { Console.WriteLine("--> " + System.Reflection.MethodBase.GetCurrentMethod().Name); string unauthRespStr = "SIP/2.0 401 Unauthorized" + m_CRLF + "Via: SIP/2.0/UDP 213.168.225.135:5060;branch=z9hG4bKbaec65a4f8" + m_CRLF + "Via: SIP/2.0/UDP 192.168.1.2:5066;received=220.240.255.198:63994;branch=z9hG4bKbaec65a4f9" + m_CRLF + "From: \"aaron\" <sip:aaron@blueface>;tag=632743740325493750" + m_CRLF + "To: \"aaron\" <sip:aaron@blueface>;tag=as7b152585" + m_CRLF + "Contact: <sip:aaron@213.168.225.133>" + m_CRLF + "Call-ID: 1540e4c48d3b447@192.168.1.2" + m_CRLF + "CSeq: 549 REGISTER" + m_CRLF + "Max-Forwards: 70" + m_CRLF + "User-Agent: asterisk" + m_CRLF + "WWW-Authenticate: Digest realm=\"asterisk\",nonce=\"422e215b\"" + m_CRLF + "Record-Route: <sip:213.168.225.136:6060;lr>" + m_CRLF + "Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, NOTIFY" + m_CRLF + m_CRLF; StatelessProxyCore proxy = new StatelessProxyCore(null, 0); SIPResponse unauthResp = SIPResponse.ParseSIPResponse(unauthRespStr); StatelessProxyCore proxyCore = new StatelessProxyCore("213.168.225.135", 5060); SIPChannel dummyChannel = new SIPChannel(); proxyCore.GotResponse(unauthResp, new IPEndPoint(IPAddress.Parse("12.12.12.12"), 5060), dummyChannel); Console.WriteLine("-----------------------------------------"); } } */ #endif #endregion } }
/* * REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application * * The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; using HETSAPI.Models; namespace HETSAPI.Models { /// <summary> /// The rate associated with an element of a rental agreement. /// </summary> [MetaDataExtension (Description = "The rate associated with an element of a rental agreement.")] public partial class RentalAgreementRate : AuditableEntity, IEquatable<RentalAgreementRate> { /// <summary> /// Default constructor, required by entity framework /// </summary> public RentalAgreementRate() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="RentalAgreementRate" /> class. /// </summary> /// <param name="Id">A system-generated unique identifier for a RentalAgreementRate (required).</param> /// <param name="RentalAgreement">A foreign key reference to the system-generated unique identifier for a Rental Agreement (required).</param> /// <param name="ComponentName">Name of the component for the Rental Agreement for which the attached rates apply..</param> /// <param name="IsAttachment">True if this rate is for an attachment to the piece of equipment..</param> /// <param name="Rate">The dollar rate associated with this component of the rental agreement..</param> /// <param name="PercentOfEquipmentRate">For other than the actual piece of equipment, the percent of the equipment rate to use for this component of the rental agreement..</param> /// <param name="RatePeriod">The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily..</param> /// <param name="Comment">A comment about the rental of this component of the Rental Agreement..</param> /// <param name="TimeRecords">TimeRecords.</param> public RentalAgreementRate(int Id, RentalAgreement RentalAgreement, string ComponentName = null, bool? IsAttachment = null, float? Rate = null, int? PercentOfEquipmentRate = null, string RatePeriod = null, string Comment = null, List<TimeRecord> TimeRecords = null) { this.Id = Id; this.RentalAgreement = RentalAgreement; this.ComponentName = ComponentName; this.IsAttachment = IsAttachment; this.Rate = Rate; this.PercentOfEquipmentRate = PercentOfEquipmentRate; this.RatePeriod = RatePeriod; this.Comment = Comment; this.TimeRecords = TimeRecords; } /// <summary> /// A system-generated unique identifier for a RentalAgreementRate /// </summary> /// <value>A system-generated unique identifier for a RentalAgreementRate</value> [MetaDataExtension (Description = "A system-generated unique identifier for a RentalAgreementRate")] public int Id { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Rental Agreement /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Rental Agreement</value> [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Rental Agreement")] public RentalAgreement RentalAgreement { get; set; } /// <summary> /// Foreign key for RentalAgreement /// </summary> [ForeignKey("RentalAgreement")] [JsonIgnore] [MetaDataExtension (Description = "A foreign key reference to the system-generated unique identifier for a Rental Agreement")] public int? RentalAgreementId { get; set; } /// <summary> /// Name of the component for the Rental Agreement for which the attached rates apply. /// </summary> /// <value>Name of the component for the Rental Agreement for which the attached rates apply.</value> [MetaDataExtension (Description = "Name of the component for the Rental Agreement for which the attached rates apply.")] [MaxLength(150)] public string ComponentName { get; set; } /// <summary> /// True if this rate is for an attachment to the piece of equipment. /// </summary> /// <value>True if this rate is for an attachment to the piece of equipment.</value> [MetaDataExtension (Description = "True if this rate is for an attachment to the piece of equipment.")] public bool? IsAttachment { get; set; } /// <summary> /// The dollar rate associated with this component of the rental agreement. /// </summary> /// <value>The dollar rate associated with this component of the rental agreement.</value> [MetaDataExtension (Description = "The dollar rate associated with this component of the rental agreement.")] public float? Rate { get; set; } /// <summary> /// For other than the actual piece of equipment, the percent of the equipment rate to use for this component of the rental agreement. /// </summary> /// <value>For other than the actual piece of equipment, the percent of the equipment rate to use for this component of the rental agreement.</value> [MetaDataExtension (Description = "For other than the actual piece of equipment, the percent of the equipment rate to use for this component of the rental agreement.")] public int? PercentOfEquipmentRate { get; set; } /// <summary> /// The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily. /// </summary> /// <value>The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily.</value> [MetaDataExtension (Description = "The period of the rental rate. The vast majority will be hourly, but the rate could apply across a different period, e.g. daily.")] [MaxLength(50)] public string RatePeriod { get; set; } /// <summary> /// A comment about the rental of this component of the Rental Agreement. /// </summary> /// <value>A comment about the rental of this component of the Rental Agreement.</value> [MetaDataExtension (Description = "A comment about the rental of this component of the Rental Agreement.")] [MaxLength(2048)] public string Comment { get; set; } /// <summary> /// Gets or Sets TimeRecords /// </summary> public List<TimeRecord> TimeRecords { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RentalAgreementRate {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" RentalAgreement: ").Append(RentalAgreement).Append("\n"); sb.Append(" ComponentName: ").Append(ComponentName).Append("\n"); sb.Append(" IsAttachment: ").Append(IsAttachment).Append("\n"); sb.Append(" Rate: ").Append(Rate).Append("\n"); sb.Append(" PercentOfEquipmentRate: ").Append(PercentOfEquipmentRate).Append("\n"); sb.Append(" RatePeriod: ").Append(RatePeriod).Append("\n"); sb.Append(" Comment: ").Append(Comment).Append("\n"); sb.Append(" TimeRecords: ").Append(TimeRecords).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((RentalAgreementRate)obj); } /// <summary> /// Returns true if RentalAgreementRate instances are equal /// </summary> /// <param name="other">Instance of RentalAgreementRate to be compared</param> /// <returns>Boolean</returns> public bool Equals(RentalAgreementRate other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.RentalAgreement == other.RentalAgreement || this.RentalAgreement != null && this.RentalAgreement.Equals(other.RentalAgreement) ) && ( this.ComponentName == other.ComponentName || this.ComponentName != null && this.ComponentName.Equals(other.ComponentName) ) && ( this.IsAttachment == other.IsAttachment || this.IsAttachment != null && this.IsAttachment.Equals(other.IsAttachment) ) && ( this.Rate == other.Rate || this.Rate != null && this.Rate.Equals(other.Rate) ) && ( this.PercentOfEquipmentRate == other.PercentOfEquipmentRate || this.PercentOfEquipmentRate != null && this.PercentOfEquipmentRate.Equals(other.PercentOfEquipmentRate) ) && ( this.RatePeriod == other.RatePeriod || this.RatePeriod != null && this.RatePeriod.Equals(other.RatePeriod) ) && ( this.Comment == other.Comment || this.Comment != null && this.Comment.Equals(other.Comment) ) && ( this.TimeRecords == other.TimeRecords || this.TimeRecords != null && this.TimeRecords.SequenceEqual(other.TimeRecords) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.RentalAgreement != null) { hash = hash * 59 + this.RentalAgreement.GetHashCode(); } if (this.ComponentName != null) { hash = hash * 59 + this.ComponentName.GetHashCode(); } if (this.IsAttachment != null) { hash = hash * 59 + this.IsAttachment.GetHashCode(); } if (this.Rate != null) { hash = hash * 59 + this.Rate.GetHashCode(); } if (this.PercentOfEquipmentRate != null) { hash = hash * 59 + this.PercentOfEquipmentRate.GetHashCode(); } if (this.RatePeriod != null) { hash = hash * 59 + this.RatePeriod.GetHashCode(); } if (this.Comment != null) { hash = hash * 59 + this.Comment.GetHashCode(); } if (this.TimeRecords != null) { hash = hash * 59 + this.TimeRecords.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(RentalAgreementRate left, RentalAgreementRate right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(RentalAgreementRate left, RentalAgreementRate right) { return !Equals(left, right); } #endregion Operators } }
// // ColumnCellStatusIndicator.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Cairo; using Mono.Unix; using Hyena.Gui; using Hyena.Data.Gui; using Hyena.Data.Gui.Accessibility; using Banshee.Gui; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; namespace Banshee.Collection.Gui { class ColumnCellStatusIndicatorAccessible : ColumnCellAccessible, Atk.IImageImplementor { private string image_description; public ColumnCellStatusIndicatorAccessible (object bound_object, ColumnCellStatusIndicator cell, ICellAccessibleParent parent) : base (bound_object, cell as ColumnCell, parent) { image_description = cell.GetTextAlternative (bound_object); } public override void Redrawn () { string new_image_description = cell.GetTextAlternative (bound_object); if (image_description != new_image_description) GLib.Signal.Emit (this, "visible-data-changed"); image_description = new_image_description; } public string ImageLocale { get { return null; } } public bool SetImageDescription (string description) { return false; } public void GetImageSize (out int width, out int height) { if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) width = height = 16; else width = height = Int32.MinValue; } public string ImageDescription { get { return image_description; } } public void GetImagePosition (out int x, out int y, Atk.CoordType coordType) { if (!String.IsNullOrEmpty (cell.GetTextAlternative (bound_object))) { GetPosition (out x, out y, coordType); x += 4; y += 4; } else { x = y = Int32.MinValue; } } } public class ColumnCellStatusIndicator : ColumnCell, ISizeRequestCell, ITooltipCell { const int padding = 2; protected enum Icon : int { Playing, Paused, Error, Protected, External } private string [] status_names; protected string [] StatusNames { get { return status_names; } } private int pixbuf_size; protected int PixbufSize { get { return pixbuf_size; } set { pixbuf_size = value; Width = Height = value; } } private Gdk.Pixbuf [] pixbufs; protected Gdk.Pixbuf [] Pixbufs { get { return pixbufs; } } public ColumnCellStatusIndicator (string property) : this (property, true) { } public ColumnCellStatusIndicator (string property, bool expand) : base (property, expand) { RestrictSize = true; PixbufSize = 16; LoadPixbufs (); } public bool RestrictSize { get; set; } public void GetWidthRange (Pango.Layout layout, out int min_width, out int max_width) { min_width = max_width = pixbuf_size + 2 * padding; } public override Atk.Object GetAccessible (ICellAccessibleParent parent) { return new ColumnCellStatusIndicatorAccessible (BoundObject, this, parent); } public override string GetTextAlternative (object obj) { var track = obj as TrackInfo; if (track == null) return ""; int icon_index = GetIconIndex (track); if ((icon_index < 0) || (icon_index >= status_names.Length)) { return ""; } else if (icon_index == (int)Icon.Error) { return track.GetPlaybackErrorMessage () ?? ""; } else { return status_names[icon_index]; } } protected virtual int PixbufCount { get { return 5; } } protected virtual int GetIconIndex (TrackInfo track) { int icon_index = -1; if (track.PlaybackError != StreamPlaybackError.None) { icon_index = (int)(track.PlaybackError == StreamPlaybackError.Drm ? Icon.Protected : Icon.Error); } else if (track.IsPlaying) { icon_index = (int)(ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused ? Icon.Paused : Icon.Playing); } else if ((track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) { icon_index = (int)Icon.External; } else { icon_index = -1; } return icon_index; } protected virtual void LoadPixbufs () { if (pixbufs != null && pixbufs.Length > 0) { for (int i = 0; i < pixbufs.Length; i++) { if (pixbufs[i] != null) { pixbufs[i].Dispose (); pixbufs[i] = null; } } } if (pixbufs == null) { pixbufs = new Gdk.Pixbuf[PixbufCount]; } pixbufs[(int)Icon.Playing] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-start"); pixbufs[(int)Icon.Paused] = IconThemeUtils.LoadIcon (PixbufSize, "media-playback-pause"); pixbufs[(int)Icon.Error] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-unreadable", "dialog-error"); pixbufs[(int)Icon.Protected] = IconThemeUtils.LoadIcon (PixbufSize, "emblem-readonly", "dialog-error"); pixbufs[(int)Icon.External] = IconThemeUtils.LoadIcon (PixbufSize, "x-office-document"); if (status_names == null) { status_names = new string[PixbufCount]; for (int i=0; i<PixbufCount; i++) status_names[i] = ""; } status_names[(int)Icon.Playing] = Catalog.GetString ("Playing"); status_names[(int)Icon.Paused] = Catalog.GetString ("Paused"); status_names[(int)Icon.Error] = Catalog.GetString ("Error"); status_names[(int)Icon.Protected] = Catalog.GetString ("Protected"); status_names[(int)Icon.External] = Catalog.GetString ("External Document"); } public override void NotifyThemeChange () { LoadPixbufs (); } public override void Render (CellContext context, double cellWidth, double cellHeight) { TrackInfo track = BoundTrack; if (track == null) { return; } int icon_index = GetIconIndex (track); TooltipMarkup = icon_index == -1 ? null : StatusNames[icon_index]; if (icon_index < 0 || pixbufs == null || pixbufs[icon_index] == null) { return; } context.Context.Translate (0, 0.5); Gdk.Pixbuf render_pixbuf = pixbufs[icon_index]; Cairo.Rectangle pixbuf_area = new Cairo.Rectangle ((cellWidth - render_pixbuf.Width) / 2, (cellHeight - render_pixbuf.Height) / 2, render_pixbuf.Width, render_pixbuf.Height); if (!context.Opaque) { context.Context.Save (); } Gdk.CairoHelper.SetSourcePixbuf (context.Context, render_pixbuf, pixbuf_area.X, pixbuf_area.Y); context.Context.Rectangle (pixbuf_area); if (!context.Opaque) { context.Context.Clip (); context.Context.PaintWithAlpha (0.5); context.Context.Restore (); } else { context.Context.Fill (); } } public string GetTooltipMarkup (CellContext cellContext, double columnWidth) { return GetTextAlternative (BoundObject); } protected TrackInfo BoundTrack { get { return BoundObject as TrackInfo; } } } }
/* * Created by: Leslie Sanford * * Contact: jabberdabber@hotmail.com * * Last modified: 09/26/2005 */ using System; using System.Collections; namespace LSCollections { /// <summary> /// Represents a simple double-ended-queue collection of objects. /// </summary> [Serializable()] public class Deque : ICollection, IEnumerable, ICloneable { #region Deque Members #region Fields // The node at the front of the deque. private Node front = null; // The node at the back of the deque. private Node back = null; // The number of elements in the deque. private int count = 0; // The version of the deque. private long version = 0; #endregion #region Construction /// <summary> /// Initializes a new instance of the Deque class. /// </summary> public Deque() { } /// <summary> /// Initializes a new instance of the Deque class that contains /// elements copied from the specified collection. /// </summary> /// <param name="col"> /// The ICollection to copy elements from. /// </param> public Deque(ICollection col) { #region Preconditions if(col == null) { throw new ArgumentNullException("col"); } #endregion foreach(object obj in col) { PushBack(obj); } } #endregion #region Methods /// <summary> /// Removes all objects from the Deque. /// </summary> public virtual void Clear() { count = 0; front = back = null; version++; } /// <summary> /// Determines whether or not an element is in the Deque. /// </summary> /// <param name="obj"> /// The Object to locate in the Deque. /// </param> /// <returns> /// <b>true</b> if <i>obj</i> if found in the Deque; otherwise, /// <b>false</b>. /// </returns> public virtual bool Contains(object obj) { foreach(object o in this) { if(o == null && obj == null) { return true; } else if(o.Equals(obj)) { return true; } } return false; } /// <summary> /// Inserts an object at the front of the Deque. /// </summary> /// <param name="obj"> /// The object to push onto the deque; /// </param> public virtual void PushFront(object obj) { // The new node to add to the front of the deque. Node n = new Node(obj); // Link the new node to the front node. The current front node at // the front of the deque is now the second node in the deque. n.Next = front; // If the deque isn't empty if(Count > 0) { // Link the current front to the new node. front.Previous = n; } // Make the new node the front of the deque. front = n; // Keep track of the number of elements in the deque. count++; // If this is the first element in the deque. if(Count == 1) { // The front and back nodes are the same. back = front; } version++; } /// <summary> /// Inserts an object at the back of the Deque. /// </summary> /// <param name="obj"> /// The object to push onto the deque; /// </param> public virtual void PushBack(object obj) { // The new node to add to the back of the deque. Node n = new Node(obj); // Link the new node to the back node. The current back node at // the back of the deque is now the second to the last node in the // deque. n.Previous = back; // If the deque is not empty. if(Count > 0) { // Link the current back node to the new node. back.Next = n; } // Make the new node the back of the deque. back = n; // Keep track of the number of elements in the deque. count++; // If this is the first element in the deque. if(Count == 1) { // The front and back nodes are the same. front = back; } version++; } /// <summary> /// Removes and returns the object at the front of the Deque. /// </summary> /// <returns> /// The object at the front of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PopFront() { #region Preconditions if(Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion // Get the object at the front of the deque. object obj = front.Value; // Move the front back one node. front = front.Next; // Keep track of the number of nodes in the deque. count--; // If the deque is not empty. if(Count > 0) { // Tie off the previous link in the front node. front.Previous = null; } // Else the deque is empty. else { // Indicate that there is no back node. back = null; } version++; return obj; } /// <summary> /// Removes and returns the object at the back of the Deque. /// </summary> /// <returns> /// The object at the back of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PopBack() { #region Preconditions if(Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion // Get the object at the back of the deque. object obj = back.Value; // Move back node forward one node. back = back.Previous; // Keep track of the number of nodes in the deque. count--; // If the deque is not empty. if(Count > 0) { // Tie off the next link in the back node. back.Next = null; } // Else the deque is empty. else { // Indicate that there is no front node. front = null; } version++; return obj; } /// <summary> /// Returns the object at the front of the Deque without removing it. /// </summary> /// <returns> /// The object at the front of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PeekFront() { #region Preconditions if(Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion return front.Value; } /// <summary> /// Returns the object at the back of the Deque without removing it. /// </summary> /// <returns> /// The object at the back of the Deque. /// </returns> /// <exception cref="InvalidOperationException"> /// The Deque is empty. /// </exception> public virtual object PeekBack() { #region Preconditions if(Count == 0) { throw new InvalidOperationException("Deque is empty."); } #endregion return back.Value; } /// <summary> /// Copies the Deque to a new array. /// </summary> /// <returns> /// A new array containing copies of the elements of the Deque. /// </returns> public virtual object[] ToArray() { object[] array = new object[Count]; int index = 0; foreach(object obj in this) { array[index] = obj; index++; } return array; } /// <summary> /// Returns a synchronized (thread-safe) wrapper for the Deque. /// </summary> /// <param name="deque"> /// The Deque to synchronize. /// </param> /// <returns> /// A synchronized wrapper around the Deque. /// </returns> public static Deque Synchronized(Deque deque) { #region Preconditions if(deque == null) { throw new ArgumentNullException("deque"); } #endregion return new SynchronizedDeque(deque); } #endregion #region Node Class // Represents a node in the deque. [Serializable()] private class Node { private object value; private Node previous = null; private Node next = null; public Node(object value) { this.value = value; } public object Value { get { return value; } } public Node Previous { get { return previous; } set { previous = value; } } public Node Next { get { return next; } set { next = value; } } } #endregion #region DequeEnumerator Class [Serializable()] private class DequeEnumerator : IEnumerator { private Deque owner; private Node current; private bool beforeBeginning = true; private long version; public DequeEnumerator(Deque owner) { this.owner = owner; current = owner.front; this.version = owner.version; } #region IEnumerator Members public void Reset() { #region Preconditions if(version != owner.version) { throw new InvalidOperationException( "The Deque was modified after the enumerator was created."); } #endregion beforeBeginning = true; } public object Current { get { #region Preconditions if(beforeBeginning || current == null) { throw new InvalidOperationException( "The enumerator is positioned before the first " + "element of the Deque or after the last element."); } #endregion return current.Value; } } public bool MoveNext() { #region Preconditions if(version != owner.version) { throw new InvalidOperationException( "The Deque was modified after the enumerator was created."); } #endregion bool result = false; // If the enumerator is positioned before the front of the // deque. if(beforeBeginning) { // Position the enumerator at the front of the deque. current = owner.front; // Indicate that the enumerator is no longer positioned // before the beginning of the deque. beforeBeginning = false; } // Else if the enumerator has not yet reached the end of the // deque. else if(current != null) { // Move to the next element in the deque. current = current.Next; } // If the enumerator has not reached the end of the deque. if(current != null) { // Indicate that the enumerator has not reached the end of // the deque. result = true; } return result; } #endregion } #endregion #region SynchronizedDeque Class // Implements a synchronization wrapper around a deque. [Serializable()] private class SynchronizedDeque : Deque { #region SynchronziedDeque Members #region Fields // The wrapped deque. private Deque deque; // The object to lock on. private object root; #endregion #region Construction public SynchronizedDeque(Deque deque) { this.deque = deque; this.root = deque.SyncRoot; } #endregion #region Methods public override void Clear() { lock(root) { deque.Clear(); } } public override bool Contains(object obj) { bool result; lock(root) { result = deque.Contains(obj); } return result; } public override void PushFront(object obj) { lock(root) { deque.PushFront(obj); } } public override void PushBack(object obj) { lock(root) { deque.PushBack(obj); } } public override object PopFront() { object obj; lock(root) { obj = deque.PopFront(); } return obj; } public override object PopBack() { object obj; lock(root) { obj = deque.PopBack(); } return obj; } public override object PeekFront() { object obj; lock(root) { obj = deque.PeekFront(); } return obj; } public override object PeekBack() { object obj; lock(root) { obj = deque.PeekBack(); } return obj; } public override object[] ToArray() { object[] array; lock(root) { array = deque.ToArray(); } return array; } public override object Clone() { object clone; lock(root) { clone = deque.Clone(); } return clone; } public override void CopyTo(Array array, int index) { lock(root) { deque.CopyTo(array, index); } } public override IEnumerator GetEnumerator() { IEnumerator e; lock(root) { e = deque.GetEnumerator(); } return e; } #endregion #region Properties public override int Count { get { int count; lock(root) { count = deque.Count; } return count; } } public override bool IsSynchronized { get { return true; } } #endregion #endregion } #endregion #endregion #region ICollection Members /// <summary> /// Gets a value indicating whether access to the Deque is synchronized /// (thread-safe). /// </summary> public virtual bool IsSynchronized { get { return false; } } /// <summary> /// Gets the number of elements contained in the Deque. /// </summary> public virtual int Count { get { return count; } } /// <summary> /// Copies the Deque elements to an existing one-dimensional Array, /// starting at the specified array index. /// </summary> /// <param name="array"> /// The one-dimensional Array that is the destination of the elements /// copied from Deque. The Array must have zero-based indexing. /// </param> /// <param name="index"> /// The zero-based index in array at which copying begins. /// </param> public virtual void CopyTo(Array array, int index) { #region Preconditions if(array == null) { throw new ArgumentNullException("array"); } else if(index < 0) { throw new ArgumentOutOfRangeException("index", index, "Index is less than zero."); } else if(array.Rank > 1) { throw new ArgumentException("Array is multidimensional."); } else if(index >= array.Length) { throw new ArgumentException("Index is equal to or greater " + "than the length of array."); } else if(Count > array.Length - index) { throw new ArgumentException( "The number of elements in the source Deque is greater " + "than the available space from index to the end of the " + "destination array."); } #endregion int i = index; foreach(object obj in this) { array.SetValue(obj, i); i++; } } /// <summary> /// Gets an object that can be used to synchronize access to the Deque. /// </summary> public virtual object SyncRoot { get { return this; } } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that can iterate through the Deque. /// </summary> /// <returns> /// An IEnumerator for the Deque. /// </returns> public virtual IEnumerator GetEnumerator() { return new DequeEnumerator(this); } #endregion #region ICloneable Members /// <summary> /// Creates a shallow copy of the Deque. /// </summary> /// <returns> /// A shalloe copy of the Deque. /// </returns> public virtual object Clone() { Deque clone = new Deque(this); clone.version = this.version; return clone; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.MirrorPrimitives { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Some cool documentation. /// </summary> public partial class SwaggerDataTypesClient : ServiceClient<SwaggerDataTypesClient>, ISwaggerDataTypesClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the SwaggerDataTypesClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SwaggerDataTypesClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SwaggerDataTypesClient 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> public SwaggerDataTypesClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SwaggerDataTypesClient 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> public SwaggerDataTypesClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SwaggerDataTypesClient 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> public SwaggerDataTypesClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://localhost:3000/"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Product Types /// </summary> /// <param name='responseCode'> /// The desired returned status code /// </param> /// <param name='product'> /// The only parameter /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("responseCode", responseCode); tracingParameters.Add("product", product); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PatchProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (responseCode != null) { if (_httpRequest.Headers.Contains("response-code")) { _httpRequest.Headers.Remove("response-code"); } _httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }