context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace VitaliiPianykh.FileWall.Client { partial class FormRuleEdit { /// <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(FormRuleEdit)); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.textName = new DevExpress.XtraEditors.TextEdit(); this.checkLog = new DevExpress.XtraEditors.CheckEdit(); this.textProtectedPath = new DevExpress.XtraEditors.TextEdit(); this.labelControl2 = new DevExpress.XtraEditors.LabelControl(); this.buttonBrowseFolder = new DevExpress.XtraEditors.SimpleButton(); this.buttonBrowseRegistry = new DevExpress.XtraEditors.SimpleButton(); this.labelControl3 = new DevExpress.XtraEditors.LabelControl(); this.textProcessPath = new DevExpress.XtraEditors.TextEdit(); this.buttonBrowseProcess = new DevExpress.XtraEditors.SimpleButton(); this.buttonSuggestName = new DevExpress.XtraEditors.SimpleButton(); this.panelControl1 = new DevExpress.XtraEditors.PanelControl(); this.labelControl4 = new DevExpress.XtraEditors.LabelControl(); this.comboAction = new DevExpress.XtraEditors.ImageComboBoxEdit(); this.buttonApply = new DevExpress.XtraEditors.SimpleButton(); this.buttonCancel = new DevExpress.XtraEditors.SimpleButton(); this.buttonOK = new DevExpress.XtraEditors.SimpleButton(); this.imagesRuleActions = new DevExpress.Utils.ImageCollection(this.components); ((System.ComponentModel.ISupportInitialize)(this.textName.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.checkLog.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.textProtectedPath.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.textProcessPath.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.panelControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.comboAction.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imagesRuleActions)).BeginInit(); this.SuspendLayout(); // // labelControl1 // this.labelControl1.Location = new System.Drawing.Point(25, 15); this.labelControl1.Name = "labelControl1"; this.labelControl1.Size = new System.Drawing.Size(50, 13); this.labelControl1.TabIndex = 0; this.labelControl1.Text = "Rule name"; // // textName // this.textName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textName.Location = new System.Drawing.Point(81, 12); this.textName.Name = "textName"; this.textName.Size = new System.Drawing.Size(242, 20); this.textName.TabIndex = 1; this.textName.EditValueChanged += new System.EventHandler(this.textName_EditValueChanged); // // checkLog // this.checkLog.Location = new System.Drawing.Point(24, 131); this.checkLog.Name = "checkLog"; this.checkLog.Properties.Caption = "Always log"; this.checkLog.Properties.GlyphAlignment = DevExpress.Utils.HorzAlignment.Far; this.checkLog.Size = new System.Drawing.Size(73, 19); this.checkLog.TabIndex = 9; this.checkLog.EditValueChanged += new System.EventHandler(this.textName_EditValueChanged); // // textProtectedPath // this.textProtectedPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textProtectedPath.Location = new System.Drawing.Point(81, 46); this.textProtectedPath.Name = "textProtectedPath"; this.textProtectedPath.Size = new System.Drawing.Size(242, 20); this.textProtectedPath.TabIndex = 3; this.textProtectedPath.EditValueChanged += new System.EventHandler(this.textName_EditValueChanged); // // labelControl2 // this.labelControl2.Location = new System.Drawing.Point(3, 49); this.labelControl2.Name = "labelControl2"; this.labelControl2.Size = new System.Drawing.Size(72, 13); this.labelControl2.TabIndex = 3; this.labelControl2.Text = "Protected Path"; // // buttonBrowseFolder // this.buttonBrowseFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonBrowseFolder.Location = new System.Drawing.Point(329, 46); this.buttonBrowseFolder.Name = "buttonBrowseFolder"; this.buttonBrowseFolder.Size = new System.Drawing.Size(20, 20); this.buttonBrowseFolder.TabIndex = 4; this.buttonBrowseFolder.Text = "..."; this.buttonBrowseFolder.Click += new System.EventHandler(this.buttonBrowseFolder_Click); // // buttonBrowseRegistry // this.buttonBrowseRegistry.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonBrowseRegistry.Location = new System.Drawing.Point(355, 46); this.buttonBrowseRegistry.Name = "buttonBrowseRegistry"; this.buttonBrowseRegistry.Size = new System.Drawing.Size(20, 20); this.buttonBrowseRegistry.TabIndex = 5; this.buttonBrowseRegistry.Text = "..."; this.buttonBrowseRegistry.Click += new System.EventHandler(this.buttonBrowseRegistry_Click); // // labelControl3 // this.labelControl3.Location = new System.Drawing.Point(13, 80); this.labelControl3.Name = "labelControl3"; this.labelControl3.Size = new System.Drawing.Size(62, 13); this.labelControl3.TabIndex = 7; this.labelControl3.Text = "Process Path"; // // textProcessPath // this.textProcessPath.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textProcessPath.Location = new System.Drawing.Point(81, 77); this.textProcessPath.Name = "textProcessPath"; this.textProcessPath.Size = new System.Drawing.Size(242, 20); this.textProcessPath.TabIndex = 6; this.textProcessPath.EditValueChanged += new System.EventHandler(this.textName_EditValueChanged); // // buttonBrowseProcess // this.buttonBrowseProcess.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonBrowseProcess.Location = new System.Drawing.Point(329, 77); this.buttonBrowseProcess.Name = "buttonBrowseProcess"; this.buttonBrowseProcess.Size = new System.Drawing.Size(20, 20); this.buttonBrowseProcess.TabIndex = 7; this.buttonBrowseProcess.Text = "..."; this.buttonBrowseProcess.Click += new System.EventHandler(this.buttonBrowseProcess_Click); // // buttonSuggestName // this.buttonSuggestName.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonSuggestName.Location = new System.Drawing.Point(329, 12); this.buttonSuggestName.Name = "buttonSuggestName"; this.buttonSuggestName.Size = new System.Drawing.Size(20, 20); this.buttonSuggestName.TabIndex = 2; this.buttonSuggestName.Text = "..."; this.buttonSuggestName.Click += new System.EventHandler(this.buttonSuggestName_Click); // // panelControl1 // this.panelControl1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panelControl1.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.Simple; this.panelControl1.Location = new System.Drawing.Point(3, 38); this.panelControl1.Name = "panelControl1"; this.panelControl1.Size = new System.Drawing.Size(379, 2); this.panelControl1.TabIndex = 11; // // labelControl4 // this.labelControl4.Location = new System.Drawing.Point(45, 108); this.labelControl4.Name = "labelControl4"; this.labelControl4.Size = new System.Drawing.Size(30, 13); this.labelControl4.TabIndex = 12; this.labelControl4.Text = "Action"; // // comboAction // this.comboAction.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.comboAction.Location = new System.Drawing.Point(81, 105); this.comboAction.Name = "comboAction"; this.comboAction.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.comboAction.Properties.DropDownRows = 3; this.comboAction.Properties.Items.AddRange(new DevExpress.XtraEditors.Controls.ImageComboBoxItem[] { new DevExpress.XtraEditors.Controls.ImageComboBoxItem("Always allow access", 0, 0), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("Ask user about this action", 1, 1), new DevExpress.XtraEditors.Controls.ImageComboBoxItem("Deny access for this resource", 2, 2)}); this.comboAction.Properties.SmallImages = this.imagesRuleActions; this.comboAction.Size = new System.Drawing.Size(242, 20); this.comboAction.TabIndex = 8; this.comboAction.EditValueChanged += new System.EventHandler(this.textName_EditValueChanged); // // buttonApply // this.buttonApply.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonApply.Location = new System.Drawing.Point(303, 156); this.buttonApply.Name = "buttonApply"; this.buttonApply.Size = new System.Drawing.Size(75, 23); this.buttonApply.TabIndex = 12; this.buttonApply.Text = "&Apply"; this.buttonApply.Click += new System.EventHandler(this.buttonApply_Click); // // buttonCancel // this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(222, 156); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(75, 23); this.buttonCancel.TabIndex = 11; this.buttonCancel.Text = "&Cancel"; // // buttonOK // this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Location = new System.Drawing.Point(141, 156); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(75, 23); this.buttonOK.TabIndex = 10; this.buttonOK.Text = "&OK"; // // imagesRuleActions // this.imagesRuleActions.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("imagesRuleActions.ImageStream"))); // // FormRuleEdit // this.AcceptButton = this.buttonOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(390, 191); this.Controls.Add(this.buttonOK); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonApply); this.Controls.Add(this.comboAction); this.Controls.Add(this.labelControl4); this.Controls.Add(this.panelControl1); this.Controls.Add(this.buttonSuggestName); this.Controls.Add(this.buttonBrowseProcess); this.Controls.Add(this.textProcessPath); this.Controls.Add(this.labelControl3); this.Controls.Add(this.buttonBrowseRegistry); this.Controls.Add(this.buttonBrowseFolder); this.Controls.Add(this.textProtectedPath); this.Controls.Add(this.labelControl2); this.Controls.Add(this.checkLog); this.Controls.Add(this.textName); this.Controls.Add(this.labelControl1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormRuleEdit"; this.ShowIcon = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Rule Edit"; ((System.ComponentModel.ISupportInitialize)(this.textName.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.checkLog.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.textProtectedPath.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.textProcessPath.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.panelControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.comboAction.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imagesRuleActions)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraEditors.TextEdit textName; private DevExpress.XtraEditors.CheckEdit checkLog; private DevExpress.XtraEditors.TextEdit textProtectedPath; private DevExpress.XtraEditors.LabelControl labelControl2; private DevExpress.XtraEditors.SimpleButton buttonBrowseFolder; private DevExpress.XtraEditors.SimpleButton buttonBrowseRegistry; private DevExpress.XtraEditors.LabelControl labelControl3; private DevExpress.XtraEditors.TextEdit textProcessPath; private DevExpress.XtraEditors.SimpleButton buttonBrowseProcess; private DevExpress.XtraEditors.SimpleButton buttonSuggestName; private DevExpress.XtraEditors.PanelControl panelControl1; private DevExpress.XtraEditors.LabelControl labelControl4; private DevExpress.XtraEditors.ImageComboBoxEdit comboAction; private DevExpress.XtraEditors.SimpleButton buttonApply; private DevExpress.XtraEditors.SimpleButton buttonCancel; private DevExpress.XtraEditors.SimpleButton buttonOK; private DevExpress.Utils.ImageCollection imagesRuleActions; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NUnit.Framework; using ReactNative.Bridge; using ReactNative.Bridge.Queue; using ReactNative.Chakra.Executor; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ReactNative.Tests.Bridge { [TestFixture] public class ReactBridgeTests { [Test] public async Task ReactBridge_Ctor_ArgumentChecks() { await JavaScriptHelpers.Run((executor, jsQueueThread) => { using (var nativeThread = CreateNativeModulesThread()) { var reactCallback = new MockReactCallback(); Assert.That( () => new ReactBridge(null, reactCallback, nativeThread), Throws.ArgumentNullException.With.Property("ParamName").EqualTo("executor") ); Assert.That( () => new ReactBridge(executor, null, nativeThread), Throws.ArgumentNullException.With.Property("ParamName").EqualTo("reactCallback") ); Assert.That( () => new ReactBridge(executor, reactCallback, null), Throws.ArgumentNullException.With.Property("ParamName").EqualTo("nativeModulesQueueThread") ); } }); } [Test] public async Task ReactBridge_Method_ArgumentChecks() { await JavaScriptHelpers.Run((executor, jsQueueThread) => { using (var nativeThread = CreateNativeModulesThread()) { var reactCallback = new MockReactCallback(); var bridge = new ReactBridge(executor, reactCallback, nativeThread); Assert.That( () => bridge.SetGlobalVariable(null, null), Throws.ArgumentNullException.With.Property("ParamName").EqualTo("propertyName") ); } }); } [Test] public async Task ReactBridge_CallFunction() { await JavaScriptHelpers.Run(async (executor, jsQueueThread) => { using (var nativeThread = CreateNativeModulesThread()) { var bridge = new ReactBridge(executor, new MockReactCallback(), nativeThread); var token = await jsQueueThread.RunAsync(() => { bridge.CallFunction("module", "method", new JArray()); return executor.GetGlobalVariable("FunctionCalls"); }); var expected = new JArray { new JArray { "module", "method", new JArray(), }, }; Assert.That(expected.ToString(Formatting.None), Is.EqualTo(token.ToString(Formatting.None))); } }); } [Test] public async Task ReactBridge_InvokeCallback() { await JavaScriptHelpers.Run(async (executor, jsQueueThread) => { using (var nativeThread = new ActionQueue(ex => { Assert.Fail(); })) { var bridge = new ReactBridge(executor, new MockReactCallback(), nativeThread); var token = await jsQueueThread.RunAsync(() => { bridge.InvokeCallback(1, new JArray()); return executor.GetGlobalVariable("CallbackCalls"); }); var expected = new JArray { new JArray { 1, new JArray(), }, }; Assert.That(expected.ToString(Formatting.None), Is.EqualTo(token.ToString(Formatting.None))); } }); } [Test] public void ReactBridge_ReactCallbacks() { using (var nativeThread = CreateNativeModulesThread()) { var jsonResponse = JArray.Parse("[[42,17],[16,22],[[],[\"foo\"]]]"); var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (module, method, args) => { Assert.AreEqual(module, "module"); Assert.AreEqual(method, "method"); return jsonResponse; } }; var callbacks = new List<Tuple<int, int, JArray>>(); var eventHandler = new AutoResetEvent(false); var callback = new MockReactCallback { InvokeHandler = (moduleId, methodId, args) => callbacks.Add(Tuple.Create(moduleId, methodId, args)), OnBatchCompleteHandler = () => eventHandler.Set(), }; var bridge = new ReactBridge(executor, callback, nativeThread); bridge.CallFunction("module", "method", new JArray()); Assert.IsTrue(eventHandler.WaitOne()); Assert.AreEqual(2, callbacks.Count); Assert.AreEqual(42, callbacks[0].Item1); Assert.AreEqual(16, callbacks[0].Item2); Assert.AreEqual(0, callbacks[0].Item3.Count); Assert.AreEqual(17, callbacks[1].Item1); Assert.AreEqual(22, callbacks[1].Item2); Assert.AreEqual(1, callbacks[1].Item3.Count); Assert.AreEqual("foo", callbacks[1].Item3[0].Value<string>()); } } [Test] public void ReactBridge_ValidJavaScriptResponse() { var responses = new[] { JToken.Parse("null"), JToken.Parse("undefined"), JArray.Parse("[[],[],[]]"), JArray.Parse("[[1],[1],[[]]]"), JArray.Parse("[[1],[1],[[1,2,3]], 42]"), }; var n = responses.Length; using (var nativeThread = CreateNativeModulesThread()) { var count = 0; var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (module, method, args) => { return responses[count++]; } }; var bridge = new ReactBridge(executor, new MockReactCallback(), nativeThread); for (var i = 0; i < n; ++i) { bridge.CallFunction("module", "method", new JArray()); } Assert.AreEqual(n, count); } } [Test] public void ReactBridge_InvalidJavaScriptResponse() { var responses = new[] { JArray.Parse("[null,[],[]]"), JArray.Parse("[[],null,[]]"), JArray.Parse("[[],[],null]"), JArray.Parse("[[42],[],[]]"), JArray.Parse("[[],[42],[]]"), JArray.Parse("[[],[],[42]]"), JArray.Parse("[[42],[42],[]]"), JArray.Parse("[[42],[42],[[],[]]]"), JArray.Parse("[[]]"), JArray.Parse("[[],[]]"), JObject.Parse("{}"), JToken.Parse("0"), }; var n = responses.Length; using (var nativeThread = CreateNativeModulesThread()) { var count = 0; var executor = new MockJavaScriptExecutor { OnCallFunctionReturnFlushedQueue = (module, method, args) => { return responses[count++]; } }; var bridge = new ReactBridge(executor, new MockReactCallback(), nativeThread); for (var i = 0; i < n; ++i) { Assert.That( () => bridge.CallFunction("module", "method", new JArray()), Throws.InvalidOperationException ); } Assert.AreEqual(n, count); } } [Test] public async Task ReactBridge_SyncCallback() { var jsFactories = new Func<IJavaScriptExecutor>[] { () => new ChakraJavaScriptExecutor(null), #if WINDOWS_UWP () => new NativeJavaScriptExecutor(), #endif }; foreach (var jsFactory in jsFactories) { await JavaScriptHelpers.Run(async (executor, jsQueueThread) => { using (var nativeThread = CreateNativeModulesThread()) { var moduleId = 42; var methodId = 7; var called = 0; var callback = new MockReactCallback { InvokeSyncHandler = (mod, met, arg) => { Assert.AreEqual(moduleId, mod); Assert.AreEqual(methodId, met); Assert.AreEqual(0, arg.Count); ++called; return JValue.CreateNull(); }, }; var bridge = new ReactBridge(executor, callback, nativeThread); await jsQueueThread.RunAsync(() => { bridge.CallFunction("SyncModule", "test", new JArray { 42, 7, new JArray() }); }); Assert.AreEqual(1, called); } }, jsFactory, @"Resources/sync.js"); } } [Test] public async Task ReactBridge_FlushQueueImmediate() { var jsFactories = new Func<IJavaScriptExecutor>[] { () => new ChakraJavaScriptExecutor(null), #if WINDOWS_UWP () => new NativeJavaScriptExecutor(), #endif }; foreach (var jsFactory in jsFactories) { await JavaScriptHelpers.Run(async (executor, jsQueueThread) => { using (var nativeThread = CreateNativeModulesThread()) { var moduleId = 42; var methodId = 7; var called = 0; var countdownEvent = new CountdownEvent(1); var callback = new MockReactCallback { InvokeHandler = (mod, met, arg) => { Assert.AreEqual(moduleId, mod); Assert.AreEqual(methodId, met); Assert.AreEqual(1, arg.Count); Assert.AreEqual("foo", arg[0].Value<string>()); ++called; }, OnBatchCompleteHandler = () => countdownEvent.Signal(), }; var bridge = new ReactBridge(executor, callback, nativeThread); await jsQueueThread.RunAsync(() => { bridge.CallFunction("FlushQueueImmediateModule", "test", new JArray { 10, new JArray { new JArray { 42 }, new JArray { 7 }, new JArray { new JArray { "foo" } } } }); }); // wait for `OnBatchComplete` in background // so we don't block native module thread await Task.Run(new Action(countdownEvent.Wait)); Assert.AreEqual(10, called); } }, jsFactory, @"Resources/immediate.js"); } } private static IActionQueue CreateNativeModulesThread() { return CreateNativeModulesThread(ex => Assert.Fail(ex.ToString())); } private static IActionQueue CreateNativeModulesThread(Action<Exception> exceptionHandler) { return new ActionQueue(exceptionHandler); } } }
// 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.IO; using System.Linq; using System.Text; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Feedback.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Packaging; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; protected readonly IServiceProvider ServiceProvider; private readonly IVsUIShellOpenDocument _shellOpenDocument; private readonly IVsTextManager _textManager; // Not readonly because it needs to be set in the derived class' constructor. private VisualStudioProjectTracker _projectTracker; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; private readonly ForegroundThreadAffinitizedObject _foregroundObject = new ForegroundThreadAffinitizedObject(); private PackageInstallerService _packageInstallerService; private PackageSearchService _packageSearchService; public VisualStudioWorkspaceImpl( SVsServiceProvider serviceProvider, WorkspaceBackgroundWork backgroundWork) : base( CreateHostServices(serviceProvider), backgroundWork) { this.ServiceProvider = serviceProvider; _textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; _shellOpenDocument = serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); var session = serviceProvider.GetService(typeof(SVsLog)) as IVsSqmMulti; var profileService = serviceProvider.GetService(typeof(SVsFeedbackProfile)) as IVsFeedbackProfile; // We have Watson hits where this came back null, so guard against it if (profileService != null) { Sqm.LogSession(session, profileService.IsMicrosoftInternal); } } internal static HostServices CreateHostServices(SVsServiceProvider serviceProvider) { var composition = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); return MefV1HostServices.Create(composition.DefaultExportProvider); } protected void InitializeStandardVisualStudioWorkspace(SVsServiceProvider serviceProvider, SaveEventsService saveEventsService) { var projectTracker = new VisualStudioProjectTracker(serviceProvider); // Ensure the document tracking service is initialized on the UI thread var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); var documentProvider = new RoslynDocumentProvider(projectTracker, serviceProvider, documentTrackingService); projectTracker.DocumentProvider = documentProvider; projectTracker.MetadataReferenceProvider = this.Services.GetService<VisualStudioMetadataReferenceManager>(); projectTracker.RuleSetFileProvider = this.Services.GetService<VisualStudioRuleSetManager>(); this.SetProjectTracker(projectTracker); var workspaceHost = new VisualStudioWorkspaceHost(this); projectTracker.RegisterWorkspaceHost(workspaceHost); projectTracker.StartSendingEventsToWorkspaceHost(workspaceHost); saveEventsService.StartSendingSaveEvents(); // Ensure the options factory services are initialized on the UI thread this.Services.GetService<IOptionService>(); // Ensure the nuget package services are initialized on the UI thread. _packageSearchService = this.Services.GetService<IPackageSearchService>() as PackageSearchService; _packageInstallerService = (PackageInstallerService)this.Services.GetService<IPackageInstallerService>(); _packageInstallerService.Connect(this); } /// <summary>NOTE: Call only from derived class constructor</summary> protected void SetProjectTracker(VisualStudioProjectTracker projectTracker) { _projectTracker = projectTracker; } internal VisualStudioProjectTracker ProjectTracker { get { return _projectTracker; } } internal void ClearReferenceCache() { _projectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return this.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } public override bool TryApplyChanges(Microsoft.CodeAnalysis.Solution newSolution) { // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.CouldNotFindProject, projectId)); } } internal EnvDTE.Project TryGetDTEProject(ProjectId projectId) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; return TryGetProjectData(projectId, out hostProject, out hierarchy, out project) ? project : null; } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; try { GetProjectData(projectId, out hostProject, out hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); } } protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; VSLangProj.Reference reference = vsProject.References.Find(filePath); if (reference != null) { reference.Remove(); } } } protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; vsProject.References.AddProject(refProject); } protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } IVisualStudioHostProject hostProject; IVsHierarchy hierarchy; EnvDTE.Project project; GetProjectData(projectId, out hostProject, out hierarchy, out project); IVisualStudioHostProject refHostProject; IVsHierarchy refHierarchy; EnvDTE.Project refProject; GetProjectData(projectReference.ProjectId, out refHostProject, out refHierarchy, out refProject); VSLangProj.VSProject vsProject = (VSLangProj.VSProject)project.Object; foreach (VSLangProj.Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(info.Id.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { string folderPath; if (!project.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); string folderPath; if (!folder.TryGetFullPath(out folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.CouldNotFindLocationOfFol); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = _projectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var document = this.GetHostDocument(documentId); if (document != null) { var project = document.Project.Hierarchy as IVsProject3; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } int result; project.RemoveItem(0, itemId, out result); } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public bool TryGetInfoBarData(out IVsWindowFrame frame, out IVsInfoBarUIFactory factory) { frame = null; factory = null; var monitorSelectionService = ServiceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; object value = null; // We want to get whichever window is currently in focus (including toolbars) as we could have had an exception thrown from the error list or interactive window if (monitorSelectionService != null && ErrorHandler.Succeeded(monitorSelectionService.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_WindowFrame, out value))) { frame = value as IVsWindowFrame; } else { return false; } factory = ServiceProvider.GetService(typeof(SVsInfoBarUIFactory)) as IVsInfoBarUIFactory; return frame != null && factory != null; } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.ThisWorkspaceOnlySupportsOpeningDocumentsOnTheUIThread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { IVsWindowFrame frame; if (TryGetFrame(document, out frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. uint itemid; IVsUIHierarchy uiHierarchy; OLEServiceProvider oleServiceProvider; return ErrorHandler.Succeeded(_shellOpenDocument.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out oleServiceProvider, out uiHierarchy, out itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { IVsUIHierarchy uiHierarchy; IVsWindowFrame frame; int isOpen; if (ErrorHandler.Succeeded(_shellOpenDocument.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out uiHierarchy, null, out frame, out isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); if (hostProject.Hierarchy == sharedHierarchy) { // How? return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { _packageInstallerService?.Disconnect(this); _packageSearchService?.Dispose(); // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); uint editVerdict; uint editResultFlags; // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out editVerdict, prgfMoreInfo: out editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } public TInterface GetVsService<TService, TInterface>() where TService : class where TInterface : class { return this.ServiceProvider.GetService(typeof(TService)) as TInterface; } internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.AssertIsForeground(); IVsHierarchy referencingHierarchy; IVsHierarchy referencedHierarchy; if (!TryGetHierarchy(referencingProject, out referencingHierarchy) || !TryGetHierarchy(referencedProject, out referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3; if (referencingProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3; if (referencedProjectFlavor3 != null) { string unused; if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = GetVsService<SVsReferenceManager, IVsReferenceManager>(); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { uint cookie; if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage(SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage(SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as PersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo additionalDocumentInfo) { _workspace.OnAdditionalDocumentAdded(additionalDocumentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId additionalDocumentId) { _workspace.OnAdditionalDocumentRemoved(additionalDocumentId); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation) { _workspace.OnHasAllInformationChanged(projectId, hasAllInformation); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace System.ServiceModel.Dispatcher { public sealed class DispatchOperation { private readonly string _action; private readonly SynchronizedCollection<FaultContractInfo> _faultContractInfos; private IDispatchMessageFormatter _formatter; private IDispatchFaultFormatter _faultFormatter; private IOperationInvoker _invoker; private bool _isSessionOpenNotificationEnabled; private readonly string _name; private readonly SynchronizedCollection<IParameterInspector> _parameterInspectors; private readonly DispatchRuntime _parent; private readonly string _replyAction; private bool _deserializeRequest = true; private bool _serializeReply = true; private readonly bool _isOneWay; private bool _autoDisposeParameters = true; private bool _hasNoDisposableParameters; private bool _isFaultFormatterSetExplicit; public DispatchOperation(DispatchRuntime parent, string name, string action) { if (parent == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parent"); if (name == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("name"); _parent = parent; _name = name; _action = action; _faultContractInfos = parent.NewBehaviorCollection<FaultContractInfo>(); _parameterInspectors = parent.NewBehaviorCollection<IParameterInspector>(); _isOneWay = true; } public DispatchOperation(DispatchRuntime parent, string name, string action, string replyAction) : this(parent, name, action) { _replyAction = replyAction; _isOneWay = false; } public bool IsOneWay { get { return _isOneWay; } } public string Action { get { return _action; } } public SynchronizedCollection<FaultContractInfo> FaultContractInfos { get { return _faultContractInfos; } } public bool AutoDisposeParameters { get { return _autoDisposeParameters; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _autoDisposeParameters = value; } } } internal IDispatchMessageFormatter Formatter { get { return _formatter; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _formatter = value; } } } internal IDispatchFaultFormatter FaultFormatter { get { if (_faultFormatter == null) { _faultFormatter = new DataContractSerializerFaultFormatter(_faultContractInfos); } return _faultFormatter; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _faultFormatter = value; _isFaultFormatterSetExplicit = true; } } } internal bool IsFaultFormatterSetExplicit { get { return _isFaultFormatterSetExplicit; } } internal bool HasNoDisposableParameters { get { return _hasNoDisposableParameters; } set { _hasNoDisposableParameters = value; } } internal IDispatchMessageFormatter InternalFormatter { get { return _formatter; } set { _formatter = value; } } internal IOperationInvoker InternalInvoker { get { return _invoker; } set { _invoker = value; } } public IOperationInvoker Invoker { get { return _invoker; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _invoker = value; } } } internal bool IsSessionOpenNotificationEnabled { get { return _isSessionOpenNotificationEnabled; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _isSessionOpenNotificationEnabled = value; } } } public string Name { get { return _name; } } public SynchronizedCollection<IParameterInspector> ParameterInspectors { get { return _parameterInspectors; } } public DispatchRuntime Parent { get { return _parent; } } public string ReplyAction { get { return _replyAction; } } public bool DeserializeRequest { get { return _deserializeRequest; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _deserializeRequest = value; } } } public bool SerializeReply { get { return _serializeReply; } set { lock (_parent.ThisLock) { _parent.InvalidateRuntime(); _serializeReply = value; } } } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Shapes; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Data; namespace MahApps.Metro.Controls { /// <summary> /// A Button that allows the user to toggle between two states. /// </summary> [TemplatePart(Name = PART_BackgroundTranslate, Type = typeof(TranslateTransform))] [TemplatePart(Name = PART_DraggingThumb, Type = typeof(Thumb))] [TemplatePart(Name = PART_SwitchTrack, Type = typeof(Grid))] [TemplatePart(Name = PART_ThumbIndicator, Type = typeof(Shape))] [TemplatePart(Name = PART_ThumbTranslate, Type = typeof(TranslateTransform))] public class ToggleSwitchButton : ToggleButton { private const string PART_BackgroundTranslate = "PART_BackgroundTranslate"; private const string PART_DraggingThumb = "PART_DraggingThumb"; private const string PART_SwitchTrack = "PART_SwitchTrack"; private const string PART_ThumbIndicator = "PART_ThumbIndicator"; private const string PART_ThumbTranslate = "PART_ThumbTranslate"; private TranslateTransform _BackgroundTranslate; private Thumb _DraggingThumb; private Grid _SwitchTrack; private Shape _ThumbIndicator; private TranslateTransform _ThumbTranslate; [Obsolete(@"This property will be deleted in the next release. You should use OnSwitchBrush and OffSwitchBrush to change the switch's brushes.")] public static readonly DependencyProperty SwitchForegroundProperty = DependencyProperty.Register("SwitchForeground", typeof(Brush), typeof(ToggleSwitchButton), new PropertyMetadata(null, (o, e) => ((ToggleSwitchButton)o).OnSwitchBrush = e.NewValue as Brush)); public static readonly DependencyProperty OnSwitchBrushProperty = DependencyProperty.Register("OnSwitchBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty OffSwitchBrushProperty = DependencyProperty.Register("OffSwitchBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty ThumbIndicatorBrushProperty = DependencyProperty.Register("ThumbIndicatorBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty ThumbIndicatorDisabledBrushProperty = DependencyProperty.Register("ThumbIndicatorDisabledBrush", typeof(Brush), typeof(ToggleSwitchButton), null); public static readonly DependencyProperty ThumbIndicatorWidthProperty = DependencyProperty.Register("ThumbIndicatorWidth", typeof(double), typeof(ToggleSwitchButton), new PropertyMetadata(13d)); /// <summary> /// Gets/sets the brush used for the control's foreground. /// </summary> [Obsolete(@"This property will be deleted in the next release. You should use OnSwitchBrush and OffSwitchBrush to change the switch's brushes.")] public Brush SwitchForeground { get { return (Brush)GetValue(SwitchForegroundProperty); } set { SetValue(SwitchForegroundProperty, value); } } /// <summary> /// Gets/sets the brush used for the on-switch's foreground. /// </summary> public Brush OnSwitchBrush { get { return (Brush)GetValue(OnSwitchBrushProperty); } set { SetValue(OnSwitchBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the off-switch's foreground. /// </summary> public Brush OffSwitchBrush { get { return (Brush)GetValue(OffSwitchBrushProperty); } set { SetValue(OffSwitchBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the thumb indicator. /// </summary> public Brush ThumbIndicatorBrush { get { return (Brush)GetValue(ThumbIndicatorBrushProperty); } set { SetValue(ThumbIndicatorBrushProperty, value); } } /// <summary> /// Gets/sets the brush used for the thumb indicator. /// </summary> public Brush ThumbIndicatorDisabledBrush { get { return (Brush)GetValue(ThumbIndicatorDisabledBrushProperty); } set { SetValue(ThumbIndicatorDisabledBrushProperty, value); } } /// <summary> /// Gets/sets the width of the thumb indicator. /// </summary> public double ThumbIndicatorWidth { get { return (double)GetValue(ThumbIndicatorWidthProperty); } set { SetValue(ThumbIndicatorWidthProperty, value); } } public ToggleSwitchButton() { DefaultStyleKey = typeof(ToggleSwitchButton); Checked += ToggleSwitchButton_Checked; Unchecked += ToggleSwitchButton_Checked; } void ToggleSwitchButton_Checked(object sender, RoutedEventArgs e) { UpdateThumb(); } DoubleAnimation _thumbAnimation; private void UpdateThumb() { if (_ThumbTranslate != null && _SwitchTrack != null && _ThumbIndicator != null) { double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth) : 0; _thumbAnimation = new DoubleAnimation(); _thumbAnimation.To = destination; _thumbAnimation.Duration = TimeSpan.FromMilliseconds(500); _thumbAnimation.EasingFunction = new ExponentialEase() { Exponent = 9 }; _thumbAnimation.FillBehavior = FillBehavior.Stop; AnimationTimeline currentAnimation = _thumbAnimation; _thumbAnimation.Completed += (sender, e) => { if (_thumbAnimation != null && currentAnimation == _thumbAnimation) { _ThumbTranslate.X = destination; _thumbAnimation = null; } }; _ThumbTranslate.BeginAnimation(TranslateTransform.XProperty, _thumbAnimation); } } protected override void OnToggle() { IsChecked = IsChecked != true; UpdateThumb(); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _BackgroundTranslate = GetTemplateChild(PART_BackgroundTranslate) as TranslateTransform; _DraggingThumb = GetTemplateChild(PART_DraggingThumb) as Thumb; _SwitchTrack = GetTemplateChild(PART_SwitchTrack) as Grid; _ThumbIndicator = GetTemplateChild(PART_ThumbIndicator) as Shape; _ThumbTranslate = GetTemplateChild(PART_ThumbTranslate) as TranslateTransform; if (_ThumbIndicator != null && _BackgroundTranslate != null) { Binding translationBinding; translationBinding = new System.Windows.Data.Binding("X"); translationBinding.Source = _ThumbTranslate; BindingOperations.SetBinding(_BackgroundTranslate, TranslateTransform.XProperty, translationBinding); } if (_DraggingThumb != null && _SwitchTrack != null && _ThumbIndicator != null && _ThumbTranslate != null) { _DraggingThumb.DragStarted += _DraggingThumb_DragStarted; _DraggingThumb.DragDelta += _DraggingThumb_DragDelta; _DraggingThumb.DragCompleted += _DraggingThumb_DragCompleted; _SwitchTrack.SizeChanged += _SwitchTrack_SizeChanged; } } private double? _lastDragPosition; private bool _isDragging; void _DraggingThumb_DragStarted(object sender, DragStartedEventArgs e) { if (_ThumbTranslate != null) { _ThumbTranslate.BeginAnimation(TranslateTransform.XProperty, null); double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth) : 0; _ThumbTranslate.X = destination; _thumbAnimation = null; } _lastDragPosition = _ThumbTranslate.X; _isDragging = false; } void _DraggingThumb_DragDelta(object sender, DragDeltaEventArgs e) { if (_lastDragPosition.HasValue) { if (Math.Abs(e.HorizontalChange) > 3) _isDragging = true; if (_SwitchTrack != null && _ThumbIndicator != null) { double lastDragPosition = _lastDragPosition.Value; _ThumbTranslate.X = Math.Min(ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth), Math.Max(0, lastDragPosition + e.HorizontalChange)); } } } void _DraggingThumb_DragCompleted(object sender, DragCompletedEventArgs e) { _lastDragPosition = null; if (!_isDragging) { OnToggle(); } else if (_ThumbTranslate != null && _SwitchTrack != null) { if (!IsChecked.GetValueOrDefault() && _ThumbTranslate.X + 6.5 >= _SwitchTrack.ActualWidth / 2) { OnToggle(); } else if (IsChecked.GetValueOrDefault() && _ThumbTranslate.X + 6.5 <= _SwitchTrack.ActualWidth / 2) { OnToggle(); } else UpdateThumb(); } } void _SwitchTrack_SizeChanged(object sender, SizeChangedEventArgs e) { if (_ThumbTranslate != null && _SwitchTrack != null && _ThumbIndicator != null) { double destination = IsChecked.GetValueOrDefault() ? ActualWidth - (_SwitchTrack.Margin.Left + _SwitchTrack.Margin.Right + _ThumbIndicator.ActualWidth) : 0; _ThumbTranslate.X = destination; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.ServiceAuth; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class UserAccountServicesConnector : BaseServiceConnector, IUserAccountService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public UserAccountServicesConnector() { } public UserAccountServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public UserAccountServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig assetConfig = source.Configs["UserAccountService"]; if (assetConfig == null) { m_log.Error("[ACCOUNT CONNECTOR]: UserAccountService missing from OpenSim.ini"); throw new Exception("User account connector init error"); } string serviceURI = assetConfig.GetString("UserAccountServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ACCOUNT CONNECTOR]: No Server URI named in section UserAccountService"); throw new Exception("User account connector init error"); } m_ServerURI = serviceURI; base.Initialise(source, "UserAccountService"); } public virtual UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccount"; sendData["ScopeID"] = scopeID; sendData["FirstName"] = firstName.ToString(); sendData["LastName"] = lastName.ToString(); return SendAndGetReply(sendData); } public virtual UserAccount GetUserAccount(UUID scopeID, string email) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccount"; sendData["ScopeID"] = scopeID; sendData["Email"] = email; return SendAndGetReply(sendData); } public virtual UserAccount GetUserAccount(UUID scopeID, UUID userID) { //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccount {0}", userID); Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccount"; sendData["ScopeID"] = scopeID; sendData["UserID"] = userID.ToString(); return SendAndGetReply(sendData); } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getaccounts"; sendData["ScopeID"] = scopeID.ToString(); sendData["query"] = query; string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/accounts"; // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message); } List<UserAccount> accounts = new List<UserAccount>(); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && replyData["result"].ToString() == "null") { return accounts; } Dictionary<string, object>.ValueCollection accountList = replyData.Values; //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object acc in accountList) { if (acc is Dictionary<string, object>) { UserAccount pinfo = new UserAccount((Dictionary<string, object>)acc); accounts.Add(pinfo); } else m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccounts received invalid response type {0}", acc.GetType()); } } else m_log.DebugFormat("[ACCOUNTS CONNECTOR]: GetUserAccounts received null response"); return accounts; } public void InvalidateCache(UUID userID) { } public List<UserAccount> GetUserAccountsWhere(UUID scopeID, string where) { return null; // Not implemented for regions } public virtual bool StoreUserAccount(UserAccount data) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "setaccount"; Dictionary<string, object> structData = data.ToKeyValuePairs(); foreach (KeyValuePair<string, object> kvp in structData) { if (kvp.Value == null) { m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Null value for {0}", kvp.Key); continue; } sendData[kvp.Key] = kvp.Value.ToString(); } if (SendAndGetReply(sendData) != null) return true; else return false; } /// <summary> /// Create user remotely. Note this this is not part of the IUserAccountsService /// </summary> /// <param name="first"></param> /// <param name="last"></param> /// <param name="password"></param> /// <param name="email"></param> /// <param name="scopeID"></param> /// <returns></returns> public virtual UserAccount CreateUser(string first, string last, string password, string email, UUID scopeID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "createuser"; sendData["FirstName"] = first; sendData["LastName"] = last; sendData["Password"] = password; if (!string.IsNullOrEmpty(email)) sendData["Email"] = first; sendData["ScopeID"] = scopeID.ToString(); return SendAndGetReply(sendData); } private UserAccount SendAndGetReply(Dictionary<string, object> sendData) { string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/accounts"; // m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: GetUserAccount received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message); } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); UserAccount account = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) { account = new UserAccount((Dictionary<string, object>)replyData["result"]); } } return account; } private bool SendAndGetBoolReply(Dictionary<string, object> sendData) { string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/accounts"; //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { //m_log.DebugFormat("[ACCOUNTS CONNECTOR]: reply = {0}", reply); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount reply data does not contain result field"); } else m_log.DebugFormat("[ACCOUNTS CONNECTOR]: Set or Create UserAccount received empty reply"); } catch (Exception e) { m_log.DebugFormat("[ACCOUNT CONNECTOR]: Exception when contacting user accounts server at {0}: {1}", uri, e.Message); } return false; } } }
// ChildrenTools v0.2 // Useful stuff for GameObjects on the Hierarchy right click menu. // 2016/10/10 01:26 PM #if UNITY_EDITOR using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; public class ChildrenTools { // Select [MenuItem("GameObject/Children Tools/Select/All Children", false, 10)] static void SelectAllChildren() { var allChildren = new List<Transform>(); foreach (var t in Selection.transforms) { allChildren.AddRange(t.GetComponentsInChildren<Transform>()); } Selection.objects = allChildren.Select(x => x.gameObject).ToArray(); } [MenuItem("GameObject/Children Tools/Select/All Parents", false, 10)] static void SelectAllParents() { var allChildren = new List<Transform>(); foreach (var t in Selection.transforms) { allChildren.AddRange(t.GetComponentsInParent<Transform>()); } Selection.objects = allChildren.Select(x => x.gameObject).ToArray(); } [MenuItem("GameObject/Children Tools/Select/All With Similar Name And Parent Structure", false, 10)] static void SelectSimilarChildren() { Transform selected = Selection.activeTransform; // Get a list of all parents. var selectedParents = new List<Transform>(); var current = selected; while (true) { if (current.parent) { selectedParents.Add(current.parent); current = current.parent; } else break; } // Get all transforms with the same name and the same parent. var allNamed = GameObject.FindObjectsOfType<Transform>() .Where( x => OnlyLetters(x.name) == OnlyLetters(selected.name) && SameParentsName(x, selected)); Selection.objects = allNamed.Select(x => x.gameObject).ToArray(); } // Sort [MenuItem("GameObject/Children Tools/Sort/Children By Name", false, 10)] static void SortByName() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.name); int i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Sort/Children By X", false, 10)] static void SortByX() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.position.x); int i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Sort/Children By Y", false, 10)] static void SortByY() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.position.y); int i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Sort/Children By Z", false, 10)] static void SortByZ() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.position.z); int i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Sort/Children By Magnitude", false, 10)] static void SortBySqrMagnitude() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.position.sqrMagnitude); int i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Reposition [MenuItem("GameObject/Children Tools/Reposition/To Position 0", false, 10)] static void RelocateToPos0() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected); Vector3 displacement = selected.localPosition; foreach (var t in firstChildren) t.localPosition += displacement; selected.localPosition = Vector3.zero; UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Reposition/To The Center Of All Children", false, 10)] static void RelocateToCenterOfChildren() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .Where(x => x != selected); // Calculate the average of all positions Vector3 averagePos = Vector3.zero; foreach (var t in firstChildren) averagePos += t.localPosition; averagePos /= firstChildren.Count(); // Center of everything averagePos += selected.localPosition; // Updating to new positions Vector3 displacement = selected.localPosition - averagePos; foreach (var t in firstChildren) t.localPosition += displacement; selected.localPosition = averagePos; UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Snap // ALL [MenuItem("GameObject/Children Tools/Snap/All To 0.01", false, 10)] static void SnapAllToDot01() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) { t.localPosition = Snap(t.localPosition, 0.01f); t.localEulerAngles = Snap(t.localEulerAngles, 0.01f); t.localScale = Snap(t.localScale, 0.01f); } UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Snap/All To 0.1", false, 10)] static void SnapAllToDot1() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) { t.localPosition = Snap(t.localPosition, 0.1f); t.localEulerAngles = Snap(t.localEulerAngles, 0.1f); t.localScale = Snap(t.localScale, 0.1f); } UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Position [MenuItem("GameObject/Children Tools/Snap/Pos/All To 0.01", false, 10)] static void SnapPosToDot01() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) t.localPosition = Snap(t.localPosition, 0.01f); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Snap/Pos/All To 0.1", false, 10)] static void SnapPosToDot1() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) t.localPosition = Snap(t.localPosition, 0.1f); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Rotation [MenuItem("GameObject/Children Tools/Snap/Rotation/All To 0.01", false, 10)] static void SnapEulerToDot01() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) t.localEulerAngles = Snap(t.localEulerAngles, 0.01f); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Snap/Rotation/All To 0.1", false, 10)] static void SnapEulerToDot1() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) t.localEulerAngles = Snap(t.localEulerAngles, 0.1f); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Scale [MenuItem("GameObject/Children Tools/Snap/Scale/All To 0.01", false, 10)] static void SnapScaleToDot1() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) t.localScale = Snap(t.localScale, 0.01f); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Snap/Scale/All To 0.1", false, 10)] static void SnapScaleToDot01() { var all = Selection.activeTransform.GetComponentsInChildren<Transform>(); foreach (var t in all) t.localScale = Snap(t.localScale, 0.1f); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Rename [MenuItem("GameObject/Children Tools/Rename/Enumerate", false, 10)] static void RenameEnumerate() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected); int i = 0; foreach (var t in firstChildren) { var name = string.Format( "{0} ({1})", RemoveBetween(t.name, '(', ')').Trim(), i++); t.name = name; } UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Rename/Enumerate By Magnitude", false, 10)] static void RenameEnumerateByMagnitude() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected); int i = 0; foreach (var t in firstChildren) { var name = string.Format( "{0} ({1})", RemoveBetween(t.name, '(', ')').Trim(), i++); t.name = name; } UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Rename/Enumerate And Sort By Magnitude", false, 10)] static void RenameEnumerateAndSortByMagnitude() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.position.sqrMagnitude); // Rename int i = 0; foreach (var t in firstChildren) { var name = string.Format( "{0} ({1})", RemoveBetween(t.name, '(', ')').Trim(), i++); t.name = name; } // Sort i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } [MenuItem("GameObject/Children Tools/Rename/Enumerate And Sort By X", false, 10)] static void RenameEnumerateAndSortByX() { var selected = Selection.activeTransform; var firstChildren = selected.GetComponentsInChildren<Transform>() .Where(x => x.parent == selected) .OrderBy(x => x.position.x); // Rename int i = 0; foreach (var t in firstChildren) { var name = string.Format( "{0} ({1})", RemoveBetween(t.name, '(', ')').Trim(), i++); t.name = name; } // Sort i = 0; foreach (var t in firstChildren) t.SetSiblingIndex(i++); UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // Groups [MenuItem("GameObject/Children Tools/Group/Into New Game Object", false, 10)] static void GroupIntoNewGameObject() { if (Selection.transforms.Length < 1) return; var selected = Selection.activeTransform; var name = "[New Group]"; var parent = GameObject.Find(name); parent = !parent ? new GameObject(name) : parent; parent.transform.SetParent(selected.parent); parent.transform.SetAsLastSibling(); foreach (var t in Selection.transforms) t.SetParent(parent.transform); Selection.objects = new GameObject[] { parent }; UnityEditor.SceneManagement.EditorSceneManager.MarkAllScenesDirty(); } // General public static string RemoveBetween(string text, char begin, char end) { Regex re = new Regex(string.Format("\\{0}.*?\\{1}", begin, end)); return re.Replace(text, string.Empty); } public static string OnlyLetters(string text) { return new string(text.Where(x => char.IsLetter(x)).ToArray()); } public static bool SameParentsName(Transform one, Transform two) { // Test for the the same parents. while (true) { // Until they don't have parents. if (one.parent == null || two.parent == null) { // Equally orphans? if (one.parent == null && two.parent == null) return true; else return false; } // Let's continue when having the same parent name. if (OnlyLetters(one.parent.name) == OnlyLetters(two.parent.name)) { // Next one = one.parent; two = two.parent; } // Or we don't. else { return false; } } } public static Vector3 Snap(Vector3 vector, float size) { return new Vector3( Mathf.Round(vector.x / size) * size, Mathf.Round(vector.y / size) * size, Mathf.Round(vector.z / size) * size ); } } #endif
using EIDSS.Reports.BaseControls.Report; using EIDSS.Reports.Document.Human.CaseInvestigation; namespace EIDSS.Reports.Document.Veterinary.LivestockInvestigation { partial class LivestockInvestigationReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LivestockInvestigationReport)); this.DetailReportInfo = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailInfo = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable4 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell73 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell74 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell(); this.DividerCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellBarcode = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell(); this.LivestockCaseTableAdapter = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockInvestigationDataSetTableAdapters.spRepVetLivestockCaseTableAdapter(); this.LivestockInvestigationDataSet = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockInvestigationDataSet(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReportHerd = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailHerd = new DevExpress.XtraReports.UI.DetailBand(); this.xrSubreportHerd = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportClinical = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailClinical = new DevExpress.XtraReports.UI.DetailBand(); this.ClinicalInvestigationSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.ReportHeaderClinical = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel(); this.DetailReportEpi = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailEpi = new DevExpress.XtraReports.UI.DetailBand(); this.EpiSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.reportHeaderBand1 = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel(); this.DetailReportVaccinations = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailVaccinations = new DevExpress.XtraReports.UI.DetailBand(); this.VaccinationSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportRapidTest = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailRapidTest = new DevExpress.XtraReports.UI.DetailBand(); this.RapidTestSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportDiagnosis = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailDiagnosis = new DevExpress.XtraReports.UI.DetailBand(); this.DiagnosisSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportOutbreak = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailOutbreak = new DevExpress.XtraReports.UI.DetailBand(); this.xrLabel4 = new DevExpress.XtraReports.UI.XRLabel(); this.ControlMeasuresSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.DetailReportSample = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailSample = new DevExpress.XtraReports.UI.DetailBand(); this.SampleSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.AnimalSubreport = new DevExpress.XtraReports.UI.XRSubreport(); this.MapPictureBox = new DevExpress.XtraReports.UI.XRPictureBox(); this.DetailReportMap = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailMap = new DevExpress.XtraReports.UI.DetailBand(); this.DetailReportAnimal = new DevExpress.XtraReports.UI.DetailReportBand(); this.DetailAnimal = new DevExpress.XtraReports.UI.DetailBand(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.LivestockInvestigationDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // this.PageFooter.StylePriority.UseBorders = false; // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; // // tableBaseHeader // this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // DetailReportInfo // this.DetailReportInfo.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailInfo}); this.DetailReportInfo.DataAdapter = this.LivestockCaseTableAdapter; this.DetailReportInfo.DataMember = "spRepVetLivestockCase"; this.DetailReportInfo.DataSource = this.LivestockInvestigationDataSet; resources.ApplyResources(this.DetailReportInfo, "DetailReportInfo"); this.DetailReportInfo.Level = 0; this.DetailReportInfo.Name = "DetailReportInfo"; // // DetailInfo // this.DetailInfo.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable4, this.xrTable2, this.xrTable1}); resources.ApplyResources(this.DetailInfo, "DetailInfo"); this.DetailInfo.Name = "DetailInfo"; this.DetailInfo.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.DetailInfo.StylePriority.UsePadding = false; this.DetailInfo.StylePriority.UseTextAlignment = false; // // xrTable4 // resources.ApplyResources(this.xrTable4, "xrTable4"); this.xrTable4.Name = "xrTable4"; this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow20}); this.xrTable4.StylePriority.UseBorders = false; this.xrTable4.StylePriority.UseTextAlignment = false; // // xrTableRow20 // this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell14, this.xrTableCell20}); this.xrTableRow20.Name = "xrTableRow20"; this.xrTableRow20.StylePriority.UseBorders = false; this.xrTableRow20.StylePriority.UseFont = false; resources.ApplyResources(this.xrTableRow20, "xrTableRow20"); // // xrTableCell14 // this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); // // xrTableCell20 // this.xrTableCell20.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.OwnershipType")}); this.xrTableCell20.Multiline = true; this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTable2 // resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow3, this.xrTableRow19, this.xrTableRow18, this.xrTableRow17, this.xrTableRow9, this.xrTableRow16, this.xrTableRow15, this.xrTableRow14, this.xrTableRow13, this.xrTableRow12, this.xrTableRow11, this.xrTableRow10}); // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2, this.xrTableCell9, this.xrTableCell3, this.xrTableCell8}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // xrTableCell9 // this.xrTableCell9.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.ReportedName")}); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 0, 0, 100F); this.xrTableCell3.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // xrTableCell8 // this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.InvestigationName")}); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // xrTableRow19 // this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell55, this.xrTableCell56, this.xrTableCell57, this.xrTableCell59}); this.xrTableRow19.Name = "xrTableRow19"; resources.ApplyResources(this.xrTableRow19, "xrTableRow19"); // // xrTableCell55 // this.xrTableCell55.Name = "xrTableCell55"; resources.ApplyResources(this.xrTableCell55, "xrTableCell55"); // // xrTableCell56 // this.xrTableCell56.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell56.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.ReportedDate", "{0:dd/MM/yyyy}")}); this.xrTableCell56.Name = "xrTableCell56"; this.xrTableCell56.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell56, "xrTableCell56"); // // xrTableCell57 // this.xrTableCell57.Name = "xrTableCell57"; this.xrTableCell57.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 0, 0, 100F); this.xrTableCell57.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell57, "xrTableCell57"); // // xrTableCell59 // this.xrTableCell59.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.AssignedDate", "{0:dd/MM/yyyy}")}); this.xrTableCell59.Name = "xrTableCell59"; this.xrTableCell59.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell59, "xrTableCell59"); // // xrTableRow18 // this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell51, this.xrTableCell52, this.xrTableCell53, this.xrTableCell54}); this.xrTableRow18.Name = "xrTableRow18"; resources.ApplyResources(this.xrTableRow18, "xrTableRow18"); // // xrTableCell51 // this.xrTableCell51.Name = "xrTableCell51"; resources.ApplyResources(this.xrTableCell51, "xrTableCell51"); // // xrTableCell52 // this.xrTableCell52.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell52.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.EnteredName")}); this.xrTableCell52.Name = "xrTableCell52"; this.xrTableCell52.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell52, "xrTableCell52"); // // xrTableCell53 // this.xrTableCell53.Name = "xrTableCell53"; this.xrTableCell53.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 0, 0, 100F); this.xrTableCell53.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell53, "xrTableCell53"); // // xrTableCell54 // this.xrTableCell54.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell54.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.DateOfInvestigation", "{0:dd/MM/yyyy}")}); this.xrTableCell54.Name = "xrTableCell54"; this.xrTableCell54.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell54, "xrTableCell54"); // // xrTableRow17 // this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell47, this.xrTableCell48, this.xrTableCell49, this.xrTableCell50}); this.xrTableRow17.Name = "xrTableRow17"; resources.ApplyResources(this.xrTableRow17, "xrTableRow17"); // // xrTableCell47 // this.xrTableCell47.Name = "xrTableCell47"; resources.ApplyResources(this.xrTableCell47, "xrTableCell47"); // // xrTableCell48 // this.xrTableCell48.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.DataEntryDate", "{0:dd/MM/yyyy HH:mm}")}); this.xrTableCell48.Name = "xrTableCell48"; this.xrTableCell48.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell48, "xrTableCell48"); // // xrTableCell49 // this.xrTableCell49.Name = "xrTableCell49"; resources.ApplyResources(this.xrTableCell49, "xrTableCell49"); // // xrTableCell50 // this.xrTableCell50.Name = "xrTableCell50"; resources.ApplyResources(this.xrTableCell50, "xrTableCell50"); // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell24}); this.xrTableRow9.Name = "xrTableRow9"; resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); // // xrTableCell24 // this.xrTableCell24.Name = "xrTableCell24"; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); // // xrTableRow16 // this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell45}); this.xrTableRow16.Name = "xrTableRow16"; resources.ApplyResources(this.xrTableRow16, "xrTableRow16"); // // xrTableCell45 // resources.ApplyResources(this.xrTableCell45, "xrTableCell45"); this.xrTableCell45.Name = "xrTableCell45"; this.xrTableCell45.StylePriority.UseFont = false; // // xrTableRow15 // this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell38, this.xrTableCell39, this.xrTableCell72}); this.xrTableRow15.Name = "xrTableRow15"; resources.ApplyResources(this.xrTableRow15, "xrTableRow15"); // // xrTableCell38 // resources.ApplyResources(this.xrTableCell38, "xrTableCell38"); this.xrTableCell38.Name = "xrTableCell38"; this.xrTableCell38.StylePriority.UseFont = false; // // xrTableCell39 // this.xrTableCell39.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell39.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmName")}); this.xrTableCell39.Name = "xrTableCell39"; this.xrTableCell39.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell39, "xrTableCell39"); // // xrTableCell72 // this.xrTableCell72.Name = "xrTableCell72"; resources.ApplyResources(this.xrTableCell72, "xrTableCell72"); // // xrTableRow14 // this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell34, this.xrTableCell35, this.xrTableCell73}); this.xrTableRow14.Name = "xrTableRow14"; resources.ApplyResources(this.xrTableRow14, "xrTableRow14"); // // xrTableCell34 // resources.ApplyResources(this.xrTableCell34, "xrTableCell34"); this.xrTableCell34.Name = "xrTableCell34"; this.xrTableCell34.StylePriority.UseFont = false; // // xrTableCell35 // this.xrTableCell35.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell35.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmCode")}); this.xrTableCell35.Name = "xrTableCell35"; this.xrTableCell35.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell35, "xrTableCell35"); // // xrTableCell73 // this.xrTableCell73.Name = "xrTableCell73"; resources.ApplyResources(this.xrTableCell73, "xrTableCell73"); // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell30, this.xrTableCell31, this.xrTableCell74}); this.xrTableRow13.Name = "xrTableRow13"; resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); // // xrTableCell30 // this.xrTableCell30.Name = "xrTableCell30"; resources.ApplyResources(this.xrTableCell30, "xrTableCell30"); // // xrTableCell31 // this.xrTableCell31.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmerName")}); this.xrTableCell31.Name = "xrTableCell31"; this.xrTableCell31.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); // // xrTableCell74 // this.xrTableCell74.Name = "xrTableCell74"; resources.ApplyResources(this.xrTableCell74, "xrTableCell74"); // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell26, this.xrTableCell27, this.xrTableCell28, this.xrTableCell29}); this.xrTableRow12.Name = "xrTableRow12"; resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); // // xrTableCell26 // this.xrTableCell26.Name = "xrTableCell26"; resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); // // xrTableCell27 // this.xrTableCell27.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell27.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmPhone")}); this.xrTableCell27.Name = "xrTableCell27"; this.xrTableCell27.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); // // xrTableCell28 // this.xrTableCell28.Name = "xrTableCell28"; this.xrTableCell28.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 0, 0, 100F); this.xrTableCell28.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell28, "xrTableCell28"); // // xrTableCell29 // this.xrTableCell29.Name = "xrTableCell29"; resources.ApplyResources(this.xrTableCell29, "xrTableCell29"); // // xrTableRow11 // this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell22, this.xrTableCell23, this.xrTableCell25}); this.xrTableRow11.Name = "xrTableRow11"; resources.ApplyResources(this.xrTableRow11, "xrTableRow11"); // // xrTableCell22 // this.xrTableCell22.Name = "xrTableCell22"; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); // // xrTableCell23 // this.xrTableCell23.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmFax")}); this.xrTableCell23.Name = "xrTableCell23"; this.xrTableCell23.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // xrTableCell25 // this.xrTableCell25.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell25.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmAddress")}); this.xrTableCell25.Name = "xrTableCell25"; this.xrTableCell25.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 0, 0, 100F); this.xrTableCell25.StylePriority.UseBorders = false; this.xrTableCell25.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // xrTableRow10 // this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell18, this.xrTableCell19, this.xrTableCell32, this.xrTableCell33, this.DividerCell, this.xrTableCell21}); this.xrTableRow10.Name = "xrTableRow10"; resources.ApplyResources(this.xrTableRow10, "xrTableRow10"); // // xrTableCell18 // this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableCell19 // this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmEMail")}); this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell32 // this.xrTableCell32.Name = "xrTableCell32"; this.xrTableCell32.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 0, 0, 100F); this.xrTableCell32.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell32, "xrTableCell32"); // // xrTableCell33 // this.xrTableCell33.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell33.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLatitude", "{0:f5}")}); this.xrTableCell33.Name = "xrTableCell33"; this.xrTableCell33.StylePriority.UseBorders = false; this.xrTableCell33.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell33, "xrTableCell33"); // // DividerCell // this.DividerCell.Name = "DividerCell"; this.DividerCell.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.DividerCell, "DividerCell"); // // xrTableCell21 // this.xrTableCell21.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLongitude", "{0:f5}")}); this.xrTableCell21.Name = "xrTableCell21"; this.xrTableCell21.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow4, this.xrTableRow6, this.xrTableRow7, this.xrTableRow8}); this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UsePadding = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.cellBarcode, this.xrTableCell4, this.xrTableCell15}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Multiline = true; this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseFont = false; this.xrTableCell1.StylePriority.UseTextAlignment = false; // // cellBarcode // resources.ApplyResources(this.cellBarcode, "cellBarcode"); this.cellBarcode.Name = "cellBarcode"; this.cellBarcode.StylePriority.UseFont = false; this.cellBarcode.StylePriority.UseTextAlignment = false; // // xrTableCell4 // resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F); this.xrTableCell4.StylePriority.UseFont = false; this.xrTableCell4.StylePriority.UsePadding = false; // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FieldAccessionID")}); this.xrTableCell15.Name = "xrTableCell15"; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.xrTableCell6}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableCell6 // this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.None; this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.CaseIdentifier")}); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.StylePriority.UseBorders = false; this.xrTableCell6.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell42}); this.xrTableRow4.Name = "xrTableRow4"; resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); // // xrTableCell7 // this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableCell42 // this.xrTableCell42.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell42.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.AllDiagnoses")}); this.xrTableCell42.Name = "xrTableCell42"; this.xrTableCell42.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell42, "xrTableCell42"); // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell43, this.xrTableCell46, this.xrTableCell63, this.xrTableCell62}); this.xrTableRow6.Name = "xrTableRow6"; resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); // // xrTableCell43 // this.xrTableCell43.Name = "xrTableCell43"; resources.ApplyResources(this.xrTableCell43, "xrTableCell43"); // // xrTableCell46 // this.xrTableCell46.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell46.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.CaseType")}); this.xrTableCell46.Name = "xrTableCell46"; this.xrTableCell46.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell46, "xrTableCell46"); // // xrTableCell63 // this.xrTableCell63.Name = "xrTableCell63"; this.xrTableCell63.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F); this.xrTableCell63.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell63, "xrTableCell63"); // // xrTableCell62 // this.xrTableCell62.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell62.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.ReportType")}); this.xrTableCell62.Name = "xrTableCell62"; this.xrTableCell62.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell62, "xrTableCell62"); // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell64, this.xrTableCell65, this.xrTableCell66, this.xrTableCell67}); this.xrTableRow7.Name = "xrTableRow7"; resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); // // xrTableCell64 // this.xrTableCell64.Name = "xrTableCell64"; resources.ApplyResources(this.xrTableCell64, "xrTableCell64"); // // xrTableCell65 // this.xrTableCell65.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell65.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.CaseClassification")}); this.xrTableCell65.Name = "xrTableCell65"; this.xrTableCell65.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell65, "xrTableCell65"); // // xrTableCell66 // this.xrTableCell66.Name = "xrTableCell66"; this.xrTableCell66.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F); this.xrTableCell66.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell66, "xrTableCell66"); // // xrTableCell67 // this.xrTableCell67.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell67.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.OutbreakID")}); this.xrTableCell67.Name = "xrTableCell67"; this.xrTableCell67.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell67, "xrTableCell67"); // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell68, this.xrTableCell69, this.xrTableCell70, this.xrTableCell71}); this.xrTableRow8.Name = "xrTableRow8"; resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); // // xrTableCell68 // this.xrTableCell68.Name = "xrTableCell68"; resources.ApplyResources(this.xrTableCell68, "xrTableCell68"); // // xrTableCell69 // this.xrTableCell69.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell69.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.SessionID")}); this.xrTableCell69.Name = "xrTableCell69"; this.xrTableCell69.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell69, "xrTableCell69"); // // xrTableCell70 // this.xrTableCell70.Name = "xrTableCell70"; this.xrTableCell70.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F); this.xrTableCell70.StylePriority.UsePadding = false; resources.ApplyResources(this.xrTableCell70, "xrTableCell70"); // // xrTableCell71 // this.xrTableCell71.Name = "xrTableCell71"; this.xrTableCell71.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell71, "xrTableCell71"); // // LivestockCaseTableAdapter // this.LivestockCaseTableAdapter.ClearBeforeFill = true; // // LivestockInvestigationDataSet // this.LivestockInvestigationDataSet.DataSetName = "LivestockInvestigationDataSet"; this.LivestockInvestigationDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // xrTableCell10 // this.xrTableCell10.Name = "xrTableCell10"; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableCell11 // this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLatitude", "{0:#.00}")}); this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); // // xrTableCell12 // this.xrTableCell12.Name = "xrTableCell12"; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // xrTableCell13 // this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetLivestockCase.FarmLongitude", "{0:#.00}")}); this.xrTableCell13.Name = "xrTableCell13"; resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); // // DetailReportHerd // this.DetailReportHerd.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailHerd}); this.DetailReportHerd.Level = 1; this.DetailReportHerd.Name = "DetailReportHerd"; // // DetailHerd // this.DetailHerd.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrSubreportHerd}); resources.ApplyResources(this.DetailHerd, "DetailHerd"); this.DetailHerd.Name = "DetailHerd"; this.DetailHerd.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // xrSubreportHerd // resources.ApplyResources(this.xrSubreportHerd, "xrSubreportHerd"); this.xrSubreportHerd.Name = "xrSubreportHerd"; this.xrSubreportHerd.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.HerdReport(); // // DetailReportClinical // this.DetailReportClinical.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailClinical, this.ReportHeaderClinical}); this.DetailReportClinical.Level = 3; this.DetailReportClinical.Name = "DetailReportClinical"; // // DetailClinical // this.DetailClinical.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.ClinicalInvestigationSubreport}); resources.ApplyResources(this.DetailClinical, "DetailClinical"); this.DetailClinical.Name = "DetailClinical"; // // ClinicalInvestigationSubreport // resources.ApplyResources(this.ClinicalInvestigationSubreport, "ClinicalInvestigationSubreport"); this.ClinicalInvestigationSubreport.Name = "ClinicalInvestigationSubreport"; // // ReportHeaderClinical // this.ReportHeaderClinical.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel2}); resources.ApplyResources(this.ReportHeaderClinical, "ReportHeaderClinical"); this.ReportHeaderClinical.Name = "ReportHeaderClinical"; this.ReportHeaderClinical.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // xrLabel2 // this.xrLabel2.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel2, "xrLabel2"); this.xrLabel2.Name = "xrLabel2"; this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel2.StylePriority.UseBorders = false; this.xrLabel2.StylePriority.UseFont = false; this.xrLabel2.StylePriority.UseTextAlignment = false; // // DetailReportEpi // this.DetailReportEpi.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailEpi, this.reportHeaderBand1}); this.DetailReportEpi.Level = 2; this.DetailReportEpi.Name = "DetailReportEpi"; // // DetailEpi // this.DetailEpi.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.EpiSubreport}); resources.ApplyResources(this.DetailEpi, "DetailEpi"); this.DetailEpi.Name = "DetailEpi"; // // EpiSubreport // resources.ApplyResources(this.EpiSubreport, "EpiSubreport"); this.EpiSubreport.Name = "EpiSubreport"; // // reportHeaderBand1 // this.reportHeaderBand1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel3}); resources.ApplyResources(this.reportHeaderBand1, "reportHeaderBand1"); this.reportHeaderBand1.Name = "reportHeaderBand1"; this.reportHeaderBand1.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // xrLabel3 // this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel3, "xrLabel3"); this.xrLabel3.Name = "xrLabel3"; this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel3.StylePriority.UseBorders = false; this.xrLabel3.StylePriority.UseFont = false; this.xrLabel3.StylePriority.UseTextAlignment = false; // // DetailReportVaccinations // this.DetailReportVaccinations.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailVaccinations}); this.DetailReportVaccinations.Level = 6; this.DetailReportVaccinations.Name = "DetailReportVaccinations"; // // DetailVaccinations // this.DetailVaccinations.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.VaccinationSubreport}); resources.ApplyResources(this.DetailVaccinations, "DetailVaccinations"); this.DetailVaccinations.Name = "DetailVaccinations"; this.DetailVaccinations.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // VaccinationSubreport // resources.ApplyResources(this.VaccinationSubreport, "VaccinationSubreport"); this.VaccinationSubreport.Name = "VaccinationSubreport"; this.VaccinationSubreport.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationReport(); // // DetailReportRapidTest // this.DetailReportRapidTest.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailRapidTest}); this.DetailReportRapidTest.Level = 9; this.DetailReportRapidTest.Name = "DetailReportRapidTest"; // // DetailRapidTest // this.DetailRapidTest.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.RapidTestSubreport}); resources.ApplyResources(this.DetailRapidTest, "DetailRapidTest"); this.DetailRapidTest.Name = "DetailRapidTest"; this.DetailRapidTest.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // RapidTestSubreport // resources.ApplyResources(this.RapidTestSubreport, "RapidTestSubreport"); this.RapidTestSubreport.Name = "RapidTestSubreport"; this.RapidTestSubreport.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.RapidTestReport(); // // DetailReportDiagnosis // this.DetailReportDiagnosis.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailDiagnosis}); this.DetailReportDiagnosis.Level = 5; this.DetailReportDiagnosis.Name = "DetailReportDiagnosis"; // // DetailDiagnosis // this.DetailDiagnosis.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.DiagnosisSubreport}); resources.ApplyResources(this.DetailDiagnosis, "DetailDiagnosis"); this.DetailDiagnosis.Name = "DetailDiagnosis"; this.DetailDiagnosis.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // DiagnosisSubreport // resources.ApplyResources(this.DiagnosisSubreport, "DiagnosisSubreport"); this.DiagnosisSubreport.Name = "DiagnosisSubreport"; this.DiagnosisSubreport.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.DiagnosisReport(); // // DetailReportOutbreak // this.DetailReportOutbreak.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailOutbreak}); this.DetailReportOutbreak.Level = 4; this.DetailReportOutbreak.Name = "DetailReportOutbreak"; // // DetailOutbreak // this.DetailOutbreak.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLabel4, this.ControlMeasuresSubreport}); resources.ApplyResources(this.DetailOutbreak, "DetailOutbreak"); this.DetailOutbreak.Name = "DetailOutbreak"; this.DetailOutbreak.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // xrLabel4 // this.xrLabel4.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrLabel4, "xrLabel4"); this.xrLabel4.Name = "xrLabel4"; this.xrLabel4.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel4.StylePriority.UseBorders = false; this.xrLabel4.StylePriority.UseFont = false; this.xrLabel4.StylePriority.UseTextAlignment = false; // // ControlMeasuresSubreport // resources.ApplyResources(this.ControlMeasuresSubreport, "ControlMeasuresSubreport"); this.ControlMeasuresSubreport.Name = "ControlMeasuresSubreport"; // // DetailReportSample // this.DetailReportSample.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailSample}); this.DetailReportSample.Level = 7; this.DetailReportSample.Name = "DetailReportSample"; // // DetailSample // this.DetailSample.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.SampleSubreport}); resources.ApplyResources(this.DetailSample, "DetailSample"); this.DetailSample.Name = "DetailSample"; this.DetailSample.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // SampleSubreport // resources.ApplyResources(this.SampleSubreport, "SampleSubreport"); this.SampleSubreport.Name = "SampleSubreport"; this.SampleSubreport.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockSampleReport(); // // AnimalSubreport // resources.ApplyResources(this.AnimalSubreport, "AnimalSubreport"); this.AnimalSubreport.Name = "AnimalSubreport"; this.AnimalSubreport.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockAnimalCSReport(); // // MapPictureBox // resources.ApplyResources(this.MapPictureBox, "MapPictureBox"); this.MapPictureBox.Name = "MapPictureBox"; this.MapPictureBox.Sizing = DevExpress.XtraPrinting.ImageSizeMode.Squeeze; // // DetailReportMap // this.DetailReportMap.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailMap}); this.DetailReportMap.Level = 10; this.DetailReportMap.Name = "DetailReportMap"; // // DetailMap // this.DetailMap.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.MapPictureBox}); resources.ApplyResources(this.DetailMap, "DetailMap"); this.DetailMap.Name = "DetailMap"; // // DetailReportAnimal // this.DetailReportAnimal.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.DetailAnimal}); this.DetailReportAnimal.Level = 8; this.DetailReportAnimal.Name = "DetailReportAnimal"; // // DetailAnimal // this.DetailAnimal.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.AnimalSubreport}); resources.ApplyResources(this.DetailAnimal, "DetailAnimal"); this.DetailAnimal.Name = "DetailAnimal"; this.DetailAnimal.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand; // // LivestockInvestigationReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.DetailReportInfo, this.DetailReportHerd, this.DetailReportClinical, this.DetailReportEpi, this.DetailReportVaccinations, this.DetailReportRapidTest, this.DetailReportDiagnosis, this.DetailReportOutbreak, this.DetailReportSample, this.DetailReportMap, this.DetailReportAnimal}); resources.ApplyResources(this, "$this"); this.Version = "14.1"; this.Controls.SetChildIndex(this.DetailReportAnimal, 0); this.Controls.SetChildIndex(this.DetailReportMap, 0); this.Controls.SetChildIndex(this.DetailReportSample, 0); this.Controls.SetChildIndex(this.DetailReportOutbreak, 0); this.Controls.SetChildIndex(this.DetailReportDiagnosis, 0); this.Controls.SetChildIndex(this.DetailReportRapidTest, 0); this.Controls.SetChildIndex(this.DetailReportVaccinations, 0); this.Controls.SetChildIndex(this.DetailReportEpi, 0); this.Controls.SetChildIndex(this.DetailReportClinical, 0); this.Controls.SetChildIndex(this.DetailReportHerd, 0); this.Controls.SetChildIndex(this.DetailReportInfo, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.LivestockInvestigationDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailReportBand DetailReportInfo; private DevExpress.XtraReports.UI.DetailBand DetailInfo; private EIDSS.Reports.Document.Veterinary.LivestockInvestigation.LivestockInvestigationDataSetTableAdapters.spRepVetLivestockCaseTableAdapter LivestockCaseTableAdapter; private LivestockInvestigationDataSet LivestockInvestigationDataSet; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell cellBarcode; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell55; private DevExpress.XtraReports.UI.XRTableCell xrTableCell56; private DevExpress.XtraReports.UI.XRTableCell xrTableCell57; private DevExpress.XtraReports.UI.XRTableCell xrTableCell59; private DevExpress.XtraReports.UI.XRTableRow xrTableRow18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell51; private DevExpress.XtraReports.UI.XRTableCell xrTableCell52; private DevExpress.XtraReports.UI.XRTableCell xrTableCell53; private DevExpress.XtraReports.UI.XRTableCell xrTableCell54; private DevExpress.XtraReports.UI.XRTableRow xrTableRow17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell47; private DevExpress.XtraReports.UI.XRTableCell xrTableCell48; private DevExpress.XtraReports.UI.XRTableCell xrTableCell49; private DevExpress.XtraReports.UI.XRTableCell xrTableCell50; private DevExpress.XtraReports.UI.XRTableRow xrTableRow16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell45; private DevExpress.XtraReports.UI.XRTableRow xrTableRow15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell38; private DevExpress.XtraReports.UI.XRTableCell xrTableCell39; private DevExpress.XtraReports.UI.XRTableRow xrTableRow14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell34; private DevExpress.XtraReports.UI.XRTableCell xrTableCell35; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell30; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private DevExpress.XtraReports.UI.XRTableCell xrTableCell28; private DevExpress.XtraReports.UI.XRTableCell xrTableCell29; private DevExpress.XtraReports.UI.XRTableRow xrTableRow11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableRow xrTableRow10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTable xrTable4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.DetailReportBand DetailReportHerd; private DevExpress.XtraReports.UI.DetailBand DetailHerd; private DevExpress.XtraReports.UI.XRSubreport xrSubreportHerd; private DevExpress.XtraReports.UI.DetailReportBand DetailReportClinical; private DevExpress.XtraReports.UI.DetailBand DetailClinical; private DevExpress.XtraReports.UI.XRSubreport ClinicalInvestigationSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportEpi; private DevExpress.XtraReports.UI.DetailBand DetailEpi; private DevExpress.XtraReports.UI.XRSubreport EpiSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportVaccinations; private DevExpress.XtraReports.UI.DetailBand DetailVaccinations; private DevExpress.XtraReports.UI.XRSubreport VaccinationSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportRapidTest; private DevExpress.XtraReports.UI.DetailBand DetailRapidTest; private DevExpress.XtraReports.UI.XRSubreport RapidTestSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportDiagnosis; private DevExpress.XtraReports.UI.DetailBand DetailDiagnosis; private DevExpress.XtraReports.UI.XRSubreport DiagnosisSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportOutbreak; private DevExpress.XtraReports.UI.DetailBand DetailOutbreak; private DevExpress.XtraReports.UI.XRSubreport ControlMeasuresSubreport; private DevExpress.XtraReports.UI.DetailReportBand DetailReportSample; private DevExpress.XtraReports.UI.DetailBand DetailSample; private DevExpress.XtraReports.UI.XRSubreport AnimalSubreport; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeaderClinical; private DevExpress.XtraReports.UI.XRLabel xrLabel2; private DevExpress.XtraReports.UI.ReportHeaderBand reportHeaderBand1; private DevExpress.XtraReports.UI.XRLabel xrLabel3; private DevExpress.XtraReports.UI.XRLabel xrLabel4; private DevExpress.XtraReports.UI.XRPictureBox MapPictureBox; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell42; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell43; private DevExpress.XtraReports.UI.XRTableCell xrTableCell46; private DevExpress.XtraReports.UI.XRTableCell xrTableCell63; private DevExpress.XtraReports.UI.XRTableCell xrTableCell62; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell64; private DevExpress.XtraReports.UI.XRTableCell xrTableCell65; private DevExpress.XtraReports.UI.XRTableCell xrTableCell66; private DevExpress.XtraReports.UI.XRTableCell xrTableCell67; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell68; private DevExpress.XtraReports.UI.XRTableCell xrTableCell69; private DevExpress.XtraReports.UI.XRTableCell xrTableCell70; private DevExpress.XtraReports.UI.XRTableCell xrTableCell71; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell72; private DevExpress.XtraReports.UI.XRTableCell xrTableCell73; private DevExpress.XtraReports.UI.XRTableCell xrTableCell74; private DevExpress.XtraReports.UI.XRTableCell xrTableCell32; private DevExpress.XtraReports.UI.XRTableCell xrTableCell33; private DevExpress.XtraReports.UI.XRTableCell DividerCell; private DevExpress.XtraReports.UI.DetailReportBand DetailReportMap; private DevExpress.XtraReports.UI.DetailBand DetailMap; private DevExpress.XtraReports.UI.DetailReportBand DetailReportAnimal; private DevExpress.XtraReports.UI.DetailBand DetailAnimal; private DevExpress.XtraReports.UI.XRSubreport SampleSubreport; } }
using Kitware.VTK; using System; // input file is C:\VTK\VolumeRendering\Testing\Tcl\TestFixedPointRayCasterNearest.tcl // output file is AVTestFixedPointRayCasterNearest.cs /// <summary> /// The testing class derived from AVTestFixedPointRayCasterNearest /// </summary> public class AVTestFixedPointRayCasterNearestClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVTestFixedPointRayCasterNearest(String [] argv) { //Prefix Content is: "" // Create a gaussian[] gs = new vtkImageGaussianSource(); gs.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); gs.SetMaximum((double)255.0); gs.SetStandardDeviation((double)5); gs.SetCenter((double)15,(double)15,(double)15); // threshold to leave a gap that should show up for[] // gradient opacity[] t = new vtkImageThreshold(); t.SetInputConnection((vtkAlgorithmOutput)gs.GetOutputPort()); t.ReplaceInOn(); t.SetInValue((double)0); t.ThresholdBetween((double)150,(double)200); // Use a shift scale to convert to unsigned char[] ss = new vtkImageShiftScale(); ss.SetInputConnection((vtkAlgorithmOutput)t.GetOutputPort()); ss.SetOutputScalarTypeToUnsignedChar(); // grid will be used for two component dependent[] grid0 = new vtkImageGridSource(); grid0.SetDataScalarTypeToUnsignedChar(); grid0.SetGridSpacing((int)10,(int)10,(int)10); grid0.SetLineValue((double)200); grid0.SetFillValue((double)10); grid0.SetDataExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); // use dilation to thicken the grid[] d = new vtkImageContinuousDilate3D(); d.SetInputConnection((vtkAlgorithmOutput)grid0.GetOutputPort()); d.SetKernelSize((int)3,(int)3,(int)3); // Now make a two component dependent[] iac = new vtkImageAppendComponents(); iac.AddInput((vtkDataObject)d.GetOutput()); iac.AddInput((vtkDataObject)ss.GetOutput()); // Some more gaussians for the four component indepent case[] gs1 = new vtkImageGaussianSource(); gs1.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); gs1.SetMaximum((double)255.0); gs1.SetStandardDeviation((double)4); gs1.SetCenter((double)5,(double)5,(double)5); t1 = new vtkImageThreshold(); t1.SetInputConnection((vtkAlgorithmOutput)gs1.GetOutputPort()); t1.ReplaceInOn(); t1.SetInValue((double)0); t1.ThresholdBetween((double)150,(double)256); gs2 = new vtkImageGaussianSource(); gs2.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); gs2.SetMaximum((double)255.0); gs2.SetStandardDeviation((double)4); gs2.SetCenter((double)12,(double)12,(double)12); gs3 = new vtkImageGaussianSource(); gs3.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); gs3.SetMaximum((double)255.0); gs3.SetStandardDeviation((double)4); gs3.SetCenter((double)19,(double)19,(double)19); t3 = new vtkImageThreshold(); t3.SetInputConnection((vtkAlgorithmOutput)gs3.GetOutputPort()); t3.ReplaceInOn(); t3.SetInValue((double)0); t3.ThresholdBetween((double)150,(double)256); gs4 = new vtkImageGaussianSource(); gs4.SetWholeExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); gs4.SetMaximum((double)255.0); gs4.SetStandardDeviation((double)4); gs4.SetCenter((double)26,(double)26,(double)26); //tk window skipped.. iac1 = new vtkImageAppendComponents(); iac1.AddInput((vtkDataObject)t1.GetOutput()); iac1.AddInput((vtkDataObject)gs2.GetOutput()); iac2 = new vtkImageAppendComponents(); iac2.AddInput((vtkDataObject)iac1.GetOutput()); iac2.AddInput((vtkDataObject)t3.GetOutput()); iac3 = new vtkImageAppendComponents(); iac3.AddInput((vtkDataObject)iac2.GetOutput()); iac3.AddInput((vtkDataObject)gs4.GetOutput()); // create the four component dependend - [] // use lines in x, y, z for colors[] gridR = new vtkImageGridSource(); gridR.SetDataScalarTypeToUnsignedChar(); gridR.SetGridSpacing((int)10,(int)100,(int)100); gridR.SetLineValue((double)250); gridR.SetFillValue((double)100); gridR.SetDataExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); dR = new vtkImageContinuousDilate3D(); dR.SetInputConnection((vtkAlgorithmOutput)gridR.GetOutputPort()); dR.SetKernelSize((int)2,(int)2,(int)2); gridG = new vtkImageGridSource(); gridG.SetDataScalarTypeToUnsignedChar(); gridG.SetGridSpacing((int)100,(int)10,(int)100); gridG.SetLineValue((double)250); gridG.SetFillValue((double)100); gridG.SetDataExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); dG = new vtkImageContinuousDilate3D(); dG.SetInputConnection((vtkAlgorithmOutput)gridG.GetOutputPort()); dG.SetKernelSize((int)2,(int)2,(int)2); gridB = new vtkImageGridSource(); gridB.SetDataScalarTypeToUnsignedChar(); gridB.SetGridSpacing((int)100,(int)100,(int)10); gridB.SetLineValue((double)0); gridB.SetFillValue((double)250); gridB.SetDataExtent((int)0,(int)30,(int)0,(int)30,(int)0,(int)30); dB = new vtkImageContinuousDilate3D(); dB.SetInputConnection((vtkAlgorithmOutput)gridB.GetOutputPort()); dB.SetKernelSize((int)2,(int)2,(int)2); // need some appending[] iacRG = new vtkImageAppendComponents(); iacRG.AddInput((vtkDataObject)dR.GetOutput()); iacRG.AddInput((vtkDataObject)dG.GetOutput()); iacRGB = new vtkImageAppendComponents(); iacRGB.AddInput((vtkDataObject)iacRG.GetOutput()); iacRGB.AddInput((vtkDataObject)dB.GetOutput()); iacRGBA = new vtkImageAppendComponents(); iacRGBA.AddInput((vtkDataObject)iacRGB.GetOutput()); iacRGBA.AddInput((vtkDataObject)ss.GetOutput()); // We need a bunch of opacity functions[] // this one is a simple ramp to .2[] rampPoint2 = new vtkPiecewiseFunction(); rampPoint2.AddPoint((double)0,(double)0.0); rampPoint2.AddPoint((double)255,(double)0.2); // this one is a simple ramp to 1[] ramp1 = new vtkPiecewiseFunction(); ramp1.AddPoint((double)0,(double)0.0); ramp1.AddPoint((double)255,(double)1.0); // this one shows a sharp surface[] surface = new vtkPiecewiseFunction(); surface.AddPoint((double)0,(double)0.0); surface.AddPoint((double)10,(double)0.0); surface.AddPoint((double)50,(double)1.0); surface.AddPoint((double)255,(double)1.0); // this one is constant 1[] constant1 = new vtkPiecewiseFunction(); constant1.AddPoint((double)0,(double)1.0); constant1.AddPoint((double)255,(double)1.0); // this one is used for gradient opacity[] gop = new vtkPiecewiseFunction(); gop.AddPoint((double)0,(double)0.0); gop.AddPoint((double)20,(double)0.0); gop.AddPoint((double)60,(double)1.0); gop.AddPoint((double)255,(double)1.0); // We need a bunch of color functions[] // This one is a simple rainbow[] rainbow = new vtkColorTransferFunction(); rainbow.SetColorSpaceToHSV(); rainbow.HSVWrapOff(); rainbow.AddHSVPoint((double)0,(double)0.1,(double)1.0,(double)1.0); rainbow.AddHSVPoint((double)255,(double)0.9,(double)1.0,(double)1.0); // this is constant red[] red = new vtkColorTransferFunction(); red.AddRGBPoint((double)0,(double)1,(double)0,(double)0); red.AddRGBPoint((double)255,(double)1,(double)0,(double)0); // this is constant green[] green = new vtkColorTransferFunction(); green.AddRGBPoint((double)0,(double)0,(double)1,(double)0); green.AddRGBPoint((double)255,(double)0,(double)1,(double)0); // this is constant blue[] blue = new vtkColorTransferFunction(); blue.AddRGBPoint((double)0,(double)0,(double)0,(double)1); blue.AddRGBPoint((double)255,(double)0,(double)0,(double)1); // this is constant yellow[] yellow = new vtkColorTransferFunction(); yellow.AddRGBPoint((double)0,(double)1,(double)1,(double)0); yellow.AddRGBPoint((double)255,(double)1,(double)1,(double)0); ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); renWin.SetSize((int)500,(int)500); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); ren1.GetCullers().InitTraversal(); culler = (vtkFrustumCoverageCuller)ren1.GetCullers().GetNextItem(); culler.SetSortingStyleToBackToFront(); // We need 25 mapper / actor pairs which we will render[] // in a grid. Going down we will vary the input data[] // with the top row unsigned char, then float, then[] // two dependent components, then four dependent components[] // then four independent components. Going across we[] // will vary the rendering method with MIP, Composite,[] // Composite Shade, Composite GO, and Composite GO Shade.[] j = 0; while((j) < 5) { i = 0; while((i) < 5) { volumeProperty[i,j] = new vtkVolumeProperty(); volumeMapper[i,j] = new vtkFixedPointVolumeRayCastMapper(); volumeMapper[i,j].SetSampleDistance((float)0.25); volume[i,j] = new vtkVolume(); volume[i,j].SetMapper((vtkAbstractVolumeMapper)volumeMapper[i,j]); volume[i,j].SetProperty((vtkVolumeProperty)volumeProperty[i,j]); volume[i,j].AddPosition((double)i*30,(double)j*30,(double)0); ren1.AddVolume((vtkProp)volume[i,j]); i = i + 1; } j = j + 1; } i = 0; while((i) < 5) { volumeMapper[0,i].SetInputConnection(t.GetOutputPort()); volumeMapper[1,i].SetInputConnection(ss.GetOutputPort()); volumeMapper[2,i].SetInputConnection(iac.GetOutputPort()); volumeMapper[3,i].SetInputConnection(iac3.GetOutputPort()); volumeMapper[4,i].SetInputConnection(iacRGBA.GetOutputPort()); volumeMapper[i,0].SetBlendModeToMaximumIntensity(); volumeMapper[i,1].SetBlendModeToComposite(); volumeMapper[i,2].SetBlendModeToComposite(); volumeMapper[i,3].SetBlendModeToComposite(); volumeMapper[i,4].SetBlendModeToComposite(); volumeProperty[0,i].IndependentComponentsOn(); volumeProperty[1,i].IndependentComponentsOn(); volumeProperty[2,i].IndependentComponentsOff(); volumeProperty[3,i].IndependentComponentsOn(); volumeProperty[4,i].IndependentComponentsOff(); volumeProperty[0,i].SetColor(rainbow); volumeProperty[0,i].SetScalarOpacity(rampPoint2); volumeProperty[0,i].SetGradientOpacity(constant1); volumeProperty[1,i].SetColor(rainbow); volumeProperty[1,i].SetScalarOpacity(rampPoint2); volumeProperty[1,i].SetGradientOpacity(constant1); volumeProperty[2,i].SetColor(rainbow); volumeProperty[2,i].SetScalarOpacity(rampPoint2); volumeProperty[2,i].SetGradientOpacity(constant1); volumeProperty[3,i].SetColor(0, red); volumeProperty[3,i].SetColor(1, green); volumeProperty[3,i].SetColor(2, blue ); volumeProperty[3,i].SetColor(3, yellow); volumeProperty[3,i].SetScalarOpacity(0,rampPoint2); volumeProperty[3,i].SetScalarOpacity(1,rampPoint2); volumeProperty[3,i].SetScalarOpacity(2,rampPoint2); volumeProperty[3,i].SetScalarOpacity(3,rampPoint2); volumeProperty[3,i].SetGradientOpacity(0,constant1); volumeProperty[3,i].SetGradientOpacity(1,constant1); volumeProperty[3,i].SetGradientOpacity(2,constant1); volumeProperty[3,i].SetGradientOpacity(3,constant1); volumeProperty[3,i].SetComponentWeight(0,1); volumeProperty[3,i].SetComponentWeight(1,1); volumeProperty[3,i].SetComponentWeight(2,1); volumeProperty[3,i].SetComponentWeight(3,1); volumeProperty[4,i].SetColor(rainbow); volumeProperty[4,i].SetScalarOpacity(rampPoint2); volumeProperty[4,i].SetGradientOpacity(constant1); volumeProperty[i,2].ShadeOn(); volumeProperty[i,4].ShadeOn((int)0); volumeProperty[i,4].ShadeOn((int)1); volumeProperty[i,4].ShadeOn((int)2); volumeProperty[i,4].ShadeOn((int)3); i = i + 1; } volumeProperty[0,0].SetScalarOpacity((vtkPiecewiseFunction)ramp1); volumeProperty[1,0].SetScalarOpacity((vtkPiecewiseFunction)ramp1); volumeProperty[2,0].SetScalarOpacity((vtkPiecewiseFunction)ramp1); volumeProperty[3,0].SetScalarOpacity((int)0,(vtkPiecewiseFunction)surface); volumeProperty[3,0].SetScalarOpacity((int)1,(vtkPiecewiseFunction)surface); volumeProperty[3,0].SetScalarOpacity((int)2,(vtkPiecewiseFunction)surface); volumeProperty[3,0].SetScalarOpacity((int)3,(vtkPiecewiseFunction)surface); volumeProperty[4,0].SetScalarOpacity((vtkPiecewiseFunction)ramp1); volumeProperty[0,2].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[1,2].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[2,2].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[3,2].SetScalarOpacity((int)0,(vtkPiecewiseFunction)surface); volumeProperty[3,2].SetScalarOpacity((int)1,(vtkPiecewiseFunction)surface); volumeProperty[3,2].SetScalarOpacity((int)2,(vtkPiecewiseFunction)surface); volumeProperty[3,2].SetScalarOpacity((int)3,(vtkPiecewiseFunction)surface); volumeProperty[4,2].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[0,4].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[1,4].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[2,4].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[3,4].SetScalarOpacity((int)0,(vtkPiecewiseFunction)surface); volumeProperty[3,4].SetScalarOpacity((int)1,(vtkPiecewiseFunction)surface); volumeProperty[3,4].SetScalarOpacity((int)2,(vtkPiecewiseFunction)surface); volumeProperty[3,4].SetScalarOpacity((int)3,(vtkPiecewiseFunction)surface); volumeProperty[4,4].SetScalarOpacity((vtkPiecewiseFunction)surface); volumeProperty[0,3].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[1,3].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[2,3].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[3,3].SetGradientOpacity((int)0,(vtkPiecewiseFunction)gop); volumeProperty[3,3].SetGradientOpacity((int)2,(vtkPiecewiseFunction)gop); volumeProperty[4,3].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[3,3].SetScalarOpacity((int)0,(vtkPiecewiseFunction)ramp1); volumeProperty[3,3].SetScalarOpacity((int)2,(vtkPiecewiseFunction)ramp1); volumeProperty[0,4].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[1,4].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[2,4].SetGradientOpacity((vtkPiecewiseFunction)gop); volumeProperty[3,4].SetGradientOpacity((int)0,(vtkPiecewiseFunction)gop); volumeProperty[3,4].SetGradientOpacity((int)2,(vtkPiecewiseFunction)gop); volumeProperty[4,4].SetGradientOpacity((vtkPiecewiseFunction)gop); renWin.Render(); ren1.GetActiveCamera().Dolly((double)1.3); ren1.GetActiveCamera().Azimuth((double)15); ren1.GetActiveCamera().Elevation((double)5); ren1.ResetCameraClippingRange(); iren.Initialize(); //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkImageGaussianSource gs; static vtkImageThreshold t; static vtkImageShiftScale ss; static vtkImageGridSource grid0; static vtkImageContinuousDilate3D d; static vtkImageAppendComponents iac; static vtkImageGaussianSource gs1; static vtkImageThreshold t1; static vtkImageGaussianSource gs2; static vtkImageGaussianSource gs3; static vtkImageThreshold t3; static vtkImageGaussianSource gs4; static vtkImageAppendComponents iac1; static vtkImageAppendComponents iac2; static vtkImageAppendComponents iac3; static vtkImageGridSource gridR; static vtkImageContinuousDilate3D dR; static vtkImageGridSource gridG; static vtkImageContinuousDilate3D dG; static vtkImageGridSource gridB; static vtkImageContinuousDilate3D dB; static vtkImageAppendComponents iacRG; static vtkImageAppendComponents iacRGB; static vtkImageAppendComponents iacRGBA; static vtkPiecewiseFunction rampPoint2; static vtkPiecewiseFunction ramp1; static vtkPiecewiseFunction surface; static vtkPiecewiseFunction constant1; static vtkPiecewiseFunction gop; static vtkColorTransferFunction rainbow; static vtkColorTransferFunction red; static vtkColorTransferFunction green; static vtkColorTransferFunction blue; static vtkColorTransferFunction yellow; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkFrustumCoverageCuller culler; static int j; static int i; static vtkVolumeProperty[,] volumeProperty = new vtkVolumeProperty[100,100]; static vtkFixedPointVolumeRayCastMapper[,] volumeMapper = new vtkFixedPointVolumeRayCastMapper[100,100]; static vtkVolume[,] volume = new vtkVolume[100,100]; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGaussianSource Getgs() { return gs; } ///<summary> A Set Method for Static Variables </summary> public static void Setgs(vtkImageGaussianSource toSet) { gs = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageThreshold Gett() { return t; } ///<summary> A Set Method for Static Variables </summary> public static void Sett(vtkImageThreshold toSet) { t = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageShiftScale Getss() { return ss; } ///<summary> A Set Method for Static Variables </summary> public static void Setss(vtkImageShiftScale toSet) { ss = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGridSource Getgrid0() { return grid0; } ///<summary> A Set Method for Static Variables </summary> public static void Setgrid0(vtkImageGridSource toSet) { grid0 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageContinuousDilate3D Getd() { return d; } ///<summary> A Set Method for Static Variables </summary> public static void Setd(vtkImageContinuousDilate3D toSet) { d = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents Getiac() { return iac; } ///<summary> A Set Method for Static Variables </summary> public static void Setiac(vtkImageAppendComponents toSet) { iac = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGaussianSource Getgs1() { return gs1; } ///<summary> A Set Method for Static Variables </summary> public static void Setgs1(vtkImageGaussianSource toSet) { gs1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageThreshold Gett1() { return t1; } ///<summary> A Set Method for Static Variables </summary> public static void Sett1(vtkImageThreshold toSet) { t1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGaussianSource Getgs2() { return gs2; } ///<summary> A Set Method for Static Variables </summary> public static void Setgs2(vtkImageGaussianSource toSet) { gs2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGaussianSource Getgs3() { return gs3; } ///<summary> A Set Method for Static Variables </summary> public static void Setgs3(vtkImageGaussianSource toSet) { gs3 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageThreshold Gett3() { return t3; } ///<summary> A Set Method for Static Variables </summary> public static void Sett3(vtkImageThreshold toSet) { t3 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGaussianSource Getgs4() { return gs4; } ///<summary> A Set Method for Static Variables </summary> public static void Setgs4(vtkImageGaussianSource toSet) { gs4 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents Getiac1() { return iac1; } ///<summary> A Set Method for Static Variables </summary> public static void Setiac1(vtkImageAppendComponents toSet) { iac1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents Getiac2() { return iac2; } ///<summary> A Set Method for Static Variables </summary> public static void Setiac2(vtkImageAppendComponents toSet) { iac2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents Getiac3() { return iac3; } ///<summary> A Set Method for Static Variables </summary> public static void Setiac3(vtkImageAppendComponents toSet) { iac3 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGridSource GetgridR() { return gridR; } ///<summary> A Set Method for Static Variables </summary> public static void SetgridR(vtkImageGridSource toSet) { gridR = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageContinuousDilate3D GetdR() { return dR; } ///<summary> A Set Method for Static Variables </summary> public static void SetdR(vtkImageContinuousDilate3D toSet) { dR = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGridSource GetgridG() { return gridG; } ///<summary> A Set Method for Static Variables </summary> public static void SetgridG(vtkImageGridSource toSet) { gridG = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageContinuousDilate3D GetdG() { return dG; } ///<summary> A Set Method for Static Variables </summary> public static void SetdG(vtkImageContinuousDilate3D toSet) { dG = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageGridSource GetgridB() { return gridB; } ///<summary> A Set Method for Static Variables </summary> public static void SetgridB(vtkImageGridSource toSet) { gridB = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageContinuousDilate3D GetdB() { return dB; } ///<summary> A Set Method for Static Variables </summary> public static void SetdB(vtkImageContinuousDilate3D toSet) { dB = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents GetiacRG() { return iacRG; } ///<summary> A Set Method for Static Variables </summary> public static void SetiacRG(vtkImageAppendComponents toSet) { iacRG = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents GetiacRGB() { return iacRGB; } ///<summary> A Set Method for Static Variables </summary> public static void SetiacRGB(vtkImageAppendComponents toSet) { iacRGB = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkImageAppendComponents GetiacRGBA() { return iacRGBA; } ///<summary> A Set Method for Static Variables </summary> public static void SetiacRGBA(vtkImageAppendComponents toSet) { iacRGBA = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPiecewiseFunction GetrampPoint2() { return rampPoint2; } ///<summary> A Set Method for Static Variables </summary> public static void SetrampPoint2(vtkPiecewiseFunction toSet) { rampPoint2 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPiecewiseFunction Getramp1() { return ramp1; } ///<summary> A Set Method for Static Variables </summary> public static void Setramp1(vtkPiecewiseFunction toSet) { ramp1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPiecewiseFunction Getsurface() { return surface; } ///<summary> A Set Method for Static Variables </summary> public static void Setsurface(vtkPiecewiseFunction toSet) { surface = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPiecewiseFunction Getconstant1() { return constant1; } ///<summary> A Set Method for Static Variables </summary> public static void Setconstant1(vtkPiecewiseFunction toSet) { constant1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPiecewiseFunction Getgop() { return gop; } ///<summary> A Set Method for Static Variables </summary> public static void Setgop(vtkPiecewiseFunction toSet) { gop = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkColorTransferFunction Getrainbow() { return rainbow; } ///<summary> A Set Method for Static Variables </summary> public static void Setrainbow(vtkColorTransferFunction toSet) { rainbow = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkColorTransferFunction Getred() { return red; } ///<summary> A Set Method for Static Variables </summary> public static void Setred(vtkColorTransferFunction toSet) { red = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkColorTransferFunction Getgreen() { return green; } ///<summary> A Set Method for Static Variables </summary> public static void Setgreen(vtkColorTransferFunction toSet) { green = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkColorTransferFunction Getblue() { return blue; } ///<summary> A Set Method for Static Variables </summary> public static void Setblue(vtkColorTransferFunction toSet) { blue = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkColorTransferFunction Getyellow() { return yellow; } ///<summary> A Set Method for Static Variables </summary> public static void Setyellow(vtkColorTransferFunction toSet) { yellow = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkFrustumCoverageCuller Getculler() { return culler; } ///<summary> A Set Method for Static Variables </summary> public static void Setculler(vtkFrustumCoverageCuller toSet) { culler = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getj() { return j; } ///<summary> A Set Method for Static Variables </summary> public static void Setj(int toSet) { j = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Geti() { return i; } ///<summary> A Set Method for Static Variables </summary> public static void Seti(int toSet) { i = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkVolumeProperty[,] GetvolumeProperty() { return volumeProperty; } ///<summary> A Set Method for Static Variables </summary> public static void SetvolumeProperty(vtkVolumeProperty[,] toSet) { volumeProperty = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkFixedPointVolumeRayCastMapper[,] GetvolumeMapper() { return volumeMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetvolumeMapper(vtkFixedPointVolumeRayCastMapper[,] toSet) { volumeMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkVolume[,] Getvolume() { return volume; } ///<summary> A Set Method for Static Variables </summary> public static void Setvolume(vtkVolume[,] toSet) { volume = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(gs!= null){gs.Dispose();} if(t!= null){t.Dispose();} if(ss!= null){ss.Dispose();} if(grid0!= null){grid0.Dispose();} if(d!= null){d.Dispose();} if(iac!= null){iac.Dispose();} if(gs1!= null){gs1.Dispose();} if(t1!= null){t1.Dispose();} if(gs2!= null){gs2.Dispose();} if(gs3!= null){gs3.Dispose();} if(t3!= null){t3.Dispose();} if(gs4!= null){gs4.Dispose();} if(iac1!= null){iac1.Dispose();} if(iac2!= null){iac2.Dispose();} if(iac3!= null){iac3.Dispose();} if(gridR!= null){gridR.Dispose();} if(dR!= null){dR.Dispose();} if(gridG!= null){gridG.Dispose();} if(dG!= null){dG.Dispose();} if(gridB!= null){gridB.Dispose();} if(dB!= null){dB.Dispose();} if(iacRG!= null){iacRG.Dispose();} if(iacRGB!= null){iacRGB.Dispose();} if(iacRGBA!= null){iacRGBA.Dispose();} if(rampPoint2!= null){rampPoint2.Dispose();} if(ramp1!= null){ramp1.Dispose();} if(surface!= null){surface.Dispose();} if(constant1!= null){constant1.Dispose();} if(gop!= null){gop.Dispose();} if(rainbow!= null){rainbow.Dispose();} if(red!= null){red.Dispose();} if(green!= null){green.Dispose();} if(blue!= null){blue.Dispose();} if(yellow!= null){yellow.Dispose();} if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(culler!= null){culler.Dispose();} } } //--- end of script --//
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: FormatterServices ** ** ** Purpose: Provides some static methods to aid with the implementation ** of a Formatter for Serialization. ** ** ============================================================*/ namespace System.Runtime.Serialization { using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Security; using System.Security.Permissions; using System.Runtime.Serialization.Formatters; using System.Runtime.Remoting; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using System.IO; using System.Text; using System.Globalization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public static class FormatterServices { #if FEATURE_SERIALIZATION internal static Dictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable = new Dictionary<MemberHolder, MemberInfo[]>(32); [System.Security.SecurityCritical] private static bool unsafeTypeForwardersIsEnabled = false; [System.Security.SecurityCritical] private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false; private static Object s_FormatterServicesSyncObject = null; private static Object formatterServicesSyncObject { get { if (s_FormatterServicesSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_FormatterServicesSyncObject, o, null); } return s_FormatterServicesSyncObject; } } [SecuritySafeCritical] static FormatterServices() { // Static initialization touches security critical types, so we need an // explicit static constructor to allow us to mark it safe critical. } private static MemberInfo[] GetSerializableMembers(RuntimeType type) { // get the list of all fields FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); int countProper = 0; for (int i = 0; i < fields.Length; i++) { if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized) continue; countProper++; } if (countProper != fields.Length) { FieldInfo[] properFields = new FieldInfo[countProper]; countProper = 0; for (int i = 0; i < fields.Length; i++) { if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized) continue; properFields[countProper] = fields[i]; countProper++; } return properFields; } else return fields; } private static bool CheckSerializable(RuntimeType type) { if (type.IsSerializable) { return true; } return false; } private static MemberInfo[] InternalGetSerializableMembers(RuntimeType type) { List<SerializationFieldInfo> allMembers = null; MemberInfo[] typeMembers; FieldInfo [] typeFields; RuntimeType parentType; Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null"); //< if (type.IsInterface) { return new MemberInfo[0]; } if (!(CheckSerializable(type))) { throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", type.FullName, type.Module.Assembly.FullName)); } //Get all of the serializable members in the class to be serialized. typeMembers = GetSerializableMembers(type); //If this class doesn't extend directly from object, walk its hierarchy and //get all of the private and assembly-access fields (e.g. all fields that aren't //virtual) and include them in the list of things to be serialized. parentType = (RuntimeType)(type.BaseType); if (parentType != null && parentType != (RuntimeType)typeof(Object)) { RuntimeType[] parentTypes = null; int parentTypeCount = 0; bool classNamesUnique = GetParentTypes(parentType, out parentTypes, out parentTypeCount); if (parentTypeCount > 0){ allMembers = new List<SerializationFieldInfo>(); for (int i = 0; i < parentTypeCount;i++){ parentType = parentTypes[i]; if (!CheckSerializable(parentType)) { throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", parentType.FullName, parentType.Module.Assembly.FullName)); } typeFields = parentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); String typeName = classNamesUnique ? parentType.Name : parentType.FullName; foreach (FieldInfo field in typeFields) { // Family and Assembly fields will be gathered by the type itself. if (!field.IsNotSerialized) { allMembers.Add(new SerializationFieldInfo((RuntimeFieldInfo)field, typeName)); } } } //If we actually found any new MemberInfo's, we need to create a new MemberInfo array and //copy all of the members which we've found so far into that. if (allMembers!=null && allMembers.Count>0) { MemberInfo[] membersTemp = new MemberInfo[allMembers.Count + typeMembers.Length]; Array.Copy(typeMembers, membersTemp, typeMembers.Length); ((ICollection)allMembers).CopyTo(membersTemp, typeMembers.Length); typeMembers = membersTemp; } } } return typeMembers; } private static bool GetParentTypes(RuntimeType parentType, out RuntimeType[] parentTypes, out int parentTypeCount){ //Check if there are any dup class names. Then we need to include as part of //typeName to prefix the Field names in SerializationFieldInfo /*out*/ parentTypes = null; /*out*/ parentTypeCount = 0; bool unique = true; RuntimeType objectType = (RuntimeType)typeof(object); for (RuntimeType t1 = parentType; t1 != objectType; t1 = (RuntimeType)t1.BaseType) { if (t1.IsInterface) continue; string t1Name = t1.Name; for(int i=0;unique && i<parentTypeCount;i++){ string t2Name = parentTypes[i].Name; if (t2Name.Length == t1Name.Length && t2Name[0] == t1Name[0] && t1Name == t2Name){ unique = false; break; } } //expand array if needed if (parentTypes == null || parentTypeCount == parentTypes.Length){ RuntimeType[] tempParentTypes = new RuntimeType[Math.Max(parentTypeCount*2, 12)]; if (parentTypes != null) Array.Copy(parentTypes, 0, tempParentTypes, 0, parentTypeCount); parentTypes = tempParentTypes; } parentTypes[parentTypeCount++] = t1; } return unique; } // Get all of the Serializable members for a particular class. For all practical intents and // purposes, this is the non-transient, non-static members (fields and properties). In order to // be included, properties must have both a getter and a setter. N.B.: A class // which implements ISerializable or has a serialization surrogate may not use all of these members // (or may have additional members). [System.Security.SecurityCritical] // auto-generated_required public static MemberInfo[] GetSerializableMembers(Type type) { return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All)); } // Get all of the Serializable Members for a particular class. If we're not cloning, this is all // non-transient, non-static fields. If we are cloning, include the transient fields as well since // we know that we're going to live inside of the same context. [System.Security.SecurityCritical] // auto-generated_required public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) { MemberInfo[] members; if ((object)type==null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } MemberHolder mh = new MemberHolder(type, context); //If we've already gathered the members for this type, just return them. if (m_MemberInfoTable.ContainsKey(mh)) { return m_MemberInfoTable[mh]; } lock (formatterServicesSyncObject) { //If we've already gathered the members for this type, just return them. if (m_MemberInfoTable.ContainsKey(mh)) { return m_MemberInfoTable[mh]; } members = InternalGetSerializableMembers((RuntimeType)type); m_MemberInfoTable[mh] = members; } return members; } static readonly Type[] advancedTypes = new Type[]{ typeof(System.DelegateSerializationHolder), #if FEATURE_REMOTING typeof(System.Runtime.Remoting.ObjRef), typeof(System.Runtime.Remoting.IEnvoyInfo), typeof(System.Runtime.Remoting.Lifetime.ISponsor), #endif }; public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) { if (securityLevel == TypeFilterLevel.Low){ for(int i=0;i<advancedTypes.Length;i++){ if (advancedTypes[i].IsAssignableFrom(t)) throw new SecurityException(Environment.GetResourceString("Serialization_TypeSecurity", advancedTypes[i].FullName, t.FullName)); } } } #endif // FEATURE_SERIALIZATION // Gets a new instance of the object. The entire object is initalized to 0 and no // constructors have been run. **THIS MEANS THAT THE OBJECT MAY NOT BE IN A STATE // CONSISTENT WITH ITS INTERNAL REQUIREMENTS** This method should only be used for // deserialization when the user intends to immediately populate all fields. This method // will not create an unitialized string because it is non-sensical to create an empty // instance of an immutable type. // [System.Security.SecurityCritical] // auto-generated_required public static Object GetUninitializedObject(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } return nativeGetUninitializedObject((RuntimeType)type); } [System.Security.SecurityCritical] // auto-generated_required public static Object GetSafeUninitializedObject(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } #if FEATURE_REMOTING if (Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.ConstructionCall)) || Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.LogicalCallContext)) || Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Contexts.SynchronizationAttribute))) return nativeGetUninitializedObject((RuntimeType)type); #endif try { return nativeGetSafeUninitializedObject((RuntimeType)type); } catch(SecurityException e) { throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), e); } } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetSafeUninitializedObject(RuntimeType type); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetUninitializedObject(RuntimeType type); #if FEATURE_SERIALIZATION [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool GetEnableUnsafeTypeForwarders(); [SecuritySafeCritical] internal static bool UnsafeTypeForwardersIsEnabled() { if (!unsafeTypeForwardersIsEnabledInitialized) { unsafeTypeForwardersIsEnabled = GetEnableUnsafeTypeForwarders(); unsafeTypeForwardersIsEnabledInitialized = true; } return unsafeTypeForwardersIsEnabled; } #endif private static Binder s_binder = Type.DefaultBinder; [System.Security.SecurityCritical] internal static void SerializationSetValue(MemberInfo fi, Object target, Object value) { Contract.Requires(fi != null); RtFieldInfo rtField = fi as RtFieldInfo; if (rtField != null) { rtField.CheckConsistency(target); rtField.UnsafeSetValue(target, value, BindingFlags.Default, s_binder, null); return; } SerializationFieldInfo serField = fi as SerializationFieldInfo; if (serField != null) { serField.InternalSetValue(target, value, BindingFlags.Default, s_binder, null); return; } throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldInfo")); } // Fill in the members of obj with the data contained in data. // Returns the number of members populated. // [System.Security.SecurityCritical] // auto-generated_required public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) { if (obj==null) { throw new ArgumentNullException("obj"); } if (members==null) { throw new ArgumentNullException("members"); } if (data==null) { throw new ArgumentNullException("data"); } if (members.Length!=data.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_DataLengthDifferent")); } Contract.EndContractBlock(); MemberInfo mi; BCLDebug.Trace("SER", "[PopulateObjectMembers]Enter."); for (int i=0; i<members.Length; i++) { mi = members[i]; if (mi==null) { throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i)); } //If we find an empty, it means that the value was never set during deserialization. //This is either a forward reference or a null. In either case, this may break some of the //invariants mantained by the setter, so we'll do nothing with it for right now. if (data[i]!=null) { if (mi.MemberType==MemberTypes.Field) { SerializationSetValue(mi, obj, data[i]); } else { throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo")); } BCLDebug.Trace("SER", "[PopulateObjectMembers]\tType:", obj.GetType(), "\tMember:", members[i].Name, " with member type: ", ((FieldInfo)members[i]).FieldType); } //Console.WriteLine("X"); } BCLDebug.Trace("SER", "[PopulateObjectMembers]Leave."); return obj; } // Extracts the data from obj. members is the array of members which we wish to // extract (must be FieldInfos or PropertyInfos). For each supplied member, extract the matching value and // return it in a Object[] of the same size. // [System.Security.SecurityCritical] // auto-generated_required public static Object[] GetObjectData(Object obj, MemberInfo[] members) { if (obj==null) { throw new ArgumentNullException("obj"); } if (members==null) { throw new ArgumentNullException("members"); } Contract.EndContractBlock(); int numberOfMembers = members.Length; Object[] data = new Object[numberOfMembers]; MemberInfo mi; for (int i=0; i<numberOfMembers; i++) { mi=members[i]; if (mi==null) { throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i)); } if (mi.MemberType==MemberTypes.Field) { Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo, "[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo."); RtFieldInfo rfi = mi as RtFieldInfo; if (rfi != null) { rfi.CheckConsistency(obj); data[i] = rfi.UnsafeGetValue(obj); } else { data[i] = ((SerializationFieldInfo)mi).InternalGetValue(obj); } } else { throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo")); } } return data; } [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) throw new ArgumentNullException("innerSurrogate"); Contract.EndContractBlock(); return new SurrogateForCyclicalReference(innerSurrogate); } /*=============================GetTypeFromAssembly============================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ [System.Security.SecurityCritical] // auto-generated_required public static Type GetTypeFromAssembly(Assembly assem, String name) { if (assem==null) throw new ArgumentNullException("assem"); Contract.EndContractBlock(); return assem.GetType(name, false, false); } /*============================LoadAssemblyFromString============================ **Action: Loads an assembly from a given string. The current assembly loading story ** is quite confusing. If the assembly is in the fusion cache, we can load it ** using the stringized-name which we transmitted over the wire. If that fails, ** we try for a lookup of the assembly using the simple name which is the first ** part of the assembly name. If we can't find it that way, we'll return null ** as our failure result. **Returns: The loaded assembly or null if it can't be found. **Arguments: assemblyName -- The stringized assembly name. **Exceptions: None ==============================================================================*/ internal static Assembly LoadAssemblyFromString(String assemblyName) { // // Try using the stringized assembly name to load from the fusion cache. // BCLDebug.Trace("SER", "[LoadAssemblyFromString]Looking for assembly: ", assemblyName); Assembly found = Assembly.Load(assemblyName); return found; } internal static Assembly LoadAssemblyFromStringNoThrow(String assemblyName) { try { return LoadAssemblyFromString(assemblyName); } catch (Exception e){ BCLDebug.Trace("SER", "[LoadAssemblyFromString]", e.ToString()); } return null; } internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) { if ((object)type == null) { throw new ArgumentNullException("type"); } object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); if (typeAttributes != null && typeAttributes.Length > 0) { hasTypeForwardedFrom = true; TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)typeAttributes[0]; return typeForwardedFromAttribute.AssemblyFullName; } else { hasTypeForwardedFrom = false; return type.Assembly.FullName; } } internal static string GetClrTypeFullName(Type type) { if (type.IsArray) { return GetClrTypeFullNameForArray(type); } else { return GetClrTypeFullNameForNonArrayTypes(type); } } static string GetClrTypeFullNameForArray(Type type) { int rank = type.GetArrayRank(); if (rank == 1) { return String.Format(CultureInfo.InvariantCulture, "{0}{1}", GetClrTypeFullName(type.GetElementType()), "[]"); } else { StringBuilder builder = new StringBuilder(GetClrTypeFullName(type.GetElementType())).Append("["); for (int commaIndex = 1; commaIndex < rank; commaIndex++) { builder.Append(","); } builder.Append("]"); return builder.ToString(); } } static string GetClrTypeFullNameForNonArrayTypes(Type type) { if (!type.IsGenericType) { return type.FullName; } Type[] genericArguments = type.GetGenericArguments(); StringBuilder builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("["); bool hasTypeForwardedFrom; foreach (Type genericArgument in genericArguments) { builder.Append("[").Append(GetClrTypeFullName(genericArgument)).Append(", "); builder.Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom)).Append("],"); } //remove the last comma and close typename for generic with a close bracket return builder.Remove(builder.Length - 1, 1).Append("]").ToString(); } } internal sealed class SurrogateForCyclicalReference : ISerializationSurrogate { ISerializationSurrogate innerSurrogate; internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) throw new ArgumentNullException("innerSurrogate"); this.innerSurrogate = innerSurrogate; } [System.Security.SecurityCritical] // auto-generated public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { innerSurrogate.GetObjectData(obj, info, context); } [System.Security.SecurityCritical] // auto-generated public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { return innerSurrogate.SetObjectData(obj, info, context, selector); } } }
namespace ControlzEx.Showcase { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; public class UniformGridEx : Panel { public static readonly DependencyProperty FirstColumnProperty = DependencyProperty.Register(nameof(FirstColumn), typeof(int), typeof(UniformGridEx), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsMeasure), ValidateFirstColumn); public static readonly DependencyProperty ColumnsProperty = DependencyProperty.Register(nameof(Columns), typeof(int), typeof(UniformGridEx), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsMeasure), ValidateColumns); public static readonly DependencyProperty RowsProperty = DependencyProperty.Register(nameof(Rows), typeof(int), typeof(UniformGridEx), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.AffectsMeasure), ValidateRows); public static readonly DependencyProperty ShowGridLinesProperty = DependencyProperty.Register(nameof(ShowGridLines), typeof(bool), typeof(UniformGridEx), new FrameworkPropertyMetadata(false, OnShowGridLinesChanged)); public static readonly DependencyProperty GridLinesRendererProperty = DependencyProperty.Register(nameof(GridLinesRenderer), typeof(GridLinesRendererBase), typeof(UniformGridEx), new PropertyMetadata(default(UniformGridGridLinesRenderer), OnGridLinesRendererChanged)); private int columns; private int rows; public int FirstColumn { get => (int)this.GetValue(FirstColumnProperty); set => this.SetValue(FirstColumnProperty, value); } public int Columns { get => (int)this.GetValue(ColumnsProperty); set => this.SetValue(ColumnsProperty, value); } public int Rows { get => (int)this.GetValue(RowsProperty); set => this.SetValue(RowsProperty, value); } public bool ShowGridLines { get => (bool)this.GetValue(ShowGridLinesProperty); set => this.SetValue(ShowGridLinesProperty, value); } public GridLinesRendererBase GridLinesRenderer { get => (GridLinesRendererBase)this.GetValue(GridLinesRendererProperty); set => this.SetValue(GridLinesRendererProperty, value); } protected override int VisualChildrenCount => base.VisualChildrenCount + (this.GridLinesRenderer is not null ? 1 : 0); private static bool ValidateFirstColumn(object o) { return (int)o >= 0; } private static bool ValidateColumns(object o) { return (int)o >= 0; } private static bool ValidateRows(object o) { return (int)o >= 0; } protected override Visual GetVisualChild(int index) { if (index != base.VisualChildrenCount) { return base.GetVisualChild(index); } return this.GridLinesRenderer is not null ? (Visual)this.GridLinesRenderer : throw new ArgumentOutOfRangeException(nameof(index), index, null); } protected override Size MeasureOverride(Size constraint) { this.UpdateComputedValues(); var availableSize = new Size(constraint.Width / this.columns, constraint.Height / this.rows); var minChildWidth = 0.0; var minChildHeight = 0.0; var index = 0; for (var count = this.InternalChildren.Count; index < count; ++index) { var internalChild = this.InternalChildren[index]; internalChild.Measure(availableSize); var desiredSize = internalChild.DesiredSize; if (minChildWidth < desiredSize.Width) { minChildWidth = desiredSize.Width; } if (minChildHeight < desiredSize.Height) { minChildHeight = desiredSize.Height; } } return new Size(minChildWidth * this.columns, minChildHeight * this.rows); } protected override Size ArrangeOverride(Size arrangeSize) { var finalRect = new Rect(0.0, 0.0, arrangeSize.Width / this.columns, arrangeSize.Height / this.rows); var columnWidth = finalRect.Width; var rowHeight = finalRect.Height; var adjustedWidth = arrangeSize.Width - 1.0; finalRect.X += finalRect.Width * this.FirstColumn; foreach (UIElement internalChild in this.InternalChildren) { internalChild.Arrange(finalRect); if (internalChild.Visibility != Visibility.Collapsed) { finalRect.X += columnWidth; if (finalRect.X >= adjustedWidth) { finalRect.Y += finalRect.Height; finalRect.X = 0.0; } } } this.EnsureGridLinesRenderer()?.UpdateRenderBounds(arrangeSize, this.columns, columnWidth, this.rows, rowHeight); return arrangeSize; } private void UpdateComputedValues() { this.columns = this.Columns; this.rows = this.Rows; if (this.FirstColumn >= this.columns) { this.FirstColumn = 0; } if (this.rows != 0 && this.columns != 0) { return; } var visibleChildrenCount = 0; var index = 0; for (var count = this.InternalChildren.Count; index < count; ++index) { if (this.InternalChildren[index].Visibility != Visibility.Collapsed) { ++visibleChildrenCount; } } if (visibleChildrenCount == 0) { visibleChildrenCount = 1; } if (this.rows == 0) { if (this.columns > 0) { this.rows = (visibleChildrenCount + this.FirstColumn + (this.columns - 1)) / this.columns; } else { this.rows = (int)Math.Sqrt(visibleChildrenCount); if (this.rows * this.rows < visibleChildrenCount) { ++this.rows; } this.columns = this.rows; } } else { if (this.columns != 0) { return; } this.columns = (visibleChildrenCount + (this.rows - 1)) / this.rows; } } private GridLinesRendererBase EnsureGridLinesRenderer() { if (this.ShowGridLines) { this.GridLinesRenderer ??= this.CreateGridLinesRenderer(); if (this.GridLinesRenderer.Parent != this) { this.AddVisualChild(this.GridLinesRenderer); } } else if (this.ShowGridLines == false && this.GridLinesRenderer is not null) { this.RemoveVisualChild(this.GridLinesRenderer); } return this.GridLinesRenderer; } protected virtual GridLinesRendererBase CreateGridLinesRenderer() { return new UniformGridGridLinesRenderer(); } private static void OnShowGridLinesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var grid = (UniformGridEx)d; grid.InvalidateVisual(); } private static void OnGridLinesRendererChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var grid = (UniformGridEx)d; grid.InvalidateVisual(); } } }
// 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.Threading; using Xunit; namespace System.Net.Sockets.Tests { public class ReceiveMessageFrom { [OuterLoop] // TODO: Issue #11345 [Fact] public void Success() { if (Socket.OSSupportsIPv4) { using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sender.Bind(new IPEndPoint(IPAddress.Loopback, 0)); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port)); } IPPacketInformation packetInformation; SocketFlags flags = SocketFlags.None; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation); Assert.Equal(1024, len); Assert.Equal(sender.LocalEndPoint, remoteEP); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address); sender.Dispose(); } } } [OuterLoop] // TODO: Issue #11345 [Fact] public void Success_IPv6() { if (Socket.OSSupportsIPv6) { using (Socket receiver = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.IPv6Loopback); receiver.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true); Socket sender = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); sender.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.IPv6Loopback, port)); } IPPacketInformation packetInformation; SocketFlags flags = SocketFlags.None; EndPoint remoteEP = new IPEndPoint(IPAddress.IPv6Any, 0); int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation); Assert.Equal(1024, len); Assert.Equal(sender.LocalEndPoint, remoteEP); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address); sender.Dispose(); } } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false)] [InlineData(true)] public void Success_APM(bool ipv4) { AddressFamily family; IPAddress loopback, any; SocketOptionLevel level; if (ipv4) { if (!Socket.OSSupportsIPv4) return; family = AddressFamily.InterNetwork; loopback = IPAddress.Loopback; any = IPAddress.Any; level = SocketOptionLevel.IP; } else { if (!Socket.OSSupportsIPv6) return; family = AddressFamily.InterNetworkV6; loopback = IPAddress.IPv6Loopback; any = IPAddress.IPv6Any; level = SocketOptionLevel.IPv6; } using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(loopback); receiver.SetSocketOption(level, SocketOptionName.PacketInformation, true); sender.Bind(new IPEndPoint(loopback, 0)); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1024], new IPEndPoint(loopback, port)); } IPPacketInformation packetInformation; SocketFlags flags = SocketFlags.None; EndPoint remoteEP = new IPEndPoint(any, 0); IAsyncResult ar = receiver.BeginReceiveMessageFrom(new byte[1024], 0, 1024, flags, ref remoteEP, null, null); int len = receiver.EndReceiveMessageFrom(ar, ref flags, ref remoteEP, out packetInformation); Assert.Equal(1024, len); Assert.Equal(sender.LocalEndPoint, remoteEP); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address); } } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(false, 0)] [InlineData(false, 1)] [InlineData(false, 2)] [InlineData(true, 0)] [InlineData(true, 1)] [InlineData(true, 2)] public void Success_EventArgs(bool ipv4, int bufferMode) { AddressFamily family; IPAddress loopback, any; SocketOptionLevel level; if (ipv4) { if (!Socket.OSSupportsIPv4) return; family = AddressFamily.InterNetwork; loopback = IPAddress.Loopback; any = IPAddress.Any; level = SocketOptionLevel.IP; } else { if (!Socket.OSSupportsIPv6) return; family = AddressFamily.InterNetworkV6; loopback = IPAddress.IPv6Loopback; any = IPAddress.IPv6Any; level = SocketOptionLevel.IPv6; } using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp)) using (var saea = new SocketAsyncEventArgs()) { int port = receiver.BindToAnonymousPort(loopback); receiver.SetSocketOption(level, SocketOptionName.PacketInformation, true); sender.Bind(new IPEndPoint(loopback, 0)); saea.RemoteEndPoint = new IPEndPoint(any, 0); switch (bufferMode) { case 0: // single buffer saea.SetBuffer(new byte[1024], 0, 1024); break; case 1: // single buffer in buffer list saea.BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1024]) }; break; case 2: // multiple buffers in buffer list saea.BufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[512]), new ArraySegment<byte>(new byte[512]) }; break; } var mres = new ManualResetEventSlim(); saea.Completed += delegate { mres.Set(); }; bool pending = receiver.ReceiveMessageFromAsync(saea); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1024], new IPEndPoint(loopback, port)); } if (pending) Assert.True(mres.Wait(30000), "Expected operation to complete within timeout"); Assert.Equal(1024, saea.BytesTransferred); Assert.Equal(sender.LocalEndPoint, saea.RemoteEndPoint); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, saea.ReceiveMessageFromPacketInfo.Address); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ImagesOperations operations. /// </summary> internal partial class ImagesOperations : IServiceOperations<ComputeManagementClient>, IImagesOperations { /// <summary> /// Initializes a new instance of the ImagesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ImagesOperations(ComputeManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ComputeManagementClient /// </summary> public ComputeManagementClient Client { get; private set; } /// <summary> /// Create or update an image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Image operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<Image>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string imageName, Image parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<Image> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, imageName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes an Image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string imageName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<OperationStatusResponse> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, imageName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets an image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Image>> GetWithHttpMessagesAsync(string resourceGroupName, string imageName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (imageName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "imageName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("imageName", imageName); tracingParameters.Add("expand", expand); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{imageName}", System.Uri.EscapeDataString(imageName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(expand))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Image>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Image>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets the list of images under a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Image>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroup", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Image>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Image>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets the list of Images in the subscription. Use nextLink property in the /// response to get the next page of Images. Do this till nextLink is not null /// to fetch all the Images. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Image>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Compute/images").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Image>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Image>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Create or update an image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Image operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Image>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string imageName, Image parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (imageName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "imageName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("imageName", imageName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{imageName}", System.Uri.EscapeDataString(imageName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Image>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Image>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Image>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Deletes an Image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string imageName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (imageName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "imageName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2016-04-30-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("imageName", imageName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/images/{imageName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{imageName}", System.Uri.EscapeDataString(imageName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationStatusResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<OperationStatusResponse>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets the list of images under a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Image>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByResourceGroupNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Image>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Image>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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> /// Gets the list of Images in the subscription. Use nextLink property in the /// response to get the next page of Images. Do this till nextLink is not null /// to fetch all the Images. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<Image>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } 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; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<Image>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<Image>>(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.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; } } }
namespace Nancy.Tests.Unit.ErrorHandling { using System; using System.IO; using FakeItEasy; using Nancy.Configuration; using Nancy.ErrorHandling; using Nancy.Responses.Negotiation; using Nancy.ViewEngines; using Xunit; using Xunit.Extensions; public class DefaultStatusCodeHandlerFixture { private readonly IResponseNegotiator responseNegotiator; private readonly IStatusCodeHandler statusCodeHandler; public DefaultStatusCodeHandlerFixture() { var environment = new DefaultNancyEnvironment(); environment.Tracing( enabled: true, displayErrorTraces: true); this.responseNegotiator = A.Fake<IResponseNegotiator>(); this.statusCodeHandler = new DefaultStatusCodeHandler(this.responseNegotiator, environment); } [Theory] [InlineData(HttpStatusCode.Continue)] [InlineData(HttpStatusCode.SwitchingProtocols)] [InlineData(HttpStatusCode.Processing)] [InlineData(HttpStatusCode.Checkpoint)] [InlineData(HttpStatusCode.OK)] [InlineData(HttpStatusCode.Created)] [InlineData(HttpStatusCode.Accepted)] [InlineData(HttpStatusCode.NonAuthoritativeInformation)] [InlineData(HttpStatusCode.NoContent)] [InlineData(HttpStatusCode.ResetContent)] [InlineData(HttpStatusCode.PartialContent)] [InlineData(HttpStatusCode.MultipleStatus)] [InlineData(HttpStatusCode.IMUsed)] [InlineData(HttpStatusCode.MultipleChoices)] [InlineData(HttpStatusCode.MovedPermanently)] [InlineData(HttpStatusCode.Found)] [InlineData(HttpStatusCode.SeeOther)] [InlineData(HttpStatusCode.NotModified)] [InlineData(HttpStatusCode.UseProxy)] [InlineData(HttpStatusCode.SwitchProxy)] [InlineData(HttpStatusCode.TemporaryRedirect)] [InlineData(HttpStatusCode.ResumeIncomplete)] [InlineData(HttpStatusCode.Unauthorized)] public void Should_not_handle_non_error_codes(HttpStatusCode statusCode) { var result = this.statusCodeHandler.HandlesStatusCode(statusCode, null); result.ShouldBeFalse(); } [Theory] [InlineData(HttpStatusCode.Continue)] [InlineData(HttpStatusCode.SwitchingProtocols)] [InlineData(HttpStatusCode.Processing)] [InlineData(HttpStatusCode.Checkpoint)] [InlineData(HttpStatusCode.OK)] [InlineData(HttpStatusCode.Created)] [InlineData(HttpStatusCode.Accepted)] [InlineData(HttpStatusCode.NonAuthoritativeInformation)] [InlineData(HttpStatusCode.NoContent)] [InlineData(HttpStatusCode.ResetContent)] [InlineData(HttpStatusCode.PartialContent)] [InlineData(HttpStatusCode.MultipleStatus)] [InlineData(HttpStatusCode.IMUsed)] [InlineData(HttpStatusCode.MultipleChoices)] [InlineData(HttpStatusCode.MovedPermanently)] [InlineData(HttpStatusCode.Found)] [InlineData(HttpStatusCode.SeeOther)] [InlineData(HttpStatusCode.NotModified)] [InlineData(HttpStatusCode.UseProxy)] [InlineData(HttpStatusCode.SwitchProxy)] [InlineData(HttpStatusCode.TemporaryRedirect)] [InlineData(HttpStatusCode.ResumeIncomplete)] [InlineData(HttpStatusCode.Unauthorized)] public void Should_not_respond_when_handling_non_error_codes(HttpStatusCode statusCode) { // Given var context = new NancyContext(); // When this.statusCodeHandler.Handle(statusCode, context); // Then context.Response.ShouldBeNull(); } [Fact] public void Should_set_response_contents_if_required() { // Given var context = new NancyContext(); context.Response = new Response(); // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then context.Response.Contents.ShouldNotBeNull(); } [Fact] public void Should_not_overwrite_response_contents() { // Given var context = new NancyContext(); Action<Stream> contents = stream => { }; context.Response = new Response() { StatusCode = HttpStatusCode.NotFound, Contents = contents }; // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then context.Response.Contents.ShouldEqual(contents); } [Fact] public void Should_overwrite_response_contents_if_the_body_is_null_object() { // Given var context = new NancyContext(); context.Response = new Response { StatusCode = HttpStatusCode.NotFound }; A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).Throws(new ViewNotFoundException(string.Empty)); // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then using (var stream = new MemoryStream()) { context.Response.Contents.Invoke(stream); stream.ToArray().Length.ShouldBeGreaterThan(0); } } [Fact] public void Should_create_response_if_it_doesnt_exist_in_context() { // Given var context = new NancyContext(); // When this.statusCodeHandler.Handle(HttpStatusCode.NotFound, context); // Then context.Response.ShouldNotBeNull(); } [Fact] public void Should_leave_reponse_stream_open_if_response_is_InternalServerError() { // Given var context = new NancyContext(); var memoryStream = new MemoryStream(); // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); context.Response.Contents(memoryStream); // Then memoryStream.CanRead.ShouldBeTrue(); } [Fact] public void Should_negotiate_response_with_content_negotiator() { // Given var context = new NancyContext(); // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); // Then A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).MustHaveHappened(); } [Fact] public void Should_render_html_response_from_static_resources() { // Given var context = new NancyContext(); A.CallTo(() => this.responseNegotiator.NegotiateResponse(A<DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult>._, context)).Throws(new ViewNotFoundException(string.Empty)); // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); // Then Assert.Equal("text/html", context.Response.ContentType); } [Fact] public void Should_reset_negotiation_context() { // Given var context = new NancyContext(); var negotiationContext = new NegotiationContext { ViewName = "Index" }; context.NegotiationContext = negotiationContext; // When this.statusCodeHandler.Handle(HttpStatusCode.InternalServerError, context); // Then Assert.Null(context.NegotiationContext.ViewName); } [Fact] public void Should_be_xml_serializable() { // Given var environment = new DefaultNancyEnvironment(); environment.AddValue(Xml.XmlConfiguration.Default); environment.Tracing( enabled: true, displayErrorTraces: true); var serializer = new Nancy.Responses.DefaultXmlSerializer(environment); var model = new DefaultStatusCodeHandler.DefaultStatusCodeHandlerResult() { StatusCode = HttpStatusCode.NotFound, Message = "not found", Details = "not found details" }; // When var xml = new System.Xml.XmlDocument(); using (var stream = new MemoryStream()) { serializer.Serialize("application/xml", model, stream); stream.Position = 0; xml.Load(stream); } // Then Assert.Equal("DefaultStatusCodeHandlerResult", xml.DocumentElement.Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.IO; using System.Net.Test.Common; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { // Note: Disposing the HttpClient object automatically disposes the handler within. So, it is not necessary // to separately Dispose (or have a 'using' statement) for the handler. public class HttpClientHandlerTest { readonly ITestOutputHelper _output; private const string ExpectedContent = "Test contest"; private const string Username = "testuser"; private const string Password = "password"; private readonly NetworkCredential _credential = new NetworkCredential(Username, Password); public readonly static object[][] EchoServers = HttpTestServers.EchoServers; public readonly static object[][] VerifyUploadServers = HttpTestServers.VerifyUploadServers; public readonly static object[][] CompressedServers = HttpTestServers.CompressedServers; public readonly static object[][] HeaderValueAndUris = { new object[] { "X-CustomHeader", "x-value", HttpTestServers.RemoteEchoServer }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RemoteEchoServer }, new object[] { "X-CustomHeader", "x-value", HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, new object[] { "X-Cust-Header-NoValue", "" , HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.RemoteEchoServer, hops:1) }, }; public readonly static object[][] Http2Servers = HttpTestServers.Http2Servers; // Standard HTTP methods defined in RFC7231: http://tools.ietf.org/html/rfc7231#section-4.3 // "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE" public readonly static IEnumerable<object[]> HttpMethods = GetMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS", "TRACE", "CUSTOM1"); public readonly static IEnumerable<object[]> HttpMethodsThatAllowContent = GetMethods("GET", "POST", "PUT", "DELETE", "CUSTOM1"); private static IEnumerable<object[]> GetMethods(params string[] methods) { foreach (string method in methods) { foreach (bool secure in new[] { true, false }) { yield return new object[] { method, secure }; } } } public HttpClientHandlerTest(ITestOutputHelper output) { _output = output; } [Fact] public void Ctor_ExpectedDefaultPropertyValues() { using (var handler = new HttpClientHandler()) { // Same as .NET Framework (Desktop). Assert.True(handler.AllowAutoRedirect); Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions); CookieContainer cookies = handler.CookieContainer; Assert.NotNull(cookies); Assert.Equal(0, cookies.Count); Assert.Null(handler.Credentials); Assert.Equal(50, handler.MaxAutomaticRedirections); Assert.False(handler.PreAuthenticate); Assert.Equal(null, handler.Proxy); Assert.True(handler.SupportsAutomaticDecompression); Assert.True(handler.SupportsProxy); Assert.True(handler.SupportsRedirectConfiguration); Assert.True(handler.UseCookies); Assert.False(handler.UseDefaultCredentials); Assert.True(handler.UseProxy); // Changes from .NET Framework (Desktop). Assert.Equal(DecompressionMethods.GZip | DecompressionMethods.Deflate, handler.AutomaticDecompression); Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Get_ReturnsZero() { using (var handler = new HttpClientHandler()) { Assert.Equal(0, handler.MaxRequestContentBufferSize); } } [Fact] public void MaxRequestContentBufferSize_Set_ThrowsPlatformNotSupportedException() { using (var handler = new HttpClientHandler()) { Assert.Throws<PlatformNotSupportedException>(() => handler.MaxRequestContentBufferSize = 1024); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task UseDefaultCredentials_SetToFalseAndServerNeedsAuth_StatusCodeUnauthorized(bool useProxy) { var handler = new HttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.NegotiateAuthUriForDefaultCreds(secure:false); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Theory, MemberData(nameof(EchoServers))] public async Task SendAsync_SimpleGet_Success(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(remoteServer)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Fact] public async Task SendAsync_MultipleRequestsReusingSameClient_Success() { using (var client = new HttpClient()) { HttpResponseMessage response; for (int i = 0; i < 3; i++) { response = await client.GetAsync(HttpTestServers.RemoteEchoServer); Assert.Equal(HttpStatusCode.OK, response.StatusCode); response.Dispose(); } } } [Fact] public async Task GetAsync_ResponseContentAfterClientAndHandlerDispose_Success() { HttpResponseMessage response = null; using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer); } Assert.NotNull(response); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } [Fact] public async Task SendAsync_Cancel_CancellationTokenPropagates() { var cts = new CancellationTokenSource(); cts.Cancel(); using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, HttpTestServers.RemoteEchoServer); TaskCanceledException ex = await Assert.ThrowsAsync<TaskCanceledException>(() => client.SendAsync(request, cts.Token)); Assert.True(cts.Token.IsCancellationRequested, "cts token IsCancellationRequested"); Assert.True(ex.CancellationToken.IsCancellationRequested, "exception token IsCancellationRequested"); } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_ContentDecompressed(Uri server) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(server)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [Theory, MemberData(nameof(CompressedServers))] public async Task GetAsync_DefaultAutomaticDecompression_HeadersRemoved(Uri server) { using (var client = new HttpClient()) using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [Fact] public async Task GetAsync_ServerNeedsAuthAndSetCredential_StatusCodeOK() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_ServerNeedsAuthAndNoCredential_StatusCodeUnauthorized() { using (var client = new HttpClient()) { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectFalse_RedirectFromHttpToHttp_StatusCodeRedirect() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = false; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttp_StatusCodeOK() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpToHttps_StatusCodeOK() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.SecureRemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectFromHttpsToHttp_StatusCodeRedirect() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:true, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } } [Fact] public async Task GetAsync_AllowAutoRedirectTrue_RedirectToUriWithParams_RequestMsgUriSet() { var handler = new HttpClientHandler(); handler.AllowAutoRedirect = true; Uri targetUri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); using (var client = new HttpClient(handler)) { Uri uri = HttpTestServers.RedirectUriForDestinationUri(secure:false, destinationUri:targetUri, hops:1); _output.WriteLine("Uri: {0}", uri); using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(targetUri, response.RequestMessage.RequestUri); } } } [Theory] [InlineData(6)] public async Task GetAsync_MaxAutomaticRedirectionsNServerHopsNPlus1_Throw(int hops) { var handler = new HttpClientHandler(); handler.MaxAutomaticRedirections = hops; using (var client = new HttpClient(handler)) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.RemoteEchoServer, hops:(hops + 1)))); } } [Fact] public async Task GetAsync_CredentialIsNetworkCredentialUriRedirect_StatusCodeUnauthorized() { var handler = new HttpClientHandler(); handler.Credentials = _credential; using (var client = new HttpClient(handler)) { Uri redirectUri = HttpTestServers.RedirectUriForCreds(secure:false, userName:Username, password:Password); using (HttpResponseMessage unAuthResponse = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.Unauthorized, unAuthResponse.StatusCode); } } } [Fact] public async Task GetAsync_CredentialIsCredentialCacheUriRedirect_StatusCodeOK() { Uri uri = HttpTestServers.BasicAuthUriForCreds(secure:false, userName:Username, password:Password); Uri redirectUri = HttpTestServers.RedirectUriForCreds(secure:false, userName:Username, password:Password); _output.WriteLine(uri.AbsoluteUri); _output.WriteLine(redirectUri.AbsoluteUri); var credentialCache = new CredentialCache(); credentialCache.Add(uri, "Basic", _credential); var handler = new HttpClientHandler(); handler.Credentials = credentialCache; using (var client = new HttpClient(handler)) { using (HttpResponseMessage response = await client.GetAsync(redirectUri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.False(TestHelper.JsonMessageContainsKey(responseText, "Cookie")); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue) { var handler = new HttpClientHandler(); var cookieContainer = new CookieContainer(); cookieContainer.Add(HttpTestServers.RemoteEchoServer, new Cookie(cookieName, cookieValue)); handler.CookieContainer = cookieContainer; using (var client = new HttpClient(handler)) { using (HttpResponseMessage httpResponse = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory] [InlineData("cookieName1", "cookieValue1")] public async Task GetAsync_RedirectResponseHasCookie_CookieSentToFinalUri(string cookieName, string cookieValue) { Uri uri = HttpTestServers.RedirectUriForDestinationUri( secure:false, destinationUri:HttpTestServers.RemoteEchoServer, hops:1); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add( "X-SetCookie", string.Format("{0}={1};Path=/", cookieName, cookieValue)); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { string responseText = await httpResponse.Content.ReadAsStringAsync(); _output.WriteLine(responseText); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, cookieName, cookieValue)); } } } [Theory, MemberData(nameof(HeaderValueAndUris))] public async Task GetAsync_RequestHeadersAddCustomHeaders_HeaderAndValueSent(string name, string value, Uri uri) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add(name, value); using (HttpResponseMessage httpResponse = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); string responseText = await httpResponse.Content.ReadAsStringAsync(); Assert.True(TestHelper.JsonMessageContainsKeyValue(responseText, name, value)); } } } private static KeyValuePair<string, string> GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; string value = new string(repeat, valueCount); return new KeyValuePair<string, string>(name, value); } public static object[][] CookieNameValues = { // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256) }, new object[] { GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257) }, new object[] { new KeyValuePair<string, string>( ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM") } }; [Theory] [MemberData(nameof(CookieNameValues))] public async Task GetAsync_ResponseWithSetCookieHeaders_AllCookiesRead(KeyValuePair<string, string> cookie1) { var cookie2 = new KeyValuePair<string, string>(".AspNetCore.Session", "RAExEmXpoCbueP_QYM"); var cookie3 = new KeyValuePair<string, string>("name", "value"); string url = string.Format( "http://httpbin.org/cookies/set?{0}={1}&{2}={3}&{4}={5}", cookie1.Key, cookie1.Value, cookie2.Key, cookie2.Value, cookie3.Key, cookie3.Value); var handler = new HttpClientHandler() { AllowAutoRedirect = false }; using (var client = new HttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(url)) { Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); CookieCollection cookies = handler.CookieContainer.GetCookies(new Uri(url)); Assert.Equal(3, handler.CookieContainer.Count); Assert.Equal(cookie1.Value, cookies[cookie1.Key].Value); Assert.Equal(cookie2.Value, cookies[cookie2.Key].Value); Assert.Equal(cookie3.Value, cookies[cookie3.Key].Value); } } [Fact] public async Task GetAsync_ResponseHeadersRead_ReadFromEachIterativelyDoesntDeadlock() { using (var client = new HttpClient()) { const int NumGets = 5; Task<HttpResponseMessage>[] responseTasks = (from _ in Enumerable.Range(0, NumGets) select client.GetAsync(HttpTestServers.RemoteEchoServer, HttpCompletionOption.ResponseHeadersRead)).ToArray(); for (int i = responseTasks.Length - 1; i >= 0; i--) // read backwards to increase likelihood that we wait on a different task than has data available { using (HttpResponseMessage response = await responseTasks[i]) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } } [Fact] public async Task SendAsync_HttpRequestMsgResponseHeadersRead_StatusCodeOK() { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, HttpTestServers.SecureRemoteEchoServer); using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [ActiveIssue(4259, PlatformID.AnyUnix)] [OuterLoop] [Fact] public async Task SendAsync_ReadFromSlowStreamingServer_PartialDataReturned() { // TODO: This is a placeholder until GitHub Issue #2383 gets resolved. const string SlowStreamingServer = "http://httpbin.org/drip?numbytes=8192&duration=15&delay=1&code=200"; int bytesRead; byte[] buffer = new byte[8192]; using (var client = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Get, SlowStreamingServer); using (HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)) { Stream stream = await response.Content.ReadAsStreamAsync(); bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length); } _output.WriteLine("Bytes read from stream: {0}", bytesRead); Assert.True(bytesRead < buffer.Length, "bytesRead should be less than buffer.Length"); } } #region Post Methods Tests [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethodTwice_StringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "Test String"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); HttpResponseMessage response; using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } // Repeat call. content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServers))] public async Task PostAsync_CallMethod_UnicodeStringContent(Uri remoteServer) { using (var client = new HttpClient()) { string data = "\ub4f1\uffc7\u4e82\u67ab4\uc6d4\ud1a0\uc694\uc77c\uffda3\u3155\uc218\uffdb"; var content = new StringContent(data, Encoding.UTF8); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(data); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } [Theory, MemberData(nameof(VerifyUploadServersStreamsAndExpectedData))] public async Task PostAsync_CallMethod_StreamContent(Uri remoteServer, Stream requestContentStream, byte[] expectedData) { using (var client = new HttpClient()) { HttpContent content = new StreamContent(requestContentStream); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } public static IEnumerable<object[]> VerifyUploadServersStreamsAndExpectedData { get { foreach (object[] serverArr in VerifyUploadServers) { Uri server = (Uri)serverArr[0]; byte[] data = new byte[1234]; new Random(42).NextBytes(data); // A MemoryStream { var memStream = new MemoryStream(data, writable: false); yield return new object[] { server, memStream, data }; } // A stream that provides the data synchronously and has a known length { var wrappedMemStream = new MemoryStream(data, writable: false); var syncKnownLengthStream = new DelegateStream( canReadFunc: () => wrappedMemStream.CanRead, canSeekFunc: () => wrappedMemStream.CanSeek, lengthFunc: () => wrappedMemStream.Length, positionGetFunc: () => wrappedMemStream.Position, readAsyncFunc: (buffer, offset, count, token) => wrappedMemStream.ReadAsync(buffer, offset, count, token)); yield return new object[] { server, syncKnownLengthStream, data }; } // A stream that provides the data synchronously and has an unknown length { int syncUnknownLengthStreamOffset = 0; var syncUnknownLengthStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: (buffer, offset, count, token) => { int bytesRemaining = data.Length - syncUnknownLengthStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, count); Array.Copy(data, syncUnknownLengthStreamOffset, buffer, offset, bytesToCopy); syncUnknownLengthStreamOffset += bytesToCopy; return Task.FromResult(bytesToCopy); }); yield return new object[] { server, syncUnknownLengthStream, data }; } // A stream that provides the data asynchronously { int asyncStreamOffset = 0, maxDataPerRead = 100; var asyncStream = new DelegateStream( canReadFunc: () => true, canSeekFunc: () => false, readAsyncFunc: async (buffer, offset, count, token) => { await Task.Delay(1).ConfigureAwait(false); int bytesRemaining = data.Length - asyncStreamOffset; int bytesToCopy = Math.Min(bytesRemaining, Math.Min(maxDataPerRead, count)); Array.Copy(data, asyncStreamOffset, buffer, offset, bytesToCopy); asyncStreamOffset += bytesToCopy; return bytesToCopy; }); yield return new object[] { server, asyncStream, data }; } } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_NullContent(Uri remoteServer) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.PostAsync(remoteServer, null)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory, MemberData(nameof(EchoServers))] public async Task PostAsync_CallMethod_EmptyContent(Uri remoteServer) { using (var client = new HttpClient()) { var content = new StringContent(string.Empty); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, string.Empty); } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task PostAsync_Redirect_ResultingGetFormattedCorrectly(bool secure) { const string ContentString = "This is the content string."; var content = new StringContent(ContentString); Uri redirectUri = HttpTestServers.RedirectUriForDestinationUri( secure, secure ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer, 1); using (var client = new HttpClient()) using (HttpResponseMessage response = await client.PostAsync(redirectUri, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); Assert.DoesNotContain(ContentString, responseContent); Assert.DoesNotContain("Content-Length", responseContent); } } [Theory] [InlineData(HttpStatusCode.MethodNotAllowed, "Custom description")] [InlineData(HttpStatusCode.MethodNotAllowed, "")] public async Task GetAsync_CallMethod_ExpectedStatusLine(HttpStatusCode statusCode, string reasonPhrase) { using (var client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.StatusCodeUri( false, (int)statusCode, reasonPhrase))) { Assert.Equal(statusCode, response.StatusCode); Assert.Equal(reasonPhrase, response.ReasonPhrase); } } } [Fact] public async Task PostAsync_Post_ChannelBindingHasExpectedValue() { using (var client = new HttpClient()) { string expectedContent = "Test contest"; var content = new ChannelBindingAwareContent(expectedContent); using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); ChannelBinding channelBinding = content.ChannelBinding; Assert.NotNull(channelBinding); _output.WriteLine("Channel Binding: {0}", channelBinding); } } } #endregion #region Various HTTP Method Tests [Theory, MemberData(nameof(HttpMethods))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithNoContent_MethodCorrectlySent( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); } } } [Theory, MemberData(nameof(HttpMethodsThatAllowContent))] public async Task SendAsync_SendRequestUsingMethodToEchoServerWithContent_Success( string method, bool secureServer) { using (var client = new HttpClient()) { var request = new HttpRequestMessage( new HttpMethod(method), secureServer ? HttpTestServers.SecureRemoteEchoServer : HttpTestServers.RemoteEchoServer); request.Content = new StringContent(ExpectedContent); using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); TestHelper.VerifyRequestMethod(response, method); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, ExpectedContent); } } } #endregion #region Version tests // The HTTP RFC 7230 states that servers are NOT required to respond back with the same // minor version if they support a higher minor version. In fact, the RFC states that // servers SHOULD send back the highest minor version they support. So, testing the // response version to see if the client sent a particular request version only works // for some servers. In particular the 'Http2Servers' used in these tests always seem // to echo the minor version of the request. [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion10_ServerReceivesVersion10Request(Uri server) { Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(1, 0), server); Assert.Equal(new Version(1, 0), responseVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion11_ServerReceivesVersion11Request(Uri server) { Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(1, 1), server); Assert.Equal(new Version(1, 1), responseVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersionNotSpecified_ServerReceivesVersion11Request(Uri server) { Version responseVersion = await SendRequestAndGetResponseVersionAsync(null, server); Assert.Equal(new Version(1, 1), responseVersion); } [Theory, MemberData(nameof(Http2Servers))] public async Task SendAsync_RequestVersion20_ResponseVersion20IfHttp2Supported(Uri server) { // We don't currently have a good way to test whether HTTP/2 is supported without // using the same mechanism we're trying to test, so for now we allow both 2.0 and 1.1 responses. Version responseVersion = await SendRequestAndGetResponseVersionAsync(new Version(2, 0), server); Assert.True( responseVersion == new Version(2, 0) || responseVersion == new Version(1, 1), "Response version " + responseVersion); } private async Task<Version> SendRequestAndGetResponseVersionAsync(Version requestVersion, Uri server) { var request = new HttpRequestMessage(HttpMethod.Get, server); if (requestVersion != null) { request.Version = requestVersion; } else { // The default value for HttpRequestMessage.Version is Version(1,1). // So, we need to set something different to test the "unknown" version. request.Version = new Version(0,0); } using (var client = new HttpClient()) using (HttpResponseMessage response = await client.SendAsync(request)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); return response.Version; } } #endregion #region SSL Version tests [Theory] [InlineData("SSLv2", HttpTestServers.SSLv2RemoteServer)] [InlineData("SSLv3", HttpTestServers.SSLv3RemoteServer)] public async Task GetAsync_UnsupportedSSLVersion_Throws(string name, string url) { using (HttpClient client = new HttpClient()) { await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url)); } } [Theory] [InlineData("TLSv1.0", HttpTestServers.TLSv10RemoteServer)] [InlineData("TLSv1.1", HttpTestServers.TLSv11RemoteServer)] [InlineData("TLSv1.2", HttpTestServers.TLSv12RemoteServer)] public async Task GetAsync_SupportedSSLVersion_Succeeds(string name, string url) { using (HttpClient client = new HttpClient()) using (await client.GetAsync(url)) { } } #endregion #region Proxy tests [Theory] [MemberData(nameof(CredentialsForProxy))] public void Proxy_BypassFalse_GetRequestGoesThroughCustomProxy(ICredentials creds, bool wrapCredsInCache) { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: creds != null && creds != CredentialCache.DefaultCredentials, expectCreds: true); Uri proxyUrl = new Uri($"http://localhost:{port}"); const string BasicAuth = "Basic"; if (wrapCredsInCache) { Assert.IsAssignableFrom<NetworkCredential>(creds); var cache = new CredentialCache(); cache.Add(proxyUrl, BasicAuth, (NetworkCredential)creds); creds = cache; } using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, creds) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task<string> responseStringTask = responseTask.ContinueWith(t => t.Result.Content.ReadAsStringAsync(), TaskScheduler.Default).Unwrap(); Task.WaitAll(proxyTask, responseTask, responseStringTask); TestHelper.VerifyResponseBody(responseStringTask.Result, responseTask.Result.Content.Headers.ContentMD5, false, null); Assert.Equal(Encoding.ASCII.GetString(proxyTask.Result.ResponseContent), responseStringTask.Result); NetworkCredential nc = creds?.GetCredential(proxyUrl, BasicAuth); string expectedAuth = nc == null || nc == CredentialCache.DefaultCredentials ? null : string.IsNullOrEmpty(nc.Domain) ? $"{nc.UserName}:{nc.Password}" : $"{nc.Domain}\\{nc.UserName}:{nc.Password}"; Assert.Equal(expectedAuth, proxyTask.Result.AuthenticationHeaderValue); } } [Theory] [MemberData(nameof(BypassedProxies))] public async Task Proxy_BypassTrue_GetRequestDoesntGoesThroughCustomProxy(IWebProxy proxy) { using (var client = new HttpClient(new HttpClientHandler() { Proxy = proxy })) using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer)) { TestHelper.VerifyResponseBody( await response.Content.ReadAsStringAsync(), response.Content.Headers.ContentMD5, false, null); } } [Fact] public void Proxy_HaveNoCredsAndUseAuthenticatedCustomProxy_ProxyAuthenticationRequiredStatusCode() { int port; Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync( out port, requireAuth: true, expectCreds: false); Uri proxyUrl = new Uri($"http://localhost:{port}"); using (var handler = new HttpClientHandler() { Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null) }) using (var client = new HttpClient(handler)) { Task<HttpResponseMessage> responseTask = client.GetAsync(HttpTestServers.RemoteEchoServer); Task.WaitAll(proxyTask, responseTask); Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode); } } private static IEnumerable<object[]> BypassedProxies() { yield return new object[] { null }; yield return new object[] { new PlatformNotSupportedWebProxy() }; yield return new object[] { new UseSpecifiedUriWebProxy(new Uri($"http://{Guid.NewGuid().ToString().Substring(0, 15)}:12345"), bypass: true) }; } private static IEnumerable<object[]> CredentialsForProxy() { yield return new object[] { null, false }; foreach (bool wrapCredsInCache in new[] { true, false }) { yield return new object[] { CredentialCache.DefaultCredentials, wrapCredsInCache }; yield return new object[] { new NetworkCredential("user:name", "password"), wrapCredsInCache }; yield return new object[] { new NetworkCredential("username", "password", "dom:\\ain"), wrapCredsInCache }; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Messaging.EventHubs.Diagnostics; using Azure.Messaging.EventHubs.Tests; using Moq; using NUnit.Framework; namespace Azure.Messaging.EventHubs.Primitives.Tests { /// <summary> /// The suite of tests for the <see cref="PartitionLoadBalancer" /> /// class. /// </summary> /// [TestFixture] public class PartitionLoadBalancerTests { private const string FullyQualifiedNamespace = "fqns"; private const string EventHubName = "name"; private const string ConsumerGroup = "consumerGroup"; /// <summary> /// Verifies that partitions owned by a <see cref="PartitionLoadBalancer" /> are immediately available to be claimed by another loadbalancer /// after StopAsync is called. /// </summary> /// [Test] public async Task RelinquishOwnershipAsyncRelinquishesPartitionOwnershipOtherClientsConsiderThemClaimableImmediately() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer1 = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); var loadbalancer2 = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0)); // Start the load balancer so that it claims a random partition until none are left. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer1.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); // All partitions are owned by loadbalancer1. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer1.OwnerIdentifier)), Is.EqualTo(NumberOfPartitions)); // Stopping the load balancer should relinquish all partition ownership. await loadbalancer1.RelinquishOwnershipAsync(CancellationToken.None); completeOwnership = await storageManager.ListOwnershipAsync(loadbalancer1.FullyQualifiedNamespace, loadbalancer1.EventHubName, loadbalancer1.ConsumerGroup); // No partitions are owned by loadbalancer1. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer1.OwnerIdentifier)), Is.EqualTo(0)); // Start loadbalancer2 so that the load balancer claims a random partition until none are left. // All partitions should be immediately claimable even though they were just claimed by the loadbalancer1. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer2.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(loadbalancer1.FullyQualifiedNamespace, loadbalancer1.EventHubName, loadbalancer1.ConsumerGroup); // All partitions are owned by loadbalancer2. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer2.OwnerIdentifier)), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncClaimsAllClaimablePartitions() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0)); // Start the load balancer so that it claims a random partition until none are left. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); // All partitions are owned by load balancer. Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task IsBalancedIsCorrectWithOneProcessor() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0), "No partitions should be owned."); // Start the load balancer so that it claims a random partition until none are left. for (var index = 0; index < NumberOfPartitions; ++index) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); Assert.That(loadBalancer.IsBalanced, Is.False, "The load balancer should not believe the state is balanced while partitions remain unclaimed."); } // The load balancer should not consider itself balanced until a cycle is run with no partitions claimed. Run one additional // cycle to satisfy that condition. Assert.That(loadBalancer.IsBalanced, Is.False, "The load balancer should not believe the state is balanced until no partition is claimed during a cycle."); await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // All partitions are owned by load balancer. completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(loadBalancer.IsBalanced, Is.True, "The load balancer should believe the state is balanced when it owns all partitions."); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task IsBalancedIsCorrectWithMultipleProcessorsAndAnEventDistribution() { const int MinimumPartitionCount = 4; const int NumberOfPartitions = 12; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); var completeOwnership = Enumerable.Empty<EventProcessorPartitionOwnership>(); // Create partitions owned by a different load balancer. var secondLoadBalancerId = Guid.NewGuid().ToString(); var secondLoadBalancerPartitions = Enumerable.Range(1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(secondLoadBalancerPartitions.Select(i => i.ToString()), secondLoadBalancerId)); // Create partitions owned by a different load balancer. var thirdLoadBalancerId = Guid.NewGuid().ToString(); var thirdLoadBalancerPartitions = Enumerable.Range(secondLoadBalancerPartitions.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(thirdLoadBalancerPartitions.Select(i => i.ToString()), thirdLoadBalancerId)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Ensure that there is exactly the minimum number of partitions available to be owned. var unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(MinimumPartitionCount), "There should be exactly the balanced share of partitions left unowned."); // Run load balancing cycles until the load balancer believes that the state is balanced or the minimum count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (MinimumPartitionCount * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(0), "There no partitions left unowned."); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(loadBalancer.IsBalanced, Is.True, "The load balancer should believe the state is balanced when it owns the correct number of partitions."); Assert.That(cycleCount, Is.EqualTo(MinimumPartitionCount + 1), "The load balancer should have reached a balanced state once all partitions were owned and the next cycle claimed none."); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task IsBalancedIsCorrectWithMultipleProcessorsAndAnUnevenDistribution() { const int MinimumPartitionCount = 4; const int NumberOfPartitions = 13; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadBalancer = new PartitionLoadBalancer(storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); var completeOwnership = Enumerable.Empty<EventProcessorPartitionOwnership>(); // Create partitions owned by a different load balancer. var secondLoadBalancerId = Guid.NewGuid().ToString(); var secondLoadBalancerPartitions = Enumerable.Range(1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(secondLoadBalancerPartitions.Select(i => i.ToString()), secondLoadBalancerId)); // Create partitions owned by a different load balancer. var thirdLoadBalancerId = Guid.NewGuid().ToString(); var thirdLoadBalancerPartitions = Enumerable.Range(secondLoadBalancerPartitions.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(thirdLoadBalancerPartitions.Select(i => i.ToString()), thirdLoadBalancerId)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Ensure that there is exactly one more than the minimum number of partitions available to be owned. var unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(MinimumPartitionCount + 1), $"There should be { MinimumPartitionCount + 1 } partitions left unowned."); // Run load balancing cycles until the load balancer believes that the state is balanced or the minimum count is quadrupled. var cycleCount = 0; while ((!loadBalancer.IsBalanced) && (cycleCount < (MinimumPartitionCount * 4))) { await loadBalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); ++cycleCount; } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); unownedPartitions = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); Assert.That(unownedPartitions.Count(), Is.EqualTo(0), "There no partitions left unowned."); Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions), "All partitions should be owned."); Assert.That(loadBalancer.IsBalanced, Is.True, "The load balancer should believe the state is balanced when it owns the correct number of partitions."); Assert.That(cycleCount, Is.EqualTo(MinimumPartitionCount + 2), "The load balancer should have reached a balanced state once all partitions were owned and the next cycle claimed none."); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> to claim ownership of a claimable partition /// when it owns exactly the calculated MinimumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncClaimsPartitionsWhenOwnedEqualsMinimumOwnedPartitionsCount() { const int MinimumPartitionCount = 4; const int NumberOfPartitions = 13; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumPartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create partitions owned by a different load balancer. var loadbalancer3Id = Guid.NewGuid().ToString(); var loadbalancer3PartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MinimumPartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer3PartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); var claimablePartitionIds = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Count(), Is.EqualTo(MinimumPartitionCount)); Assert.That(ownedByloadbalancer1.Any(owned => claimablePartitionIds.Contains(owned.PartitionId)), Is.False); // Start the load balancer to claim ownership from of a Partition even though ownedPartitionCount == MinimumOwnedPartitionsCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Count(), Is.GreaterThan(MinimumPartitionCount)); Assert.That(ownedByloadbalancer1.Any(owned => claimablePartitionIds.Contains(owned.PartitionId)), Is.True); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> steal ownership of a partition /// from another <see cref="PartitionLoadBalancer" /> the other load balancer owns greater than the calculated MaximumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncStealsPartitionsWhenThisLoadbalancerOwnsMinPartitionsAndOtherLoadbalancerOwnsGreatherThanMaxPartitions() { const int MinimumpartitionCount = 4; const int MaximumpartitionCount = 5; const int NumberOfPartitions = 14; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var stealablePartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MaximumpartitionCount + 1); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(stealablePartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); var ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.False); // Verify load balancer 3 has stealable partitions. Assert.That(ownedByloadbalancer3.Count(), Is.GreaterThan(MaximumpartitionCount)); // Start the load balancer to steal ownership from of a when ownedPartitionCount == MinimumOwnedPartitionsCount but a loadbalancer owns > MaximumPartitionCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.True); // Verify load balancer 3 now does not own > MaximumPartitionCount. Assert.That(ownedByloadbalancer3.Count(), Is.EqualTo(MaximumpartitionCount)); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> steal ownership of a partition /// from another <see cref="PartitionLoadBalancer" /> the other load balancer owns exactly the calculated MaximumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncStealsPartitionsWhenThisLoadbalancerOwnsLessThanMinPartitionsAndOtherLoadbalancerOwnsMaxPartitions() { const int MinimumpartitionCount = 4; const int MaximumpartitionCount = 5; const int NumberOfPartitions = 12; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create more partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount - 1); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create more partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var stealablePartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MaximumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(stealablePartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); var ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.False); // Verify load balancer 3 has stealable partitions. Assert.That(ownedByloadbalancer3.Count(), Is.EqualTo(MaximumpartitionCount)); // Start the load balancer to steal ownership from of a when ownedPartitionCount == MinimumOwnedPartitionsCount but a load balancer owns > MaximumPartitionCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.True); // Verify load balancer 3 now does not own > MaximumPartitionCount. Assert.That(ownedByloadbalancer3.Count(), Is.LessThan(MaximumpartitionCount)); } /// <summary> /// Verify logs for the <see cref="PartitionLoadBalancer" />. /// </summary> /// [Test] public async Task VerifiesEventProcessorLogs() { const int NumberOfPartitions = 4; const int MinimumpartitionCount = NumberOfPartitions / 2; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var completeOwnership = CreatePartitionOwnership(partitionIds.Skip(1), loadbalancer2Id); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); var mockLog = new Mock<PartitionLoadBalancerEventSource>(); loadbalancer.Logger = mockLog.Object; for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } await loadbalancer.RelinquishOwnershipAsync(CancellationToken.None); mockLog.Verify(m => m.RenewOwnershipStart(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.RenewOwnershipComplete(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.ClaimOwnershipStart(It.Is<string>(p => partitionIds.Contains(p)))); mockLog.Verify(m => m.MinimumPartitionsPerEventProcessor(MinimumpartitionCount)); mockLog.Verify(m => m.CurrentOwnershipCount(MinimumpartitionCount, loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.StealPartition(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.ShouldStealPartition(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.UnclaimedPartitions(It.Is<HashSet<string>>(set => set.Count == 0 || set.All(item => partitionIds.Contains(item))))); } /// <summary> /// Creates a collection of <see cref="PartitionOwnership" /> based on the specified arguments. /// </summary> /// /// <param name="partitionIds">A collection of partition identifiers that the collection will be associated with.</param> /// <param name="identifier">The owner identifier of the EventProcessorClient owning the collection.</param> /// /// <returns>A collection of <see cref="PartitionOwnership" />.</returns> /// private IEnumerable<EventProcessorPartitionOwnership> CreatePartitionOwnership(IEnumerable<string> partitionIds, string identifier) { return partitionIds .Select(partitionId => new EventProcessorPartitionOwnership { FullyQualifiedNamespace = FullyQualifiedNamespace, EventHubName = EventHubName, ConsumerGroup = ConsumerGroup, OwnerIdentifier = identifier, PartitionId = partitionId, LastModifiedTime = DateTimeOffset.UtcNow, Version = Guid.NewGuid().ToString() }).ToList(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { public class Random { // // Private Constants // private const int MBIG = int.MaxValue; private const int MSEED = 161803398; private const int MZ = 0; // // Member Variables // private int _inext; private int _inextp; private int[] _seedArray = new int[56]; // // Public Constants // // // Native Declarations // // // Constructors // /*========================================================================================= **Action: Initializes a new instance of the Random class, using a default seed value ===========================================================================================*/ public Random() : this(GenerateSeed()) { } /*========================================================================================= **Action: Initializes a new instance of the Random class, using a specified seed value ===========================================================================================*/ public Random(int Seed) { int ii = 0; int mj, mk; //Initialize our Seed array. int subtraction = (Seed == int.MinValue) ? int.MaxValue : Math.Abs(Seed); mj = MSEED - subtraction; _seedArray[55] = mj; mk = 1; for (int i = 1; i < 55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position. if ((ii += 21) >= 55) ii -= 55; _seedArray[ii] = mk; mk = mj - mk; if (mk < 0) mk += MBIG; mj = _seedArray[ii]; } for (int k = 1; k < 5; k++) { for (int i = 1; i < 56; i++) { int n = i + 30; if (n >= 55) n -= 55; _seedArray[i] -= _seedArray[1 + n]; if (_seedArray[i] < 0) _seedArray[i] += MBIG; } } _inext = 0; _inextp = 21; Seed = 1; } // // Package Private Methods // /*====================================Sample==================================== **Action: Return a new random number [0..1) and reSeed the Seed array. **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ protected virtual double Sample() { //Including this division at the end gives us significantly improved //random number distribution. return (InternalSample() * (1.0 / MBIG)); } private int InternalSample() { int retVal; int locINext = _inext; int locINextp = _inextp; if (++locINext >= 56) locINext = 1; if (++locINextp >= 56) locINextp = 1; retVal = _seedArray[locINext] - _seedArray[locINextp]; if (retVal == MBIG) retVal--; if (retVal < 0) retVal += MBIG; _seedArray[locINext] = retVal; _inext = locINext; _inextp = locINextp; return retVal; } [ThreadStatic] private static Random? t_threadRandom; private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed()); /*=====================================GenerateSeed===================================== **Returns: An integer that can be used as seed values for consecutively creating lots of instances on the same thread within a short period of time. ========================================================================================*/ private static int GenerateSeed() { Random? rnd = t_threadRandom; if (rnd == null) { int seed; lock (s_globalRandom) { seed = s_globalRandom.Next(); } rnd = new Random(seed); t_threadRandom = rnd; } return rnd.Next(); } /*==================================GenerateGlobalSeed==================================== **Action: Creates a number to use as global seed. **Returns: An integer that is safe to use as seed values for thread-local seed generators. ==========================================================================================*/ private static unsafe int GenerateGlobalSeed() { int result; Interop.GetRandomBytes((byte*)&result, sizeof(int)); return result; } // // Public Instance Methods // /*=====================================Next===================================== **Returns: An int [0..int.MaxValue) **Arguments: None **Exceptions: None. ==============================================================================*/ public virtual int Next() { return InternalSample(); } private double GetSampleForLargeRange() { // The distribution of double value returned by Sample // is not distributed well enough for a large range. // If we use Sample for a range [int.MinValue..int.MaxValue) // We will end up getting even numbers only. int result = InternalSample(); // Note we can't use addition here. The distribution will be bad if we do that. bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample if (negative) { result = -result; } double d = result; d += (int.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1) d /= 2 * (uint)int.MaxValue - 1; return d; } /*=====================================Next===================================== **Returns: An int [minvalue..maxvalue) **Arguments: minValue -- the least legal value for the Random number. ** maxValue -- One greater than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next(int minValue, int maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException(nameof(minValue), SR.Format(SR.Argument_MinMaxValue, nameof(minValue), nameof(maxValue))); } long range = (long)maxValue - minValue; if (range <= int.MaxValue) { return ((int)(Sample() * range) + minValue); } else { return (int)((long)(GetSampleForLargeRange() * range) + minValue); } } /*=====================================Next===================================== **Returns: An int [0..maxValue) **Arguments: maxValue -- One more than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next(int maxValue) { if (maxValue < 0) { throw new ArgumentOutOfRangeException(nameof(maxValue), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(maxValue))); } return (int)(Sample() * maxValue); } /*=====================================Next===================================== **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ public virtual double NextDouble() { return Sample(); } /*==================================NextBytes=================================== **Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled. **Returns:Void **Arguments: buffer -- the array to be filled. **Exceptions: None ==============================================================================*/ public virtual void NextBytes(byte[] buffer) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)InternalSample(); } } public virtual void NextBytes(Span<byte> buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)Next(); } } } }
using System; using System.Linq; using System.Net; using System.Threading; using EnvDTE; using EnvDTE80; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.VersionControl.Client; using Microsoft.VisualStudio.TeamFoundation; using VsExt.AutoShelve.EventArgs; using System.Collections.Generic; // Ref http://visualstudiogallery.msdn.microsoft.com/080540cb-e35f-4651-b71c-86c73e4a633d namespace VsExt.AutoShelve { public class TfsAutoShelve : SAutoShelveService, IAutoShelveService, IDisposable { private Timer _timer; private IServiceProvider serviceProvider; private string _extensionName = Resources.ExtensionName; public TfsAutoShelve(IServiceProvider sp) { serviceProvider = sp; try { var autoResetEvent = new AutoResetEvent(false); _timer = new Timer(GetAutoShelveCallback(), autoResetEvent, Timeout.Infinite, Timeout.Infinite); } catch { } } #region IAutoShelveService private bool _isRunning = false; public bool IsRunning { get { return _isRunning; } } private ushort _maxShelvesets; public ushort MaximumShelvesets { get { return (IsDateSpecificShelvesetName) ? _maxShelvesets : (ushort)0; } set { _maxShelvesets = value; } } private string _shelvesetName; public string ShelvesetName { get { return _shelvesetName; } set { _shelvesetName = value; IsDateSpecificShelvesetName = string.Format(ShelvesetName, null, null, "IsDate", null, null).Contains("IsDate"); IsWorkspaceSpecificShelvesetName = string.Format(ShelvesetName, "IsWorkspace", null, null, null, null).Contains("IsWorkspace"); } } public double TimerInterval { get; set; } public void CreateShelveset(bool force = false) { try { if (TfsExt == null) return; var domainUri = WebUtility.UrlDecode(_tfsExt.ActiveProjectContext.DomainUri); var teamProjectCollection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(domainUri)); teamProjectCollection.Credentials = CredentialCache.DefaultNetworkCredentials; teamProjectCollection.EnsureAuthenticated(); var service = (VersionControlServer)teamProjectCollection.GetService(typeof(VersionControlServer)); var allLocalWorkspaceInfo = Workstation.Current.GetAllLocalWorkspaceInfo(); foreach (var workspaceInfo in allLocalWorkspaceInfo) { // Replace(/,"") before comparing domainUri to prevent: "TFS Auto Shelve shelved 0 pending changes. Shelveset Name: " if (workspaceInfo.MappedPaths.Length <= 0 || workspaceInfo.ServerUri.ToString().Replace("/", string.Empty) != domainUri.Replace("/", string.Empty)) continue; var workspace = service.GetWorkspace(workspaceInfo); CreateShelveset(service, workspace, force); } } catch (Exception ex) { _tfsExt = null; // Force re-init on next attempt if (OnShelvesetCreated != null) { var autoShelveEventArg = new ShelvesetCreatedEventArgs { ExecutionException = ex }; OnShelvesetCreated(this, autoShelveEventArg); } } } #region Events public event EventHandler<ShelvesetCreatedEventArgs> OnShelvesetCreated; public event EventHandler<TfsConnectionErrorEventArgs> OnTfsConnectionError; public event EventHandler OnStart; public event EventHandler OnStop; #endregion #endregion #region Private Members private bool IsDateSpecificShelvesetName { get; set; } private bool IsWorkspaceSpecificShelvesetName { get; set; } private TeamFoundationServerExt _tfsExt; private TeamFoundationServerExt TfsExt { get { if (_tfsExt != null) return _tfsExt; try { DTE2 dte = (DTE2)this.serviceProvider.GetService(typeof(DTE)); var obj = (TeamFoundationServerExt)dte.GetObject("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt"); if (obj.ActiveProjectContext.DomainUri == null) throw new NullReferenceException("Microsoft.VisualStudio.TeamFoundation.TeamFoundationServerExt.ActiveProjectContext.DomainUri cannot be null"); else _tfsExt = obj; } catch (Exception ex) { Stop(); // Disable timer to prevent Ref: Q&A "endless error dialogs" @ http://visualstudiogallery.msdn.microsoft.com/080540cb-e35f-4651-b71c-86c73e4a633d if (OnTfsConnectionError != null) { OnTfsConnectionError(this, new TfsConnectionErrorEventArgs{ConnectionError = ex }); } } return _tfsExt; } } private string CleanShelvesetName(string shelvesetName) { if (!string.IsNullOrWhiteSpace(shelvesetName)) { string cleanName = shelvesetName.Replace("/", string.Empty).Replace(":", string.Empty).Replace("<", string.Empty).Replace(">", string.Empty).Replace("\\", string.Empty).Replace("|", string.Empty).Replace("*", string.Empty).Replace("?", string.Empty).Replace(";", string.Empty); if (cleanName.Length > 64) { return cleanName.Substring(0, 63); } return cleanName; } return shelvesetName; } /// <summary> /// /// </summary> /// <param name="service"></param> /// <param name="workspace"></param> /// <param name="force">True when the user manually initiates a ShelveSet via the Team menu or mapped shortcut key.</param> private void CreateShelveset(VersionControlServer service, Workspace workspace, bool force) { // Build event args for notification create shelveset result var autoShelveEventArg = new ShelvesetCreatedEventArgs(); autoShelveEventArg.ShelvesetChangeCount = 0; // Shouldn't be necessary, but forcing it to be safe. try { // If there are no pending changes that have changed since the last shelveset then there is nothing to do bool isDelta = false; var pendingChanges = workspace.GetPendingChanges(); int numPending = pendingChanges.Count(); if (numPending > 0) { if (!force) { var lastShelveset = GetPastShelvesets(service, workspace).FirstOrDefault(); if (lastShelveset == null) { // If there are pending changes and no shelveset yet exists, then create shelveset. isDelta = true; } else { // Compare numPending to shelvedChanges.Count(); Force shelveset if they differ // Otherwise, resort to comparing file HashValues var shelvedChanges = service.QueryShelvedChanges(lastShelveset).FirstOrDefault(); isDelta = (shelvedChanges == null || numPending != shelvedChanges.PendingChanges.Count()) || pendingChanges.DifferFrom(shelvedChanges.PendingChanges); } } if (force || isDelta) { autoShelveEventArg.ShelvesetChangeCount = numPending; // Build a new, valid shelve set name var setname = string.Format(ShelvesetName, workspace.Name, workspace.OwnerName, DateTime.Now, workspace.OwnerName.GetDomain(), workspace.OwnerName.GetLogin()); setname = CleanShelvesetName(setname); // Actually create a new Shelveset var shelveset = new Shelveset(service, setname, workspace.OwnerName); autoShelveEventArg.ShelvesetName = setname; shelveset.Comment = string.Format("Shelved by {0}. {1} items", _extensionName, numPending); workspace.Shelve(shelveset, pendingChanges, ShelvingOptions.Replace); // Clean up past Shelvesets if (MaximumShelvesets > 0) { foreach (var set in GetPastShelvesets(service, workspace).Skip(MaximumShelvesets)) { service.DeleteShelveset(set); autoShelveEventArg.ShelvesetsPurgeCount++; } } } } } catch (Exception ex) { _tfsExt = null; // Force re-init on next attempt autoShelveEventArg.ExecutionException = ex; } // Fire event for each VS instance to report results if (OnShelvesetCreated != null) { OnShelvesetCreated(this, autoShelveEventArg); } } private IEnumerable<Shelveset> GetPastShelvesets(VersionControlServer service, Workspace workspace) { var pastShelvesets = service.QueryShelvesets(null, workspace.OwnerName).Where(s => s.Comment != null && s.Comment.Contains(_extensionName)); if (pastShelvesets != null && pastShelvesets.Count() > 0) { if (IsWorkspaceSpecificShelvesetName) { pastShelvesets = pastShelvesets.Where(s => s.Name.Contains(workspace.Name)); } return pastShelvesets.OrderByDescending(s => s.CreationDate); } else { return pastShelvesets; } } #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } //// NOTE: Leave out the finalizer altogether if this class doesn't //// own unmanaged resources itself, but leave the other methods //// exactly as they are. //~TfsAutoShelve() //{ // // Finalizer calls Dispose(false) // Dispose(false); //} // The bulk of the clean-up code is implemented in Dispose(bool) protected virtual void Dispose(bool disposeManaged) { if (_timer != null) { _timer.Dispose(); } } #endregion private TimerCallback GetAutoShelveCallback() { TimerCallback timerCallback = state => { CreateShelveset(); } ; return timerCallback; } public void Start() { _timer.Change(TimeSpan.FromMinutes(TimerInterval), TimeSpan.FromMinutes(TimerInterval)); _isRunning = true; if (OnStart != null) { OnStart(this, new System.EventArgs()); } } public void Stop() { if (!_isRunning) return; _timer.Change(Timeout.Infinite, Timeout.Infinite); _isRunning = false; if (OnStop != null) { OnStop(this, new System.EventArgs()); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestNotZAndNotCSByte() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanTwoComparisonOpTest__TestNotZAndNotCSByte { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(SByte); private const int Op2ElementCount = VectorSize / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private BooleanTwoComparisonOpTest__DataTable<SByte, SByte> _dataTable; static BooleanTwoComparisonOpTest__TestNotZAndNotCSByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); } public BooleanTwoComparisonOpTest__TestNotZAndNotCSByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (sbyte)(random.Next(sbyte.MinValue, sbyte.MaxValue)); } _dataTable = new BooleanTwoComparisonOpTest__DataTable<SByte, SByte>(_data1, _data2, VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.TestNotZAndNotC( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Avx.TestNotZAndNotC( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Avx.TestNotZAndNotC( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() {var method = typeof(Avx).GetMethod(nameof(Avx.TestNotZAndNotC), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Avx.TestNotZAndNotC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCSByte(); var result = Avx.TestNotZAndNotC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Avx.TestNotZAndNotC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(SByte[] left, SByte[] right, bool result, [CallerMemberName] string method = "") { var expectedResult1 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult1 &= (((left[i] & right[i]) == 0)); } var expectedResult2 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult2 &= (((~left[i] & right[i]) == 0)); } if (((expectedResult1 == false) && (expectedResult2 == false)) != result) { Succeeded = false; Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestNotZAndNotC)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using XCommon.Application.Authentication; using XCommon.Application.Authentication.Entity; using XCommon.Application.Executes; using XCommon.Entity.Register; using XCommon.Entity.Register.Enumerators; using XCommon.Entity.Register.Filter; using XCommon.EF.Application.Register.Interface; using XCommon.Patterns.Ioc; using XCommon.Patterns.Repository.Entity; using XCommon.Patterns.Specification.Validation; using XCommon.Util; using System.Linq; namespace XCommon.EF.Application.Authentication { public class LoginBusiness : ILoginBusiness { #region Inject [Inject] private ITicketManager TicketManager { get; set; } [Inject] private IPeopleBusiness PeopleBusiness { get; set; } [Inject] private IUsersBusiness UsersBusiness { get; set; } [Inject] private IUsersProvidersBusiness UsersProvidersBusiness { get; set; } [Inject] private IUsersRolesBusiness UsersRolesBusiness { get; set; } [Inject] private ISpecificationValidation<SignInEntity> ValidateSignIn { get; set; } [Inject] private ISpecificationValidation<SignUpEntity> ValidateSignUp { get; set; } #endregion public LoginBusiness() { Kernel.Resolve(this); } #region Public Methods public virtual async Task<Execute> ChangePasswordAsync(PasswordChangeEntity info) { var result = new Execute(); var user = await UsersBusiness.GetByKeyAsync(TicketManager.UserKey); if (user == null) { result.AddError(Resources.Authentication.InvalidUserPassword); return result; } if (!await VerifyPasswordHashAsync(user, info.PasswordCurrent)) { result.AddError(Resources.Authentication.PasswordNotMatch); return result; } if (info.PasswordNew != info.PasswordConfirm) { } user.Action = EntityAction.Update; user.PasswordHash = await GetPasswordHashAsync(user, info.PasswordNew); result.AddMessage(await UsersBusiness.SaveAsync(user)); return result; } public virtual async Task<Execute> ConfirmEmailAsync(Guid userKey, string token) { throw new NotImplementedException(); } public virtual async Task<Execute> ConfirmPhoneAsync(Guid userKey, string token) { var result = new Execute(); var user = await UsersBusiness.GetByKeyAsync(userKey); return result; } public virtual async Task<Execute> RecoveryPasswordAsync(PasswordRecoveryEntity info) { throw new NotImplementedException(); } public virtual async Task<Execute> RecoveryPasswordRequestTokenAsync(string email) { throw new NotImplementedException(); } public virtual async Task<Execute> RecoveryPasswordValidateTokenAsync(Guid userKey, string token) { throw new NotImplementedException(); } public virtual async Task<Execute<TicketEntity>> SignInAsync(SignInEntity signIn) { var result = new Execute<TicketEntity>(); if (!await ValidateSignIn.IsSatisfiedByAsync(signIn, result)) { return result; } var person = await PeopleBusiness.GetFirstByFilterAsync(new PeopleFilter { Email = signIn.User }); if (person == null) { result.AddMessage(ExecuteMessageType.Error, Resources.Authentication.InvalidUserPassword); return result; } var user = await UsersBusiness.GetByKeyAsync(person.IdPerson); if (user == null) { result.AddMessage(ExecuteMessageType.Error, Resources.Authentication.InvalidUserPassword); return result; } if (signIn.Provider == ProviderType.Local) { if (!await VerifyPasswordHashAsync(user, signIn.Password)) { result.AddMessage(ExecuteMessageType.Error, Resources.Authentication.InvalidUserPassword); return result; } result.Entity = new TicketEntity { Culture = person.Culture, Key = person.IdPerson, Name = person.Name, Roles = await GetUserRolesAsync(user) }; await SetTicketCustomValuesAsync(result.Entity); return result; } var provider = await UsersProvidersBusiness.GetFirstByFilterAsync(new UsersProvidersFilter { IdUser = person.IdPerson, Provider = signIn.Provider }); if (provider == null) { result.AddMessage(ExecuteMessageType.Error, Resources.Authentication.InvalidUserPassword); return result; } result.Entity = new TicketEntity { Culture = person.Culture, Key = person.IdPerson, Name = person.Name, Roles = await GetUserRolesAsync(user) }; await SetTicketCustomValuesAsync(result.Entity); return result; } public async Task<Execute<TicketEntity>> SignUpAsync(SignUpEntity signUp) { var result = new Execute<TicketEntity>(); if (!await ValidateSignUp.IsSatisfiedByAsync(signUp, result)) { return result; } var (person, user, provider) = await CastNewUser(signUp); using (var db = new Context.XCommonDbContext()) { using (var transaction = await db.Database.BeginTransactionAsync()) { result.AddMessage(await PeopleBusiness.SaveAsync(person, db)); result.AddMessage(await UsersBusiness.SaveAsync(user, db)); result.AddMessage(await UsersProvidersBusiness.SaveAsync(provider, db)); if (!result.HasErro) { transaction.Commit(); } } } if (!result.HasErro) { result.Entity = new TicketEntity { Culture = person.Culture, Key = person.IdPerson, Name = person.Name, Roles = await GetUserRolesAsync(user) }; } return result; } #endregion #region Protected protected virtual async Task SetTicketCustomValuesAsync(TicketEntity ticket) { await Task.Yield(); } protected virtual async Task<List<string>> GetUserRolesAsync(UsersEntity user) { var result = await UsersRolesBusiness.GetByFilterAsync(new UsersRolesFilter { IdUser = user.IdUser }); return result.Select(c => c.Role).ToList(); } protected virtual async Task<string> GetPasswordHashAsync(UsersEntity user, string password) { return await Task.FromResult(Hash.GetMD5(password)); } protected virtual async Task<bool> VerifyPasswordHashAsync(UsersEntity user, string input) { return await Task.FromResult(Hash.VerifyMD5(input, user.PasswordHash)); } protected virtual async Task<(PeopleEntity person, UsersEntity user, UsersProvidersEntity provider)> CastNewUser(SignUpEntity signUp) { var person = new PeopleEntity { Action = EntityAction.New, IdPerson = Guid.NewGuid(), Name = signUp.Name, Email = signUp.Email, Birthday = signUp.BirthDay, Culture = signUp.Language, Gender = signUp.Male ? GenderType.Male : GenderType.Female, CreatedAt = DateTime.Now, ChangedAt = DateTime.Now, ImageCover = signUp.UrlCover, ImageProfile = signUp.UrlImage }; var user = new UsersEntity { Action = EntityAction.New, IdUser = person.IdPerson, IdPerson = person.IdPerson, AccessFailedCount = 0, EmailConfirmed = false, LockoutEnabled = false, PasswordHash = string.Empty, PhoneConfirmed = false, ProfileComplete = false }; if (signUp.Provider == ProviderType.Local) { user.PasswordHash = await GetPasswordHashAsync(user, signUp.Password); } var userProvider = new UsersProvidersEntity { Action = EntityAction.New, IdUserProvide = Guid.NewGuid(), IdUser = person.IdPerson, Provider = signUp.Provider, ProviderDefault = true, ProviderToken = signUp.Token, ProviderUrlCover = signUp.UrlCover, ProviderUrlImage = signUp.UrlImage }; return await Task.FromResult((person, user, userProvider)); } #endregion } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\EnvironmentQuery\Tests\EnvQueryTest_Trace.h:18 namespace UnrealEngine { [ManageType("ManageEnvQueryTest_Trace")] public partial class ManageEnvQueryTest_Trace : UEnvQueryTest_Trace, IManageWrapper { public ManageEnvQueryTest_Trace(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_UpdateNodeVersion(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UEnvQueryTest_Trace_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods public override void UpdateNodeVersion() => E__Supper__UEnvQueryTest_Trace_UpdateNodeVersion(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UEnvQueryTest_Trace_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UEnvQueryTest_Trace_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UEnvQueryTest_Trace_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UEnvQueryTest_Trace_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UEnvQueryTest_Trace_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UEnvQueryTest_Trace_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UEnvQueryTest_Trace_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UEnvQueryTest_Trace_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UEnvQueryTest_Trace_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UEnvQueryTest_Trace_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UEnvQueryTest_Trace_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UEnvQueryTest_Trace_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UEnvQueryTest_Trace_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UEnvQueryTest_Trace_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UEnvQueryTest_Trace_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManageEnvQueryTest_Trace self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManageEnvQueryTest_Trace(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManageEnvQueryTest_Trace>(PtrDesc); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.AccessControl; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32; using NuGet; using Splat; namespace Squirrel { public sealed partial class UpdateManager : IUpdateManager, IEnableLogger { readonly string rootAppDirectory; readonly string applicationName; readonly IFileDownloader urlDownloader; readonly string updateUrlOrPath; IDisposable updateLock; public UpdateManager(string urlOrPath, string applicationName = null, string rootDirectory = null, IFileDownloader urlDownloader = null) { Contract.Requires(!String.IsNullOrEmpty(urlOrPath)); Contract.Requires(!String.IsNullOrEmpty(applicationName)); updateUrlOrPath = urlOrPath; this.applicationName = applicationName ?? UpdateManager.getApplicationName(); this.urlDownloader = urlDownloader ?? new FileDownloader(); if (rootDirectory != null) { this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName); return; } this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName); } public async Task<UpdateInfo> CheckForUpdate(bool ignoreDeltaUpdates = false, Action<int> progress = null) { var checkForUpdate = new CheckForUpdateImpl(rootAppDirectory); await acquireUpdateLock(); return await checkForUpdate.CheckForUpdate(Utility.LocalReleaseFileForAppDir(rootAppDirectory), updateUrlOrPath, ignoreDeltaUpdates, progress, urlDownloader); } public async Task DownloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null) { var downloadReleases = new DownloadReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await downloadReleases.DownloadReleases(updateUrlOrPath, releasesToDownload, progress, urlDownloader); } public async Task<string> ApplyReleases(UpdateInfo updateInfo, Action<int> progress = null) { var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); return await applyReleases.ApplyReleases(updateInfo, false, false, progress); } public async Task FullInstall(bool silentInstall = false, Action<int> progress = null) { var updateInfo = await CheckForUpdate(); await DownloadReleases(updateInfo.ReleasesToApply); var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await applyReleases.ApplyReleases(updateInfo, silentInstall, true, progress); } public async Task FullUninstall() { var applyReleases = new ApplyReleasesImpl(rootAppDirectory); await acquireUpdateLock(); await applyReleases.FullUninstall(); } public Task<RegistryKey> CreateUninstallerRegistryEntry(string uninstallCmd, string quietSwitch) { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); return installHelpers.CreateUninstallerRegistryEntry(uninstallCmd, quietSwitch); } public Task<RegistryKey> CreateUninstallerRegistryEntry() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); return installHelpers.CreateUninstallerRegistryEntry(); } public void RemoveUninstallerRegistryEntry() { var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory); installHelpers.RemoveUninstallerRegistryEntry(); } public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); installHelpers.CreateShortcutsForExecutable(exeName, locations, updateOnly); } public void RemoveShortcutsForExecutable(string exeName, ShortcutLocation locations) { var installHelpers = new ApplyReleasesImpl(rootAppDirectory); installHelpers.RemoveShortcutsForExecutable(exeName, locations); } public Version CurrentlyInstalledVersion(string executable = null) { executable = executable ?? Path.GetDirectoryName(typeof(UpdateManager).Assembly.Location); if (!executable.StartsWith(rootAppDirectory, StringComparison.OrdinalIgnoreCase)) { return null; } var appDirName = executable.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) .FirstOrDefault(x => x.StartsWith("app-", StringComparison.OrdinalIgnoreCase)); if (appDirName == null) return null; return appDirName.ToVersion(); } public string ApplicationName { get { return applicationName; } } public string RootAppDirectory { get { return rootAppDirectory; } } public bool IsInstalledApp { get { return Assembly.GetExecutingAssembly().Location.StartsWith(RootAppDirectory, StringComparison.OrdinalIgnoreCase); } } public void Dispose() { var disp = Interlocked.Exchange(ref updateLock, null); if (disp != null) { disp.Dispose(); } } static bool exiting = false; public static void RestartApp(string exeToStart = null, string arguments = null) { // NB: Here's how this method works: // // 1. We're going to pass the *name* of our EXE and the params to // Update.exe // 2. Update.exe is going to grab our PID (via getting its parent), // then wait for us to exit. // 3. We exit cleanly, dropping any single-instance mutexes or // whatever. // 4. Update.exe unblocks, then we launch the app again, possibly // launching a different version than we started with (this is why // we take the app's *name* rather than a full path) exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location); var argsArg = arguments != null ? String.Format("-a \"{0}\"", arguments) : ""; exiting = true; Process.Start(getUpdateExe(), String.Format("--processStartAndWait {0} {1}", exeToStart, argsArg)); // NB: We have to give update.exe some time to grab our PID, but // we can't use WaitForInputIdle because we probably don't have // whatever WaitForInputIdle considers a message loop. Thread.Sleep(500); Environment.Exit(0); } public static string GetLocalAppDataDirectory(string assemblyLocation = null) { // Try to divine our our own install location via reading tea leaves // // * We're Update.exe, running in the app's install folder // * We're Update.exe, running on initial install from SquirrelTemp // * We're a C# EXE with Squirrel linked in var assembly = Assembly.GetEntryAssembly(); if (assemblyLocation == null && assembly == null) { // dunno lol return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } assemblyLocation = assemblyLocation ?? assembly.Location; if (Path.GetFileName(assemblyLocation).Equals("update.exe", StringComparison.OrdinalIgnoreCase)) { // NB: Both the "SquirrelTemp" case and the "App's folder" case // mean that the root app dir is one up var oneFolderUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), ".."); return Path.GetFullPath(oneFolderUpFromAppFolder); } var twoFoldersUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..\\.."); return Path.GetFullPath(twoFoldersUpFromAppFolder); } ~UpdateManager() { if (updateLock != null && !exiting) { throw new Exception("You must dispose UpdateManager!"); } } Task<IDisposable> acquireUpdateLock() { if (updateLock != null) return Task.FromResult(updateLock); return Task.Run(() => { var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory))); IDisposable theLock; try { theLock = ModeDetector.InUnitTestRunner() ? Disposable.Create(() => {}) : new SingleGlobalInstance(key, TimeSpan.FromMilliseconds(2000)); } catch (TimeoutException) { throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates"); } var ret = Disposable.Create(() => { theLock.Dispose(); updateLock = null; }); updateLock = ret; return ret; }); } static string getApplicationName() { var fi = new FileInfo(getUpdateExe()); return fi.Directory.Name; } static string getUpdateExe() { var assembly = Assembly.GetEntryAssembly(); // Are we update.exe? if (assembly != null && Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) && assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 && assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1) { return Path.GetFullPath(assembly.Location); } assembly = Assembly.GetExecutingAssembly(); var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe"); var target = new FileInfo(updateDotExe); if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?"); return target.FullName; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.IO; using System.Globalization; using NeuralNetworkLib; namespace OnlabNeuralis { public class NeuralModelSimulator : IModelSimulator { MLPDll mlp; public const double MAX_NEURON_VALUE = 1; public const double MIN_NEURON_VALUE = -1; private const int EPOCH_COUNT = 10000; public NeuralModelSimulator() { mlp = new MLPDll(new int[] { 50, 4 }, 7); } //public NeuralModelSimulator(String filename) //{ // mlp = new MLPDll(filename); //} public void Train(IModelSimulator sourceSimulator, double treshold) { Random r = new Random(); double mu = 0.0001; long count = 0; double errors = 0, errors2 = double.MaxValue; double[] error = new double[4]; do { for (int i2 = 0; i2 < EPOCH_COUNT; ++i2) { double angle = r.NextDouble() * 2 * Math.PI;//veletlen szog CarModelState carstate = new CarModelState(new PointD(ComMath.Normal(r.NextDouble(), 0, 1, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), ComMath.Normal(r.NextDouble(), 0, 1, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), new PointD(ComMath.Normal(Math.Cos(angle), -1, 1, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY), ComMath.Normal(Math.Sin(angle), -1, 1, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY))); CarModelInput carinput = new CarModelInput(); //= new CarModelInput(ComMath.Normal(r.NextDouble(), 0, 1, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED), // ComMath.Normal(r.NextDouble(), 0, 1, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED)); carinput.Angle = ComMath.Normal(r.NextDouble(), 0, 1, CarModelInput.MIN_ANGLE, CarModelInput.MAX_ANGLE); CarModelState state, state2; double[] output; sourceSimulator.SimulateModel(carstate, carinput, out state); this.SimulateModel(carstate, carinput, out state2, out output); error = new double[4]; error[0] = -output[0] + ComMath.Normal(state.Position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); error[1] = -output[1] + ComMath.Normal(state.Position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); error[2] = -output[2] + ComMath.Normal(state.Orientation.X, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); error[3] = -output[3] + ComMath.Normal(state.Orientation.Y, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); count++; mlp.Train(mu, error); errors += error[0] * error[0] + error[1] * error[1] + error[2] * error[2] + error[3] * error[3]; } errors /= EPOCH_COUNT; //if (errors2 < errors) mu *= 0.75; errors2 = errors; System.Console.WriteLine(errors.ToString()); } while (errors > treshold); // mlp.SaveNN("neuralmodel.mlp"); } //dont use, not fully implemented /*public void TrainLM(IModelSimulator sourceSimulator, double treshold) { List<TrainingPoint> tp = NeuralModelSimulator.GenerateTrainingPoints(sourceSimulator, 11); double error; do { error = mlp.TrainLM(tp); System.Console.WriteLine(error.ToString()); } while (error > treshold); } */ //public static List<TrainingPoint> GenerateTrainingPoints(IModelSimulator sourceSimulator, int cc) //{ // List<TrainingPoint> tp = new List<TrainingPoint>(); // TextWriter tw = new StreamWriter("trainingpoints.dat"); // for (int i1 = 0; i1 < cc; ++i1) // { // for (int i2 = 0; i2 < cc; ++i2) // { // for (int i3 = 0; i3 < cc; ++i3) // { // for (int i4 = 0; i4 < cc; ++i4) // { // for (int i5 = 0; i5 < cc; ++i5) // { // double angle = ComMath.Normal(i3, 0, cc - 1, 0, 2 * Math.PI); // double[] input = new double[6]; // input[0] = ComMath.Normal(i1, 0, cc - 1, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // input[1] = ComMath.Normal(i2, 0, cc - 1, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // input[2] = ComMath.Normal(Math.Cos(angle), -1, 1, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // input[3] = ComMath.Normal(Math.Sin(angle), -1, 1, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // input[4] = ComMath.Normal(i4, 0, cc - 1, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // input[5] = ComMath.Normal(i5, 0, cc - 1, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // CarModelState carstate = new CarModelState(new PointD(ComMath.Normal(input[0], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X), // ComMath.Normal(input[1], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y)), // new PointD(ComMath.Normal(input[2], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY), // ComMath.Normal(input[3], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY))); // CarModelInput carinput = new CarModelInput(ComMath.Normal(input[4], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED), // ComMath.Normal(input[5], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED)); // CarModelState state; // sourceSimulator.SimulateModel(carstate, carinput, out state); // double[] desiredOutput = new double[4]; // desiredOutput[0] = ComMath.Normal(state.Position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // desiredOutput[1] = ComMath.Normal(state.Position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // desiredOutput[2] = ComMath.Normal(state.Orientation.X, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // desiredOutput[3] = ComMath.Normal(state.Orientation.Y, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); // tp.Add(new TrainingPoint(input, desiredOutput)); // for (int ii = 0; ii < input.Length; ii++) // { // tw.Write(String.Format(CultureInfo.InvariantCulture, "{0:0.###############}", input[ii]) + ","); // } // for (int ii = 0; ii < desiredOutput.Length - 1; ii++) // { // tw.Write(String.Format(CultureInfo.InvariantCulture, "{0:0.###############}", desiredOutput[ii]) + ","); // } // tw.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:0.###############}", desiredOutput[desiredOutput.Length - 1])); // } // } // } // } // } // tw.Flush(); // tw.Close(); // return tp; //} #region ModelSimulator Members public void SimulateModel(CarModelState state, CarModelInput input, out CarModelState output) { SimulateModel(state, input, CarModel.SIMULATION_TIME_STEP, out output); } public void SimulateModel(CarModelState state, CarModelInput input, out CarModelState output, out double[] NNOutput) { SimulateModel(state, input, CarModel.SIMULATION_TIME_STEP, out output, out NNOutput); } public void SimulateModel(CarModelState state, CarModelInput input, double timeStep, out CarModelState output) { double[] NNout; SimulateModel(state, input, timeStep, out output, out NNout); } public void SimulateModel(CarModelState state, CarModelInput input, double timeStep, out CarModelState output, out double[] NNOutput) { double[] inputs = new double[7]; if (NeuralController.INPUT_TYPE == inputType.wheelAngle) { inputs[6] = ComMath.Normal(input.Angle, CarModelInput.MIN_ANGLE, CarModelInput.MAX_ANGLE, MIN_NEURON_VALUE, MAX_NEURON_VALUE); } else if (NeuralController.INPUT_TYPE == inputType.wheelSpeed) { inputs[4] = ComMath.Normal(input.LeftSpeed, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED, MIN_NEURON_VALUE, MAX_NEURON_VALUE); inputs[5] = ComMath.Normal(input.RightSpeed, CarModelInput.MIN_SPEED, CarModelInput.MAX_SPEED, MIN_NEURON_VALUE, MAX_NEURON_VALUE); } inputs[0] = ComMath.Normal(state.Position.X, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X, MIN_NEURON_VALUE, MAX_NEURON_VALUE); inputs[1] = ComMath.Normal(state.Position.Y, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y, MIN_NEURON_VALUE, MAX_NEURON_VALUE); inputs[2] = ComMath.Normal(state.Orientation.X, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); inputs[3] = ComMath.Normal(state.Orientation.Y, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY, MIN_NEURON_VALUE, MAX_NEURON_VALUE); NNOutput = mlp.Output(inputs); double X = ComMath.Normal(NNOutput[0], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_POS_X, CarModelState.MAX_POS_X); double Y = ComMath.Normal(NNOutput[1], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_POS_Y, CarModelState.MAX_POS_Y); double oX = ComMath.Normal(NNOutput[2], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY); double oY = ComMath.Normal(NNOutput[3], MIN_NEURON_VALUE, MAX_NEURON_VALUE, CarModelState.MIN_OR_XY, CarModelState.MAX_OR_XY); output = new CarModelState(new PointD(X, Y), new PointD(oX, oY)); } public void CalcErrorSensibility(double[] errors, out double[] sensitibility) { mlp.SetOutputError(errors); mlp.Backpropagate(); sensitibility = mlp.SensitibilityD(); } public IModelSimulator Clone() { NeuralModelSimulator ret = new NeuralModelSimulator(); ret.mlp = new MLPDll(this.mlp); return ret; } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; namespace WebsitePanel.Providers.Mail { [Serializable] public class MailAccount : ServiceProviderItem { private bool enabled = true; private string password; private string replyTo; private bool responderEnabled; private string responderSubject; private string responderMessage; private string firstName; // SM private string lastName; // SM private bool deleteOnForward; private string[] forwardingAddresses; private string signature; private bool passwordLocked; private int maxMailboxSize; private bool changePassword; private bool isDomainAdmin; private bool isDomainAdminEnabled; private bool retainLocalCopy; public bool UnlimitedSize { get { return (maxMailboxSize < 0); } set { if (value) { maxMailboxSize = 0; } } } public string ReplyTo { get { return this.replyTo; } set { this.replyTo = value; } } public string ResponderSubject { get { return this.responderSubject; } set { this.responderSubject = value; } } public string ResponderMessage { get { return this.responderMessage; } set { this.responderMessage = value; } } public bool ResponderEnabled { get { return this.responderEnabled; } set { this.responderEnabled = value; } } public bool Enabled { get { return this.enabled; } set { this.enabled = value; } } [Persistent] public string Password { get { return this.password; } set { this.password = value; } } #region SmarterMail /// <summary> /// First Name /// </summary> public string FirstName { get { return firstName; } set { firstName = value; } } /// <summary> /// Last name /// </summary> public string LastName { get { return lastName; } set { lastName = value; } } public bool DeleteOnForward { get { return deleteOnForward; } set { deleteOnForward = value; } } public string[] ForwardingAddresses { get { return forwardingAddresses; } set { forwardingAddresses = value; } } public string Signature { get { return signature; } set { signature = value; } } public bool IsDomainAdminEnabled { get { return isDomainAdminEnabled; } set { isDomainAdminEnabled = value; } } public bool IsDomainAdmin { get { return isDomainAdmin; } set { isDomainAdmin = value; } } public bool PasswordLocked { get { return passwordLocked; } set { passwordLocked = value; } } public int MaxMailboxSize { get { return maxMailboxSize; } set { maxMailboxSize = value; } } public bool ChangePassword { get { return changePassword; } set { changePassword = value; } } #endregion #region MDaemon public bool RetainLocalCopy { get { return retainLocalCopy; } set { retainLocalCopy = value; } } #endregion #region hMailServer public bool SignatureEnabled { get; set; } public string SignatureHTML { get; set; } public bool ForwardingEnabled { get; set; } public long Size { get; set; } public string LastLogonTime { get; set; } public long QuotaUsed { get; set; } public bool ResponderExpires {get;set;} public string ResponderExpirationDate { get; set; } #endregion #region IceWarp public int IceWarpAccountType { get; set; } public int IceWarpAccountState { get; set; } public int IceWarpRespondType { get; set; } public bool RespondOnlyBetweenDates { get; set; } // Added this because Calendar Control used did not allow null values public DateTime RespondFrom { get; set; } public DateTime RespondTo { get; set; } public string RespondWithReplyFrom { get; set; } public int RespondPeriodInDays { get; set; } public bool DeleteOlder { get; set; } public int DeleteOlderDays { get; set; } public bool ForwardOlder { get; set; } public int ForwardOlderDays { get; set; } public string ForwardOlderTo { get; set; } public int MaxMessageSizeMegaByte { get; set; } public int MegaByteSendLimit { get; set; } public int NumberSendLimit { get; set; } public string FullName { get; set; } #endregion } }
// Copyright 2018 Esri. // // 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 Android.App; using Android.OS; using Android.Widget; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Rasters; using Esri.ArcGISRuntime.UI.Controls; using System; using System.Collections.Generic; using System.Linq; using ArcGISRuntime.Samples.Managers; namespace ArcGISRuntime.Samples.RasterRgbRenderer { [Activity (ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData("7c4c679ab06a4df19dc497f577f111bd")] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "RGB renderer", category: "Layers", description: "Apply an RGB renderer to a raster layer to enhance feature visibility.", instructions: "Choose one of the stretch parameter types. The other options will adjust based on the chosen type. Add your inputs and select the 'Update' button to update the renderer.", tags: new[] { "analysis", "color", "composite", "imagery", "multiband", "multispectral", "pan-sharpen", "photograph", "raster", "spectrum", "stretch", "visualization" })] public class RasterRgbRenderer : Activity { // Reference to the MapView used in the sample. private MapView _myMapView; // Reference to the raster layer to render. private RasterLayer _rasterLayer; // Layout panels to contain the UI for entering different renderer parameters. private LinearLayout _minMaxLayout; private LinearLayout _percentClipLayout; private LinearLayout _stdDeviationLayout; // Spinner for choosing the type of parameters input to use. private Spinner _parameterInputTypeSpinner; // Input controls for minimum and maximum RGB parameter values. private Spinner _minRedSpinner; private Spinner _minGreenSpinner; private Spinner _minBlueSpinner; private Spinner _maxRedSpinner; private Spinner _maxGreenSpinner; private Spinner _maxBlueSpinner; // Input controls for minimum and maximum percent clip values. private SeekBar _minPercentClipSlider; private SeekBar _maxPercentClipSlider; // Input control for the standard deviation factor value. private Spinner _stdDeviationFactorSpinner; // Button to apply the renderer. private Button _applyRendererButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Raster RGB renderer"; // Create the UI for inputting renderer parameters. CreateLayout(); // Initialize the map and raster layer. Initialize(); } private void CreateLayout() { #region UI for selecting parameter type and applying the renderer // Create a vertical layout for the page. LinearLayout mainLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add some padding to the layout. mainLayout.SetPadding(20, 0, 0, 5); // Create a horizontal layout for the parameter type list and button to apply the renderer. LinearLayout parameterTypeLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal }; string[] stretchTypes = { "Min Max", "Percent Clip", "Standard Deviation" }; ArrayAdapter<string> stretchTypesAdapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, stretchTypes); // Create the spinner control for choosing the stretch parameter input type and handle its ItemSelected event. _parameterInputTypeSpinner = new Spinner(this) { Adapter = stretchTypesAdapter, DropDownWidth = 340 }; _parameterInputTypeSpinner.ItemSelected += ParameterInputTypeSpinner_ItemSelected; // Create the button that applies the renderer and handle its Click event. _applyRendererButton = new Button(this) { Text = "Apply", Enabled = false }; _applyRendererButton.Click += ApplyRendererButton_Click; // Add a label, parameter type spinner control, and the apply button. TextView parameterTypeTextView = new TextView(this) { Text = "Stretch type: " }; parameterTypeLayout.AddView(parameterTypeTextView); parameterTypeLayout.AddView(_parameterInputTypeSpinner); parameterTypeLayout.AddView(_applyRendererButton); // Add the parameter UI choice controls to the main layout. mainLayout.AddView(parameterTypeLayout); #endregion #region UI for defining min/max RGB values // Create a horizontal layout for the min/max RGB inputs. _minMaxLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal }; // Create a range of values from 0-255 and an adapter to display them. int[] minMaxValues = Enumerable.Range(0, 256).ToArray(); ArrayAdapter<int> minMaxValuesAdapter = new ArrayAdapter<int>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, minMaxValues); // Get the width of the current device (in pixels). int widthPixels = Resources.DisplayMetrics.WidthPixels; // Use 1/5 of the device width for the drop down. int dropDownWidth = widthPixels / 5; // Create controls for specifying the minimum and maximum red values (0-255). _minRedSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = minMaxValuesAdapter, DropDownWidth = dropDownWidth }; _minRedSpinner.SetSelection(0); _maxRedSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = minMaxValuesAdapter, DropDownWidth = dropDownWidth }; _maxRedSpinner.SetSelection(255); // Set the background color to indicate which values the inputs are for. _minRedSpinner.SetBackgroundColor(Android.Graphics.Color.DarkRed); _maxRedSpinner.SetBackgroundColor(Android.Graphics.Color.DarkRed); // Create controls for specifying the minimum and maximum green values (0-255). _minGreenSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = minMaxValuesAdapter, DropDownWidth = dropDownWidth }; _minGreenSpinner.SetSelection(0); _maxGreenSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = minMaxValuesAdapter, DropDownWidth = dropDownWidth }; _maxGreenSpinner.SetSelection(255); // Set the background color to indicate which values the inputs are for. _minGreenSpinner.SetBackgroundColor(Android.Graphics.Color.DarkGreen); _maxGreenSpinner.SetBackgroundColor(Android.Graphics.Color.DarkGreen); // Create controls for specifying the minimum and maximum blue values (0-255). _minBlueSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = minMaxValuesAdapter, DropDownWidth = dropDownWidth }; _minBlueSpinner.SetSelection(0); _maxBlueSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = minMaxValuesAdapter, DropDownWidth = dropDownWidth }; _maxBlueSpinner.SetSelection(255); // Set the background color to indicate which values the inputs are for. _minBlueSpinner.SetBackgroundColor(Android.Graphics.Color.DarkBlue); _maxBlueSpinner.SetBackgroundColor(Android.Graphics.Color.DarkBlue); // Create vertical layouts for the color inputs (so they align properly). LinearLayout redInputsLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; LinearLayout greenInputsLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; LinearLayout blueInputsLayout = new LinearLayout(this) { Orientation = Orientation.Vertical }; // Add the color inputs to their corresponding layout. redInputsLayout.AddView(_minRedSpinner); redInputsLayout.AddView(_maxRedSpinner); greenInputsLayout.AddView(_minGreenSpinner); greenInputsLayout.AddView(_maxGreenSpinner); blueInputsLayout.AddView(_minBlueSpinner); blueInputsLayout.AddView(_maxBlueSpinner); // Add the vertical color inputs to the horizontal parent layout. _minMaxLayout.SetPadding(50, 10, 0, 10); _minMaxLayout.AddView(redInputsLayout); _minMaxLayout.AddView(greenInputsLayout); _minMaxLayout.AddView(blueInputsLayout); // Add the UI layouts to the main layout mainLayout.AddView(_minMaxLayout); #endregion #region UI for defining percent clip values // Create a (hidden) vertical layout for the min/max percent clip sliders. _percentClipLayout = new LinearLayout(this) { Orientation = Orientation.Vertical, Visibility = Android.Views.ViewStates.Gone }; // Apply some padding for the layout. _percentClipLayout.SetPadding(20, 5, 0, 20); // Create the minimum and maximum percent sliders (SeekBar). _minPercentClipSlider = new SeekBar(this) { Max = 100, Progress = 0 }; _maxPercentClipSlider = new SeekBar(this) { Max = 100, Progress = 0 }; // Set the SeekBar dimensions and a left margin. ActionBar.LayoutParams layoutParamsSeekBar = new ActionBar.LayoutParams(400, 30) { LeftMargin = 5 }; _minPercentClipSlider.LayoutParameters = layoutParamsSeekBar; _maxPercentClipSlider.LayoutParameters = layoutParamsSeekBar; // Create labels for minimum and maximum percent. TextView minimumSliderLabel = new TextView(this) { Text = "Min: " }; TextView maximumSliderLabel = new TextView(this) { Text = "Max: " }; // Create horizontal layouts for the minimum and maximum controls. LinearLayout minPercentClipLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal }; LinearLayout maxPercentClipLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal }; // Add min and max percent controls to their corresponding layouts. minPercentClipLayout.AddView(minimumSliderLabel); minPercentClipLayout.AddView(_minPercentClipSlider); maxPercentClipLayout.AddView(maximumSliderLabel); maxPercentClipLayout.AddView(_maxPercentClipSlider); // Add the slider layouts to the percent clip layout. _percentClipLayout.AddView(minPercentClipLayout); _percentClipLayout.AddView(maxPercentClipLayout); // Add the percent clip UI to the main layout. mainLayout.AddView(_percentClipLayout); #endregion #region UI for defining standard deviation factor // Create a range of values from 0-5 (in 0.5 increments) and an adapter to display them. IEnumerable<int> wholeStdDevs = Enumerable.Range(1, 10); List<double> halfStdDevs = wholeStdDevs.Select(i => (double)i / 2).ToList(); ArrayAdapter<double> stdDevFactorsAdapter = new ArrayAdapter<double>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, halfStdDevs); // Create a drop down (Spinner) control for specifying the standard deviation factor (0.0 - 5.0). _stdDeviationFactorSpinner = new Spinner(this, SpinnerMode.Dropdown) { Adapter = stdDevFactorsAdapter, DropDownWidth = dropDownWidth }; // Set the default selection to the 4th item (value of 2.0) _stdDeviationFactorSpinner.SetSelection(4); // Create a label (TextView) for the Spinner. TextView factorLabel = new TextView(this) { Text = "Factor: " }; // Create a horizontal layout for the controls. LinearLayout stdDevFactorLayout = new LinearLayout(this) { Orientation = Orientation.Horizontal }; // Add the controls for selecting a standard deviation factor. stdDevFactorLayout.AddView(factorLabel); stdDevFactorLayout.AddView(_stdDeviationFactorSpinner); // Create the standard deviation factor layout and add the controls. _stdDeviationLayout = new LinearLayout(this) { Orientation = Orientation.Vertical, Visibility = Android.Views.ViewStates.Gone }; _stdDeviationLayout.SetPadding(50, 5, 0, 5); _stdDeviationLayout.AddView(stdDevFactorLayout); // Add the standard deviation layout to the main layout. mainLayout.AddView(_stdDeviationLayout); #endregion // Create the map view control. _myMapView = new MapView(this); // Add the map view to the layout. mainLayout.AddView(_myMapView); // Set the layout as the sample view. SetContentView(mainLayout); } private async void Initialize() { // Create a map with a streets basemap. Map myMap = new Map(BasemapStyle.ArcGISStreets); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); try { // Create and load a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); await _rasterLayer.LoadAsync(); // Once the layer is loaded, enable the button to apply a new renderer. _applyRendererButton.Enabled = true; // Create a viewpoint with the raster's full extent. Viewpoint fullRasterExtent = new Viewpoint(_rasterLayer.FullExtent); // Set the initial viewpoint for the map. myMap.InitialViewpoint = fullRasterExtent; // Add the layer to the map. myMap.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. _myMapView.Map = myMap; } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } } private void ParameterInputTypeSpinner_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { // See which parameter (stretch) type was selected. string selectedStretchType = ((TextView)e.View).Text; // Hide all UI controls for the input parameters. _minMaxLayout.Visibility = Android.Views.ViewStates.Gone; _percentClipLayout.Visibility = Android.Views.ViewStates.Gone; _stdDeviationLayout.Visibility = Android.Views.ViewStates.Gone; // See which type was selected and show the corresponding input controls. switch (selectedStretchType) { case "Min Max": _minMaxLayout.Visibility = Android.Views.ViewStates.Visible; break; case "Percent Clip": _percentClipLayout.Visibility = Android.Views.ViewStates.Visible; break; case "Standard Deviation": _stdDeviationLayout.Visibility = Android.Views.ViewStates.Visible; break; } } private void ApplyRendererButton_Click(object sender, EventArgs e) { // Create the correct type of StretchParameters with the corresponding user inputs. StretchParameters stretchParameters = null; // See which type is selected and apply the corresponding input parameters to create the renderer. switch (_parameterInputTypeSpinner.SelectedItem.ToString()) { case "Min Max": // Read the minimum and maximum values for the red, green, and blue bands. double minRed = Convert.ToDouble(_minRedSpinner.SelectedItem); double minGreen = Convert.ToDouble(_minGreenSpinner.SelectedItem); double minBlue = Convert.ToDouble(_minBlueSpinner.SelectedItem); double maxRed = Convert.ToDouble(_maxRedSpinner.SelectedItem); double maxGreen = Convert.ToDouble(_maxGreenSpinner.SelectedItem); double maxBlue = Convert.ToDouble(_maxBlueSpinner.SelectedItem); // Create an array of the minimum and maximum values. double[] minValues = { minRed, minGreen, minBlue }; double[] maxValues = { maxRed, maxGreen, maxBlue }; // Create a new MinMaxStretchParameters with the values. stretchParameters = new MinMaxStretchParameters(minValues, maxValues); break; case "Percent Clip": // Get the percentile cutoff below which values in the raster dataset are to be clipped. double minimumPercent = Convert.ToDouble(_minPercentClipSlider.Progress); // Get the percentile cutoff above which pixel values in the raster dataset are to be clipped. double maximumPercent = Convert.ToDouble(_maxPercentClipSlider.Progress); // Create a new PercentClipStretchParameters with the inputs. stretchParameters = new PercentClipStretchParameters(minimumPercent, maximumPercent); break; case "Standard Deviation": // Read the standard deviation factor (the number of standard deviations used to define the range of pixel values). double standardDeviationFactor = Convert.ToDouble(_stdDeviationFactorSpinner.SelectedItem); // Create a new StandardDeviationStretchParameters with the selected number of standard deviations. stretchParameters = new StandardDeviationStretchParameters(standardDeviationFactor); break; } // Create an array to specify the raster bands (red, green, blue). int[] bands = { 0, 1, 2 }; // Create the RgbRenderer with the stretch parameters created above, then apply it to the raster layer. RgbRenderer rasterRenderer = new RgbRenderer(stretchParameters, bands, null, true); _rasterLayer.Renderer = rasterRenderer; } private static string GetRasterPath() { return DataManager.GetDataFolder("7c4c679ab06a4df19dc497f577f111bd", "raster-file", "Shasta.tif"); } } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Drawing; using System.Drawing.Design; using System.Web.UI; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// The MultiHandleSlider extender provides a feature-rich extension to a regular asp:Textbox control. /// It allows you to choose a single value or multiple values in a range through a graphical slider /// interface. It supports one handle, dual handles, or any number of handles bound to values of the /// asp:TextBox or asp:Label controls. It also provides options for read-only access, custom graphic /// styling, hover and drag handle styles, as well as the mouse and keyboard support for accessibility. /// </summary> [Designer(typeof(MultiHandleSliderExtenderDesigner))] [ClientCssResource(Constants.MultiHandleSliderName)] [ClientScriptResource("Sys.Extended.UI.MultiHandleSliderBehavior", Constants.MultiHandleSliderName)] [TargetControlType(typeof(TextBox))] [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(DragDropScripts))] [RequiredScript(typeof(AnimationScripts))] [RequiredScript(typeof(TimerScript))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.MultiHandleSliderName + Constants.IconPostfix)] public class MultiHandleSliderExtender : ExtenderControlBase { /// <summary> /// The lowest value on the slider /// </summary> [Description("The lowest value on the slider.")] [ExtenderControlProperty] [DefaultValue("0")] [ClientPropertyName("minimum")] public int Minimum { get { return GetPropertyValue("Minimum", 0); } set { SetPropertyValue("Minimum", value); } } /// <summary> /// The highest value on the slider /// </summary> [Description("The highest value on the slider.")] [ExtenderControlProperty] [DefaultValue("100")] [ClientPropertyName("maximum")] public int Maximum { get { return GetPropertyValue("Maximum", 100); } set { SetPropertyValue("Maximum", value); } } /// <summary> /// The slider rail length in pixels /// </summary> [Description("The length of the slider rail in pixels.")] [ExtenderControlProperty] [DefaultValue(150)] [ClientPropertyName("length")] public int Length { get { return GetPropertyValue("Length", 150); } set { SetPropertyValue("Length", value); } } /// <summary> /// Determines the number of discrete locations on the slider. Otherwise, the slider is continous /// </summary> [Description("Determines number of discrete locations on the slider; otherwise, the slider is continous.")] [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("steps")] public int Steps { get { return GetPropertyValue("Steps", 0); } set { SetPropertyValue("Steps", value); } } /// <summary> /// Determines if the slider will show an inner selected range rail. Otherwise, it will be displayed as a uniform rail /// </summary> [Description("Determines if the slider will show an inner selected range rail; otherwise, it will display as a uniform rail.")] [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("showInnerRail")] public bool ShowInnerRail { get { return GetPropertyValue("ShowInnerRail", false); } set { SetPropertyValue("ShowInnerRail", value); } } /// <summary> /// Determines how the inner rail style is handled /// </summary> [Description("Determines how the inner rail style is handled.")] [ExtenderControlProperty] [DefaultValue(MultiHandleInnerRailStyle.AsIs)] [ClientPropertyName("innerRailStyle")] public MultiHandleInnerRailStyle InnerRailStyle { get { return GetPropertyValue("InnerRailStyle", MultiHandleInnerRailStyle.AsIs); } set { SetPropertyValue("InnerRailStyle", value); } } /// <summary> /// Determines if the slider's orientation is horizontal or vertical /// </summary> [ExtenderControlProperty] [Description("Determines if the slider's orientation is horizontal or vertical.")] [DefaultValue(SliderOrientation.Horizontal)] [ClientPropertyName("orientation")] public SliderOrientation Orientation { get { return GetPropertyValue("Orientation", SliderOrientation.Horizontal); } set { SetPropertyValue("Orientation", value); } } /// <summary> /// Determines if changes events to the slider's values are raised during dragging. /// Otherwise, they are raised when dragging is completed /// </summary> [Description("Determines if changes to the slider's values are raised as an event when dragging; otherwise, they are raised on drag end.")] [ExtenderControlProperty] [DefaultValue(true)] [ClientPropertyName("raiseChangeOnlyOnMouseUp")] public bool RaiseChangeOnlyOnMouseUp { get { return GetPropertyValue("RaiseChangeOnlyOnMouseUp", true); } set { SetPropertyValue("RaiseChangeOnlyOnMouseUp", value); } } /// <summary> /// Determines if the inner rail range can be dragged as a whole, moving both handles defining it /// </summary> [Description("Determines if the inner rail range can be dragged as a whole, moving both handles defining it.")] [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("enableInnerRangeDrag")] public bool EnableInnerRangeDrag { get { return GetPropertyValue("EnableInnerRangeDrag", false); } set { SetPropertyValue("EnableInnerRangeDrag", value); } } /// <summary> /// Determines if clicking the rail will detect and move the closest handle /// </summary> [Description("Determines if clicking on the rail will detect and move the closest handle.")] [ExtenderControlProperty] [DefaultValue(true)] [ClientPropertyName("enableRailClick")] public bool EnableRailClick { get { return GetPropertyValue("EnableRailClick", true); } set { SetPropertyValue("EnableRailClick", value); } } /// <summary> /// Determines if the slider and its values can be manipulated /// </summary> [Description("Determines if the slider and its values can be manipulated.")] [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("isReadOnly")] public bool IsReadOnly { get { return GetPropertyValue("IsReadOnly", false); } set { SetPropertyValue("IsReadOnly", value); } } /// <summary> /// Determines if the slider will respond to arrow keys when it has focus /// </summary> [Description("Determines if the slider will respond to arrow keys when it has focus.")] [ExtenderControlProperty] [DefaultValue(true)] [ClientPropertyName("enableKeyboard")] public bool EnableKeyboard { get { return GetPropertyValue("EnableKeyboard", true); } set { SetPropertyValue("EnableKeyboard", value); } } /// <summary> /// Determines if the slider will respond to the mouse wheel when it has focus /// </summary> [Description("Determines if the slider will respond to the mouse wheel when it has focus.")] [ExtenderControlProperty] [DefaultValue(true)] [ClientPropertyName("enableMouseWheel")] public bool EnableMouseWheel { get { return GetPropertyValue("EnableMouseWheel", true); } set { SetPropertyValue("EnableMouseWheel", value); } } /// <summary> /// Determines the number of slider points to increment or decrement using the /// keyboard or mouse wheel. It is ignored if the steps property is used /// </summary> [Description("Determines the number of points to increment or decrement the slider using the keyboard or mousewheel; ignored if steps is used.")] [ExtenderControlProperty] [DefaultValue(1)] [ClientPropertyName("increment")] public int Increment { get { return GetPropertyValue("Increment", 1); } set { SetPropertyValue("Increment", value); } } /// <summary> /// Determines if a control is server-side /// </summary> [ExtenderControlProperty(true, true)] [ClientPropertyName("_isServerControl")] public bool IsServerControl { get { return true; } } /// <summary> /// The list of controls used to bind slider handle values. These should be Label or TextBox controls /// </summary> [Description("The list of controls used to bind slider handle values. These should be Label or TextBox controls.")] [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [DefaultValue(null)] [NotifyParentProperty(true)] [Editor(typeof(MultiHandleSliderTargetsEditor), typeof(UITypeEditor))] public Collection<MultiHandleSliderTarget> MultiHandleSliderTargets { get { if(!DesignMode) return ClientMultiHandleSliderTargets; return new Collection<MultiHandleSliderTarget>(); } } /// <summary> /// The list of controls used to bind slider handle values. These should be Label or TextBox controls /// </summary> [Description("The list of controls used to bind slider handle values. These should be Label or TextBox controls.")] [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [ExtenderControlProperty(true, true)] [ClientPropertyName("multiHandleSliderTargets")] public Collection<MultiHandleSliderTarget> ClientMultiHandleSliderTargets { get { return GetPropertyValue<Collection<MultiHandleSliderTarget>>("MultiHandleSliderTargets", null); } set { SetPropertyValue<Collection<MultiHandleSliderTarget>>("MultiHandleSliderTargets", value); } } /// <summary> /// Determines if the slider handles display of an animation effect when the position is changed /// </summary> [Description("Determines if the slider handles display an animation effect when changing position.")] [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("enableHandleAnimation")] public bool EnableHandleAnimation { get { return GetPropertyValue("EnableHandleAnimation", false); } set { SetPropertyValue("EnableHandleAnimation", value); } } /// <summary> /// Determines if the slider handles will show a style effect when they are hovered over /// </summary> [Description("Determines if the slider handles will show a style effect when they are hovered over.")] [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("showHandleHoverStyle")] public bool ShowHandleHoverStyle { get { return GetPropertyValue("ShowHandleHoverStyle", false); } set { SetPropertyValue("ShowHandleHoverStyle", value); } } /// <summary> /// Determines if the slider handles will show a style effect when they are being dragged /// </summary> [Description("Determines if the slider handles will show a style effect when they are being dragged.")] [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("showHandleDragStyle")] public bool ShowHandleDragStyle { get { return GetPropertyValue("ShowHandleDragStyle", false); } set { SetPropertyValue("ShowHandleDragStyle", value); } } /// <summary> /// Determines the total duration of an animation effect in seconds /// </summary> [Description("Determines the total duration of the animation effect, in seconds.")] [ExtenderControlProperty] [DefaultValue(0.02f)] [ClientPropertyName("handleAnimationDuration")] public float HandleAnimationDuration { get { return GetPropertyValue("HandleAnimationDuration", 0.1f); } set { SetPropertyValue("HandleAnimationDuration", value); } } /// <summary> /// Determines text to display as a tooltip; {0} denotes the current handle's value in the format string /// </summary> [Description("Determines the text to display as the tooltip; {0} denotes the current handle's value in the format string.")] [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("tooltipText")] public string TooltipText { get { return GetPropertyValue("TooltipText", String.Empty); } set { SetPropertyValue("TooltipText", value); } } /// <summary> /// A master style to apply to slider graphical elements /// </summary> [Description("The master style to apply to slider graphical elements.")] [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("cssClass")] public string CssClass { get { return GetPropertyValue("CssClass", String.Empty); } set { SetPropertyValue("CssClass", value); } } /// <summary> /// An event raised when the slider is completely loaded on the page /// </summary> [ExtenderControlEvent] [Description("The event raised when the slider is completely loaded on the page.")] [ClientPropertyName("load")] [DefaultValue("")] public string OnClientLoad { get { return GetPropertyValue("OnClientLoad", String.Empty); } set { SetPropertyValue("OnClientLoad", value); } } /// <summary> /// An event raised when a user initiates the drag operation on the slider /// </summary> [ExtenderControlEvent] [Description("The event raised when the user initiates a drag operation on the slider.")] [ClientPropertyName("dragStart")] [DefaultValue("")] public string OnClientDragStart { get { return GetPropertyValue("OnClientDragStart", String.Empty); } set { SetPropertyValue("OnClientDragStart", value); } } /// <summary> /// An event raised when a user drags the slider /// </summary> [ExtenderControlEvent] [Description("The event raised when the user drags the slider.")] [ClientPropertyName("drag")] [DefaultValue("")] public string OnClientDrag { get { return GetPropertyValue("OnClientDrag", String.Empty); } set { SetPropertyValue("OnClientDrag", value); } } /// <summary> /// An event raised when a user drops the slider /// </summary> [ExtenderControlEvent] [Description("The event raised when the user drops the slider.")] [ClientPropertyName("dragEnd")] [DefaultValue("")] public string OnClientDragEnd { get { return GetPropertyValue("OnClientDragEnd", String.Empty); } set { SetPropertyValue("OnClientDragEnd", value); } } /// <summary> /// An event raised when the slider changes its state /// </summary> [ExtenderControlEvent] [Description("The event raised when the slider changes its state.")] [ClientPropertyName("valueChanged")] [DefaultValue("")] public string OnClientValueChanged { get { return GetPropertyValue("OnClientValueChanged", String.Empty); } set { SetPropertyValue("OnClientValueChanged", value); } } public MultiHandleSliderExtender() { EnableClientState = true; } /// <summary> /// ID of a control to use for a single handle /// </summary> /// <remarks> /// Only used as a backward-compatibility feature for users that wish to upgrade /// their existing controls. The server control should be a TextBox or Label control /// </remarks> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [DefaultValue("")] [ClientPropertyName("boundControlID")] public string BoundControlID { get { return GetPropertyValue("BoundControlID", String.Empty); } set { SetPropertyValue("BoundControlID", value); } } /// <summary> /// The number of decimal digits in a single slider's value /// </summary> /// <remarks> /// 0 means an integer value. Only used as a backward-compatibility feature /// for users wishing to upgrade their existing controls /// </remarks> [ExtenderControlProperty] [ClientPropertyName("decimals")] [DefaultValue(0)] public int Decimals { get { return GetPropertyValue("Decimals", 0); } set { SetPropertyValue("Decimals", value); } } /// <summary> /// A CSS class of a single handle /// </summary> /// <remarks> /// Only used as a backward-compatibility feature for users wishing to /// upgrade their existing controls /// </remarks> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("handleCssClass")] public string HandleCssClass { get { return GetPropertyValue("HandleCssClass", String.Empty); } set { SetPropertyValue("HandleCssClass", value); } } /// <summary> /// A CSS class for the slider's rail element /// </summary> /// <remarks> /// Only used as a backward-compatibility feature for users /// wishing to upgrade their existing controls /// </remarks> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("railCssClass")] public string RailCssClass { get { return GetPropertyValue("RailCssClass", String.Empty); } set { SetPropertyValue("RailCssClass", value); } } /// <summary> /// URL for an image to display in the slider's handle /// </summary> /// <remarks> /// Only used as a backward-compatibility feature for users wishing to /// upgrade their existing controls /// </remarks> [ExtenderControlProperty] [DefaultValue(""), Editor("System.Web.UI.Design.ImageUrlEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor)), UrlProperty] [ClientPropertyName("handleImageUrl")] public string HandleImageUrl { get { return GetPropertyValue("HandleImageUrl", String.Empty); } set { SetPropertyValue("HandleImageUrl", value); } } } } #pragma warning restore 1591
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using gagr = Google.Api.Gax.ResourceNames; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Dataproc.V1 { /// <summary>Settings for <see cref="BatchControllerClient"/> instances.</summary> public sealed partial class BatchControllerSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="BatchControllerSettings"/>.</summary> /// <returns>A new instance of the default <see cref="BatchControllerSettings"/>.</returns> public static BatchControllerSettings GetDefault() => new BatchControllerSettings(); /// <summary>Constructs a new <see cref="BatchControllerSettings"/> object with default settings.</summary> public BatchControllerSettings() { } private BatchControllerSettings(BatchControllerSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); CreateBatchSettings = existing.CreateBatchSettings; CreateBatchOperationsSettings = existing.CreateBatchOperationsSettings.Clone(); GetBatchSettings = existing.GetBatchSettings; ListBatchesSettings = existing.ListBatchesSettings; DeleteBatchSettings = existing.DeleteBatchSettings; OnCopy(existing); } partial void OnCopy(BatchControllerSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.CreateBatch</c> and <c>BatchControllerClient.CreateBatchAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings CreateBatchSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// Long Running Operation settings for calls to <c>BatchControllerClient.CreateBatch</c> and /// <c>BatchControllerClient.CreateBatchAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings CreateBatchOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.GetBatch</c> and <c>BatchControllerClient.GetBatchAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetBatchSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.ListBatches</c> and <c>BatchControllerClient.ListBatchesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ListBatchesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>BatchControllerClient.DeleteBatch</c> and <c>BatchControllerClient.DeleteBatchAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings DeleteBatchSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="BatchControllerSettings"/> object.</returns> public BatchControllerSettings Clone() => new BatchControllerSettings(this); } /// <summary> /// Builder class for <see cref="BatchControllerClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> public sealed partial class BatchControllerClientBuilder : gaxgrpc::ClientBuilderBase<BatchControllerClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public BatchControllerSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BatchControllerClientBuilder() { UseJwtAccessWithScopes = BatchControllerClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref BatchControllerClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<BatchControllerClient> task); /// <summary>Builds the resulting client.</summary> public override BatchControllerClient Build() { BatchControllerClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<BatchControllerClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<BatchControllerClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private BatchControllerClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return BatchControllerClient.Create(callInvoker, Settings); } private async stt::Task<BatchControllerClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return BatchControllerClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => BatchControllerClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => BatchControllerClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => BatchControllerClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>BatchController client wrapper, for convenient use.</summary> /// <remarks> /// The BatchController provides methods to manage batch workloads. /// </remarks> public abstract partial class BatchControllerClient { /// <summary> /// The default endpoint for the BatchController service, which is a host of "dataproc.googleapis.com" and a /// port of 443. /// </summary> public static string DefaultEndpoint { get; } = "dataproc.googleapis.com:443"; /// <summary>The default BatchController scopes.</summary> /// <remarks> /// The default BatchController scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="BatchControllerClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="BatchControllerClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="BatchControllerClient"/>.</returns> public static stt::Task<BatchControllerClient> CreateAsync(st::CancellationToken cancellationToken = default) => new BatchControllerClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="BatchControllerClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="BatchControllerClientBuilder"/>. /// </summary> /// <returns>The created <see cref="BatchControllerClient"/>.</returns> public static BatchControllerClient Create() => new BatchControllerClientBuilder().Build(); /// <summary> /// Creates a <see cref="BatchControllerClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="BatchControllerSettings"/>.</param> /// <returns>The created <see cref="BatchControllerClient"/>.</returns> internal static BatchControllerClient Create(grpccore::CallInvoker callInvoker, BatchControllerSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } BatchController.BatchControllerClient grpcClient = new BatchController.BatchControllerClient(callInvoker); return new BatchControllerClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC BatchController client</summary> public virtual BatchController.BatchControllerClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> CreateBatch(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(CreateBatchRequest request, st::CancellationToken cancellationToken) => CreateBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>CreateBatch</c>.</summary> public virtual lro::OperationsClient CreateBatchOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>CreateBatch</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> PollOnceCreateBatch(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Batch, BatchOperationMetadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateBatchOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>CreateBatch</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> PollOnceCreateBatchAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<Batch, BatchOperationMetadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), CreateBatchOperationsClient, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> CreateBatch(string parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatch(new CreateBatchRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(string parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatchAsync(new CreateBatchRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(string parent, Batch batch, string batchId, st::CancellationToken cancellationToken) => CreateBatchAsync(parent, batch, batchId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<Batch, BatchOperationMetadata> CreateBatch(gagr::LocationName parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatch(new CreateBatchRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(gagr::LocationName parent, Batch batch, string batchId, gaxgrpc::CallSettings callSettings = null) => CreateBatchAsync(new CreateBatchRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), Batch = gax::GaxPreconditions.CheckNotNull(batch, nameof(batch)), BatchId = batchId ?? "", }, callSettings); /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="parent"> /// Required. The parent resource where this batch will be created. /// </param> /// <param name="batch"> /// Required. The batch to create. /// </param> /// <param name="batchId"> /// Optional. The ID to use for the batch, which will become the final component of /// the batch's resource name. /// /// This value must be 4-63 characters. Valid characters are `/[a-z][0-9]-/`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(gagr::LocationName parent, Batch batch, string batchId, st::CancellationToken cancellationToken) => CreateBatchAsync(parent, batch, batchId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Batch GetBatch(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(GetBatchRequest request, st::CancellationToken cancellationToken) => GetBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Batch GetBatch(string name, gaxgrpc::CallSettings callSettings = null) => GetBatch(new GetBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(string name, gaxgrpc::CallSettings callSettings = null) => GetBatchAsync(new GetBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(string name, st::CancellationToken cancellationToken) => GetBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual Batch GetBatch(BatchName name, gaxgrpc::CallSettings callSettings = null) => GetBatch(new GetBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(BatchName name, gaxgrpc::CallSettings callSettings = null) => GetBatchAsync(new GetBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="name"> /// Required. The name of the batch to retrieve. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<Batch> GetBatchAsync(BatchName name, st::CancellationToken cancellationToken) => GetBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatches(new ListBatchesRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(string parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatchesAsync(new ListBatchesRequest { Parent = gax::GaxPreconditions.CheckNotNullOrEmpty(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(gagr::LocationName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatches(new ListBatchesRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists batch workloads. /// </summary> /// <param name="parent"> /// Required. The parent, which owns this collection of batches. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. A value of <c>null</c> or an empty string retrieves the first /// page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. A value of /// <c>null</c> or <c>0</c> uses a server-defined page size. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public virtual gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(gagr::LocationName parent, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListBatchesAsync(new ListBatchesRequest { ParentAsLocationName = gax::GaxPreconditions.CheckNotNull(parent, nameof(parent)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteBatch(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(DeleteBatchRequest request, st::CancellationToken cancellationToken) => DeleteBatchAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteBatch(string name, gaxgrpc::CallSettings callSettings = null) => DeleteBatch(new DeleteBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(string name, gaxgrpc::CallSettings callSettings = null) => DeleteBatchAsync(new DeleteBatchRequest { Name = gax::GaxPreconditions.CheckNotNullOrEmpty(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(string name, st::CancellationToken cancellationToken) => DeleteBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual void DeleteBatch(BatchName name, gaxgrpc::CallSettings callSettings = null) => DeleteBatch(new DeleteBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(BatchName name, gaxgrpc::CallSettings callSettings = null) => DeleteBatchAsync(new DeleteBatchRequest { BatchName = gax::GaxPreconditions.CheckNotNull(name, nameof(name)), }, callSettings); /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="name"> /// Required. The name of the batch resource to delete. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task DeleteBatchAsync(BatchName name, st::CancellationToken cancellationToken) => DeleteBatchAsync(name, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>BatchController client wrapper implementation, for convenient use.</summary> /// <remarks> /// The BatchController provides methods to manage batch workloads. /// </remarks> public sealed partial class BatchControllerClientImpl : BatchControllerClient { private readonly gaxgrpc::ApiCall<CreateBatchRequest, lro::Operation> _callCreateBatch; private readonly gaxgrpc::ApiCall<GetBatchRequest, Batch> _callGetBatch; private readonly gaxgrpc::ApiCall<ListBatchesRequest, ListBatchesResponse> _callListBatches; private readonly gaxgrpc::ApiCall<DeleteBatchRequest, wkt::Empty> _callDeleteBatch; /// <summary> /// Constructs a client wrapper for the BatchController service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="BatchControllerSettings"/> used within this client.</param> public BatchControllerClientImpl(BatchController.BatchControllerClient grpcClient, BatchControllerSettings settings) { GrpcClient = grpcClient; BatchControllerSettings effectiveSettings = settings ?? BatchControllerSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); CreateBatchOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.CreateBatchOperationsSettings); _callCreateBatch = clientHelper.BuildApiCall<CreateBatchRequest, lro::Operation>(grpcClient.CreateBatchAsync, grpcClient.CreateBatch, effectiveSettings.CreateBatchSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callCreateBatch); Modify_CreateBatchApiCall(ref _callCreateBatch); _callGetBatch = clientHelper.BuildApiCall<GetBatchRequest, Batch>(grpcClient.GetBatchAsync, grpcClient.GetBatch, effectiveSettings.GetBatchSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callGetBatch); Modify_GetBatchApiCall(ref _callGetBatch); _callListBatches = clientHelper.BuildApiCall<ListBatchesRequest, ListBatchesResponse>(grpcClient.ListBatchesAsync, grpcClient.ListBatches, effectiveSettings.ListBatchesSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callListBatches); Modify_ListBatchesApiCall(ref _callListBatches); _callDeleteBatch = clientHelper.BuildApiCall<DeleteBatchRequest, wkt::Empty>(grpcClient.DeleteBatchAsync, grpcClient.DeleteBatch, effectiveSettings.DeleteBatchSettings).WithGoogleRequestParam("name", request => request.Name); Modify_ApiCall(ref _callDeleteBatch); Modify_DeleteBatchApiCall(ref _callDeleteBatch); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_CreateBatchApiCall(ref gaxgrpc::ApiCall<CreateBatchRequest, lro::Operation> call); partial void Modify_GetBatchApiCall(ref gaxgrpc::ApiCall<GetBatchRequest, Batch> call); partial void Modify_ListBatchesApiCall(ref gaxgrpc::ApiCall<ListBatchesRequest, ListBatchesResponse> call); partial void Modify_DeleteBatchApiCall(ref gaxgrpc::ApiCall<DeleteBatchRequest, wkt::Empty> call); partial void OnConstruction(BatchController.BatchControllerClient grpcClient, BatchControllerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC BatchController client</summary> public override BatchController.BatchControllerClient GrpcClient { get; } partial void Modify_CreateBatchRequest(ref CreateBatchRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetBatchRequest(ref GetBatchRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListBatchesRequest(ref ListBatchesRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteBatchRequest(ref DeleteBatchRequest request, ref gaxgrpc::CallSettings settings); /// <summary>The long-running operations client for <c>CreateBatch</c>.</summary> public override lro::OperationsClient CreateBatchOperationsClient { get; } /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<Batch, BatchOperationMetadata> CreateBatch(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateBatchRequest(ref request, ref callSettings); return new lro::Operation<Batch, BatchOperationMetadata>(_callCreateBatch.Sync(request, callSettings), CreateBatchOperationsClient); } /// <summary> /// Creates a batch workload that executes asynchronously. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<Batch, BatchOperationMetadata>> CreateBatchAsync(CreateBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CreateBatchRequest(ref request, ref callSettings); return new lro::Operation<Batch, BatchOperationMetadata>(await _callCreateBatch.Async(request, callSettings).ConfigureAwait(false), CreateBatchOperationsClient); } /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override Batch GetBatch(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBatchRequest(ref request, ref callSettings); return _callGetBatch.Sync(request, callSettings); } /// <summary> /// Gets the batch workload resource representation. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<Batch> GetBatchAsync(GetBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetBatchRequest(ref request, ref callSettings); return _callGetBatch.Async(request, callSettings); } /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable sequence of <see cref="Batch"/> resources.</returns> public override gax::PagedEnumerable<ListBatchesResponse, Batch> ListBatches(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListBatchesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListBatchesRequest, ListBatchesResponse, Batch>(_callListBatches, request, callSettings); } /// <summary> /// Lists batch workloads. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A pageable asynchronous sequence of <see cref="Batch"/> resources.</returns> public override gax::PagedAsyncEnumerable<ListBatchesResponse, Batch> ListBatchesAsync(ListBatchesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListBatchesRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListBatchesRequest, ListBatchesResponse, Batch>(_callListBatches, request, callSettings); } /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override void DeleteBatch(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteBatchRequest(ref request, ref callSettings); _callDeleteBatch.Sync(request, callSettings); } /// <summary> /// Deletes the batch workload resource. If the batch is not in terminal state, /// the delete fails and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task DeleteBatchAsync(DeleteBatchRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteBatchRequest(ref request, ref callSettings); return _callDeleteBatch.Async(request, callSettings); } } public partial class ListBatchesRequest : gaxgrpc::IPageRequest { } public partial class ListBatchesResponse : gaxgrpc::IPageResponse<Batch> { /// <summary>Returns an enumerator that iterates through the resources in this response.</summary> public scg::IEnumerator<Batch> GetEnumerator() => Batches.GetEnumerator(); sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } public static partial class BatchController { public partial class BatchControllerClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Security.Interfaces.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Java.Security.Interfaces { /// <summary> /// <para>The base interface for Digital Signature Algorithm (DSA) public or private keys. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAKey", AccessFlags = 1537)] public partial interface IDSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the DSA key parameters.</para><para></para> /// </summary> /// <returns> /// <para>the DSA key parameters. </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Ljava/security/interfaces/DSAParams;", AccessFlags = 1025)] global::Java.Security.Interfaces.IDSAParams GetParams() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The base interface for PKCS#1 RSA public and private keys. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAKey", AccessFlags = 1537)] public partial interface IRSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the modulus.</para><para></para> /// </summary> /// <returns> /// <para>the modulus. </para> /// </returns> /// <java-name> /// getModulus /// </java-name> [Dot42.DexImport("getModulus", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetModulus() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDSAPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 7776497482533790279; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPrivateKey", AccessFlags = 1537)] public partial interface IDSAPrivateKey : global::Java.Security.Interfaces.IDSAKey, global::Java.Security.IPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the private key value <c> x </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private key value <c> x </c> . </para> /// </returns> /// <java-name> /// getX /// </java-name> [Dot42.DexImport("getX", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetX() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for key generators that can generate DSA key pairs. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAKeyPairGenerator /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAKeyPairGenerator", AccessFlags = 1537)] public partial interface IDSAKeyPairGenerator /* scope: __dot42__ */ { /// <summary> /// <para>Initializes this generator with the prime (<c> p </c> ), subprime (<c> q </c> ), and base (<c> g </c> ) values from the specified parameters.</para><para></para> /// </summary> /// <java-name> /// initialize /// </java-name> [Dot42.DexImport("initialize", "(Ljava/security/interfaces/DSAParams;Ljava/security/SecureRandom;)V", AccessFlags = 1025)] void Initialize(global::Java.Security.Interfaces.IDSAParams @params, global::Java.Security.SecureRandom random) /* MethodBuilder.Create */ ; /// <summary> /// <para>Initializes this generator for the specified modulus length. Valid values for the modulus length are the multiples of 8 between 512 and 1024. </para><para>The parameter <c> genParams </c> specifies whether this method should generate new prime (<c> p </c> ), subprime (<c> q </c> ), and base (<c> g </c> ) values or whether it will use the pre-calculated values for the specified modulus length. Default parameters are available for modulus lengths of 512 and 1024 bits.</para><para></para> /// </summary> /// <java-name> /// initialize /// </java-name> [Dot42.DexImport("initialize", "(IZLjava/security/SecureRandom;)V", AccessFlags = 1025)] void Initialize(int modlen, bool genParams, global::Java.Security.SecureRandom random) /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Multi-Prime RSA private key. Specified by . </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAMultiPrimePrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAMultiPrimePrivateCrtKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAMultiPrimePrivateCrtKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>the serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 618058533534628008; } /// <summary> /// <para>The interface for a Multi-Prime RSA private key. Specified by . </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAMultiPrimePrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAMultiPrimePrivateCrtKey", AccessFlags = 1537)] public partial interface IRSAMultiPrimePrivateCrtKey : global::Java.Security.Interfaces.IRSAPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the CRT coefficient, <c> q^-1 mod p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT coefficient. </para> /// </returns> /// <java-name> /// getCrtCoefficient /// </java-name> [Dot42.DexImport("getCrtCoefficient", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetCrtCoefficient() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the information for the additional primes.</para><para></para> /// </summary> /// <returns> /// <para>the information for the additional primes, or <c> null </c> if there are only the two primes (<c> p, q </c> ), </para> /// </returns> /// <java-name> /// getOtherPrimeInfo /// </java-name> [Dot42.DexImport("getOtherPrimeInfo", "()[Ljava/security/spec/RSAOtherPrimeInfo;", AccessFlags = 1025)] global::Java.Security.Spec.RSAOtherPrimeInfo[] GetOtherPrimeInfo() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> p </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> p </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeP /// </java-name> [Dot42.DexImport("getPrimeP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> q </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> q </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeQ /// </java-name> [Dot42.DexImport("getPrimeQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the prime <c> p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> p </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentP /// </java-name> [Dot42.DexImport("getPrimeExponentP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the prime <c> q </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> q </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentQ /// </java-name> [Dot42.DexImport("getPrimeExponentQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the public exponent <c> e </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public exponent <c> e </c> . </para> /// </returns> /// <java-name> /// getPublicExponent /// </java-name> [Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for an PKCS#1 RSA private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 5187144804936595022; } /// <summary> /// <para>The interface for an PKCS#1 RSA private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateKey", AccessFlags = 1537)] public partial interface IRSAPrivateKey : global::Java.Security.IPrivateKey, global::Java.Security.Interfaces.IRSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the private exponent <c> d </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private exponent <c> d </c> . </para> /// </returns> /// <java-name> /// getPrivateExponent /// </java-name> [Dot42.DexImport("getPrivateExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrivateExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IDSAPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = 1234526332779022332; } /// <summary> /// <para>The interface for a Digital Signature Algorithm (DSA) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAPublicKey", AccessFlags = 1537)] public partial interface IDSAPublicKey : global::Java.Security.Interfaces.IDSAKey, global::Java.Security.IPublicKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the public key value <c> y </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public key value <c> y </c> . </para> /// </returns> /// <java-name> /// getY /// </java-name> [Dot42.DexImport("getY", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetY() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IECPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -3314988629879632826; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPublicKey", AccessFlags = 1537)] public partial interface IECPublicKey : global::Java.Security.IPublicKey, global::Java.Security.Interfaces.IECKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the public point <c> W </c> on an elliptic curve (EC).</para><para></para> /// </summary> /// <returns> /// <para>the public point <c> W </c> on an elliptic curve (EC). </para> /// </returns> /// <java-name> /// getW /// </java-name> [Dot42.DexImport("getW", "()Ljava/security/spec/ECPoint;", AccessFlags = 1025)] global::Java.Security.Spec.ECPoint GetW() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a PKCS#1 RSA public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPublicKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAPublicKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -8727434096241101194; } /// <summary> /// <para>The interface for a PKCS#1 RSA public key. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPublicKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPublicKey", AccessFlags = 1537)] public partial interface IRSAPublicKey : global::Java.Security.IPublicKey, global::Java.Security.Interfaces.IRSAKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the public exponent <c> e </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public exponent <c> e </c> . </para> /// </returns> /// <java-name> /// getPublicExponent /// </java-name> [Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The base interface for Elliptic Curve (EC) public or private keys. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECKey", AccessFlags = 1537)] public partial interface IECKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the EC key parameters.</para><para></para> /// </summary> /// <returns> /// <para>the EC key parameters. </para> /// </returns> /// <java-name> /// getParams /// </java-name> [Dot42.DexImport("getParams", "()Ljava/security/spec/ECParameterSpec;", AccessFlags = 1025)] global::Java.Security.Spec.ECParameterSpec GetParams() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for a PKCS#1 RSA private key using CRT information values. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateCrtKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IRSAPrivateCrtKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -5682214253527700368; } /// <summary> /// <para>The interface for a PKCS#1 RSA private key using CRT information values. </para> /// </summary> /// <java-name> /// java/security/interfaces/RSAPrivateCrtKey /// </java-name> [Dot42.DexImport("java/security/interfaces/RSAPrivateCrtKey", AccessFlags = 1537)] public partial interface IRSAPrivateCrtKey : global::Java.Security.Interfaces.IRSAPrivateKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the CRT coefficient, <c> q^-1 mod p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT coefficient. </para> /// </returns> /// <java-name> /// getCrtCoefficient /// </java-name> [Dot42.DexImport("getCrtCoefficient", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetCrtCoefficient() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> p </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> p </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeP /// </java-name> [Dot42.DexImport("getPrimeP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime factor <c> q </c> of <c> n </c> .</para><para></para> /// </summary> /// <returns> /// <para>the prime factor <c> q </c> of <c> n </c> . </para> /// </returns> /// <java-name> /// getPrimeQ /// </java-name> [Dot42.DexImport("getPrimeQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the primet <c> p </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> p </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentP /// </java-name> [Dot42.DexImport("getPrimeExponentP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the CRT exponent of the prime <c> q </c> .</para><para></para> /// </summary> /// <returns> /// <para>the CRT exponent of the prime <c> q </c> . </para> /// </returns> /// <java-name> /// getPrimeExponentQ /// </java-name> [Dot42.DexImport("getPrimeExponentQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPrimeExponentQ() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the public exponent <c> e </c> .</para><para></para> /// </summary> /// <returns> /// <para>the public exponent <c> e </c> . </para> /// </returns> /// <java-name> /// getPublicExponent /// </java-name> [Dot42.DexImport("getPublicExponent", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetPublicExponent() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for Digital Signature Algorithm (DSA) specific parameters. </para> /// </summary> /// <java-name> /// java/security/interfaces/DSAParams /// </java-name> [Dot42.DexImport("java/security/interfaces/DSAParams", AccessFlags = 1537)] public partial interface IDSAParams /* scope: __dot42__ */ { /// <summary> /// <para>Returns the base (<c> g </c> ) value.</para><para></para> /// </summary> /// <returns> /// <para>the base (<c> g </c> ) value. </para> /// </returns> /// <java-name> /// getG /// </java-name> [Dot42.DexImport("getG", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetG() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the prime (<c> p </c> ) value.</para><para></para> /// </summary> /// <returns> /// <para>the prime (<c> p </c> ) value. </para> /// </returns> /// <java-name> /// getP /// </java-name> [Dot42.DexImport("getP", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetP() /* MethodBuilder.Create */ ; /// <summary> /// <para>Returns the subprime (<c> q </c> value.</para><para></para> /// </summary> /// <returns> /// <para>the subprime (<c> q </c> value. </para> /// </returns> /// <java-name> /// getQ /// </java-name> [Dot42.DexImport("getQ", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetQ() /* MethodBuilder.Create */ ; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPrivateKey", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IECPrivateKeyConstants /* scope: __dot42__ */ { /// <summary> /// <para>The serial version identifier. </para> /// </summary> /// <java-name> /// serialVersionUID /// </java-name> [Dot42.DexImport("serialVersionUID", "J", AccessFlags = 25)] public const long SerialVersionUID = -7896394956925609184; } /// <summary> /// <para>The interface for an Elliptic Curve (EC) private key. </para> /// </summary> /// <java-name> /// java/security/interfaces/ECPrivateKey /// </java-name> [Dot42.DexImport("java/security/interfaces/ECPrivateKey", AccessFlags = 1537)] public partial interface IECPrivateKey : global::Java.Security.IPrivateKey, global::Java.Security.Interfaces.IECKey /* scope: __dot42__ */ { /// <summary> /// <para>Returns the private value <c> S </c> .</para><para></para> /// </summary> /// <returns> /// <para>the private value <c> S </c> . </para> /// </returns> /// <java-name> /// getS /// </java-name> [Dot42.DexImport("getS", "()Ljava/math/BigInteger;", AccessFlags = 1025)] global::Java.Math.BigInteger GetS() /* MethodBuilder.Create */ ; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using log4net; using QifApi; using QifApi.Transactions; namespace MyAccounts.Business.GererMesComptes { public class OperationsRepository { private static readonly ILog _logger = LogManager.GetLogger(typeof(OperationsRepository)); private readonly GererMesComptesClient _client; private readonly QifDataImportWorker _importWorker; public OperationsRepository(GererMesComptesClient client) { _client = client; _importWorker = new QifDataImportWorker(client); } private HttpClient Transport => _client.Transport; public async Task<TransactionDeltaSet> DryRunImport(string accountId, string availableQifData) { var availableQifDom = QifMapper.ParseQifDom(availableQifData); var minDate = availableQifDom.BankTransactions.Min(t => t.Date.AddDays(-1)); var maxDate = availableQifDom.BankTransactions.Max(t => t.Date); var exportedQifData = await ExportQif(accountId, minDate, maxDate); var exportedQifDom = QifMapper.ParseQifDom(exportedQifData); var exportedByKey = exportedQifDom.BankTransactions.ToLookup(s => s.GetBankTransactionLookupKey()); var delta = new TransactionDeltaSet(); foreach (var availableBt in availableQifDom.BankTransactions) { var key = availableBt.GetBankTransactionLookupKey(); if (!exportedByKey.Contains(key)) { delta.SetAddAction(availableBt); } else { var exportedSimilars = exportedByKey[key].ToList(); if (exportedSimilars.Count > 1) { var exportedSimilar = exportedSimilars.FirstOrDefault(s => !delta.IsTargetProcessed(s) && s.Memo == availableBt.Memo); if (exportedSimilar != null) { delta.SetNothingAction(availableBt, exportedSimilar); } else { delta.SetMultipleTargetsPossibleAction(availableBt); } } else { var exportedItem = exportedSimilars.Single(); if (exportedItem.Memo != availableBt.Memo) { delta.SetUpdateMemoAction(availableBt, exportedItem); } else { delta.SetNothingAction(availableBt, exportedItem); } } } } var potentialExports = exportedQifDom.BankTransactions.Where(t => !delta.IsTargetProcessed(t)).ToList(); TryToResolveAmbiguousItems(delta, potentialExports); var toRemoveItems = exportedQifDom.BankTransactions.Where(t => !delta.IsTargetProcessed(t)); foreach (var exportedItem in toRemoveItems) { delta.SetRemoveAction(exportedItem); } return delta; } public Task<string> ExportQif(string accountId, int days) { return ExportQif(accountId, DateTime.Today.AddDays(-days - 1), DateTime.Today); } public async Task<string> ExportQif(string accountId, DateTime startDate, DateTime endData) { var dico = new Dictionary<string, string> { ["id_account"] = accountId, ["export"] = "dates", ["interval_start"] = ToUnixTime(startDate.Date).ToString(), ["interval_end"] = ToUnixTime(endData.Date).ToString(), ["format"] = "qif", ["date_format"] = "mm-dd-aaaa", ["amount_format"] = "auto", ["csv_separator"] = "semi-colon", ["csv_column"] = "yes", ["category_separator"] = "%3A%3A", ["encoding"] = "utf-8" }; var response = await Transport.PostAsync("/fr/u/finances/comptes/" + accountId + "/export.html", new FormUrlEncodedContent(dico)); response.EnsureSuccessStatusCode(); var qifData = await response.Content.ReadAsStringAsync(); qifData = qifData.Replace("\n", Environment.NewLine); return qifData; } public Task<RunImportResult> Import(string accountId, string qifData) { return _importWorker.Import(accountId, qifData); } public async Task<RunImportResult> RunImportFromDeltaActions(string accountId, List<TransactionDelta> operationsDelta) { var deltasOfAddKind = operationsDelta.Where(s => s.Action == DeltaAction.Add); var newTransactions = deltasOfAddKind.Select(i => i.Source).ToList(); RunImportResult result; var qifData = newTransactions.ToQifData(); if (newTransactions.Count == 0) { result = new RunImportResult(true, qifData); } else { result = await Import(accountId, qifData); } return result; } public async Task<string> WaitExportAvailability(string accountId, string lastImportedQifData, int secondsToWait = 20) { var sw = Stopwatch.StartNew(); bool available; var importedQifDom = QifMapper.ParseQifDom(lastImportedQifData); var importedByKey = importedQifDom.BankTransactions.ToLookup(s => s.GetBankTransactionLookupKey()); var importedKeys = new HashSet<string>(importedByKey.Select(i => i.Key)); string exportedQifData; QifDom lastExportedQifDom; do { exportedQifData = await ExportQif( accountId, importedQifDom.BankTransactions.Min(t => t.Date).AddDays(-1), importedQifDom.BankTransactions.Max(t => t.Date)); lastExportedQifDom = QifMapper.ParseQifDom(exportedQifData); var exportedbyKey = lastExportedQifDom.BankTransactions.ToLookup(s => s.GetBankTransactionLookupKey()); available = exportedbyKey.Select(s => s.Key).Where(importedKeys.Contains).Intersect(importedKeys).Count() == importedKeys.Count; if (!available) { _logger.Warn("number of imported items do not match number exported items yet"); } else { foreach (var importedKeyItems in importedByKey) { var exported = exportedbyKey[importedKeyItems.Key].ToList(); foreach (var importedKeyItem in importedKeyItems) { available = exported.Any(exportedKeyItem => string.Equals(importedKeyItem.Memo, exportedKeyItem.Memo, StringComparison.InvariantCultureIgnoreCase)); if (!available) { _logger.Warn($"item not available in export yet :{importedKeyItem.Number} - {importedKeyItem.Memo}"); break; } } if (!available) { break; } } } if (!available) { await Task.Delay(TimeSpan.FromMilliseconds(500)); } } while (sw.Elapsed.TotalSeconds < secondsToWait && !available); if (!available) { var rawExport = string.Join(Environment.NewLine, lastExportedQifDom.BankTransactions.Select( s => $"{s.GetBankTransactionLookupKey()} - {s.Amount} - {s.Memo}")); _logger.Debug($"Last received export{Environment.NewLine}{rawExport}"); throw new Exception($"Timeout, could not detect export availability during {secondsToWait} seconds"); } return exportedQifData; } private static long ToUnixTime(DateTime date) { var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); return Convert.ToInt64((date - epoch).TotalSeconds); } private void TryToResolveAmbiguousItems(TransactionDeltaSet delta, List<BasicTransaction> potentialExports) { var ambiguousItemsGroups = delta.GetDeltaByAction(DeltaAction.MultipleTargetsPossible); var toImportSplittedMemos = ambiguousItemsGroups .ToDictionary(t => t, t => new HashSet<string>(t.Source.Memo.Split(' '))); var exportSplittedMemos = potentialExports.ToDictionary(t => t, t => new HashSet<string>(t.Memo.Split(' '))); var toImportItemsByKey = ambiguousItemsGroups.ToLookup(t => t.Source.GetBankTransactionLookupKey()); var exportedItemsByKey = potentialExports.ToLookup(t => t.GetBankTransactionLookupKey()); foreach (var toImportKeyItems in toImportItemsByKey) { var key = toImportKeyItems.Key; var exportedKeyItems = exportedItemsByKey[key].ToList(); var suggestedResolution = new List<Tuple<TransactionDelta, BasicTransaction>>(); foreach (var importedKeyItem in toImportKeyItems) { var importedKeyItemWords = toImportSplittedMemos[importedKeyItem]; var nearest = exportedKeyItems .OrderByDescending(exportedKeyITem => exportSplittedMemos[exportedKeyITem].Intersect(importedKeyItemWords).Count()) .FirstOrDefault(); if (nearest != null) { exportedKeyItems.Remove(nearest); suggestedResolution.Add(Tuple.Create(importedKeyItem, nearest)); } } if (suggestedResolution.Count == toImportKeyItems.Count()) { foreach (var tuple in suggestedResolution) { delta.SetUpdateMemoAction(tuple.Item1, tuple.Item2); } } } } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetActiveJobsSpectraS3Request : Ds3Request { private bool? _aggregating; public bool? Aggregating { get { return _aggregating; } set { WithAggregating(value); } } private string _bucketId; public string BucketId { get { return _bucketId; } set { WithBucketId(value); } } private JobChunkClientProcessingOrderGuarantee? _chunkClientProcessingOrderGuarantee; public JobChunkClientProcessingOrderGuarantee? ChunkClientProcessingOrderGuarantee { get { return _chunkClientProcessingOrderGuarantee; } set { WithChunkClientProcessingOrderGuarantee(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private string _name; public string Name { get { return _name; } set { WithName(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } private Priority? _priority; public Priority? Priority { get { return _priority; } set { WithPriority(value); } } private DateTime? _rechunked; public DateTime? Rechunked { get { return _rechunked; } set { WithRechunked(value); } } private JobRequestType? _requestType; public JobRequestType? RequestType { get { return _requestType; } set { WithRequestType(value); } } private bool? _truncated; public bool? Truncated { get { return _truncated; } set { WithTruncated(value); } } private string _userId; public string UserId { get { return _userId; } set { WithUserId(value); } } public GetActiveJobsSpectraS3Request WithAggregating(bool? aggregating) { this._aggregating = aggregating; if (aggregating != null) { this.QueryParams.Add("aggregating", aggregating.ToString()); } else { this.QueryParams.Remove("aggregating"); } return this; } public GetActiveJobsSpectraS3Request WithBucketId(Guid? bucketId) { this._bucketId = bucketId.ToString(); if (bucketId != null) { this.QueryParams.Add("bucket_id", bucketId.ToString()); } else { this.QueryParams.Remove("bucket_id"); } return this; } public GetActiveJobsSpectraS3Request WithBucketId(string bucketId) { this._bucketId = bucketId; if (bucketId != null) { this.QueryParams.Add("bucket_id", bucketId); } else { this.QueryParams.Remove("bucket_id"); } return this; } public GetActiveJobsSpectraS3Request WithChunkClientProcessingOrderGuarantee(JobChunkClientProcessingOrderGuarantee? chunkClientProcessingOrderGuarantee) { this._chunkClientProcessingOrderGuarantee = chunkClientProcessingOrderGuarantee; if (chunkClientProcessingOrderGuarantee != null) { this.QueryParams.Add("chunk_client_processing_order_guarantee", chunkClientProcessingOrderGuarantee.ToString()); } else { this.QueryParams.Remove("chunk_client_processing_order_guarantee"); } return this; } public GetActiveJobsSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetActiveJobsSpectraS3Request WithName(string name) { this._name = name; if (name != null) { this.QueryParams.Add("name", name); } else { this.QueryParams.Remove("name"); } return this; } public GetActiveJobsSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetActiveJobsSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetActiveJobsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetActiveJobsSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetActiveJobsSpectraS3Request WithPriority(Priority? priority) { this._priority = priority; if (priority != null) { this.QueryParams.Add("priority", priority.ToString()); } else { this.QueryParams.Remove("priority"); } return this; } public GetActiveJobsSpectraS3Request WithRechunked(DateTime? rechunked) { this._rechunked = rechunked; if (rechunked != null) { this.QueryParams.Add("rechunked", rechunked.ToString()); } else { this.QueryParams.Remove("rechunked"); } return this; } public GetActiveJobsSpectraS3Request WithRequestType(JobRequestType? requestType) { this._requestType = requestType; if (requestType != null) { this.QueryParams.Add("request_type", requestType.ToString()); } else { this.QueryParams.Remove("request_type"); } return this; } public GetActiveJobsSpectraS3Request WithTruncated(bool? truncated) { this._truncated = truncated; if (truncated != null) { this.QueryParams.Add("truncated", truncated.ToString()); } else { this.QueryParams.Remove("truncated"); } return this; } public GetActiveJobsSpectraS3Request WithUserId(Guid? userId) { this._userId = userId.ToString(); if (userId != null) { this.QueryParams.Add("user_id", userId.ToString()); } else { this.QueryParams.Remove("user_id"); } return this; } public GetActiveJobsSpectraS3Request WithUserId(string userId) { this._userId = userId; if (userId != null) { this.QueryParams.Add("user_id", userId); } else { this.QueryParams.Remove("user_id"); } return this; } public GetActiveJobsSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/active_job"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal readonly partial struct ExpressionBinder { // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- private sealed class ExplicitConversion { private readonly ExpressionBinder _binder; private readonly Expr _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; // This is for lambda error reporting. The reason we have this is because we // store errors for lambda conversions, and then we don't bind the conversion // again to report errors. Consider the following case: // // int? x = () => null; // // When we try to convert the lambda to the nullable type int?, we first // attempt the conversion to int. If that fails, then we know there is no // conversion to int?, since int is a predef type. We then look for UserDefined // conversions, and fail. When we report the errors, we ask the lambda for its // conversion errors. But since we attempted its conversion to int and not int?, // we report the wrong error. This field is to keep track of the right type // to report the error on, so that when the lambda conversion fails, it reports // errors on the correct type. private Expr _exprDest; private readonly bool _needsExprDest; private readonly CONVERTTYPE _flags; // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- public ExplicitConversion(ExpressionBinder binder, Expr exprSrc, CType typeSrc, CType typeDest, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public Expr ExprDest { get { return _exprDest; } } /* * BindExplicitConversion * * This is a complex routine with complex parameter. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with explicit conversions. * * Note that this function calls BindImplicitConversion first, so the main * logic is only concerned with conversions that can be made explicitly, but * not implicitly. */ public bool Bind() { // To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and // canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC). Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0); // 13.2 Explicit conversions // // The following conversions are classified as explicit conversions: // // * All implicit conversions // * Explicit numeric conversions // * Explicit enumeration conversions // * Explicit reference conversions // * Explicit interface conversions // * Unboxing conversions // * Explicit type parameter conversions // * User-defined explicit conversions // * Explicit nullable conversions // * Lifted user-defined explicit conversions // // Explicit conversions can occur in cast expressions (14.6.6). // // The explicit conversions that are not implicit conversions are conversions that cannot be // proven always to succeed, conversions that are known possibly to lose information, and // conversions across domains of types sufficiently different to merit explicit notation. // The set of explicit conversions includes all implicit conversions. // Don't try user-defined conversions now because we'll try them again later. if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT)) { return true; } if (_typeSrc == null || _typeDest == null || _typeDest is MethodGroupType) { return false; } if (_typeDest is NullableType) { // This is handled completely by BindImplicitConversion. return false; } if (_typeSrc is NullableType) { return bindExplicitConversionFromNub(); } if (bindExplicitConversionFromArrayToIList()) { return true; } // if we were casting an integral constant to another constant type, // then, if the constant were in range, then the above call would have succeeded. // But it failed, and so we know that the constant is not in range switch (_typeDest.TypeKind) { default: Debug.Fail($"Bad type kind: {_typeDest.TypeKind}"); return false; case TypeKind.TK_VoidType: return false; // Can't convert to a method group or anon method. case TypeKind.TK_NullType: return false; // Can never convert TO the null type. case TypeKind.TK_ArrayType: if (bindExplicitConversionToArray((ArrayType)_typeDest)) { return true; } break; case TypeKind.TK_PointerType: if (bindExplicitConversionToPointer()) { return true; } break; case TypeKind.TK_AggregateType: { AggCastResult result = bindExplicitConversionToAggregate(_typeDest as AggregateType); if (result == AggCastResult.Success) { return true; } if (result == AggCastResult.Abort) { return false; } break; } } // No built-in conversion was found. Maybe a user-defined conversion? if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromNub() { Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // If S and T are value types and there is a builtin conversion from S => T then there is an // explicit conversion from S? => T that throws on null. if (_typeDest.IsValueType && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _typeDest, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { Expr valueSrc = _exprSrc; if (valueSrc.Type is NullableType) { valueSrc = BindNubValue(valueSrc); } Debug.Assert(valueSrc.Type == _typeSrc.StripNubs()); if (!_binder.BindExplicitConversion(valueSrc, valueSrc.Type, _typeDest, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { Debug.Fail("BindExplicitConversion failed unexpectedly"); return false; } if (_exprDest is ExprUserDefinedConversion udc) { udc.Argument = _exprSrc; } } return true; } if ((_flags & CONVERTTYPE.NOUDC) == 0) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromArrayToIList() { // 13.2.2 // // The explicit reference conversions are: // // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and // their base interfaces, provided there is an explicit reference conversion from S to T. Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); if (!(_typeSrc is ArrayType arrSrc) || !arrSrc.IsSZArray || !(_typeDest is AggregateType aggDest) || !aggDest.IsInterfaceType || aggDest.TypeArgsAll.Count != 1) { return false; } AggregateSymbol aggIList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !SymbolLoader.IsBaseAggregate(aggIList, aggDest.OwningAggregate)) && (aggIReadOnlyList == null || !SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggDest.OwningAggregate))) { return false; } CType typeArr = arrSrc.ElementType; CType typeLst = aggDest.TypeArgsAll[0]; if (!CConversions.FExpRefConv(typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces // to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from // S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (!arrayDest.IsSZArray || !(_typeSrc is AggregateType aggSrc) || !aggSrc.IsInterfaceType || aggSrc.TypeArgsAll.Count != 1) { return false; } AggregateSymbol aggIList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = SymbolLoader.GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !SymbolLoader.IsBaseAggregate(aggIList, aggSrc.OwningAggregate)) && (aggIReadOnlyList == null || !SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggSrc.OwningAggregate))) { return false; } CType typeArr = arrayDest.ElementType; CType typeLst = aggSrc.TypeArgsAll[0]; Debug.Assert(!(typeArr is MethodGroupType)); if (typeArr != typeLst && !CConversions.FExpRefConv(typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element type // TE, provided all of the following are true: // // * S and T differ only in element type. (In other words, S and T have the same number // of dimensions.) // // * An explicit reference conversion exists from SE to TE. if (arraySrc.Rank != arrayDest.Rank || arraySrc.IsSZArray != arrayDest.IsSZArray) { return false; // Ranks do not match. } if (CConversions.FExpRefConv(arraySrc.ElementType, arrayDest.ElementType)) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); } return true; } return false; } private bool bindExplicitConversionToArray(ArrayType arrayDest) { Debug.Assert(_typeSrc != null); Debug.Assert(arrayDest != null); if (_typeSrc is ArrayType arrSrc) { return bindExplicitConversionFromArrayToArray(arrSrc, arrayDest); } if (bindExplicitConversionFromIListToArray(arrayDest)) { return true; } // 13.2.2 // // The explicit reference conversions are: // // * From System.Array and the interfaces it implements, to any array-type. if (_binder.canConvert(GetPredefindType(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToPointer() { // 27.4 Pointer conversions // // in an unsafe context, the set of available explicit conversions (13.2) is extended to // include the following explicit pointer conversions: // // * From any pointer-type to any other pointer-type. // * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type. if (_typeSrc is PointerType || _typeSrc.FundamentalType <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.IsNumericType) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest); return true; } return false; } // 13.2.2 Explicit enumeration conversions // // The explicit enumeration conversions are: // // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or // decimal to any enum-type. // // * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, // float, double, or decimal. // // * From any enum-type to any other enum-type. // // * An explicit enumeration conversion between two types is processed by treating any // participating enum-type as the underlying type of that enum-type, and then performing // an implicit or explicit numeric conversion between the resulting types. private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.IsEnumType) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.OwningAggregate; if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromEnumToDecimal(aggTypeDest); } if (!aggDest.getThisType().IsNumericType && !aggDest.IsEnum() && !(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR)) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } else if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(_typeSrc.IsPredefType(PredefinedType.PT_DECIMAL)); Debug.Assert(aggTypeDest.IsEnumType); // There is an explicit conversion from decimal to all integral types. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // All casts from decimal to integer types are bound as user-defined conversions. bool bIsConversionOK = true; if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. CType underlyingType = aggTypeDest.UnderlyingEnumType; bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false); if (bIsConversionOK) { // upcast to the Enum type _binder.bindSimpleCast(_exprDest, _typeDest, out _exprDest); } } return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); Debug.Assert(aggTypeDest.IsPredefType(PredefinedType.PT_DECIMAL)); Debug.Assert(_typeSrc.IsEnumType); AggregateType underlyingType = _typeSrc.UnderlyingEnumType; // Need to first cast the source expr to its underlying type. Expr exprCast; if (_exprSrc == null) { exprCast = null; } else { _binder.bindSimpleCast(_exprSrc, underlyingType, out exprCast); } // There is always an implicit conversion from any integral type to decimal. if (exprCast.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(exprCast, _typeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // Conversions from integral types to decimal are always bound as a user-defined conversion. if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false); Debug.Assert(ok); } return AggCastResult.Success; } private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggregateSymbol aggDest = aggTypeDest.OwningAggregate; if (!aggDest.IsEnum()) { return AggCastResult.Failure; } if (_typeSrc.IsPredefType(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromDecimalToEnum(aggTypeDest); } if (_typeSrc.IsNumericType || _typeSrc.IsPredefined && _typeSrc.PredefinedType == PredefinedType.PT_CHAR) { // Transform constant to constant. if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest); return AggCastResult.Success; } else if (_typeSrc.IsPredefined && (_typeSrc.IsPredefType(PredefinedType.PT_OBJECT) || _typeSrc.IsPredefType(PredefinedType.PT_VALUE) || _typeSrc.IsPredefType(PredefinedType.PT_ENUM))) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest) { // 13.2.1 // // Because the explicit conversions include all implicit and explicit numeric conversions, // it is always possible to convert from any numeric-type to any other numeric-type using // a cast expression (14.6.6). Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.IsSimpleType || !aggTypeDest.IsSimpleType) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.OwningAggregate; Debug.Assert(_typeSrc.IsPredefined && aggDest.IsPredefined()); PredefinedType ptSrc = _typeSrc.PredefinedType; PredefinedType ptDest = aggDest.GetPredefType(); Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); ConvKind convertKind = GetConvKind(ptSrc, ptDest); // Identity and implicit conversions should already have been handled. Debug.Assert(convertKind != ConvKind.Implicit); Debug.Assert(convertKind != ConvKind.Identity); if (convertKind != ConvKind.Explicit) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _typeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } bool bConversionOk = true; if (_needsExprDest) { // Explicit conversions involving decimals are bound as user-defined conversions. if (isUserDefinedConversion(ptSrc, ptDest)) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false); } else { _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0); } } return bConversionOk ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest) { // 13.2.3 // // The explicit reference conversions are: // // * From object to any reference-type. // * From any class-type S to any class-type T, provided S is a base class of T. // * From any class-type S to any interface-type T, provided S is not sealed and // provided S does not implement T. // * From any interface-type S to any class-type T, provided T is not sealed or provided // T implements S. // * From any interface-type S to any interface-type T, provided S is not derived from T. Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!(_typeSrc is AggregateType atSrc)) { return AggCastResult.Failure; } AggregateSymbol aggSrc = atSrc.OwningAggregate; AggregateSymbol aggDest = aggTypeDest.OwningAggregate; if (SymbolLoader.HasBaseConversion(aggTypeDest, atSrc)) { if (_needsExprDest) { _binder.bindSimpleCast( _exprSrc, _typeDest, out _exprDest, aggDest.IsValueType() && aggSrc.getThisType().FundamentalType == FUNDTYPE.FT_REF ? EXPRFLAG.EXF_UNBOX : EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); } return AggCastResult.Success; } if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface()) || CConversions.HasGenericDelegateExplicitReferenceConversion(_typeSrc, aggTypeDest)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest) { // 27.4 Pointer conversions // in an unsafe context, the set of available explicit conversions (13.2) is extended to include // the following explicit pointer conversions: // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. if (!(_typeSrc is PointerType) || aggTypeDest.FundamentalType > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.IsNumericType) { return AggCastResult.Failure; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _typeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggCastResult result = bindExplicitConversionFromEnumToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionToEnum(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenAggregates(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionFromPointerToInt(aggTypeDest); if (result != AggCastResult.Failure) { return result; } if (_typeSrc is VoidType) { // No conversion is allowed to or from a void type (user defined or otherwise) // This is most likely the result of a failed anonymous method or member group conversion return AggCastResult.Abort; } return AggCastResult.Failure; } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net.Mail; using System.Text; using ASC.Common.Logging; using ASC.Mail.Data.Contracts; using ASC.Mail.Enums; using ASC.Mail.Utils; using MimeKit; namespace ASC.Mail.Extensions { public static class MimeMessageExtensions { public static void FixEncodingIssues(this MimeMessage mimeMessage, ILog logger = null) { if (logger == null) logger = new NullLog(); try { foreach (var mimeEntity in mimeMessage.BodyParts) { var textPart = mimeEntity as TextPart; if (textPart == null || textPart.Content == null || textPart.Content.Encoding != ContentEncoding.Default) { continue; } try { string charset; using (var stream = new MemoryStream()) { textPart.Content.DecodeTo(stream); var bytes = stream.ToArray(); charset = EncodingTools.DetectCharset(bytes); } if (!string.IsNullOrEmpty(charset) && (textPart.ContentType == null || string.IsNullOrEmpty(textPart.ContentType.Charset) || textPart.ContentType.Charset != charset)) { var encoding = EncodingTools.GetEncodingByCodepageName(charset); if (encoding == null) continue; var newText = textPart.GetText(charset); textPart.SetText(encoding, newText); } } catch (Exception ex) { logger.WarnFormat("MimeMessage.FixEncodingIssues->ImproveBodyEncoding: {0}", ex.Message); } } if (mimeMessage.Headers.Contains(HeaderId.From)) { var fromParsed = mimeMessage.From.FirstOrDefault(); if (fromParsed != null && !string.IsNullOrEmpty(fromParsed.Name)) { var fromHeader = mimeMessage.Headers.FirstOrDefault(h => h.Id == HeaderId.From); fromHeader.FixEncodingIssues(logger); } } if (!mimeMessage.Headers.Contains(HeaderId.Subject)) return; var subjectHeader = mimeMessage.Headers.FirstOrDefault(h => h.Id == HeaderId.Subject); subjectHeader.FixEncodingIssues(logger); } catch (Exception ex) { logger.WarnFormat("MimeMessage.FixEncodingIssues: {0}", ex.Message); } } public static void FixEncodingIssues(this Header header, ILog logger = null) { if (logger == null) logger = new NullLog(); try { var rawValueString = Encoding.UTF8.GetString(header.RawValue).Trim(); if (rawValueString.IndexOf("?q?", StringComparison.InvariantCultureIgnoreCase) > -1 || rawValueString.IndexOf("?b?", StringComparison.InvariantCultureIgnoreCase) > -1) { return; } var charset = EncodingTools.DetectCharset(header.RawValue); if (string.IsNullOrEmpty(charset)) return; var newValue = header.GetValue(charset); if (header.Value.Equals(newValue, StringComparison.InvariantCultureIgnoreCase)) return; var encoding = EncodingTools.GetEncodingByCodepageName(charset); header.SetValue(encoding, newValue); } catch (Exception ex) { logger.WarnFormat("Header.FixEncodingIssues: {0}", ex.Message); } } public static void FixDateIssues(this MimeMessage mimeMessage, DateTimeOffset? internalDate = null, ILog logger = null) { if (logger == null) logger = new NullLog(); try { if (!mimeMessage.Headers.Contains(HeaderId.Date) || mimeMessage.Date > DateTimeOffset.UtcNow) { mimeMessage.Date = internalDate ?? DateTimeOffset.UtcNow; } } catch (Exception ex) { logger.WarnFormat("MimeMessage.FixEncodingIssues: {0}", ex.Message); } } public static MailMessageData CreateMailMessage(this MimeMessage message, int mailboxId = -1, FolderType folder = FolderType.Inbox, bool unread = false, string chainId = "", DateTime? chainDate = null, string streamId = "", ILog log = null) { var mail = new MailMessageData(); if (message == null) throw new ArgumentNullException("message"); log = log ?? new NullLog(); mail.MailboxId = mailboxId; var now = DateTime.UtcNow; mail.Date = MailUtil.IsDateCorrect(message.Date.UtcDateTime) ? message.Date.UtcDateTime : now; mail.MimeMessageId = (string.IsNullOrEmpty(message.MessageId) ? MailUtil.CreateMessageId() : message.MessageId) .Trim('<', '>'); mail.ChainId = string.IsNullOrEmpty(chainId) ? mail.MimeMessageId : chainId; mail.ChainDate = chainDate ?? now; mail.MimeReplyToId = mail.ChainId.Equals(mail.MimeMessageId) || string.IsNullOrEmpty(message.InReplyTo) ? null : message.InReplyTo.Trim('<', '>'); mail.ReplyTo = message.ReplyTo.ToString(); mail.From = message.From.ToString(); mail.FromEmail = message.From != null && message.From.Mailboxes != null && message.From.Mailboxes.Any() ? message.From.Mailboxes.First().Address : ""; mail.ToList = message.To.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList(); mail.To = string.Join(", ", message.To.Mailboxes.Select(s => s.ToString())); mail.CcList = message.Cc.Mailboxes.Select(s => new MailAddress(s.Address, s.Name)).ToList(); mail.Cc = string.Join(", ", message.Cc.Mailboxes.Select(s => s.ToString())); mail.Bcc = string.Join(", ", message.Bcc.Mailboxes.Select(s => s.ToString())); mail.Subject = message.Subject ?? string.Empty; mail.Important = message.Importance == MessageImportance.High || message.Priority == MessagePriority.Urgent; mail.TextBodyOnly = false; mail.Introduction = ""; mail.Attachments = new List<MailAttachmentData>(); mail.HtmlBodyStream = new MemoryStream(); mail.ExtractMainParts(message); mail.Size = mail.HtmlBodyStream.Length > 0 ? mail.HtmlBodyStream.Length : mail.HtmlBody.Length; mail.HeaderFieldNames = new NameValueCollection(); message.Headers .ToList() .ForEach(h => mail.HeaderFieldNames.Add(h.Field, h.Value)); mail.Folder = folder; mail.IsNew = unread; mail.StreamId = string.IsNullOrEmpty(streamId) ? MailUtil.CreateStreamId() : streamId; mail.LoadCalendarInfo(message, log); return mail; } public static MailMessageData CreateCorruptedMesage(this MimeMessage message, FolderType folder = FolderType.Inbox, bool unread = false, string chainId = "", string streamId = "") { var mailMessage = new MailMessageData { HasParseError = true }; MailUtil.SkipErrors(() => mailMessage.Date = MailUtil.IsDateCorrect(message.Date.UtcDateTime) ? message.Date.UtcDateTime : DateTime.UtcNow); MailUtil.SkipErrors(() => mailMessage.MimeMessageId = (string.IsNullOrEmpty(message.MessageId) ? MailUtil.CreateMessageId() : message.MessageId) .Trim('<', '>')); MailUtil.SkipErrors(() => mailMessage.ChainId = string.IsNullOrEmpty(chainId) ? mailMessage.MimeMessageId : chainId); MailUtil.SkipErrors(() => mailMessage.MimeReplyToId = mailMessage.ChainId.Equals(mailMessage.MimeMessageId) ? null : message.InReplyTo.Trim('<', '>')); MailUtil.SkipErrors(() => mailMessage.ReplyTo = message.ReplyTo.ToString()); MailUtil.SkipErrors(() => mailMessage.From = message.From.ToString()); MailUtil.SkipErrors(() => mailMessage.FromEmail = message.From != null && message.From.Mailboxes != null && message.From.Mailboxes.Any() ? message.From.Mailboxes.First().Address : ""); MailUtil.SkipErrors(() => mailMessage.ToList = message.To.Mailboxes.Select(s => MailUtil.ExecuteSafe(() => new MailAddress(s.Address, s.Name))).ToList()); MailUtil.SkipErrors(() => mailMessage.To = string.Join(", ", message.To.Mailboxes.Select(s => s.ToString()))); MailUtil.SkipErrors(() => mailMessage.CcList = message.Cc.Mailboxes.Select(s => MailUtil.ExecuteSafe(() => new MailAddress(s.Address, s.Name))).ToList()); MailUtil.SkipErrors(() => mailMessage.Cc = string.Join(", ", message.Cc.Mailboxes.Select(s => s.ToString()))); MailUtil.SkipErrors(() => mailMessage.Bcc = string.Join(", ", message.Bcc.Mailboxes.Select(s => s.ToString()))); MailUtil.SkipErrors(() => mailMessage.Subject = message.Subject ?? string.Empty); MailUtil.SkipErrors(() => mailMessage.Important = message.Importance == MessageImportance.High || message.Priority == MessagePriority.Urgent); mailMessage.HtmlBodyStream = new MemoryStream(); using (var sw = new StreamWriter(mailMessage.HtmlBodyStream, Encoding.UTF8, 1024, true)) { sw.Write("<body><pre>&nbsp;</pre></body>"); sw.Flush(); } mailMessage.Size = mailMessage.HtmlBodyStream.Length; mailMessage.HeaderFieldNames = new NameValueCollection(); message.Headers .ToList() .ForEach(h => MailUtil.SkipErrors(() => mailMessage.HeaderFieldNames.Add(h.Field, h.Value))); mailMessage.Folder = folder; mailMessage.IsNew = unread; mailMessage.StreamId = string.IsNullOrEmpty(streamId) ? MailUtil.CreateStreamId() : streamId; mailMessage.TextBodyOnly = true; mailMessage.Introduction = ""; mailMessage.Attachments = new List<MailAttachmentData>(); MailUtil.SkipErrors(() => { var mailAttach = new MailAttachmentData { contentId = null, fileName = "message.eml", contentType = "message/rfc822", contentLocation = null, dataStream = new MemoryStream() }; message.WriteTo(mailAttach.dataStream); mailAttach.size = mailAttach.dataStream.Length; mailMessage.Attachments.Add(mailAttach); }); return mailMessage; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Text; namespace System.Net { public sealed unsafe partial class HttpListenerResponse : IDisposable { private BoundaryType _boundaryType = BoundaryType.None; private CookieCollection _cookies; private readonly HttpListenerContext _httpContext; private bool _keepAlive = true; private HttpResponseStream _responseStream; private string _statusDescription; private WebHeaderCollection _webHeaders = new WebHeaderCollection(); public WebHeaderCollection Headers { get => _webHeaders; set { _webHeaders = new WebHeaderCollection(); foreach (string headerName in value.AllKeys) { _webHeaders.Add(headerName, value[headerName]); } } } public Encoding ContentEncoding { get; set; } public string ContentType { get => Headers[HttpKnownHeaderNames.ContentType]; set { CheckDisposed(); if (string.IsNullOrEmpty(value)) { Headers.Remove(HttpKnownHeaderNames.ContentType); } else { Headers.Set(HttpKnownHeaderNames.ContentType, value); } } } private HttpListenerContext HttpListenerContext => _httpContext; private HttpListenerRequest HttpListenerRequest => HttpListenerContext.Request; internal EntitySendFormat EntitySendFormat { get => (EntitySendFormat)_boundaryType; set { CheckDisposed(); CheckSentHeaders(); if (value == EntitySendFormat.Chunked && HttpListenerRequest.ProtocolVersion.Minor == 0) { throw new ProtocolViolationException(SR.net_nochunkuploadonhttp10); } _boundaryType = (BoundaryType)value; if (value != EntitySendFormat.ContentLength) { _contentLength = -1; } } } public bool SendChunked { get => EntitySendFormat == EntitySendFormat.Chunked; set => EntitySendFormat = value ? EntitySendFormat.Chunked : EntitySendFormat.ContentLength; } // We MUST NOT send message-body when we send responses with these Status codes private static readonly int[] s_noResponseBody = { 100, 101, 204, 205, 304 }; private static bool CanSendResponseBody(int responseCode) { for (int i = 0; i < s_noResponseBody.Length; i++) { if (responseCode == s_noResponseBody[i]) { return false; } } return true; } public long ContentLength64 { get => _contentLength; set { CheckDisposed(); CheckSentHeaders(); if (value >= 0) { _contentLength = value; _boundaryType = BoundaryType.ContentLength; } else { throw new ArgumentOutOfRangeException(nameof(value), SR.net_clsmall); } } } public CookieCollection Cookies { get => _cookies ?? (_cookies = new CookieCollection()); set => _cookies = value; } public bool KeepAlive { get => _keepAlive; set { CheckDisposed(); _keepAlive = value; } } public Stream OutputStream { get { CheckDisposed(); EnsureResponseStream(); return _responseStream; } } public string RedirectLocation { get => Headers[HttpResponseHeader.Location]; set { // note that this doesn't set the status code to a redirect one CheckDisposed(); if (string.IsNullOrEmpty(value)) { Headers.Remove(HttpKnownHeaderNames.Location); } else { Headers.Set(HttpKnownHeaderNames.Location, value); } } } public string StatusDescription { get { if (_statusDescription == null) { // if the user hasn't set this, generated on the fly, if possible. // We know this one is safe, no need to verify it as in the setter. _statusDescription = HttpStatusDescription.Get(StatusCode); } if (_statusDescription == null) { _statusDescription = string.Empty; } return _statusDescription; } set { CheckDisposed(); if (value == null) { throw new ArgumentNullException(nameof(value)); } // Need to verify the status description doesn't contain any control characters except HT. We mask off the high // byte since that's how it's encoded. for (int i = 0; i < value.Length; i++) { char c = (char)(0x000000ff & (uint)value[i]); if ((c <= 31 && c != (byte)'\t') || c == 127) { throw new ArgumentException(SR.net_WebHeaderInvalidControlChars, "name"); } } _statusDescription = value; } } public void AddHeader(string name, string value) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"name={name}, value={value}"); Headers.Set(name, value); } public void AppendHeader(string name, string value) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"name={name}, value={value}"); Headers.Add(name, value); } public void AppendCookie(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"cookie: {cookie}"); Cookies.Add(cookie); } private void ComputeCookies() { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Entering Set-Cookie: {Headers[HttpResponseHeader.SetCookie]}, Set-Cookie2: {Headers[HttpKnownHeaderNames.SetCookie2]}"); if (_cookies != null) { // now go through the collection, and concatenate all the cookies in per-variant strings string setCookie2 = null, setCookie = null; for (int index = 0; index < _cookies.Count; index++) { Cookie cookie = _cookies[index]; string cookieString = cookie.ToServerString(); if (cookieString == null || cookieString.Length == 0) { continue; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Now looking at index:{index} cookie: {cookie}"); if (cookie.IsRfc2965Variant()) { setCookie2 = setCookie2 == null ? cookieString : setCookie2 + ", " + cookieString; } else { setCookie = setCookie == null ? cookieString : setCookie + ", " + cookieString; } } if (!string.IsNullOrEmpty(setCookie)) { Headers.Set(HttpKnownHeaderNames.SetCookie, setCookie); if (string.IsNullOrEmpty(setCookie2)) { Headers.Remove(HttpKnownHeaderNames.SetCookie2); } } if (!string.IsNullOrEmpty(setCookie2)) { Headers.Set(HttpKnownHeaderNames.SetCookie2, setCookie2); if (string.IsNullOrEmpty(setCookie)) { Headers.Remove(HttpKnownHeaderNames.SetCookie); } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Exiting Set-Cookie: {Headers[HttpResponseHeader.SetCookie]} Set-Cookie2: {Headers[HttpKnownHeaderNames.SetCookie2]}"); } public void Redirect(string url) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"url={url}"); Headers[HttpResponseHeader.Location] = url; StatusCode = (int)HttpStatusCode.Redirect; StatusDescription = HttpStatusDescription.Get(StatusCode); } public void SetCookie(Cookie cookie) { if (cookie == null) { throw new ArgumentNullException(nameof(cookie)); } Cookie newCookie = cookie.Clone(); int added = Cookies.InternalAdd(newCookie, true); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"cookie: {cookie}"); if (added != 1) { // The Cookie already existed and couldn't be replaced. throw new ArgumentException(SR.net_cookie_exists, nameof(cookie)); } } void IDisposable.Dispose() => Dispose(); private void CheckDisposed() { if (Disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckSentHeaders() { if (SentHeaders) { throw new InvalidOperationException(SR.net_rspsubmitted); } } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Google.Protobuf; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; using NUnit.Framework; using Grpc.Testing; namespace Grpc.IntegrationTesting { /// <summary> /// Helper methods to start client runners for performance testing. /// </summary> public class ClientRunners { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<ClientRunners>(); // Profilers to use for clients. static readonly BlockingCollection<BasicProfiler> profilers = new BlockingCollection<BasicProfiler>(); internal static void AddProfiler(BasicProfiler profiler) { GrpcPreconditions.CheckNotNull(profiler); profilers.Add(profiler); } /// <summary> /// Creates a started client runner. /// </summary> public static IClientRunner CreateStarted(ClientConfig config) { Logger.Debug("ClientConfig: {0}", config); if (config.AsyncClientThreads != 0) { Logger.Warning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value"); } if (config.CoreLimit != 0) { Logger.Warning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value"); } if (config.CoreList.Count > 0) { Logger.Warning("ClientConfig.CoreList is not supported for C#. Ignoring the value"); } var channels = CreateChannels(config.ClientChannels, config.ServerTargets, config.SecurityParams); return new ClientRunnerImpl(channels, config.ClientType, config.RpcType, config.OutstandingRpcsPerChannel, config.LoadParams, config.PayloadConfig, config.HistogramParams, () => GetNextProfiler()); } private static List<Channel> CreateChannels(int clientChannels, IEnumerable<string> serverTargets, SecurityParams securityParams) { GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1."); GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified."); var credentials = securityParams != null ? TestCredentials.CreateSslCredentials() : ChannelCredentials.Insecure; List<ChannelOption> channelOptions = null; if (securityParams != null && securityParams.ServerHostOverride != "") { channelOptions = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, securityParams.ServerHostOverride) }; } var result = new List<Channel>(); for (int i = 0; i < clientChannels; i++) { var target = serverTargets.ElementAt(i % serverTargets.Count()); var channel = new Channel(target, credentials, channelOptions); result.Add(channel); } return result; } private static BasicProfiler GetNextProfiler() { BasicProfiler result = null; profilers.TryTake(out result); return result; } } internal class ClientRunnerImpl : IClientRunner { const double SecondsToNanos = 1e9; readonly List<Channel> channels; readonly ClientType clientType; readonly RpcType rpcType; readonly PayloadConfig payloadConfig; readonly Histogram histogram; readonly List<Task> runnerTasks; readonly CancellationTokenSource stoppedCts = new CancellationTokenSource(); readonly WallClockStopwatch wallClockStopwatch = new WallClockStopwatch(); readonly AtomicCounter statsResetCount = new AtomicCounter(); public ClientRunnerImpl(List<Channel> channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams, Func<BasicProfiler> profilerFactory) { GrpcPreconditions.CheckArgument(outstandingRpcsPerChannel > 0, "outstandingRpcsPerChannel"); GrpcPreconditions.CheckNotNull(histogramParams, "histogramParams"); this.channels = new List<Channel>(channels); this.clientType = clientType; this.rpcType = rpcType; this.payloadConfig = payloadConfig; this.histogram = new Histogram(histogramParams.Resolution, histogramParams.MaxPossible); this.runnerTasks = new List<Task>(); foreach (var channel in this.channels) { for (int i = 0; i < outstandingRpcsPerChannel; i++) { var timer = CreateTimer(loadParams, 1.0 / this.channels.Count / outstandingRpcsPerChannel); var optionalProfiler = profilerFactory(); this.runnerTasks.Add(RunClientAsync(channel, timer, optionalProfiler)); } } } public ClientStats GetStats(bool reset) { var histogramData = histogram.GetSnapshot(reset); var secondsElapsed = wallClockStopwatch.GetElapsedSnapshot(reset).TotalSeconds; if (reset) { statsResetCount.Increment(); } // TODO: populate user time and system time return new ClientStats { Latencies = histogramData, TimeElapsed = secondsElapsed, TimeUser = 0, TimeSystem = 0 }; } public async Task StopAsync() { stoppedCts.Cancel(); foreach (var runnerTask in runnerTasks) { await runnerTask; } foreach (var channel in channels) { await channel.ShutdownAsync(); } } private void RunUnary(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler) { if (optionalProfiler != null) { Profilers.SetForCurrentThread(optionalProfiler); } bool profilerReset = false; var client = BenchmarkService.NewClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { // after the first stats reset, also reset the profiler. if (optionalProfiler != null && !profilerReset && statsResetCount.Count > 0) { optionalProfiler.Reset(); profilerReset = true; } stopwatch.Restart(); client.UnaryCall(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); timer.WaitForNext(); } } private async Task RunUnaryAsync(Channel channel, IInterarrivalTimer timer) { var client = BenchmarkService.NewClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await client.UnaryCallAsync(request); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } } private async Task RunStreamingPingPongAsync(Channel channel, IInterarrivalTimer timer) { var client = BenchmarkService.NewClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); using (var call = client.StreamingCall()) { while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } } private async Task RunGenericStreamingAsync(Channel channel, IInterarrivalTimer timer) { var request = CreateByteBufferRequest(); var stopwatch = new Stopwatch(); var callDetails = new CallInvocationDetails<byte[], byte[]>(channel, GenericService.StreamingCallMethod, new CallOptions()); using (var call = Calls.AsyncDuplexStreamingCall(callDetails)) { while (!stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. histogram.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); Assert.IsFalse(await call.ResponseStream.MoveNext()); } } private Task RunClientAsync(Channel channel, IInterarrivalTimer timer, BasicProfiler optionalProfiler) { if (payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams) { GrpcPreconditions.CheckArgument(clientType == ClientType.AsyncClient, "Generic client only supports async API"); GrpcPreconditions.CheckArgument(rpcType == RpcType.Streaming, "Generic client only supports streaming calls"); return RunGenericStreamingAsync(channel, timer); } GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams); if (clientType == ClientType.SyncClient) { GrpcPreconditions.CheckArgument(rpcType == RpcType.Unary, "Sync client can only be used for Unary calls in C#"); // create a dedicated thread for the synchronous client return Task.Factory.StartNew(() => RunUnary(channel, timer, optionalProfiler), TaskCreationOptions.LongRunning); } else if (clientType == ClientType.AsyncClient) { switch (rpcType) { case RpcType.Unary: return RunUnaryAsync(channel, timer); case RpcType.Streaming: return RunStreamingPingPongAsync(channel, timer); } } throw new ArgumentException("Unsupported configuration."); } private SimpleRequest CreateSimpleRequest() { GrpcPreconditions.CheckNotNull(payloadConfig.SimpleParams); return new SimpleRequest { Payload = CreateZerosPayload(payloadConfig.SimpleParams.ReqSize), ResponseSize = payloadConfig.SimpleParams.RespSize }; } private byte[] CreateByteBufferRequest() { return new byte[payloadConfig.BytebufParams.ReqSize]; } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } private static IInterarrivalTimer CreateTimer(LoadParams loadParams, double loadMultiplier) { switch (loadParams.LoadCase) { case LoadParams.LoadOneofCase.ClosedLoop: return new ClosedLoopInterarrivalTimer(); case LoadParams.LoadOneofCase.Poisson: return new PoissonInterarrivalTimer(loadParams.Poisson.OfferedLoad * loadMultiplier); default: throw new ArgumentException("Unknown load type"); } } } }
// 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.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { public static IntPtr GetMainWindowHandle(int processId) { MainWindowFinder finder = new MainWindowFinder(); return finder.FindMainWindow(processId); } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, isRemoteMachine: true) : NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine } } internal sealed class MainWindowFinder { private const int GW_OWNER = 4; private IntPtr _bestHandle; private int _processId; public IntPtr FindMainWindow(int processId) { _bestHandle = (IntPtr)0; _processId = processId; Interop.User32.EnumThreadWindowsCallback callback = new Interop.User32.EnumThreadWindowsCallback(EnumWindowsCallback); Interop.User32.EnumWindows(callback, IntPtr.Zero); GC.KeepAlive(callback); return _bestHandle; } private bool IsMainWindow(IntPtr handle) { if (Interop.User32.GetWindow(handle, GW_OWNER) != (IntPtr)0 || !Interop.User32.IsWindowVisible(handle)) return false; return true; } private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) { int processId; Interop.User32.GetWindowThreadProcessId(handle, out processId); if (processId == _processId) { if (IsMainWindow(handle)) { _bestHandle = handle; return false; } } return true; } } internal static partial class NtProcessManager { private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (;;) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount); char[] chars = new char[1024]; for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } } IntPtr moduleHandle = moduleHandles[i]; Interop.Kernel32.NtModuleInfo ntModuleInfo; if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo)) { HandleError(); continue; } var module = new ProcessModule() { ModuleMemorySize = ntModuleInfo.SizeOfImage, EntryPointAddress = ntModuleInfo.EntryPoint, BaseAddress = ntModuleInfo.BaseOfDll }; int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.ModuleName = new string(chars, 0, length); length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ? new string(chars, 4, length - 4) : new string(chars, 0, length); modules.Add(module); } return modules; } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } } internal static partial class NtProcessInfoHelper { // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; public static ProcessInfo[] GetProcessInfos() { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject()); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } } }
using System; using System.Collections.Generic; using System.Text; namespace DSPUtil { public class HRTF { public static FilterProfile diffuseDiff0() { // from Farina data 0 degrees FilterProfile lfg = new FilterProfile(); lfg.Add(new FreqGain(29.8999517172724, -0.819594013962942)); lfg.Add(new FreqGain(45.9318520170928, -0.825206846036483)); lfg.Add(new FreqGain(62.7349359370437, -0.843228404280093)); lfg.Add(new FreqGain(80.348144199439, -0.85549279781466)); lfg.Add(new FreqGain(98.812561979239, -0.885552104079416)); lfg.Add(new FreqGain(118.171554124747, -0.921814975716754)); lfg.Add(new FreqGain(138.470910523652, -0.941989434053033)); lfg.Add(new FreqGain(159.759002525445, -0.986288515963084)); lfg.Add(new FreqGain(182.086951427111, -1.03487811152306)); lfg.Add(new FreqGain(205.508810136376, -1.08724309366587)); lfg.Add(new FreqGain(230.081759247243, -1.14301616694228)); lfg.Add(new FreqGain(255.866318897917, -1.20202072457563)); lfg.Add(new FreqGain(282.926577933456, -1.29716987120868)); lfg.Add(new FreqGain(311.330442067148, -1.36375538636994)); lfg.Add(new FreqGain(341.14990292827, -1.4644642435199)); lfg.Add(new FreqGain(372.461330102897, -1.52904718749126)); lfg.Add(new FreqGain(405.345788522409, -1.61553093677067)); lfg.Add(new FreqGain(439.889383835671, -1.68163798221837)); lfg.Add(new FreqGain(476.183638720577, -1.71733965267451)); lfg.Add(new FreqGain(514.325903454604, -1.71900339686128)); lfg.Add(new FreqGain(554.419804479247, -1.66747850462173)); lfg.Add(new FreqGain(596.575735167586, -1.59447747686689)); lfg.Add(new FreqGain(640.911393547776, -1.45582456727674)); lfg.Add(new FreqGain(687.552372358488, -1.28169168214036)); lfg.Add(new FreqGain(736.632807529586, -1.08266101402942)); lfg.Add(new FreqGain(788.296092007413, -0.799257236450344)); lfg.Add(new FreqGain(842.695662798627, -0.550308170104235)); lfg.Add(new FreqGain(899.99587021156, -0.216876477890536)); lfg.Add(new FreqGain(960.372939556513, 0.123762097833653)); lfg.Add(new FreqGain(1024.01603705869, 0.504501005258036)); lfg.Add(new FreqGain(1091.12845347812, 0.806009630861022)); lfg.Add(new FreqGain(1161.92892096669, 0.970563802808751)); lfg.Add(new FreqGain(1236.65308108085, 0.993384317252108)); lfg.Add(new FreqGain(1315.55512467678, 0.899269754624433)); lfg.Add(new FreqGain(1398.90962772937, 0.71574567174392)); lfg.Add(new FreqGain(1487.01361103779, 0.42413561491627)); lfg.Add(new FreqGain(1580.18885643692, 0.0143087139306365)); lfg.Add(new FreqGain(1678.7845176806, -0.374163000274005)); lfg.Add(new FreqGain(1783.18007079301, -0.604206586990272)); lfg.Add(new FreqGain(1893.78865663959, -0.643361845768994)); lfg.Add(new FreqGain(2011.06087804797, -0.450261422187758)); lfg.Add(new FreqGain(2135.48912539139, -0.117143308385737)); lfg.Add(new FreqGain(2267.61251860637, 0.0726448007728625)); lfg.Add(new FreqGain(2408.02257075748, 0.149673576192565)); lfg.Add(new FreqGain(2557.3696992537, -0.0705597943707172)); lfg.Add(new FreqGain(2716.3707366486, -0.615399531580617)); lfg.Add(new FreqGain(2885.81762489105, -0.715844747528019)); lfg.Add(new FreqGain(3066.58751658265, -0.80980936924732)); lfg.Add(new FreqGain(3259.65455639083, -0.724599496650513)); lfg.Add(new FreqGain(3466.1036780904, -1.74219819410634)); lfg.Add(new FreqGain(3687.14683149463, -3.60307539107681)); lfg.Add(new FreqGain(3924.14215377249, -5.62149036113584)); lfg.Add(new FreqGain(4178.61672801844, -7.30684974206415)); lfg.Add(new FreqGain(4452.29373750316, -9.58452126557679)); lfg.Add(new FreqGain(4747.12503915768, -12.7988548069547)); lfg.Add(new FreqGain(5065.3304615832, -14.2817841410128)); lfg.Add(new FreqGain(5409.44550497149, -14.3089505650728)); lfg.Add(new FreqGain(5782.37961614996, -14.7676142885599)); lfg.Add(new FreqGain(6187.48787900699, -15.4620314368829)); lfg.Add(new FreqGain(6628.65986711531, -17.5471846623073)); lfg.Add(new FreqGain(7110.43065099071, -16.7838733846363)); lfg.Add(new FreqGain(7638.12068410502, -11.2810169858127)); lfg.Add(new FreqGain(8218.013729816, -6.43017437119144)); lfg.Add(new FreqGain(8857.58547111898, -2.58756224649037)); lfg.Add(new FreqGain(9565.80048575836, -3.18112947019392)); lfg.Add(new FreqGain(10353.5026895216, -5.40667046909438)); lfg.Add(new FreqGain(11233.9354678215, -3.35732869042161)); lfg.Add(new FreqGain(12223.4446965003, -1.40180859827503)); lfg.Add(new FreqGain(13342.444347283, -2.18457352314182)); lfg.Add(new FreqGain(14616.7666969568, -2.52559711716481)); lfg.Add(new FreqGain(16079.5885672628, -2.64456253082918)); lfg.Add(new FreqGain(17774.2422466263, -2.07661523855391)); lfg.Add(new FreqGain(19758.4244207167, -0.0243216938532986)); lfg.Add(new FreqGain(22110.6876081231, -0.00493030880131535)); return lfg; } public static FilterProfile diffuseDiff15() { // from Farina data -15 degrees FilterProfile lfg = new FilterProfile(); lfg.Add(new FreqGain(29.8999517172724, -0.0863917163326701)); lfg.Add(new FreqGain(45.9318520170928, -0.086646594026467)); lfg.Add(new FreqGain(62.7349359370437, -0.0874548658683244)); lfg.Add(new FreqGain(80.348144199439, -0.0879751392064135)); lfg.Add(new FreqGain(98.812561979239, -0.0890868621043947)); lfg.Add(new FreqGain(118.171554124747, -0.0902608074810529)); lfg.Add(new FreqGain(138.470910523652, -0.0909038889250574)); lfg.Add(new FreqGain(159.759002525445, -0.0923344140142375)); lfg.Add(new FreqGain(182.086951427111, -0.0937822151583515)); lfg.Add(new FreqGain(205.508810136376, -0.0951728613131329)); lfg.Add(new FreqGain(230.081759247243, -0.0964831892699499)); lfg.Add(new FreqGain(255.866318897917, -0.0977855409466679)); lfg.Add(new FreqGain(282.926577933456, -0.0996764404835705)); lfg.Add(new FreqGain(311.330442067148, -0.100486603558354)); lfg.Add(new FreqGain(341.14990292827, -0.100051270274286)); lfg.Add(new FreqGain(372.461330102897, -0.0979260196990259)); lfg.Add(new FreqGain(405.345788522409, -0.0908775515206414)); lfg.Add(new FreqGain(439.889383835671, -0.0782636965770721)); lfg.Add(new FreqGain(476.183638720577, -0.0589294155247667)); lfg.Add(new FreqGain(514.325903454604, -0.0331101724182802)); lfg.Add(new FreqGain(554.419804479247, 0.0100958113611724)); lfg.Add(new FreqGain(596.575735167586, 0.0479470506982144)); lfg.Add(new FreqGain(640.911393547776, 0.105430778442781)); lfg.Add(new FreqGain(687.552372358488, 0.168896217319817)); lfg.Add(new FreqGain(736.632807529586, 0.237255771124081)); lfg.Add(new FreqGain(788.296092007413, 0.328490953798301)); lfg.Add(new FreqGain(842.695662798627, 0.402734259074768)); lfg.Add(new FreqGain(899.99587021156, 0.494326782264423)); lfg.Add(new FreqGain(960.372939556513, 0.578128079437876)); lfg.Add(new FreqGain(1024.01603705869, 0.660125601312093)); lfg.Add(new FreqGain(1091.12845347812, 0.712681005041455)); lfg.Add(new FreqGain(1161.92892096669, 0.732542794364541)); lfg.Add(new FreqGain(1236.65308108085, 0.726404101177543)); lfg.Add(new FreqGain(1315.55512467678, 0.698273367243763)); lfg.Add(new FreqGain(1398.90962772937, 0.645682099120009)); lfg.Add(new FreqGain(1487.01361103779, 0.571255784106514)); lfg.Add(new FreqGain(1580.18885643692, 0.4830388210465)); lfg.Add(new FreqGain(1678.7845176806, 0.408070371811873)); lfg.Add(new FreqGain(1783.18007079301, 0.35550515378515)); lfg.Add(new FreqGain(1893.78865663959, 0.319200925184918)); lfg.Add(new FreqGain(2011.06087804797, 0.311247539991447)); lfg.Add(new FreqGain(2135.48912539139, 0.320676353553954)); lfg.Add(new FreqGain(2267.61251860637, 0.337219551748223)); lfg.Add(new FreqGain(2408.02257075748, 0.396218572472187)); lfg.Add(new FreqGain(2557.3696992537, 0.477239191635716)); lfg.Add(new FreqGain(2716.3707366486, 0.49349820475482)); lfg.Add(new FreqGain(2885.81762489105, 0.454308524133459)); lfg.Add(new FreqGain(3066.58751658265, 0.202619261440745)); lfg.Add(new FreqGain(3259.65455639083, -0.229775101327912)); lfg.Add(new FreqGain(3466.1036780904, -0.679735290459132)); lfg.Add(new FreqGain(3687.14683149463, -1.14273604455762)); lfg.Add(new FreqGain(3924.14215377249, -1.58712231737431)); lfg.Add(new FreqGain(4178.61672801844, -2.24464955682634)); lfg.Add(new FreqGain(4452.29373750316, -2.95221883480249)); lfg.Add(new FreqGain(4747.12503915768, -3.59713042788595)); lfg.Add(new FreqGain(5065.3304615832, -3.95400511725521)); lfg.Add(new FreqGain(5409.44550497149, -4.26734231473008)); lfg.Add(new FreqGain(5782.37961614996, -4.29752236704959)); lfg.Add(new FreqGain(6187.48787900699, -3.80417940781499)); lfg.Add(new FreqGain(6628.65986711531, -3.42269750300152)); lfg.Add(new FreqGain(7110.43065099071, -2.67952601614751)); lfg.Add(new FreqGain(7638.12068410502, -1.40074317089712)); lfg.Add(new FreqGain(8218.013729816, -0.278815569277744)); lfg.Add(new FreqGain(8857.58547111898, -0.10133776498712)); lfg.Add(new FreqGain(9565.80048575836, -1.16608058344807)); lfg.Add(new FreqGain(10353.5026895216, -1.11758243515913)); lfg.Add(new FreqGain(11233.9354678215, 0.278943448347119)); lfg.Add(new FreqGain(12223.4446965003, 0.908362838092288)); lfg.Add(new FreqGain(13342.444347283, 0.57561474694365)); lfg.Add(new FreqGain(14616.7666969568, -0.0622868258733881)); lfg.Add(new FreqGain(16079.5885672628, -0.254955438747692)); lfg.Add(new FreqGain(17774.2422466263, -0.24984582194041)); lfg.Add(new FreqGain(19758.4244207167, -0.00233095236861375)); lfg.Add(new FreqGain(22110.6876081231, -0.000536752738788648)); return lfg; } public static FilterProfile diffuseDiff30() { // from Farina data -30 degrees FilterProfile lfg = new FilterProfile(); lfg.Add(new FreqGain(29.8999517172724, 0.0153703412721632)); lfg.Add(new FreqGain(45.9318520170928, 0.0157412462362341)); lfg.Add(new FreqGain(62.7349359370437, 0.0169348231887618)); lfg.Add(new FreqGain(80.348144199439, 0.0177668016028915)); lfg.Add(new FreqGain(98.812561979239, 0.0199231953358116)); lfg.Add(new FreqGain(118.171554124747, 0.0226506268703839)); lfg.Add(new FreqGain(138.470910523652, 0.0241826281526221)); lfg.Add(new FreqGain(159.759002525445, 0.0275609026693427)); lfg.Add(new FreqGain(182.086951427111, 0.0314140735720051)); lfg.Add(new FreqGain(205.508810136376, 0.0357721055372592)); lfg.Add(new FreqGain(230.081759247243, 0.0406187033498547)); lfg.Add(new FreqGain(255.866318897917, 0.045887705945406)); lfg.Add(new FreqGain(282.926577933456, 0.0546401434119344)); lfg.Add(new FreqGain(311.330442067148, 0.0611568261029155)); lfg.Add(new FreqGain(341.14990292827, 0.0721646415370508)); lfg.Add(new FreqGain(372.461330102897, 0.0804691995918961)); lfg.Add(new FreqGain(405.345788522409, 0.0944756139816788)); lfg.Add(new FreqGain(439.889383835671, 0.110303869737514)); lfg.Add(new FreqGain(476.183638720577, 0.127959954687666)); lfg.Add(new FreqGain(514.325903454604, 0.14722607642479)); lfg.Add(new FreqGain(554.419804479247, 0.174693312387337)); lfg.Add(new FreqGain(596.575735167586, 0.196367637676681)); lfg.Add(new FreqGain(640.911393547776, 0.226502192739724)); lfg.Add(new FreqGain(687.552372358488, 0.257404487702997)); lfg.Add(new FreqGain(736.632807529586, 0.289308287895174)); lfg.Add(new FreqGain(788.296092007413, 0.330164254725067)); lfg.Add(new FreqGain(842.695662798627, 0.362004711488242)); lfg.Add(new FreqGain(899.99587021156, 0.399201023703967)); lfg.Add(new FreqGain(960.372939556513, 0.430608404836277)); lfg.Add(new FreqGain(1024.01603705869, 0.459162211936077)); lfg.Add(new FreqGain(1091.12845347812, 0.477917208748288)); lfg.Add(new FreqGain(1161.92892096669, 0.4888832470924)); lfg.Add(new FreqGain(1236.65308108085, 0.491406736478912)); lfg.Add(new FreqGain(1315.55512467678, 0.482634965114746)); lfg.Add(new FreqGain(1398.90962772937, 0.460215735460547)); lfg.Add(new FreqGain(1487.01361103779, 0.42785945371676)); lfg.Add(new FreqGain(1580.18885643692, 0.384755864426881)); lfg.Add(new FreqGain(1678.7845176806, 0.338743142917392)); lfg.Add(new FreqGain(1783.18007079301, 0.29481578763389)); lfg.Add(new FreqGain(1893.78865663959, 0.256334042859472)); lfg.Add(new FreqGain(2011.06087804797, 0.230791717775949)); lfg.Add(new FreqGain(2135.48912539139, 0.222331981999943)); lfg.Add(new FreqGain(2267.61251860637, 0.242145604431654)); lfg.Add(new FreqGain(2408.02257075748, 0.274638622926097)); lfg.Add(new FreqGain(2557.3696992537, 0.30577186219793)); lfg.Add(new FreqGain(2716.3707366486, 0.313600675670305)); lfg.Add(new FreqGain(2885.81762489105, 0.24417849843071)); lfg.Add(new FreqGain(3066.58751658265, 0.0849830918843977)); lfg.Add(new FreqGain(3259.65455639083, -0.184798841769974)); lfg.Add(new FreqGain(3466.1036780904, -0.532453036199661)); lfg.Add(new FreqGain(3687.14683149463, -0.919617070793028)); lfg.Add(new FreqGain(3924.14215377249, -1.23374473854346)); lfg.Add(new FreqGain(4178.61672801844, -1.41321418967923)); lfg.Add(new FreqGain(4452.29373750316, -1.64528910099878)); lfg.Add(new FreqGain(4747.12503915768, -1.89417809903332)); lfg.Add(new FreqGain(5065.3304615832, -1.92858810971928)); lfg.Add(new FreqGain(5409.44550497149, -1.69347768706069)); lfg.Add(new FreqGain(5782.37961614996, -1.17378189132115)); lfg.Add(new FreqGain(6187.48787900699, -0.583107768215692)); lfg.Add(new FreqGain(6628.65986711531, -0.077364511850989)); lfg.Add(new FreqGain(7110.43065099071, 0.242584278157174)); lfg.Add(new FreqGain(7638.12068410502, 0.497534967708144)); lfg.Add(new FreqGain(8218.013729816, 0.593572397741133)); lfg.Add(new FreqGain(8857.58547111898, 0.197431152769074)); lfg.Add(new FreqGain(9565.80048575836, 0.179647743864568)); lfg.Add(new FreqGain(10353.5026895216, 0.240381170494958)); lfg.Add(new FreqGain(11233.9354678215, 0.767127553409873)); lfg.Add(new FreqGain(12223.4446965003, 0.957392389217609)); lfg.Add(new FreqGain(13342.444347283, 0.575418314572688)); lfg.Add(new FreqGain(14616.7666969568, 0.178440138798458)); lfg.Add(new FreqGain(16079.5885672628, -0.0565288100190609)); lfg.Add(new FreqGain(17774.2422466263, -0.0358792500656471)); lfg.Add(new FreqGain(19758.4244207167, 2.12975819769935E-05)); lfg.Add(new FreqGain(22110.6876081231, -0.000421783662717478)); return lfg; } public static FilterProfile diffuseDiff45() { // from Farina data -45 degrees FilterProfile lfg = new FilterProfile(); lfg.Add(new FreqGain(29.8999517172724, 0.034493028904745)); lfg.Add(new FreqGain(45.9318520170928, 0.0348965563859305)); lfg.Add(new FreqGain(62.7349359370437, 0.0361962782805971)); lfg.Add(new FreqGain(80.348144199439, 0.0370951759531601)); lfg.Add(new FreqGain(98.812561979239, 0.0393802905089846)); lfg.Add(new FreqGain(118.171554124747, 0.0422391555889454)); lfg.Add(new FreqGain(138.470910523652, 0.0438547095733166)); lfg.Add(new FreqGain(159.759002525445, 0.0474495412837798)); lfg.Add(new FreqGain(182.086951427111, 0.0515476348543647)); lfg.Add(new FreqGain(205.508810136376, 0.056162673196398)); lfg.Add(new FreqGain(230.081759247243, 0.0612659549892737)); lfg.Add(new FreqGain(255.866318897917, 0.0668005443605352)); lfg.Add(new FreqGain(282.926577933456, 0.0758917506709455)); lfg.Add(new FreqGain(311.330442067148, 0.0824530823635971)); lfg.Add(new FreqGain(341.14990292827, 0.0929637778755104)); lfg.Add(new FreqGain(372.461330102897, 0.100379371162514)); lfg.Add(new FreqGain(405.345788522409, 0.111984167288103)); lfg.Add(new FreqGain(439.889383835671, 0.123975744334166)); lfg.Add(new FreqGain(476.183638720577, 0.136237010524912)); lfg.Add(new FreqGain(514.325903454604, 0.148734117891156)); lfg.Add(new FreqGain(554.419804479247, 0.165502936111769)); lfg.Add(new FreqGain(596.575735167586, 0.178043988212559)); lfg.Add(new FreqGain(640.911393547776, 0.194349156663897)); lfg.Add(new FreqGain(687.552372358488, 0.209865869797881)); lfg.Add(new FreqGain(736.632807529586, 0.22500194685938)); lfg.Add(new FreqGain(788.296092007413, 0.243525065270957)); lfg.Add(new FreqGain(842.695662798627, 0.257649467879212)); lfg.Add(new FreqGain(899.99587021156, 0.273803874204412)); lfg.Add(new FreqGain(960.372939556513, 0.28709311052957)); lfg.Add(new FreqGain(1024.01603705869, 0.299481257886807)); lfg.Add(new FreqGain(1091.12845347812, 0.309245022903803)); lfg.Add(new FreqGain(1161.92892096669, 0.317179867687928)); lfg.Add(new FreqGain(1236.65308108085, 0.321207380680425)); lfg.Add(new FreqGain(1315.55512467678, 0.318824411496162)); lfg.Add(new FreqGain(1398.90962772937, 0.307833522186889)); lfg.Add(new FreqGain(1487.01361103779, 0.289293331349614)); lfg.Add(new FreqGain(1580.18885643692, 0.261606526767296)); lfg.Add(new FreqGain(1678.7845176806, 0.228997685797403)); lfg.Add(new FreqGain(1783.18007079301, 0.197540714557954)); lfg.Add(new FreqGain(1893.78865663959, 0.17295074128593)); lfg.Add(new FreqGain(2011.06087804797, 0.156696169926535)); lfg.Add(new FreqGain(2135.48912539139, 0.148455185344538)); lfg.Add(new FreqGain(2267.61251860637, 0.154528024795868)); lfg.Add(new FreqGain(2408.02257075748, 0.157020651297763)); lfg.Add(new FreqGain(2557.3696992537, 0.147606277996199)); lfg.Add(new FreqGain(2716.3707366486, 0.131041736855722)); lfg.Add(new FreqGain(2885.81762489105, 0.0866347064265516)); lfg.Add(new FreqGain(3066.58751658265, -0.0166654973944371)); lfg.Add(new FreqGain(3259.65455639083, -0.191612322714693)); lfg.Add(new FreqGain(3466.1036780904, -0.432511035136432)); lfg.Add(new FreqGain(3687.14683149463, -0.658960079848589)); lfg.Add(new FreqGain(3924.14215377249, -0.762774466055965)); lfg.Add(new FreqGain(4178.61672801844, -0.72195332419533)); lfg.Add(new FreqGain(4452.29373750316, -0.589733799295838)); lfg.Add(new FreqGain(4747.12503915768, -0.42970971679252)); lfg.Add(new FreqGain(5065.3304615832, -0.232527169811399)); lfg.Add(new FreqGain(5409.44550497149, -0.0355174224726339)); lfg.Add(new FreqGain(5782.37961614996, 0.226790461488208)); lfg.Add(new FreqGain(6187.48787900699, 0.570687924885134)); lfg.Add(new FreqGain(6628.65986711531, 0.902844690346035)); lfg.Add(new FreqGain(7110.43065099071, 0.97846591522975)); lfg.Add(new FreqGain(7638.12068410502, 0.785508262062104)); lfg.Add(new FreqGain(8218.013729816, 0.635399466540685)); lfg.Add(new FreqGain(8857.58547111898, 0.525129410649112)); lfg.Add(new FreqGain(9565.80048575836, 0.366859907213853)); lfg.Add(new FreqGain(10353.5026895216, 0.447897246086743)); lfg.Add(new FreqGain(11233.9354678215, 0.36565051131466)); lfg.Add(new FreqGain(12223.4446965003, 0.489904439751699)); lfg.Add(new FreqGain(13342.444347283, 0.338111293138435)); lfg.Add(new FreqGain(14616.7666969568, 0.237275309909941)); lfg.Add(new FreqGain(16079.5885672628, 0.1220539710691)); lfg.Add(new FreqGain(17774.2422466263, 0.0725148136373865)); lfg.Add(new FreqGain(19758.4244207167, 0.00128859185038382)); lfg.Add(new FreqGain(22110.6876081231, 6.13639214105897E-05)); return lfg; } } }
// // Copyright (c) 2004-2021 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. // namespace NLog.Layouts { using System; using System.Collections.Generic; using System.Text; using NLog.Config; using NLog.LayoutRenderers; using NLog.Targets; /// <summary> /// A specialized layout that renders Log4j-compatible XML events. /// </summary> /// <remarks> /// This layout is not meant to be used explicitly. Instead you can use ${log4jxmlevent} layout renderer. /// </remarks> [Layout("Log4JXmlEventLayout")] [ThreadAgnostic] public class Log4JXmlEventLayout : Layout, IIncludeContext { /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayout" /> class. /// </summary> public Log4JXmlEventLayout() { Renderer = new Log4JXmlEventLayoutRenderer(); Parameters = new List<NLogViewerParameterInfo>(); Renderer.Parameters = Parameters; } /// <summary> /// Gets the <see cref="Log4JXmlEventLayoutRenderer"/> instance that renders log events. /// </summary> public Log4JXmlEventLayoutRenderer Renderer { get; } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a named parameter. /// </summary> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")] public IList<NLogViewerParameterInfo> Parameters { get => Renderer.Parameters; set => Renderer.Parameters = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeEventProperties { get => Renderer.IncludeEventProperties; set => Renderer.IncludeEventProperties = value; } /// <summary> /// Gets or sets whether to include the contents of the <see cref="ScopeContext"/> properties-dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeScopeProperties { get => Renderer.IncludeScopeProperties; set => Renderer.IncludeScopeProperties = value; } /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeScopeNested { get => Renderer.IncludeScopeNested; set => Renderer.IncludeScopeNested = value; } /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeEventProperties. Marked obsolete on NLog 5.0")] public bool IncludeAllProperties { get => IncludeEventProperties; set => IncludeEventProperties = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdc { get => Renderer.IncludeMdc; set => Renderer.IncludeMdc = value; } /// <summary> /// Gets or sets whether to include log4j:NDC in output from <see cref="ScopeContext"/> nested context. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get => Renderer.IncludeNdc; set => Renderer.IncludeNdc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsLogicalContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeScopeProperties. Marked obsolete on NLog 5.0")] public bool IncludeMdlc { get => Renderer.IncludeMdlc; set => Renderer.IncludeMdlc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> [Obsolete("Replaced by IncludeScopeNested. Marked obsolete on NLog 5.0")] public bool IncludeNdlc { get => Renderer.IncludeNdlc; set => Renderer.IncludeNdlc = value; } /// <summary> /// Gets or sets the log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout LoggerName { get => Renderer.LoggerName; set => Renderer.LoggerName = value; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout AppInfo { get => Renderer.AppInfo; set => Renderer.AppInfo = value; } /// <summary> /// Gets or sets whether the log4j:throwable xml-element should be written as CDATA /// </summary> /// <docgen category='Payload Options' order='10' /> public bool WriteThrowableCData { get => Renderer.WriteThrowableCData; set => Renderer.WriteThrowableCData = value; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get => Renderer.IncludeCallSite; set => Renderer.IncludeCallSite = value; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get => Renderer.IncludeSourceInfo; set => Renderer.IncludeSourceInfo = value; } internal override void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target) { PrecalculateBuilderInternal(logEvent, target); } /// <inheritdoc/> protected override string GetFormattedMessage(LogEventInfo logEvent) { return RenderAllocateBuilder(logEvent); } /// <inheritdoc/> protected override void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target) { Renderer.RenderAppendBuilder(logEvent, target); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Runtime_CompilerServices_AsyncTaskMethodBuilder_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder); args = new Type[]{}; method = type.GetMethod("Create", flag, null, args, null); app.RegisterCLRMethodRedirection(method, Create_0); Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>(); List<MethodInfo> lst = null; foreach(var m in type.GetMethods()) { if(m.IsGenericMethodDefinition) { if (!genericMethods.TryGetValue(m.Name, out lst)) { lst = new List<MethodInfo>(); genericMethods[m.Name] = lst; } lst.Add(m); } } args = new Type[]{typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("Start", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, Start_1); break; } } } args = new Type[]{}; method = type.GetMethod("get_Task", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Task_2); args = new Type[]{typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest>), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest>).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitOnCompleted_3); break; } } } args = new Type[]{typeof(System.Exception)}; method = type.GetMethod("SetException", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetException_4); args = new Type[]{}; method = type.GetMethod("SetResult", flag, null, args, null); app.RegisterCLRMethodRedirection(method, SetResult_5); args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_6); break; } } } args = new Type[]{typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitUnsafeOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitUnsafeOnCompleted_7); break; } } } args = new Type[]{typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitOnCompleted_8); break; } } } args = new Type[]{typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest>), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)}; if (genericMethods.TryGetValue("AwaitOnCompleted", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(void), typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest>).MakeByRefType(), typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, AwaitOnCompleted_9); break; } } } app.RegisterCLRCreateDefaultInstance(type, () => new System.Runtime.CompilerServices.AsyncTaskMethodBuilder()); } static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method) { ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.Object: { __mStack[ptr_of_this_method->Value] = instance_of_this_method; } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { var t = __domain.GetType(___obj.GetType()) as CLRType; t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method); } } break; case ObjectTypes.StaticFieldReference: { var t = __domain.GetType(ptr_of_this_method->Value); if(t is ILType) { ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.AsyncTaskMethodBuilder[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method; } break; } } static StackObject* Create_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* __ret = ILIntepreter.Minus(__esp, 0); var result_of_this_method = System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create(); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* Start_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.Start<Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* get_Task_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = instance_of_this_method.Task; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); object obj_result_of_this_method = result_of_this_method; if(obj_result_of_this_method is CrossBindingAdaptorType) { return ILIntepreter.PushObject(__ret, __mStack, ((CrossBindingAdaptorType)obj_result_of_this_method).ILInstance); } return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* AwaitOnCompleted_3(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest> @awaiter = (UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest>)typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitOnCompleted<UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest>, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.AssetLoaderRequest>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* SetException_4(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.Exception @exception = (System.Exception)typeof(System.Exception).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.SetException(@exception); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* SetResult_5(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.SetResult(); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* AwaitUnsafeOnCompleted_6(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Runtime.CompilerServices.TaskAwaiter @awaiter = (System.Runtime.CompilerServices.TaskAwaiter)typeof(System.Runtime.CompilerServices.TaskAwaiter).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* AwaitUnsafeOnCompleted_7(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance> @awaiter = (System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Runtime.CompilerServices.TaskAwaiter<ILRuntime.Runtime.Intepreter.ILTypeInstance>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* AwaitOnCompleted_8(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest> @awaiter = (UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>)typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitOnCompleted<UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForSecondsRequest>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } static StackObject* AwaitOnCompleted_9(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor @stateMachine = (Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor)typeof(Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest> @awaiter = (UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest>)typeof(UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest>).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Runtime.CompilerServices.AsyncTaskMethodBuilder instance_of_this_method = (System.Runtime.CompilerServices.AsyncTaskMethodBuilder)typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); instance_of_this_method.AwaitOnCompleted<UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest>, Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor>(ref @awaiter, ref @stateMachine); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @stateMachine; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @stateMachine; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @stateMachine); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @stateMachine; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @stateMachine); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as Knight.Framework.Hotfix.IAsyncStateMachineAdaptor.Adaptor[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @stateMachine; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @awaiter; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @awaiter; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @awaiter); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @awaiter; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @awaiter); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as UnityFx.Async.CompilerServices.AsyncAwaiter<Knight.Core.WaitAsync.WaitForEndOfFrameRequest>[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @awaiter; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return __ret; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.RecoveryServices; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ReplicationRecoveryServicesProvidersOperations operations. /// </summary> public partial interface IReplicationRecoveryServicesProvidersOperations { /// <summary> /// Refresh details from the recovery services provider. /// </summary> /// <remarks> /// The operation to refresh the information from the recovery services /// provider. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecoveryServicesProvider>> RefreshProviderWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes provider from fabric. Note: Deleting provider for any /// fabric other than SingleHost is unsupported. To maintain backward /// compatibility for released clients the object "deleteRspInput" is /// used (if the object is empty we assume that it is old client and /// continue the old behavior). /// </summary> /// <remarks> /// The operation to removes/delete(unregister) a recovery services /// provider from the vault /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the details of a recovery services provider. /// </summary> /// <remarks> /// Gets the details of registered recovery services provider. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecoveryServicesProvider>> GetWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Purges recovery service provider from fabric /// </summary> /// <remarks> /// The operation to purge(force delete) a recovery services provider /// from the vault. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> PurgeWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers for the /// fabric. /// </summary> /// <remarks> /// Lists the registered recovery services providers for the specified /// fabric. /// </remarks> /// <param name='fabricName'> /// Fabric name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers in the /// vault. This is a view only api. /// </summary> /// <remarks> /// Lists the registered recovery services providers in the vault /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Refresh details from the recovery services provider. /// </summary> /// <remarks> /// The operation to refresh the information from the recovery services /// provider. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<RecoveryServicesProvider>> BeginRefreshProviderWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes provider from fabric. Note: Deleting provider for any /// fabric other than SingleHost is unsupported. To maintain backward /// compatibility for released clients the object "deleteRspInput" is /// used (if the object is empty we assume that it is old client and /// continue the old behavior). /// </summary> /// <remarks> /// The operation to removes/delete(unregister) a recovery services /// provider from the vault /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Purges recovery service provider from fabric /// </summary> /// <remarks> /// The operation to purge(force delete) a recovery services provider /// from the vault. /// </remarks> /// <param name='fabricName'> /// Fabric name. /// </param> /// <param name='providerName'> /// Recovery services provider name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginPurgeWithHttpMessagesAsync(string fabricName, string providerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers for the /// fabric. /// </summary> /// <remarks> /// Lists the registered recovery services providers for the specified /// fabric. /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListByReplicationFabricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of registered recovery services providers in the /// vault. This is a view only api. /// </summary> /// <remarks> /// Lists the registered recovery services providers in the vault /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<RecoveryServicesProvider>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.HDInsight.Models; namespace Microsoft.Azure.Management.HDInsight { /// <summary> /// Contains all the cluster operations. /// </summary> public partial interface IClusterOperations { /// <summary> /// Begins configuring the HTTP settings on the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> Task<HDInsightOperationResponse> BeginConfiguringHttpSettingsAsync(string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters, CancellationToken cancellationToken); /// <summary> /// Begins configuring the RDP settings on the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='rdpParameters'> /// The OS profile for RDP. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> Task<HDInsightOperationResponse> BeginConfiguringRdpSettingsAsync(string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters, CancellationToken cancellationToken); /// <summary> /// Begins creating a new HDInsight cluster with the specified /// parameters. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// The cluster create request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The CreateCluster operation response. /// </returns> Task<ClusterCreateResponse> BeginCreatingAsync(string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters, CancellationToken cancellationToken); /// <summary> /// Begins deleting the specified HDInsight cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> Task<HDInsightOperationResponse> BeginDeletingAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken); /// <summary> /// Begins a resize operation on the specified HDInsight cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='resizeParameters'> /// The parameters for the resize operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The cluster long running operation response. /// </returns> Task<HDInsightOperationResponse> BeginResizingAsync(string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters, CancellationToken cancellationToken); /// <summary> /// Configures the HTTP settings on the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='httpSettingsParameters'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The azure async operation response. /// </returns> Task<OperationResource> ConfigureHttpSettingsAsync(string resourceGroupName, string clusterName, HttpSettingsParameters httpSettingsParameters, CancellationToken cancellationToken); /// <summary> /// Configures the RDP settings on the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='rdpParameters'> /// The OS profile for RDP. Use null to turn RDP off. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The azure async operation response. /// </returns> Task<OperationResource> ConfigureRdpSettingsAsync(string resourceGroupName, string clusterName, RDPSettingsParameters rdpParameters, CancellationToken cancellationToken); /// <summary> /// Creates a new HDInsight cluster with the specified parameters. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='clusterCreateParameters'> /// The cluster create request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> Task<ClusterGetResponse> CreateAsync(string resourceGroupName, string clusterName, ClusterCreateParametersExtended clusterCreateParameters, CancellationToken cancellationToken); /// <summary> /// Deletes the specified HDInsight cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The azure async operation response. /// </returns> Task<OperationResource> DeleteAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken); /// <summary> /// Gets the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> Task<ClusterGetResponse> GetAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken); /// <summary> /// Gets the capabilities for the specified location. /// </summary> /// <param name='location'> /// The location to get capabilities for. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Capabilities operation response. /// </returns> Task<CapabilitiesResponse> GetCapabilitiesAsync(string location, CancellationToken cancellationToken); /// <summary> /// Gets the configuration for the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='configurationName'> /// The type name of the hadoop configuration. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Cluster Configurations operation response. /// </returns> Task<ClusterConfigurationsResponse> GetClusterConfigurationsAsync(string resourceGroupName, string clusterName, string configurationName, CancellationToken cancellationToken); /// <summary> /// Gets the connectivity settings for the specified cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The payload for a Configure HTTP settings request. /// </returns> Task<HttpConnectivitySettings> GetConnectivitySettingsAsync(string resourceGroupName, string clusterName, CancellationToken cancellationToken); /// <summary> /// Gets the status of the Create operation. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The GetCluster operation response. /// </returns> Task<ClusterGetResponse> GetCreateStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Gets the status of the Delete operation. /// </summary> /// <param name='operationStatusLink'> /// Location value returned by the Begin operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The azure async operation response. /// </returns> Task<OperationResource> GetDeleteStatusAsync(string operationStatusLink, CancellationToken cancellationToken); /// <summary> /// Lists HDInsight clusters under the subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> Task<ClusterListResponse> ListAsync(CancellationToken cancellationToken); /// <summary> /// List the HDInsight clusters in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Cluster operation response. /// </returns> Task<ClusterListResponse> ListByResourceGroupAsync(string resourceGroupName, CancellationToken cancellationToken); /// <summary> /// Resizes the specified HDInsight cluster. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='clusterName'> /// The name of the cluster. /// </param> /// <param name='resizeParameters'> /// The parameters for the resize operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The azure async operation response. /// </returns> Task<OperationResource> ResizeAsync(string resourceGroupName, string clusterName, ClusterResizeParameters resizeParameters, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Helper class to validate objects, properties and other values using their associated /// <see cref="ValidationAttribute" /> /// custom attributes. /// </summary> public static class Validator { private static readonly ValidationAttributeStore _store = ValidationAttributeStore.Instance; /// <summary> /// Tests whether the given property value is valid. /// </summary> /// <remarks> /// This method will test each <see cref="ValidationAttribute" /> associated with the property /// identified by <paramref name="validationContext" />. If <paramref name="validationResults" /> is non-null, /// this method will add a <see cref="ValidationResult" /> to it for each validation failure. /// <para> /// If there is a <see cref="RequiredAttribute" /> found on the property, it will be evaluated before all other /// validation attributes. If the required validator fails then validation will abort, adding that single /// failure into the <paramref name="validationResults" /> when applicable, returning a value of <c>false</c>. /// </para> /// <para> /// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure, /// then all validators will be evaluated. /// </para> /// </remarks> /// <param name="value">The value to test.</param> /// <param name="validationContext"> /// Describes the property member to validate and provides services and context for the /// validators. /// </param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <returns><c>true</c> if the value is valid, <c>false</c> if any validation errors are encountered.</returns> /// <exception cref="ArgumentException"> /// When the <see cref="ValidationContext.MemberName" /> of <paramref name="validationContext" /> is not a valid /// property. /// </exception> public static bool TryValidateProperty(object value, ValidationContext validationContext, ICollection<ValidationResult> validationResults) { // Throw if value cannot be assigned to this property. That is not a validation exception. var propertyType = _store.GetPropertyType(validationContext); var propertyName = validationContext.MemberName; EnsureValidPropertyType(propertyName, propertyType, value); var result = true; var breakOnFirstError = (validationResults == null); var attributes = _store.GetPropertyValidationAttributes(validationContext); foreach (var err in GetValidationErrors(value, validationContext, attributes, breakOnFirstError)) { result = false; if (validationResults != null) { validationResults.Add(err.ValidationResult); } } return result; } /// <summary> /// Tests whether the given object instance is valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also /// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. It does not validate the /// property values of the object. /// <para> /// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation /// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be /// evaluated. /// </para> /// </remarks> /// <param name="instance">The object instance to test. It cannot be <c>null</c>.</param> /// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />. /// </exception> public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults) { return TryValidateObject(instance, validationContext, validationResults, false /*validateAllProperties*/); } /// <summary> /// Tests whether the given object instance is valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object instance's type. It also /// checks to ensure all properties marked with <see cref="RequiredAttribute" /> are set. If /// <paramref name="validateAllProperties" /> /// is <c>true</c>, this method will also evaluate the <see cref="ValidationAttribute" />s for all the immediate /// properties /// of this object. This process is not recursive. /// <para> /// If <paramref name="validationResults" /> is null, then execution will abort upon the first validation /// failure. If <paramref name="validationResults" /> is non-null, then all validation attributes will be /// evaluated. /// </para> /// <para> /// For any given property, if it has a <see cref="RequiredAttribute" /> that fails validation, no other validators /// will be evaluated for that property. /// </para> /// </remarks> /// <param name="instance">The object instance to test. It cannot be null.</param> /// <param name="validationContext">Describes the object to validate and provides services and context for the validators.</param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <param name="validateAllProperties"> /// If <c>true</c>, also evaluates all properties of the object (this process is not /// recursive over properties of the properties). /// </param> /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" />on <paramref name="validationContext" />. /// </exception> public static bool TryValidateObject(object instance, ValidationContext validationContext, ICollection<ValidationResult> validationResults, bool validateAllProperties) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (validationContext != null && instance != validationContext.ObjectInstance) { throw new ArgumentException( SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); } var result = true; var breakOnFirstError = (validationResults == null); foreach ( var err in GetObjectValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError)) { result = false; if (validationResults != null) { validationResults.Add(err.ValidationResult); } } return result; } /// <summary> /// Tests whether the given value is valid against a specified list of <see cref="ValidationAttribute" />s. /// </summary> /// <remarks> /// This method will test each <see cref="ValidationAttribute" />s specified. If /// <paramref name="validationResults" /> is non-null, this method will add a <see cref="ValidationResult" /> /// to it for each validation failure. /// <para> /// If there is a <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" />, it will /// be evaluated before all other validation attributes. If the required validator fails then validation will /// abort, adding that single failure into the <paramref name="validationResults" /> when applicable, returning a /// value of <c>false</c>. /// </para> /// <para> /// If <paramref name="validationResults" /> is null and there isn't a <see cref="RequiredAttribute" /> failure, /// then all validators will be evaluated. /// </para> /// </remarks> /// <param name="value">The value to test. It cannot be null.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. /// </param> /// <param name="validationResults">Optional collection to receive <see cref="ValidationResult" />s for the failures.</param> /// <param name="validationAttributes"> /// The list of <see cref="ValidationAttribute" />s to validate this /// <paramref name="value" /> against. /// </param> /// <returns><c>true</c> if the object is valid, <c>false</c> if any validation errors are encountered.</returns> public static bool TryValidateValue(object value, ValidationContext validationContext, ICollection<ValidationResult> validationResults, IEnumerable<ValidationAttribute> validationAttributes) { var result = true; var breakOnFirstError = validationResults == null; foreach ( var err in GetValidationErrors(value, validationContext, validationAttributes, breakOnFirstError)) { result = false; if (validationResults != null) { validationResults.Add(err.ValidationResult); } } return result; } /// <summary> /// Throws a <see cref="ValidationException" /> if the given property <paramref name="value" /> is not valid. /// </summary> /// <param name="value">The value to test.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. It cannot be <c>null</c>. /// </param> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ValidationException">When <paramref name="value" /> is invalid for this property.</exception> public static void ValidateProperty(object value, ValidationContext validationContext) { // Throw if value cannot be assigned to this property. That is not a validation exception. var propertyType = _store.GetPropertyType(validationContext); EnsureValidPropertyType(validationContext.MemberName, propertyType, value); var attributes = _store.GetPropertyValidationAttributes(validationContext); var err = GetValidationErrors(value, validationContext, attributes, false).FirstOrDefault(); if (err != null) { err.ThrowValidationException(); } } /// <summary> /// Throws a <see cref="ValidationException" /> if the given <paramref name="instance" /> is not valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type. /// </remarks> /// <param name="instance">The object instance to test. It cannot be null.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. It cannot be <c>null</c>. /// </param> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />. /// </exception> /// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception> public static void ValidateObject(object instance, ValidationContext validationContext) { ValidateObject(instance, validationContext, false /*validateAllProperties*/); } /// <summary> /// Throws a <see cref="ValidationException" /> if the given object instance is not valid. /// </summary> /// <remarks> /// This method evaluates all <see cref="ValidationAttribute" />s attached to the object's type. /// If <paramref name="validateAllProperties" /> is <c>true</c> it also validates all the object's properties. /// </remarks> /// <param name="instance">The object instance to test. It cannot be null.</param> /// <param name="validationContext"> /// Describes the object being validated and provides services and context for the /// validators. It cannot be <c>null</c>. /// </param> /// <param name="validateAllProperties">If <c>true</c>, also validates all the <paramref name="instance" />'s properties.</param> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />. /// </exception> /// <exception cref="ValidationException">When <paramref name="instance" /> is found to be invalid.</exception> public static void ValidateObject(object instance, ValidationContext validationContext, bool validateAllProperties) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } if (instance != validationContext.ObjectInstance) { throw new ArgumentException( SR.Validator_InstanceMustMatchValidationContextInstance, nameof(instance)); } var err = GetObjectValidationErrors(instance, validationContext, validateAllProperties, false).FirstOrDefault(); if (err != null) { err.ThrowValidationException(); } } /// <summary> /// Throw a <see cref="ValidationException" /> if the given value is not valid for the /// <see cref="ValidationAttribute" />s. /// </summary> /// <remarks> /// This method evaluates the <see cref="ValidationAttribute" />s supplied until a validation error occurs, /// at which time a <see cref="ValidationException" /> is thrown. /// <para> /// A <see cref="RequiredAttribute" /> within the <paramref name="validationAttributes" /> will always be evaluated /// first. /// </para> /// </remarks> /// <param name="value">The value to test. It cannot be null.</param> /// <param name="validationContext">Describes the object being tested.</param> /// <param name="validationAttributes">The list of <see cref="ValidationAttribute" />s to validate against this instance.</param> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ValidationException">When <paramref name="value" /> is found to be invalid.</exception> public static void ValidateValue(object value, ValidationContext validationContext, IEnumerable<ValidationAttribute> validationAttributes) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } var err = GetValidationErrors(value, validationContext, validationAttributes, false).FirstOrDefault(); if (err != null) { err.ThrowValidationException(); } } /// <summary> /// Creates a new <see cref="ValidationContext" /> to use to validate the type or a member of /// the given object instance. /// </summary> /// <param name="instance">The object instance to use for the context.</param> /// <param name="validationContext"> /// An parent validation context that supplies an <see cref="IServiceProvider" /> /// and <see cref="ValidationContext.Items" />. /// </param> /// <returns>A new <see cref="ValidationContext" /> for the <paramref name="instance" /> provided.</returns> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> private static ValidationContext CreateValidationContext(object instance, ValidationContext validationContext) { Debug.Assert(validationContext != null); // Create a new context using the existing ValidationContext that acts as an IServiceProvider and contains our existing items. var context = new ValidationContext(instance, validationContext, validationContext.Items); return context; } /// <summary> /// Determine whether the given value can legally be assigned into the specified type. /// </summary> /// <param name="destinationType">The destination <see cref="Type" /> for the value.</param> /// <param name="value"> /// The value to test to see if it can be assigned as the Type indicated by /// <paramref name="destinationType" />. /// </param> /// <returns><c>true</c> if the assignment is legal.</returns> /// <exception cref="ArgumentNullException">When <paramref name="destinationType" /> is null.</exception> private static bool CanBeAssigned(Type destinationType, object value) { if (value == null) { // Null can be assigned only to reference types or Nullable or Nullable<> return !destinationType.IsValueType || (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)); } // Not null -- be sure it can be cast to the right type return destinationType.IsInstanceOfType(value); } /// <summary> /// Determines whether the given value can legally be assigned to the given property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="propertyType">The type of the property.</param> /// <param name="value">The value. Null is permitted only if the property will accept it.</param> /// <exception cref="ArgumentException"> is thrown if <paramref name="value" /> is the wrong type for this property.</exception> private static void EnsureValidPropertyType(string propertyName, Type propertyType, object value) { if (!CanBeAssigned(propertyType, value)) { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, SR.Validator_Property_Value_Wrong_Type, propertyName, propertyType), nameof(value)); } } /// <summary> /// Internal iterator to enumerate all validation errors for the given object instance. /// </summary> /// <param name="instance">Object instance to test.</param> /// <param name="validationContext">Describes the object type.</param> /// <param name="validateAllProperties">if <c>true</c> also validates all properties.</param> /// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param> /// <returns> /// A collection of validation errors that result from validating the <paramref name="instance" /> with /// the given <paramref name="validationContext" />. /// </returns> /// <exception cref="ArgumentNullException">When <paramref name="instance" /> is null.</exception> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> /// <exception cref="ArgumentException"> /// When <paramref name="instance" /> doesn't match the /// <see cref="ValidationContext.ObjectInstance" /> on <paramref name="validationContext" />. /// </exception> private static IEnumerable<ValidationError> GetObjectValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError) { Debug.Assert(instance != null); if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } // Step 1: Validate the object properties' validation attributes var errors = new List<ValidationError>(); errors.AddRange(GetObjectPropertyValidationErrors(instance, validationContext, validateAllProperties, breakOnFirstError)); // We only proceed to Step 2 if there are no errors if (errors.Any()) { return errors; } // Step 2: Validate the object's validation attributes var attributes = _store.GetTypeValidationAttributes(validationContext); errors.AddRange(GetValidationErrors(instance, validationContext, attributes, breakOnFirstError)); // We only proceed to Step 3 if there are no errors if (errors.Any()) { return errors; } // Step 3: Test for IValidatableObject implementation if (instance is IValidatableObject validatable) { var results = validatable.Validate(validationContext); foreach (var result in results.Where(r => r != ValidationResult.Success)) { errors.Add(new ValidationError(null, instance, result)); } } return errors; } /// <summary> /// Internal iterator to enumerate all the validation errors for all properties of the given object instance. /// </summary> /// <param name="instance">Object instance to test.</param> /// <param name="validationContext">Describes the object type.</param> /// <param name="validateAllProperties"> /// If <c>true</c>, evaluates all the properties, otherwise just checks that /// ones marked with <see cref="RequiredAttribute" /> are not null. /// </param> /// <param name="breakOnFirstError">Whether to break on the first error or validate everything.</param> /// <returns>A list of <see cref="ValidationError" /> instances.</returns> private static IEnumerable<ValidationError> GetObjectPropertyValidationErrors(object instance, ValidationContext validationContext, bool validateAllProperties, bool breakOnFirstError) { var properties = GetPropertyValues(instance, validationContext); var errors = new List<ValidationError>(); foreach (var property in properties) { // get list of all validation attributes for this property var attributes = _store.GetPropertyValidationAttributes(property.Key); if (validateAllProperties) { // validate all validation attributes on this property errors.AddRange(GetValidationErrors(property.Value, property.Key, attributes, breakOnFirstError)); } else { // only validate the Required attributes var reqAttr = attributes.FirstOrDefault(a => a is RequiredAttribute) as RequiredAttribute; if (reqAttr != null) { // Note: we let the [Required] attribute do its own null testing, // since the user may have subclassed it and have a deeper meaning to what 'required' means var validationResult = reqAttr.GetValidationResult(property.Value, property.Key); if (validationResult != ValidationResult.Success) { errors.Add(new ValidationError(reqAttr, property.Value, validationResult)); } } } if (breakOnFirstError && errors.Any()) { break; } } return errors; } /// <summary> /// Retrieves the property values for the given instance. /// </summary> /// <param name="instance">Instance from which to fetch the properties.</param> /// <param name="validationContext">Describes the entity being validated.</param> /// <returns> /// A set of key value pairs, where the key is a validation context for the property and the value is its current /// value. /// </returns> /// <remarks>Ignores indexed properties.</remarks> private static ICollection<KeyValuePair<ValidationContext, object>> GetPropertyValues(object instance, ValidationContext validationContext) { var properties = instance.GetType().GetRuntimeProperties() .Where(p => ValidationAttributeStore.IsPublic(p) && !p.GetIndexParameters().Any()); var items = new List<KeyValuePair<ValidationContext, object>>(properties.Count()); foreach (var property in properties) { var context = CreateValidationContext(instance, validationContext); context.MemberName = property.Name; if (_store.GetPropertyValidationAttributes(context).Any()) { items.Add(new KeyValuePair<ValidationContext, object>(context, property.GetValue(instance, null))); } } return items; } /// <summary> /// Internal iterator to enumerate all validation errors for an value. /// </summary> /// <remarks> /// If a <see cref="RequiredAttribute" /> is found, it will be evaluated first, and if that fails, /// validation will abort, regardless of the <paramref name="breakOnFirstError" /> parameter value. /// </remarks> /// <param name="value">The value to pass to the validation attributes.</param> /// <param name="validationContext">Describes the type/member being evaluated.</param> /// <param name="attributes">The validation attributes to evaluate.</param> /// <param name="breakOnFirstError"> /// Whether or not to break on the first validation failure. A /// <see cref="RequiredAttribute" /> failure will always abort with that sole failure. /// </param> /// <returns>The collection of validation errors.</returns> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> private static IEnumerable<ValidationError> GetValidationErrors(object value, ValidationContext validationContext, IEnumerable<ValidationAttribute> attributes, bool breakOnFirstError) { if (validationContext == null) { throw new ArgumentNullException(nameof(validationContext)); } var errors = new List<ValidationError>(); ValidationError validationError; // Get the required validator if there is one and test it first, aborting on failure var required = attributes.FirstOrDefault(a => a is RequiredAttribute) as RequiredAttribute; if (required != null) { if (!TryValidate(value, validationContext, required, out validationError)) { errors.Add(validationError); return errors; } } // Iterate through the rest of the validators, skipping the required validator foreach (var attr in attributes) { if (attr != required) { if (!TryValidate(value, validationContext, attr, out validationError)) { errors.Add(validationError); if (breakOnFirstError) { break; } } } } return errors; } /// <summary> /// Tests whether a value is valid against a single <see cref="ValidationAttribute" /> using the /// <see cref="ValidationContext" />. /// </summary> /// <param name="value">The value to be tested for validity.</param> /// <param name="validationContext">Describes the property member to validate.</param> /// <param name="attribute">The validation attribute to test.</param> /// <param name="validationError"> /// The validation error that occurs during validation. Will be <c>null</c> when the return /// value is <c>true</c>. /// </param> /// <returns><c>true</c> if the value is valid.</returns> /// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception> private static bool TryValidate(object value, ValidationContext validationContext, ValidationAttribute attribute, out ValidationError validationError) { Debug.Assert(validationContext != null); var validationResult = attribute.GetValidationResult(value, validationContext); if (validationResult != ValidationResult.Success) { validationError = new ValidationError(attribute, value, validationResult); return false; } validationError = null; return true; } /// <summary> /// Private helper class to encapsulate a ValidationAttribute with the failed value and the user-visible /// target name against which it was validated. /// </summary> private class ValidationError { internal ValidationError(ValidationAttribute validationAttribute, object value, ValidationResult validationResult) { ValidationAttribute = validationAttribute; ValidationResult = validationResult; Value = value; } internal object Value { get; set; } internal ValidationAttribute ValidationAttribute { get; set; } internal ValidationResult ValidationResult { get; set; } internal Exception ThrowValidationException() => throw new ValidationException(ValidationResult, ValidationAttribute, Value); } } }
using Caliburn.Micro; using csShared; using csShared.Interfaces; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.Composition; using System.Globalization; using System.Linq; using System.Speech.Recognition; namespace csCommon.Plugins.SpeechPlugin { [Export(typeof(IPlugin))] public class SpeechPlugin : PropertyChangedBase, IPlugin { private readonly MenuItem speechMenuItem = new MenuItem(); private Grammar g; private bool hideFromSettings; private bool isRunning; //private object l = new object(); private SpeechRecognitionEngine recognizer; private bool reset; private IPluginScreen screen; private ISettingsScreen settings; //private DispatcherTimer timer; private bool waiting; public FloatingElement Element { get; set; } public bool Enabled { get { return AppState.Config.GetBool("Speech.Enabled", false); } set { AppState.Config.SetLocalConfig("Speech.Enabled", value.ToString()); } } public bool CanStop { get { return true; } } public ISettingsScreen Settings { get { return settings; } set { settings = value; NotifyOfPropertyChange(() => Settings); } } public IPluginScreen Screen { get { return screen; } set { screen = value; NotifyOfPropertyChange(() => Screen); } } public bool HideFromSettings { get { return hideFromSettings; } set { hideFromSettings = value; NotifyOfPropertyChange(() => HideFromSettings); } } public int Priority { get { return 1; } } public string Icon { get { return @"/csCommon;component/Resources/Icons/microphone.png"; } } public bool IsRunning { get { return isRunning; } set { isRunning = value; NotifyOfPropertyChange(() => IsRunning); } } public AppStateSettings AppState { get; set; } public string Name { get { return "SpeechPlugin"; } } public SpeechConfigViewModel Config { get; set; } public void Init() { Config = new SpeechConfigViewModel { DisplayName = "Speech" }; } /// <summary> /// Plugin started /// </summary> public void Start() { IsRunning = true; if (Enabled) { StartSpeech(); } else { StopSpeech(); } AppState.ConfigTabs.Add(Config); speechMenuItem.Clicked += MainMenuClicked; AppState.MainMenuItems.Add(speechMenuItem); } public void Pause() { IsRunning = false; } /// <summary> /// stop plugin /// </summary> public void Stop() { StopSpeech(); speechMenuItem.Clicked -= MainMenuClicked; AppState.Commands.CollectionChanged -= CommandsChanged; g = null; IsRunning = false; AppState.ConfigTabs.Remove(Config); AppState.MainMenuItems.Remove(speechMenuItem); } private void MainMenuClicked(object sender, EventArgs e) { Enabled = !Enabled; if (Enabled) { StartSpeech(); } else { AppState.TriggerNotification("Speech engine stopped"); StopSpeech(); } } private void StopSpeech() { speechMenuItem.Name = "Start Speech"; if (recognizer != null) { recognizer.RecognizeCompleted -= RecognizeCompleted; recognizer.SpeechRecognized -= SpeechRecognized; recognizer.UnloadAllGrammars(); recognizer.RecognizeAsyncStop(); recognizer = null; } } private void StartSpeech() { //ThreadPool.QueueUserWorkItem( // delegate { speechMenuItem.Name = "Stop Speech"; recognizer = new SpeechRecognitionEngine(new CultureInfo("en-US")); AppState.Commands.AddCommand("Exit", new[] { "Exit" }, null); try { //button1.Text = "Speak Now"; recognizer.SetInputToDefaultAudioDevice(); UpdateGrammar(); recognizer.RecognizeCompleted += RecognizeCompleted; recognizer.SpeechRecognized += SpeechRecognized; recognizer.RecognizeAsync(RecognizeMode.Multiple); //RecognitionResult result = recognizer.Recognize(); //button1.Text = result.Text; } catch (InvalidOperationException exception) { AppState.TriggerNotification( String.Format( "Could not recognize input from default aduio device. Is a microphone or sound card available?\r\n{0} - {1}.", exception.Source, exception.Message)); } AppState.Commands.CollectionChanged += CommandsChanged; UpdateGrammar(); // AppState.TriggerNotification("Speech engine started"); } //); } private void CommandsChanged(object sender, NotifyCollectionChangedEventArgs e) { reset = true; waiting = true; UpdateGrammar(); } /// <summary> /// Update grammar list /// </summary> public void UpdateGrammar() { if (!Enabled) return; if (waiting) { recognizer.RecognizeAsyncStop(); waiting = false; return; } recognizer.UnloadAllGrammars(); var sentences = new Choices(); IEnumerable<string> ss = from c in AppState.Commands from s in c.Sentences select s; foreach (string s in ss.GroupBy(k => k).Select(k => k.Key)) { sentences.Add(s); } var gBuilder = new GrammarBuilder(sentences); g = new Grammar(gBuilder); recognizer.LoadGrammar(g); //recognizer.RecognizeAsync(RecognizeMode.Multiple); } /// <summary> /// something was recognized, search and trigger handlers /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { if (e.Result.Confidence < 0.7) return; AppState.TriggerNotification(e.Result.Text + " (" + e.Result.Confidence + ")"); foreach (Command c in AppState.Commands) { if (c.Sentences.Contains(e.Result.Text)) { if (c.Handler != null) c.Handler(c.Id); } } } /// <summary> /// Recognition was stoped, check if it was reset and needs to be started again /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RecognizeCompleted(object sender, RecognizeCompletedEventArgs e) { if (e.Cancelled && reset) { waiting = false; reset = false; UpdateGrammar(); recognizer.RecognizeAsync(RecognizeMode.Multiple); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { internal class AttributeNamedParameterCompletionProvider : CommonCompletionProvider { private const string EqualsString = "="; private const string SpaceEqualsString = " ="; private const string ColonString = ":"; internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options) { return CompletionUtilities.IsTriggerCharacter(text, characterPosition, options); } public override async Task ProvideCompletionsAsync(CompletionContext context) { var document = context.Document; var position = context.Position; var cancellationToken = context.CancellationToken; var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); if (syntaxTree.IsInNonUserCode(position, cancellationToken)) { return; } var token = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); token = token.GetPreviousTokenIfTouchingWord(position); if (!token.IsKind(SyntaxKind.OpenParenToken, SyntaxKind.CommaToken)) { return; } var attributeArgumentList = token.Parent as AttributeArgumentListSyntax; var attributeSyntax = token.Parent.Parent as AttributeSyntax; if (attributeSyntax == null || attributeArgumentList == null) { return; } if (IsAfterNameColonArgument(token) || IsAfterNameEqualsArgument(token)) { context.IsExclusive = true; } // We actually want to collect two sets of named parameters to present the user. The // normal named parameters that come from the attribute constructors. These will be // presented like "foo:". And also the named parameters that come from the writable // fields/properties in the attribute. These will be presented like "bar =". var existingNamedParameters = GetExistingNamedParameters(attributeArgumentList, position); var workspace = document.Project.Solution.Workspace; var semanticModel = await document.GetSemanticModelForNodeAsync(attributeSyntax, cancellationToken).ConfigureAwait(false); var nameColonItems = await GetNameColonItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); var nameEqualsItems = await GetNameEqualsItemsAsync(context, semanticModel, token, attributeSyntax, existingNamedParameters).ConfigureAwait(false); context.AddItems(nameEqualsItems); // If we're after a name= parameter, then we only want to show name= parameters. // Otherwise, show name: parameters too. if (!IsAfterNameEqualsArgument(token)) { context.AddItems(nameColonItems); } } private bool IsAfterNameColonArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameColon != null) { return true; } } } } return false; } private bool IsAfterNameEqualsArgument(SyntaxToken token) { var argumentList = token.Parent as AttributeArgumentListSyntax; if (token.Kind() == SyntaxKind.CommaToken && argumentList != null) { foreach (var item in argumentList.Arguments.GetWithSeparators()) { if (item.IsToken && item.AsToken() == token) { return false; } if (item.IsNode) { var node = item.AsNode() as AttributeArgumentSyntax; if (node.NameEquals != null) { return true; } } } } return false; } private async Task<ImmutableArray<CompletionItem>> GetNameEqualsItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var attributeNamedParameters = GetAttributeNamedParameters(semanticModel, context.Position, attributeSyntax, context.CancellationToken); var unspecifiedNamedParameters = attributeNamedParameters.Where(p => !existingNamedParameters.Contains(p.Name)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); var q = from p in attributeNamedParameters where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.Create( displayText: p.Name.ToIdentifierToken().ToString() + SpaceEqualsString, insertionText: null, symbol: p, contextPosition: token.SpanStart, sortText: p.Name, rules: CompletionItemRules.Default); return q.ToImmutableArray(); } private async Task<IEnumerable<CompletionItem>> GetNameColonItemsAsync( CompletionContext context, SemanticModel semanticModel, SyntaxToken token, AttributeSyntax attributeSyntax, ISet<string> existingNamedParameters) { var parameterLists = GetParameterLists(semanticModel, context.Position, attributeSyntax, context.CancellationToken); parameterLists = parameterLists.Where(pl => IsValid(pl, existingNamedParameters)); var text = await semanticModel.SyntaxTree.GetTextAsync(context.CancellationToken).ConfigureAwait(false); return from pl in parameterLists from p in pl where !existingNamedParameters.Contains(p.Name) select SymbolCompletionItem.Create( displayText: p.Name.ToIdentifierToken().ToString() + ColonString, insertionText: null, symbol: p, contextPosition: token.SpanStart, sortText: p.Name, rules: CompletionItemRules.Default); } protected override Task<CompletionDescription> GetDescriptionWorkerAsync(Document document, CompletionItem item, CancellationToken cancellationToken) => SymbolCompletionItem.GetDescriptionAsync(item, document, cancellationToken); private bool IsValid(ImmutableArray<IParameterSymbol> parameterList, ISet<string> existingNamedParameters) { return existingNamedParameters.Except(parameterList.Select(p => p.Name)).IsEmpty(); } private ISet<string> GetExistingNamedParameters(AttributeArgumentListSyntax argumentList, int position) { var existingArguments1 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameColon != null) .Select(a => a.NameColon.Name.Identifier.ValueText); var existingArguments2 = argumentList.Arguments.Where(a => a.Span.End <= position) .Where(a => a.NameEquals != null) .Select(a => a.NameEquals.Name.Identifier.ValueText); return existingArguments1.Concat(existingArguments2).ToSet(); } private IEnumerable<ImmutableArray<IParameterSymbol>> GetParameterLists( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; if (within != null && attributeType != null) { return attributeType.InstanceConstructors.Where(c => c.IsAccessibleWithin(within)) .Select(c => c.Parameters); } return SpecializedCollections.EmptyEnumerable<ImmutableArray<IParameterSymbol>>(); } private IEnumerable<ISymbol> GetAttributeNamedParameters( SemanticModel semanticModel, int position, AttributeSyntax attribute, CancellationToken cancellationToken) { var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); var attributeType = semanticModel.GetTypeInfo(attribute, cancellationToken).Type as INamedTypeSymbol; return attributeType.GetAttributeNamedParameters(semanticModel.Compilation, within); } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return Task.FromResult(GetTextChange(selectedItem, ch)); } private TextChange? GetTextChange(CompletionItem selectedItem, char? ch) { var displayText = selectedItem.DisplayText; if (ch != null) { // If user types a space, do not complete the " =" (space and equals) at the end of a named parameter. The // typed space character will be passed through to the editor, and they can then type the '='. if (ch == ' ' && displayText.EndsWith(SpaceEqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - SpaceEqualsString.Length)); } // If the user types '=', do not complete the '=' at the end of the named parameter because the typed '=' // will be passed through to the editor. if (ch == '=' && displayText.EndsWith(EqualsString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - EqualsString.Length)); } // If the user types ':', do not complete the ':' at the end of the named parameter because the typed ':' // will be passed through to the editor. if (ch == ':' && displayText.EndsWith(ColonString, StringComparison.Ordinal)) { return new TextChange(selectedItem.Span, displayText.Remove(displayText.Length - ColonString.Length)); } } return new TextChange(selectedItem.Span, displayText); } } }
/* * 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.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Securities.Future; using QuantConnect.Securities.Option; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests that we only receive the option chain for a single future contract /// in the option universe filter. /// </summary> public class AddFutureOptionSingleOptionChainSelectedInUniverseFilterRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private bool _invested; private bool _onDataReached; private bool _optionFilterRan; private readonly HashSet<Symbol> _symbolsReceived = new HashSet<Symbol>(); private readonly HashSet<Symbol> _expectedSymbolsReceived = new HashSet<Symbol>(); private readonly Dictionary<Symbol, List<QuoteBar>> _dataReceived = new Dictionary<Symbol, List<QuoteBar>>(); private Future _es; public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 1, 6); _es = AddFuture(Futures.Indices.SP500EMini, Resolution.Minute, Market.CME); _es.SetFilter((futureFilter) => { return futureFilter.Expiration(0, 365).ExpirationCycle(new[] { 3, 6 }); }); AddFutureOption(_es.Symbol, optionContracts => { _optionFilterRan = true; var expiry = new HashSet<DateTime>(optionContracts.Select(x => x.Underlying.ID.Date)).SingleOrDefault(); // Cast to IEnumerable<Symbol> because OptionFilterContract overrides some LINQ operators like `Select` and `Where` // and cause it to mutate the underlying Symbol collection when using those operators. var symbol = new HashSet<Symbol>(((IEnumerable<Symbol>)optionContracts).Select(x => x.Underlying)).SingleOrDefault(); if (expiry == null || symbol == null) { throw new InvalidOperationException("Expected a single Option contract in the chain, found 0 contracts"); } var enumerator = optionContracts.GetEnumerator(); while (enumerator.MoveNext()) { _expectedSymbolsReceived.Add(enumerator.Current); } return optionContracts; }); } public override void OnData(Slice data) { if (!data.HasData) { return; } _onDataReached = true; var hasOptionQuoteBars = false; foreach (var qb in data.QuoteBars.Values) { if (qb.Symbol.SecurityType != SecurityType.FutureOption) { continue; } hasOptionQuoteBars = true; _symbolsReceived.Add(qb.Symbol); if (!_dataReceived.ContainsKey(qb.Symbol)) { _dataReceived[qb.Symbol] = new List<QuoteBar>(); } _dataReceived[qb.Symbol].Add(qb); } if (_invested || !hasOptionQuoteBars) { return; } foreach (var chain in data.OptionChains.Values) { var futureInvested = false; var optionInvested = false; foreach (var option in chain.Contracts.Keys) { if (futureInvested && optionInvested) { return; } var future = option.Underlying; if (!optionInvested && data.ContainsKey(option)) { var optionContract = Securities[option]; var marginModel = optionContract.BuyingPowerModel as FuturesOptionsMarginModel; if (marginModel.InitialIntradayMarginRequirement == 0 || marginModel.InitialOvernightMarginRequirement == 0 || marginModel.MaintenanceIntradayMarginRequirement == 0 || marginModel.MaintenanceOvernightMarginRequirement == 0) { throw new Exception("Unexpected margin requirements"); } if (marginModel.GetInitialMarginRequirement(optionContract, 1) == 0) { throw new Exception("Unexpected Initial Margin requirement"); } if (marginModel.GetMaintenanceMargin(optionContract) != 0) { throw new Exception("Unexpected Maintenance Margin requirement"); } MarketOrder(option, 1); _invested = true; optionInvested = true; if (marginModel.GetMaintenanceMargin(optionContract) == 0) { throw new Exception("Unexpected Maintenance Margin requirement"); } } if (!futureInvested && data.ContainsKey(future)) { MarketOrder(future, 1); _invested = true; futureInvested = true; } } } } public override void OnEndOfAlgorithm() { base.OnEndOfAlgorithm(); if (!_optionFilterRan) { throw new InvalidOperationException("Option chain filter was never ran"); } if (!_onDataReached) { throw new Exception("OnData() was never called."); } if (_symbolsReceived.Count != _expectedSymbolsReceived.Count) { throw new AggregateException($"Expected {_expectedSymbolsReceived.Count} option contracts Symbols, found {_symbolsReceived.Count}"); } var missingSymbols = new List<Symbol>(); foreach (var expectedSymbol in _expectedSymbolsReceived) { if (!_symbolsReceived.Contains(expectedSymbol)) { missingSymbols.Add(expectedSymbol); } } if (missingSymbols.Count > 0) { throw new Exception($"Symbols: \"{string.Join(", ", missingSymbols)}\" were not found in OnData"); } foreach (var expectedSymbol in _expectedSymbolsReceived) { var data = _dataReceived[expectedSymbol]; var nonDupeDataCount = data.Select(x => { x.EndTime = default(DateTime); return x; }).Distinct().Count(); if (nonDupeDataCount < 1000) { throw new Exception($"Received too few data points. Expected >=1000, found {nonDupeDataCount} for {expectedSymbol}"); } } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "2"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "-15.625%"}, {"Drawdown", "0.200%"}, {"Expectancy", "0"}, {"Net Profit", "-0.093%"}, {"Sharpe Ratio", "-11.181"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0.002"}, {"Beta", "-0.016"}, {"Annual Standard Deviation", "0.001"}, {"Annual Variance", "0"}, {"Information Ratio", "-14.343"}, {"Tracking Error", "0.044"}, {"Treynor Ratio", "0.479"}, {"Total Fees", "$3.70"}, {"Estimated Strategy Capacity", "$41000.00"}, {"Lowest Capacity Asset", "ES 31C3JQTOYO9T0|ES XCZJLC9NOB29"}, {"Fitness Score", "0.41"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "79228162514264337593543950335"}, {"Return Over Maximum Drawdown", "-185.654"}, {"Portfolio Turnover", "0.821"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "9347e3b610cfa21f7cbd968a0135c8af"} }; } }
/* ' Copyright (c) 2011 DotNetNuke Corporation ' All rights reserved. ' ' 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 Microsoft.Extensions.DependencyInjection; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Users; using DotNetNuke.Entities.Users.Social; using DotNetNuke.Framework; using DotNetNuke.Framework.JavaScriptLibraries; using DotNetNuke.Services.Exceptions; using DotNetNuke.Entities.Modules; using DotNetNuke.Web.Client.ClientResourceManagement; using DotNetNuke.Modules.Journal.Components; using DotNetNuke.Security.Roles; using DotNetNuke.Abstractions; namespace DotNetNuke.Modules.Journal { /// ----------------------------------------------------------------------------- /// <summary> /// The ViewJournal class displays the content /// </summary> /// ----------------------------------------------------------------------------- public partial class View : JournalModuleBase { private readonly INavigationManager _navigationManager; public int PageSize = 20; public bool AllowPhotos = true; public bool AllowFiles = true; public int MaxMessageLength = 250; public bool CanRender = true; public bool ShowEditor = true; public bool CanComment = true; public bool IsGroup = false; public string BaseUrl; public string ProfilePage; public int Gid = -1; public int Pid = -1; public long MaxUploadSize = Config.GetMaxUploadSize(); public bool IsPublicGroup = false; public View() { _navigationManager = DependencyProvider.GetRequiredService<INavigationManager>(); } #region Event Handlers override protected void OnInit(EventArgs e) { JavaScript.RequestRegistration(CommonJs.DnnPlugins); JavaScript.RequestRegistration(CommonJs.jQueryFileUpload); ServicesFramework.Instance.RequestAjaxAntiForgerySupport(); JavaScript.RequestRegistration(CommonJs.Knockout); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journal.js"); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/journalcomments.js"); ClientResourceManager.RegisterScript(Page, "~/DesktopModules/Journal/Scripts/mentionsInput.js"); ClientResourceManager.RegisterScript(Page, "~/Resources/Shared/Scripts/json2.js"); var isAdmin = UserInfo.IsInRole(RoleController.Instance.GetRoleById(PortalId, PortalSettings.AdministratorRoleId).RoleName); if (!Request.IsAuthenticated || (!UserInfo.IsSuperUser && !isAdmin && UserInfo.IsInRole("Unverified Users"))) { ShowEditor = false; } else { ShowEditor = EditorEnabled; } if (Settings.ContainsKey(Constants.DefaultPageSize)) { PageSize = Convert.ToInt16(Settings[Constants.DefaultPageSize]); } if (Settings.ContainsKey(Constants.MaxCharacters)) { MaxMessageLength = Convert.ToInt16(Settings[Constants.MaxCharacters]); } if (Settings.ContainsKey(Constants.AllowPhotos)) { AllowPhotos = Convert.ToBoolean(Settings[Constants.AllowPhotos]); } if (Settings.ContainsKey(Constants.AllowFiles)) { AllowFiles = Convert.ToBoolean(Settings[Constants.AllowFiles]); } ctlJournalList.Enabled = true; ctlJournalList.ProfileId = -1; ctlJournalList.PageSize = PageSize; ctlJournalList.ModuleId = ModuleId; ModuleInfo moduleInfo = ModuleContext.Configuration; foreach (var module in ModuleController.Instance.GetTabModules(TabId).Values) { if (module.ModuleDefinition.FriendlyName == "Social Groups") { if (GroupId == -1 && FilterMode == JournalMode.Auto) { ShowEditor = false; ctlJournalList.Enabled = false; } if (GroupId > 0) { RoleInfo roleInfo = RoleController.Instance.GetRoleById(moduleInfo.OwnerPortalID, GroupId); if (roleInfo != null) { if (UserInfo.IsInRole(roleInfo.RoleName)) { ShowEditor = true; CanComment = true; IsGroup = true; } else { ShowEditor = false; CanComment = false; } if (!roleInfo.IsPublic && !ShowEditor) { ctlJournalList.Enabled = false; } if (roleInfo.IsPublic && !ShowEditor) { ctlJournalList.Enabled = true; } if (roleInfo.IsPublic && ShowEditor) { ctlJournalList.Enabled = true; } if (roleInfo.IsPublic) { IsPublicGroup = true; } } else { ShowEditor = false; ctlJournalList.Enabled = false; } } } } if (!String.IsNullOrEmpty(Request.QueryString["userId"])) { ctlJournalList.ProfileId = Convert.ToInt32(Request.QueryString["userId"]); if (!UserInfo.IsSuperUser && !isAdmin && ctlJournalList.ProfileId != UserId) { ShowEditor = ShowEditor && Utilities.AreFriends(UserController.GetUserById(PortalId, ctlJournalList.ProfileId), UserInfo); } } else if (GroupId > 0) { ctlJournalList.SocialGroupId = Convert.ToInt32(Request.QueryString["groupId"]); } InitializeComponent(); base.OnInit(e); } private void InitializeComponent() { Load += Page_Load; } /// ----------------------------------------------------------------------------- /// <summary> /// Page_Load runs when the control is loaded /// </summary> /// ----------------------------------------------------------------------------- private void Page_Load(object sender, EventArgs e) { try { BaseUrl = Globals.ApplicationPath; BaseUrl = BaseUrl.EndsWith("/") ? BaseUrl : BaseUrl + "/"; BaseUrl += "DesktopModules/Journal/"; ProfilePage = _navigationManager.NavigateURL(PortalSettings.UserTabId, string.Empty, new[] {"userId=xxx"}); if (!String.IsNullOrEmpty(Request.QueryString["userId"])) { Pid = Convert.ToInt32(Request.QueryString["userId"]); ctlJournalList.ProfileId = Pid; } else if (GroupId > 0) { Gid = GroupId; ctlJournalList.SocialGroupId = GroupId; } ctlJournalList.PageSize = PageSize; } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } #endregion } }
using System; using System.Collections.Generic; namespace Terraria.ModLoader { /// <summary> /// This class represents a layer of the drawing of an object, using a certain type of InfoType to help with its drawing. /// </summary> /// <typeparam name="InfoType"></typeparam> public abstract class DrawLayer<InfoType> { /// <summary> /// The name of the mod to which this DrawLayer belongs. /// </summary> public readonly string mod; /// <summary> /// The name which identifies this DrawLayer. /// </summary> public readonly string Name; /// <summary> /// The parent of this DrawLayer. If the parent is not drawn, this layer will not be drawn either. Defaults to null, which skips the parent check. /// </summary> public readonly DrawLayer<InfoType> parent; /// <summary> /// The delegate of this method, which can either do the actual drawing or add draw data, depending on what kind of layer this is. /// </summary> public readonly Action<InfoType> layer; /// <summary> /// Whether or not this DrawLayer should be drawn. For vanilla layers, this will be set to true before all drawing-related hooks are called. For modded layers, you must set this to true or false yourself. /// </summary> public bool visible = true; /// <summary> /// Creates a DrawLayer with the given mod name, identifier name, and drawing action. /// </summary> /// <param name="mod"></param> /// <param name="name"></param> /// <param name="layer"></param> protected DrawLayer(string mod, string name, Action<InfoType> layer) { this.mod = mod; this.Name = name; this.parent = null; this.layer = layer; } /// <summary> /// Creates a DrawLayer with the given mod name, identifier name, parent layer, and drawing action. /// </summary> /// <param name="mod"></param> /// <param name="name"></param> /// <param name="parent"></param> /// <param name="layer"></param> protected DrawLayer(string mod, string name, DrawLayer<InfoType> parent, Action<InfoType> layer) { this.mod = mod; this.Name = name; this.parent = parent; this.layer = layer; } /// <summary> /// Whether or not this layer should be drawn. Returns false if visible is false. If layerList is of type List<DrawLayer<InfoType>> and parent is not null, this will also return false if the parent is not drawn. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="layers"></param> /// <returns></returns> public bool ShouldDraw<T>(IList<T> layers) where T : DrawLayer<InfoType> { if (!this.visible) { return false; } DrawLayer<InfoType> parentLayer = this.parent; while (parentLayer != null) { if (!parentLayer.visible || !layers.Contains((T)parentLayer)) { return false; } parentLayer = parentLayer.parent; } return true; } /// <summary> /// Invokes this DrawLayer's layer action. /// </summary> /// <param name="drawInfo"></param> public virtual void Draw(ref InfoType drawInfo) { this.layer(drawInfo); } } /// <summary> /// This class represents a DrawLayer for the player, and uses PlayerDrawInfo as its InfoType. Drawing should be done by adding Terraria.DataStructures.DrawData objects to Main.playerDrawData. /// </summary> public class PlayerLayer : DrawLayer<PlayerDrawInfo> { /// <summary> /// Draws the player's hair. To be honest this layer seems kind of useless. /// </summary> public static readonly PlayerLayer HairBack = CreateVanillaLayer("HairBack"); /// <summary> /// Draws the back textures of the player's mount. Also draws the player's magic carpet. /// </summary> public static readonly PlayerLayer MountBack = CreateVanillaLayer("MountBack"); /// <summary> /// Draws miscellaneous effects behind the player. /// </summary> public static readonly PlayerLayer MiscEffectsBack = CreateVanillaLayer("MiscEffectsBack"); /// <summary> /// Draws the player's back accessory and held item's backpack. /// </summary> public static readonly PlayerLayer BackAcc = CreateVanillaLayer("BackAcc"); /// <summary> /// Draws the layer's wings. /// </summary> public static readonly PlayerLayer Wings = CreateVanillaLayer("Wings"); /// <summary> /// Draws the player's balloon accessory. /// </summary> public static readonly PlayerLayer BalloonAcc = CreateVanillaLayer("BalloonAcc"); /// <summary> /// Draws the player's body and leg skin. /// </summary> public static readonly PlayerLayer Skin = CreateVanillaLayer("Skin"); /// <summary> /// Draws the player's leg armor or pants and shoes. /// </summary> public static readonly PlayerLayer Legs = CreateVanillaLayer("Legs"); /// <summary> /// Draws the player's shoe accessory. /// </summary> public static readonly PlayerLayer ShoeAcc = CreateVanillaLayer("ShoeAcc"); /// <summary> /// Draws the player's body armor or shirts. /// </summary> public static readonly PlayerLayer Body = CreateVanillaLayer("Body"); /// <summary> /// Draws the player's hand off accessory. /// </summary> public static readonly PlayerLayer HandOffAcc = CreateVanillaLayer("HandOffAcc"); /// <summary> /// Draws the player's waist accessory. /// </summary> public static readonly PlayerLayer WaistAcc = CreateVanillaLayer("WaistAcc"); /// <summary> /// Draws the player's neck accessory. /// </summary> public static readonly PlayerLayer NeckAcc = CreateVanillaLayer("NeckAcc"); /// <summary> /// Draws the player's face and eyes. /// </summary> public static readonly PlayerLayer Face = CreateVanillaLayer("Face"); /// <summary> /// Draws the player's hair. /// </summary> public static readonly PlayerLayer Hair = CreateVanillaLayer("Hair"); /// <summary> /// Draws the player's head armor. /// </summary> public static readonly PlayerLayer Head = CreateVanillaLayer("Head"); /// <summary> /// Draws the player's face accessory. /// </summary> public static readonly PlayerLayer FaceAcc = CreateVanillaLayer("FaceAcc"); /// <summary> /// Draws the front textures of the player's mount. Also draws the pulley if the player is hanging on a rope. /// </summary> public static readonly PlayerLayer MountFront = CreateVanillaLayer("MountFront"); /// <summary> /// Draws the player's shield accessory. /// </summary> public static readonly PlayerLayer ShieldAcc = CreateVanillaLayer("ShieldAcc"); /// <summary> /// Draws the player's solar shield if the player has one. /// </summary> public static readonly PlayerLayer SolarShield = CreateVanillaLayer("SolarShield"); /// <summary> /// Draws the player's held projectile if it should be drawn behind the held item and arms. /// </summary> public static readonly PlayerLayer HeldProjBack = CreateVanillaLayer("HeldProjBack"); /// <summary> /// Draws the player's held item. /// </summary> public static readonly PlayerLayer HeldItem = CreateVanillaLayer("HeldItem"); /// <summary> /// Draws the player's arms (including the armor's arms if applicable). /// </summary> public static readonly PlayerLayer Arms = CreateVanillaLayer("Arms"); /// <summary> /// Draws the player's hand on accessory. Also draws the player's held item if the player is in the middle of using a claw item. /// </summary> public static readonly PlayerLayer HandOnAcc = CreateVanillaLayer("HandOnAcc"); /// <summary> /// Draws the player's held projectile if it should be drawn in front of the held item and arms. /// </summary> public static readonly PlayerLayer HeldProjFront = CreateVanillaLayer("HeldProjFront"); /// <summary> /// Draws the player's front accessory. /// </summary> public static readonly PlayerLayer FrontAcc = CreateVanillaLayer("FrontAcc"); /// <summary> /// Draws miscellaneous effects in front of the player. /// </summary> public static readonly PlayerLayer MiscEffectsFront = CreateVanillaLayer("MiscEffectsFront"); /// <summary> /// Creates a PlayerLayer with the given mod name, identifier name, and drawing action. /// </summary> /// <param name="mod"></param> /// <param name="name"></param> /// <param name="layer"></param> public PlayerLayer(string mod, string name, Action<PlayerDrawInfo> layer) : base(mod, name, layer) { } /// <summary> /// Creates a PlayerLayer with the given mod name, identifier name, parent layer, and drawing action. /// </summary> /// <param name="mod"></param> /// <param name="name"></param> /// <param name="parent"></param> /// <param name="layer"></param> public PlayerLayer(string mod, string name, PlayerLayer parent, Action<PlayerDrawInfo> layer) : base(mod, name, parent, layer) { } private static PlayerLayer CreateVanillaLayer(string name) { return new PlayerLayer("Terraria", name, _ => {}); } } /// <summary> /// This class represents a DrawLayer for the player's map icon, and uses PlayerDrawHeadInfo as its InfoType. Drawing should be done directly through drawInfo.spriteBatch. /// </summary> public class PlayerHeadLayer : DrawLayer<PlayerHeadDrawInfo> { /// <summary> /// Draws the player's face and eyes. /// </summary> public static readonly PlayerHeadLayer Head = CreateVanillaLayer("Head"); /// <summary> /// Draws the player's hair. /// </summary> public static readonly PlayerHeadLayer Hair = CreateVanillaLayer("Hair"); /// <summary> /// Draws the player's alternate (hat) hair. /// </summary> public static readonly PlayerHeadLayer AltHair = CreateVanillaLayer("AltHair"); /// <summary> /// Draws the player's head armor. /// </summary> public static readonly PlayerHeadLayer Armor = CreateVanillaLayer("Armor"); /// <summary> /// Draws the player's face accessory. /// </summary> public static readonly PlayerHeadLayer FaceAcc = CreateVanillaLayer("FaceAcc"); /// <summary> /// Creates a PlayerHeadLayer with the given mod name, identifier name, and drawing action. /// </summary> /// <param name="mod"></param> /// <param name="name"></param> /// <param name="layer"></param> public PlayerHeadLayer(string mod, string name, Action<PlayerHeadDrawInfo> layer) : base(mod, name, layer) { } /// <summary> /// Creates a PlayerHeadLayer with the given mod name, identifier name, parent layer, and drawing action. /// </summary> /// <param name="mod"></param> /// <param name="name"></param> /// <param name="parent"></param> /// <param name="layer"></param> public PlayerHeadLayer(string mod, string name, PlayerHeadLayer parent, Action<PlayerHeadDrawInfo> layer) : base(mod, name, parent, layer) { } private static PlayerHeadLayer CreateVanillaLayer(string name) { return new PlayerHeadLayer("Terraria", name, _ => {}); } } }
// App.cs - Application startup and properties // // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.IO; using System.Text; using System.Reflection; using System.Windows.Forms; using System.Globalization; using System.Collections; using System.Diagnostics; using System.Threading; namespace NDoc.Gui { /// <summary> /// Static class with the Main method and application properties /// </summary> public sealed class App { private App() { } /// <summary> /// Application entry point /// </summary> /// <param name="args">Command line arguments</param> [STAThread] public static void Main(string[] args) { Thread.CurrentThread.Name = "GUI"; Application.Run( new MainForm( (args.Length == 1) ? args[0] : null ) ); } /// <summary> /// The NDoc SourceForge URI /// </summary> public static string WebSiteUri { get { return "http://ndoc.sourceforge.net"; } } /// <summary> /// The location where the application is running /// </summary> public static string RuntimeLocation { get { Uri uri = new Uri( Assembly.GetExecutingAssembly().CodeBase, true ); return Path.GetDirectoryName( uri.AbsolutePath ); } } /// <summary> /// The path to the license file /// </summary> public static string LicenseFilePath { get { // first try to locate license file in directory in which NDocGui is located string path = Path.Combine( RuntimeLocation, "gpl.rtf" ); if ( File.Exists( path ) == false ) path = GetSourceTreePath( @"setup\gpl.rtf" ); return path; } } /// <summary> /// Returns a path to a file based resource that /// is sompatible with the source tree structure, rather than the /// deploymeed strucutre /// </summary> /// <param name="fileName">The file to build a path for</param> /// <returns>Relative path to the file in the source tree</returns> public static string GetSourceTreePath(string fileName) { return Path.Combine( RuntimeLocation, string.Format( CultureInfo.InvariantCulture, "..{0}..{0}..{0}{1}", Path.DirectorySeparatorChar, fileName ) ); } /// <summary> /// The path to the help file /// </summary> public static string HelpFilePath { get { // first try to locate help file in directory in which NDocGui is located string path = Path.Combine( RuntimeLocation, "NDocUsersGuide.chm" ); if ( File.Exists( path ) == false ) path = GetSourceTreePath( @"UsersGuide\NDocUsersGuide.chm" ); return path; } } /// <summary> /// Given an <see cref="Exception"/> returns the deepest /// non-null InnerException /// </summary> /// <param name="e">The top Exception</param> /// <returns>The innermost Exception</returns> public static Exception GetInnermostException( Exception e ) { if ( e == null ) return null; return WalkExceptionStack( e, e.InnerException ); } private static Exception WalkExceptionStack( Exception parent, Exception inner ) { Debug.Assert( parent != null ); if ( inner == null ) return parent; return WalkExceptionStack( inner, inner.InnerException ); } /// <summary> /// Streams an exception /// </summary> /// <param name="strBld">A StringBuilder to hold the exception details</param> /// <param name="ex">The Exception</param> public static void DumpException(StringBuilder strBld, Exception ex) { if (ex != null) { strBld.Append("\r\n\r\n"); Exception tmpEx = ex; while (tmpEx != null) { strBld.AppendFormat("Exception: {0}\r\n", tmpEx.GetType()); strBld.Append(tmpEx.Message); strBld.Append("\r\n\r\n"); tmpEx = tmpEx.InnerException; } strBld.Append("\r\n"); } ReflectionTypeLoadException rtle = ex as ReflectionTypeLoadException; if (rtle != null) { Hashtable fileLoadExceptions = new Hashtable(); foreach (Exception loaderEx in rtle.LoaderExceptions) { System.IO.FileLoadException fileLoadEx = loaderEx as System.IO.FileLoadException; if (fileLoadEx != null) { if (fileLoadExceptions.ContainsKey(fileLoadEx.FileName) == false) { fileLoadExceptions.Add(fileLoadEx.FileName, null); strBld.AppendFormat("Unable to load: {0}\r\n", fileLoadEx.FileName); } } strBld.Append(loaderEx.Message + "\r\n"); strBld.Append(loaderEx.StackTrace + Environment.NewLine); } } } /// <summary> /// Dumps the details of an exception to the Trace window /// </summary> /// <param name="ex">The Exception</param> public static void BuildTraceError(Exception ex) { System.Text.StringBuilder strBld = new System.Text.StringBuilder(); App.DumpException(strBld, ex); if (ex != null) { strBld.Append("\r\n"); Exception tmpEx = ex; while (tmpEx != null) { strBld.AppendFormat("Exception: {0}\r\n", tmpEx.GetType()); strBld.Append(tmpEx.StackTrace.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")); strBld.Append("\r\n\r\n"); tmpEx = tmpEx.InnerException; } } Trace.WriteLine(strBld); } } }
using System; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Baseline; using Jasper.Logging; using Jasper.Runtime; using Jasper.Runtime.WorkerQueues; using Jasper.Transports; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Jasper.Persistence.Durability { public class DurabilityAgent : IHostedService, IDurabilityAgent, IDisposable { /// <summary> /// Strictly a testing helper /// </summary> /// <param name="host"></param> /// <returns></returns> public static DurabilityAgent ForHost(IHost host) { return host.Services.GetService<IMessagingRoot>().As<MessagingRoot>().Durability; } private readonly IMessagingAction IncomingMessages; private readonly IMessagingAction OutgoingMessages; private readonly IMessagingAction ScheduledJobs; private readonly IMessagingAction NodeReassignment; private readonly IEnvelopePersistence _storage; private readonly AdvancedSettings _settings; private readonly ILogger<DurabilityAgent> _trace; private readonly IWorkerQueue _workers; private readonly ActionBlock<IMessagingAction> _worker; private Timer _nodeReassignmentTimer; private Timer _scheduledJobTimer; private readonly bool _disabled; private bool _hasStarted; public DurabilityAgent(ITransportLogger logger, ILogger<DurabilityAgent> trace, IWorkerQueue workers, IEnvelopePersistence storage, ITransportRuntime runtime, AdvancedSettings settings) { if (storage is NulloEnvelopePersistence) { _disabled = true; return; } Logger = logger; _trace = trace; _workers = workers; _storage = storage; _settings = settings; _worker = new ActionBlock<IMessagingAction>(processAction, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1, CancellationToken = _settings.Cancellation }); NodeId = _settings.UniqueNodeId; IncomingMessages = new RecoverIncomingMessages(storage, workers, settings, logger); OutgoingMessages = new RecoverOutgoingMessages(runtime, settings, logger); NodeReassignment = new NodeReassignment(settings); ScheduledJobs = new RunScheduledJobs(settings, logger); } public ITransportLogger Logger { get; } public int NodeId { get; } // This was built mostly for testing public Task Execute(IMessagingAction action) { // this is a side effect of the agent being shut down if (action == null) return Task.CompletedTask; if (_hasStarted) { var wrapper = new MessageActionWrapper(action); _worker.Post(wrapper); return wrapper.Completion; } else { return processAction(action); } } public class MessageActionWrapper : IMessagingAction { private readonly IMessagingAction _inner; private readonly TaskCompletionSource<bool> _completion; public MessageActionWrapper(IMessagingAction inner) { _inner = inner; _completion = new TaskCompletionSource<bool>(); } public string Description => _inner.Description; public Task Completion => _completion.Task; public async Task Execute(IEnvelopePersistence storage, IDurabilityAgent agent) { try { await _inner.Execute(storage, agent); _completion.SetResult(true); } catch (Exception e) { _completion.SetException(e); } } } public Task EnqueueLocally(Envelope envelope) { return _workers.Enqueue(envelope); } public void RescheduleIncomingRecovery() { _worker.Post(IncomingMessages); } public void RescheduleOutgoingRecovery() { _worker.Post(OutgoingMessages); } public async Task StartAsync(CancellationToken stoppingToken) { if (_disabled) return; _hasStarted = true; await tryRestartConnection(); _scheduledJobTimer = new Timer(s => { _worker.Post(ScheduledJobs); _worker.Post(IncomingMessages); _worker.Post(OutgoingMessages); }, _settings, _settings.ScheduledJobFirstExecution, _settings.ScheduledJobPollingTime); _nodeReassignmentTimer = new Timer(s => { _worker.Post(NodeReassignment); }, _settings, _settings.FirstNodeReassignmentExecution, _settings.NodeReassignmentPollingTime); } private async Task processAction(IMessagingAction action) { if (_settings.Cancellation.IsCancellationRequested) return; await tryRestartConnection(); // Something is wrong, but we'll keep trying in a bit if (!_storage.Session.IsConnected()) return; try { try { if (_settings.VerboseDurabilityAgentLogging) { _trace.LogDebug("Running " + action.Description); } await action.Execute(_storage, this); } catch (Exception e) { Logger.LogException(e, message: "Running " + action.Description); } } catch (Exception e) { Logger.LogException(e, message: "Error trying to run " + action); await _storage.Session.ReleaseNodeLock(_settings.UniqueNodeId); } await _storage.Session.GetNodeLock(_settings.UniqueNodeId); } private async Task tryRestartConnection() { if (_storage.Session.IsConnected()) return; try { await _storage.Session.ConnectAndLockCurrentNode(Logger, _settings.UniqueNodeId); } catch (Exception e) { Logger.LogException(e, message: "Failure trying to restart the connection in DurabilityAgent"); } } public async Task StopAsync(CancellationToken cancellationToken) { if (_disabled) return; await _nodeReassignmentTimer.DisposeAsync(); await _scheduledJobTimer.DisposeAsync(); _worker.Complete(); try { await _worker.Completion; await _storage.Session.ReleaseNodeLock(_settings.UniqueNodeId); // Release all envelopes tagged to this node in message persistence to any node await _storage.ReassignDormantNodeToAnyNode(_settings.UniqueNodeId); } catch (Exception e) { Logger.LogException(e); } } public void Dispose() { if (_disabled) return; if (_storage.Session.IsConnected()) { _storage.Session.ReleaseNodeLock(_settings.UniqueNodeId).GetAwaiter().GetResult(); _storage.SafeDispose(); } _scheduledJobTimer?.Dispose(); _nodeReassignmentTimer?.Dispose(); } } }
//----------------------------------------------------------------------- // <copyright file="ActorSubscriber.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.Concurrent; using Akka.Actor; using Akka.Event; using Akka.Streams.Dsl; using Reactive.Streams; namespace Akka.Streams.Actors { /// <summary> /// TBD /// </summary> [Serializable] public sealed class OnSubscribe : INoSerializationVerificationNeeded, IDeadLetterSuppression { /// <summary> /// TBD /// </summary> public readonly ISubscription Subscription; /// <summary> /// TBD /// </summary> /// <param name="subscription">TBD</param> public OnSubscribe(ISubscription subscription) { Subscription = subscription; } } /// <summary> /// TBD /// </summary> public interface IActorSubscriberMessage : INoSerializationVerificationNeeded, IDeadLetterSuppression { } /// <summary> /// TBD /// </summary> [Serializable] public sealed class OnNext : IActorSubscriberMessage { /// <summary> /// TBD /// </summary> public readonly object Element; /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> public OnNext(object element) { Element = element; } } /// <summary> /// TBD /// </summary> [Serializable] public sealed class OnError : IActorSubscriberMessage { /// <summary> /// TBD /// </summary> public readonly Exception Cause; /// <summary> /// TBD /// </summary> /// <param name="cause">TBD</param> public OnError(Exception cause) { Cause = cause; } } /// <summary> /// TBD /// </summary> [Serializable] public sealed class OnComplete : IActorSubscriberMessage { /// <summary> /// TBD /// </summary> public static readonly OnComplete Instance = new OnComplete(); private OnComplete() { } } /// <summary> /// <para> /// Extend this actor to make it a /// stream subscriber with full control of stream back pressure. It will receive /// <see cref="OnNext"/>, <see cref="OnComplete"/> and <see cref="OnError"/> /// messages from the stream. It can also receive other, non-stream messages, in /// the same way as any actor. /// </para> /// <para> /// Attach the actor as a <see cref="ISubscriber{T}"/> to the stream with /// <see cref="Create{T}"/> /// </para> /// <para> /// Subclass must define the <see cref="RequestStrategy"/> to control stream back pressure. /// After each incoming message the <see cref="ActorSubscriber"/> will automatically invoke /// the <see cref="IRequestStrategy.RequestDemand"/> and propagate the returned demand to the stream. /// The provided <see cref="WatermarkRequestStrategy"/> is a good strategy if the actor /// performs work itself. /// The provided <see cref="MaxInFlightRequestStrategy"/> is useful if messages are /// queued internally or delegated to other actors. /// You can also implement a custom <see cref="IRequestStrategy"/> or call <see cref="Request"/> manually /// together with <see cref="ZeroRequestStrategy"/> or some other strategy. In that case /// you must also call <see cref="Request"/> when the actor is started or when it is ready, otherwise /// it will not receive any elements. /// </para> /// </summary> public abstract class ActorSubscriber : ActorBase { private readonly ActorSubscriberState _state = ActorSubscriberState.Instance.Apply(Context.System); private ISubscription _subscription; private long _requested; private bool _canceled; /// <summary> /// TBD /// </summary> public abstract IRequestStrategy RequestStrategy { get; } /// <summary> /// TBD /// </summary> public bool IsCanceled => _canceled; /// <summary> /// The number of stream elements that have already been requested from upstream /// but not yet received. /// </summary> protected int RemainingRequested => _requested > int.MaxValue ? int.MaxValue : (int)_requested; /// <summary> /// TBD /// </summary> /// <param name="receive">TBD</param> /// <param name="message">TBD</param> /// <returns>TBD</returns> protected internal override bool AroundReceive(Receive receive, object message) { if (message is OnNext) { _requested--; if (!_canceled) { base.AroundReceive(receive, message); Request(RequestStrategy.RequestDemand(RemainingRequested)); } } else if (message is OnSubscribe) { var onSubscribe = (OnSubscribe) message; if (_subscription == null) { _subscription = onSubscribe.Subscription; if (_canceled) { Context.Stop(Self); onSubscribe.Subscription.Cancel(); } else if (_requested != 0) { onSubscribe.Subscription.Request(RemainingRequested); } } else { onSubscribe.Subscription.Cancel(); } } else if (message is OnComplete || message is OnError) { if (!_canceled) { _canceled = true; base.AroundReceive(receive, message); } } else { base.AroundReceive(receive, message); Request(RequestStrategy.RequestDemand(RemainingRequested)); } return true; } #region Internal API /// <summary> /// TBD /// </summary> public override void AroundPreStart() { base.AroundPreStart(); Request(RequestStrategy.RequestDemand(RemainingRequested)); } /// <summary> /// TBD /// </summary> /// <param name="cause">TBD</param> /// <param name="message">TBD</param> public override void AroundPostRestart(Exception cause, object message) { var s = _state.Remove(Self); // restore previous state if (s != null) { _subscription = s.Subscription; _requested = s.Requested; _canceled = s.IsCanceled; } base.AroundPostRestart(cause, message); Request(RequestStrategy.RequestDemand(RemainingRequested)); } /// <summary> /// TBD /// </summary> /// <param name="cause">TBD</param> /// <param name="message">TBD</param> public override void AroundPreRestart(Exception cause, object message) { // some state must survive restart _state.Set(Self, new ActorSubscriberState.State(_subscription, _requested, _canceled)); base.AroundPreRestart(cause, message); } /// <summary> /// TBD /// </summary> public override void AroundPostStop() { _state.Remove(Self); if (!_canceled) _subscription?.Cancel(); base.AroundPostStop(); } #endregion /// <summary> /// Request a number of elements from upstream. /// </summary> /// <param name="n">TBD</param> protected void Request(long n) { if (n > 0 && !_canceled) { // if we don't have a subscription yet, it will be requested when it arrives _subscription?.Request(n); _requested += n; } } /// <summary> /// <para> /// Cancel upstream subscription. /// No more elements will be delivered after cancel. /// </para> /// <para> /// The <see cref="ActorSubscriber"/> will be stopped immediately after signaling cancellation. /// In case the upstream subscription has not yet arrived the Actor will stay alive /// until a subscription arrives, cancel it and then stop itself. /// </para> /// </summary> protected void Cancel() { if (!_canceled) { if (_subscription != null) { Context.Stop(Self); _subscription.Cancel(); } else { _canceled = true; } } } /// <summary> /// Attach a <see cref="ActorSubscriber"/> actor as a <see cref="ISubscriber{T}"/> /// to a <see cref="IPublisher{T}"/> or <see cref="IFlow{TOut,TMat}"/> /// </summary> /// <typeparam name="T">TBD</typeparam> /// <param name="ref">TBD</param> /// <returns>TBD</returns> public static ISubscriber<T> Create<T>(IActorRef @ref) => new ActorSubscriberImpl<T>(@ref); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> public sealed class ActorSubscriberImpl<T> : ISubscriber<T> { private readonly IActorRef _impl; /// <summary> /// TBD /// </summary> /// <param name="impl">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when the specified <paramref name="impl"/> is undefined. /// </exception> public ActorSubscriberImpl(IActorRef impl) { if (impl == null) throw new ArgumentNullException(nameof(impl), "ActorSubscriberImpl requires actor impl to be defined"); _impl = impl; } /// <summary> /// TBD /// </summary> /// <param name="subscription">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when the specified <paramref name="subscription"/> is undefined. /// </exception> public void OnSubscribe(ISubscription subscription) { if (subscription == null) throw new ArgumentNullException(nameof(subscription), "OnSubscribe requires subscription to be defined"); _impl.Tell(new OnSubscribe(subscription)); } /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> public void OnNext(T element) => OnNext((object)element); /// <summary> /// TBD /// </summary> /// <param name="element">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when the specified <paramref name="element"/> is undefined. /// </exception> public void OnNext(object element) { if (element == null) throw new ArgumentNullException(nameof(element), "OnNext requires provided element not to be null"); _impl.Tell(new OnNext(element)); } /// <summary> /// TBD /// </summary> /// <param name="cause">TBD</param> /// <exception cref="ArgumentNullException"> /// This exception is thrown when the specified <paramref name="cause"/> is undefined. /// </exception> public void OnError(Exception cause) { if (cause == null) throw new ArgumentNullException(nameof(cause), "OnError has no cause defined"); _impl.Tell(new OnError(cause)); } /// <summary> /// TBD /// </summary> public void OnComplete() => _impl.Tell(Actors.OnComplete.Instance); } /// <summary> /// TBD /// </summary> public sealed class ActorSubscriberState : ExtensionIdProvider<ActorSubscriberState>, IExtension { /// <summary> /// TBD /// </summary> [Serializable] public sealed class State { /// <summary> /// TBD /// </summary> public readonly ISubscription Subscription; /// <summary> /// TBD /// </summary> public readonly long Requested; /// <summary> /// TBD /// </summary> public readonly bool IsCanceled; /// <summary> /// TBD /// </summary> /// <param name="subscription">TBD</param> /// <param name="requested">TBD</param> /// <param name="isCanceled">TBD</param> public State(ISubscription subscription, long requested, bool isCanceled) { Subscription = subscription; Requested = requested; IsCanceled = isCanceled; } } /// <summary> /// TBD /// </summary> public static readonly ActorSubscriberState Instance = new ActorSubscriberState(); private ActorSubscriberState() { } private readonly ConcurrentDictionary<IActorRef, State> _state = new ConcurrentDictionary<IActorRef, State>(); /// <summary> /// TBD /// </summary> /// <param name="actorRef">TBD</param> /// <returns>TBD</returns> public State Get(IActorRef actorRef) { _state.TryGetValue(actorRef, out var state); return state; } /// <summary> /// TBD /// </summary> /// <param name="actorRef">TBD</param> /// <param name="s">TBD</param> /// <returns>TBD</returns> public void Set(IActorRef actorRef, State s) => _state.AddOrUpdate(actorRef, s, (@ref, oldState) => s); /// <summary> /// TBD /// </summary> /// <param name="actorRef">TBD</param> /// <returns>TBD</returns> public State Remove(IActorRef actorRef) { State s; return _state.TryRemove(actorRef, out s) ? s : null; } /// <summary> /// TBD /// </summary> /// <param name="system">TBD</param> /// <returns>TBD</returns> public override ActorSubscriberState CreateExtension(ExtendedActorSystem system) => new ActorSubscriberState(); } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK 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; using VR = UnityEngine.VR; /// <summary> /// Sample that allows you to play with various VR settings. /// </summary> public class OVRSceneSampleController : MonoBehaviour { /// <summary> /// The key that quits the application. /// </summary> public KeyCode quitKey = KeyCode.Escape; /// <summary> /// An optional texture that appears before the menu fades in. /// </summary> public Texture fadeInTexture = null; /// <summary> /// Controls how quickly the player's speed and rotation change based on input. /// </summary> public float speedRotationIncrement = 0.05f; private OVRPlayerController playerController = null; // Handle to OVRCameraRig private OVRCameraRig cameraController = null; /// <summary> /// We can set the layer to be anything we want to, this allows /// a specific camera to render it. /// </summary> public string layerName = "Default"; // Vision mode on/off private bool visionMode = true; // We want to hold onto GridCube, for potential sharing // of the menu RenderTarget OVRGridCube gridCube = null; #if SHOW_DK2_VARIABLES private string strVisionMode = "Vision Enabled: ON"; #endif #region MonoBehaviour Message Handlers /// <summary> /// Awake this instance. /// </summary> void Awake() { // Find camera controller OVRCameraRig[] cameraControllers; cameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if (cameraControllers.Length == 0) { Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached."); } else if (cameraControllers.Length > 1) { Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached."); } else { cameraController = cameraControllers[0]; } // Find player controller OVRPlayerController[] playerControllers; playerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>(); if (playerControllers.Length == 0) { Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached."); } else if (playerControllers.Length > 1) { Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached."); } else { playerController = playerControllers[0]; } } /// <summary> /// Start this instance. /// </summary> void Start() { // Make sure to hide cursor if (Application.isEditor == false) { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } // CameraController updates if (cameraController != null) { // Add a GridCube component to this object gridCube = gameObject.AddComponent<OVRGridCube>(); gridCube.SetOVRCameraController(ref cameraController); } } /// <summary> /// Update this instance. /// </summary> void Update() { // Recenter pose UpdateRecenterPose(); // Turn On/Off Vision Mode UpdateVisionMode(); // Update Speed and Rotation Scale if (playerController != null) UpdateSpeedAndRotationScaleMultiplier(); // Toggle Fullscreen if (Input.GetKeyDown(KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen; if (Input.GetKeyDown(KeyCode.M)) UnityEngine.XR.XRSettings.showDeviceView = !UnityEngine.XR.XRSettings.showDeviceView; #if !UNITY_ANDROID || UNITY_EDITOR // Escape Application if (Input.GetKeyDown(quitKey)) Application.Quit(); #endif } #endregion /// <summary> /// Updates the vision mode. /// </summary> void UpdateVisionMode() { if (Input.GetKeyDown(KeyCode.F2)) { visionMode ^= visionMode; OVRManager.tracker.isEnabled = visionMode; } } /// <summary> /// Updates the speed and rotation scale multiplier. /// </summary> void UpdateSpeedAndRotationScaleMultiplier() { float moveScaleMultiplier = 0.0f; playerController.GetMoveScaleMultiplier(ref moveScaleMultiplier); if (Input.GetKeyDown(KeyCode.Alpha7)) { moveScaleMultiplier -= speedRotationIncrement; } else if (Input.GetKeyDown(KeyCode.Alpha8)) { moveScaleMultiplier += speedRotationIncrement; } playerController.SetMoveScaleMultiplier(moveScaleMultiplier); float rotationScaleMultiplier = 0.0f; playerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier); if (Input.GetKeyDown(KeyCode.Alpha9)) { rotationScaleMultiplier -= speedRotationIncrement; } else if (Input.GetKeyDown(KeyCode.Alpha0)) { rotationScaleMultiplier += speedRotationIncrement; } playerController.SetRotationScaleMultiplier(rotationScaleMultiplier); } /// <summary> /// Recenter pose /// </summary> void UpdateRecenterPose() { if (Input.GetKeyDown(KeyCode.R)) OVRManager.display.RecenterPose(); } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace JobMatcher.Service.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// 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.Reflection; using System.Reflection.Emit; using System.Runtime.InteropServices.Tests.Common; using Xunit; namespace System.Runtime.InteropServices.Tests { public partial class GetComInterfaceForObjectTests { [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_GenericWithValidClass_ReturnsExpected() { var o = new ClassWithInterface(); IntPtr iUnknown = Marshal.GetComInterfaceForObject<ClassWithInterface, INonGenericInterface>(o); try { Assert.NotEqual(IntPtr.Zero, iUnknown); } finally { Marshal.Release(iUnknown); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_GenericWithValidStruct_ReturnsExpected() { var o = new StructWithInterface(); IntPtr iUnknown = Marshal.GetComInterfaceForObject<StructWithInterface, INonGenericInterface>(o); try { Assert.NotEqual(IntPtr.Zero, iUnknown); } finally { Marshal.Release(iUnknown); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_NonGenericWithValidClass_ReturnsExpected() { var o = new ClassWithInterface(); IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(INonGenericInterface)); try { Assert.NotEqual(IntPtr.Zero, iUnknown); } finally { Marshal.Release(iUnknown); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_NonGenericWithValidStruct_ReturnsExpected() { var o = new StructWithInterface(); IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(INonGenericInterface)); try { Assert.NotEqual(IntPtr.Zero, iUnknown); } finally { Marshal.Release(iUnknown); } } [Theory] [InlineData(CustomQueryInterfaceMode.Allow)] [InlineData(CustomQueryInterfaceMode.Ignore)] [InlineData(CustomQueryInterfaceMode.Allow + 1)] [InlineData(CustomQueryInterfaceMode.Ignore - 1)] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_NonGenericCustomQueryInterfaceModeWithValidClass_ReturnsExpected(CustomQueryInterfaceMode mode) { var o = new ClassWithInterface(); IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(INonGenericInterface), mode); try { Assert.NotEqual(IntPtr.Zero, iUnknown); } finally { Marshal.Release(iUnknown); } } [Theory] [InlineData(CustomQueryInterfaceMode.Allow)] [InlineData(CustomQueryInterfaceMode.Ignore)] [InlineData(CustomQueryInterfaceMode.Allow + 1)] [InlineData(CustomQueryInterfaceMode.Ignore - 1)] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_NonGenericCustomQueryInterfaceModeWithValidStruct_ReturnsExpected(CustomQueryInterfaceMode mode) { var o = new StructWithInterface(); IntPtr iUnknown = Marshal.GetComInterfaceForObject(o, typeof(INonGenericInterface), mode); try { Assert.NotEqual(IntPtr.Zero, iUnknown); } finally { Marshal.Release(iUnknown); } } public class ClassWithInterface : INonGenericInterface { } public struct StructWithInterface : INonGenericInterface { } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] public void GetComInterfaceForObject_Unix_ThrowsPlatformNotSupportedException() { Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComInterfaceForObject(null, null)); Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComInterfaceForObject(null, null, CustomQueryInterfaceMode.Allow)); Assert.Throws<PlatformNotSupportedException>(() => Marshal.GetComInterfaceForObject<int, int>(1)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_NullObject_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("o", () => Marshal.GetComInterfaceForObject(null, typeof(INonGenericInterface))); AssertExtensions.Throws<ArgumentNullException>("o", () => Marshal.GetComInterfaceForObject(null, typeof(INonGenericInterface), CustomQueryInterfaceMode.Allow)); AssertExtensions.Throws<ArgumentNullException>("o", () => Marshal.GetComInterfaceForObject<string, string>(null)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("t", () => Marshal.GetComInterfaceForObject(new object(), null)); AssertExtensions.Throws<ArgumentNullException>("t", () => Marshal.GetComInterfaceForObject(new object(), null, CustomQueryInterfaceMode.Allow)); } public static IEnumerable<object[]> GetComInterfaceForObject_InvalidType_TestData() { yield return new object[] { typeof(int).MakeByRefType() }; yield return new object[] { typeof(int).MakePointerType() }; yield return new object[] { typeof(string) }; yield return new object[] { typeof(NonGenericClass) }; yield return new object[] { typeof(GenericClass<>) }; yield return new object[] { typeof(GenericClass<string>) }; yield return new object[] { typeof(AbstractClass) }; yield return new object[] { typeof(GenericStruct<>) }; yield return new object[] { typeof(GenericStruct<string>) }; yield return new object[] { typeof(IGenericInterface<>) }; yield return new object[] { typeof(IGenericInterface<string>) }; yield return new object[] { typeof(GenericClass<>).GetTypeInfo().GenericTypeParameters[0] }; AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type"); yield return new object[] { typeBuilder }; yield return new object[] { typeof(NonComVisibleClass) }; yield return new object[] { typeof(NonComVisibleStruct) }; yield return new object[] { typeof(INonComVisibleInterface) }; AssemblyBuilder collectibleAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Assembly"), AssemblyBuilderAccess.RunAndCollect); ModuleBuilder collectibleModuleBuilder = collectibleAssemblyBuilder.DefineDynamicModule("Module"); TypeBuilder collectibleTypeBuilder = collectibleModuleBuilder.DefineType("Type", TypeAttributes.Interface | TypeAttributes.Abstract); Type collectibleType = collectibleTypeBuilder.CreateType(); yield return new object[] { collectibleType }; } [Theory] [MemberData(nameof(GetComInterfaceForObject_InvalidType_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_InvalidType_ThrowsArgumentException(Type type) { AssertExtensions.Throws<ArgumentException>("t", () => Marshal.GetComInterfaceForObject(new object(), type)); AssertExtensions.Throws<ArgumentException>("t", () => Marshal.GetComInterfaceForObject(new object(), type, CustomQueryInterfaceMode.Allow)); } public static IEnumerable<object[]> GetComInterfaceForObject_InvalidObject_TestData() { yield return new object[] { new GenericClass<string>() }; yield return new object[] { new GenericStruct<string>() }; } [Theory] [MemberData(nameof(GetComInterfaceForObject_InvalidObject_TestData))] [PlatformSpecific(TestPlatforms.Windows)] public void GetComInterfaceForObject_InvalidObject_ThrowsArgumentException(object o) { AssertExtensions.Throws<ArgumentException>("o", () => Marshal.GetComInterfaceForObject(o, typeof(INonGenericInterface))); AssertExtensions.Throws<ArgumentException>("o", () => Marshal.GetComInterfaceForObject(o, typeof(INonGenericInterface), CustomQueryInterfaceMode.Allow)); AssertExtensions.Throws<ArgumentException>("o", () => Marshal.GetComInterfaceForObject<object, INonGenericInterface>(o)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetTypedObjectForIUnknown_UncastableType_ThrowsInvalidCastException() { Assert.Throws<InvalidCastException>(() => Marshal.GetComInterfaceForObject(new object(), typeof(INonGenericInterface))); Assert.Throws<InvalidCastException>(() => Marshal.GetComInterfaceForObject(new object(), typeof(INonGenericInterface), CustomQueryInterfaceMode.Allow)); Assert.Throws<InvalidCastException>(() => Marshal.GetComInterfaceForObject<object, INonGenericInterface>(new object())); } } }
// // Copyright (c) 2004-2020 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. // namespace NLog.Config { using System; using System.Collections.Generic; using System.Reflection; using NLog.Common; using NLog.Internal; using NLog.LayoutRenderers; /// <summary> /// Factory for class-based items. /// </summary> /// <typeparam name="TBaseType">The base type of each item.</typeparam> /// <typeparam name="TAttributeType">The type of the attribute used to annotate items.</typeparam> internal class Factory<TBaseType, TAttributeType> : INamedItemFactory<TBaseType, Type>, IFactory where TBaseType : class where TAttributeType : NameBaseAttribute { private readonly Dictionary<string, GetTypeDelegate> _items = new Dictionary<string, GetTypeDelegate>(StringComparer.OrdinalIgnoreCase); private readonly ConfigurationItemFactory _parentFactory; internal Factory(ConfigurationItemFactory parentFactory) { _parentFactory = parentFactory; } private delegate Type GetTypeDelegate(); /// <summary> /// Scans the assembly. /// </summary> /// <param name="types">The types to scan.</param> /// <param name="prefix">The prefix.</param> public void ScanTypes(Type[] types, string prefix) { foreach (Type t in types) { try { RegisterType(t, prefix); } catch (Exception exception) { InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName); if (exception.MustBeRethrown()) { throw; } } } } /// <summary> /// Registers the type. /// </summary> /// <param name="type">The type to register.</param> /// <param name="itemNamePrefix">The item name prefix.</param> public void RegisterType(Type type, string itemNamePrefix) { if (typeof(TBaseType).IsAssignableFrom(type)) { IEnumerable<TAttributeType> attributes = type.GetCustomAttributes<TAttributeType>(false); if (attributes != null) { foreach (TAttributeType attr in attributes) { RegisterDefinition(itemNamePrefix + attr.Name, type); } } } } /// <summary> /// Registers the item based on a type name. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="typeName">Name of the type.</param> public void RegisterNamedType(string itemName, string typeName) { _items[itemName] = () => Type.GetType(typeName, false); } /// <summary> /// Clears the contents of the factory. /// </summary> public void Clear() { _items.Clear(); } /// <summary> /// Registers a single type definition. /// </summary> /// <param name="itemName">The item name.</param> /// <param name="itemDefinition">The type of the item.</param> public void RegisterDefinition(string itemName, Type itemDefinition) { _items[itemName] = () => itemDefinition; } /// <summary> /// Tries to get registered item definition. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">Reference to a variable which will store the item definition.</param> /// <returns>Item definition.</returns> public bool TryGetDefinition(string itemName, out Type result) { GetTypeDelegate getTypeDelegate; if (!_items.TryGetValue(itemName, out getTypeDelegate)) { result = null; return false; } try { result = getTypeDelegate(); return result != null; } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } // delegate invocation failed - type is not available result = null; return false; } } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public virtual bool TryCreateInstance(string itemName, out TBaseType result) { Type type; if (!TryGetDefinition(itemName, out type)) { result = null; return false; } result = (TBaseType)_parentFactory.CreateInstance(type); return true; } /// <summary> /// Creates an item instance. /// </summary> /// <param name="itemName">The name of the item.</param> /// <returns>Created item.</returns> public virtual TBaseType CreateInstance(string itemName) { if (TryCreateInstance(itemName, out TBaseType result)) { return result; } var message = typeof(TBaseType).Name + " cannot be found: '" + itemName + "'"; if (itemName != null && (itemName.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) || itemName.StartsWith("iis", StringComparison.OrdinalIgnoreCase))) { //common mistake and probably missing NLog.Web message += ". Is NLog.Web not included?"; } throw new ArgumentException(message); } } /// <summary> /// Factory specialized for <see cref="LayoutRenderer"/>s. /// </summary> class LayoutRendererFactory : Factory<LayoutRenderer, LayoutRendererAttribute> { public LayoutRendererFactory(ConfigurationItemFactory parentFactory) : base(parentFactory) { } private Dictionary<string, FuncLayoutRenderer> _funcRenderers; /// <summary> /// Clear all func layouts /// </summary> public void ClearFuncLayouts() { _funcRenderers = null; } /// <summary> /// Register a layout renderer with a callback function. /// </summary> /// <param name="name">Name of the layoutrenderer, without ${}.</param> /// <param name="renderer">the renderer that renders the value.</param> public void RegisterFuncLayout(string name, FuncLayoutRenderer renderer) { _funcRenderers = _funcRenderers ?? new Dictionary<string, FuncLayoutRenderer>(StringComparer.OrdinalIgnoreCase); //overwrite current if there is one _funcRenderers[name] = renderer; } /// <summary> /// Tries to create an item instance. /// </summary> /// <param name="itemName">Name of the item.</param> /// <param name="result">The result.</param> /// <returns>True if instance was created successfully, false otherwise.</returns> public override bool TryCreateInstance(string itemName, out LayoutRenderer result) { //first try func renderers, as they should have the possibility to overwrite a current one. if (_funcRenderers != null) { FuncLayoutRenderer funcResult; var succesAsFunc = _funcRenderers.TryGetValue(itemName, out funcResult); if (succesAsFunc) { result = funcResult; return true; } } var success = base.TryCreateInstance(itemName, out result); return success; } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using Vevo.DataAccessLib; using Vevo.DataAccessLib.Cart; using Vevo.Domain; using Vevo.Domain.DataInterfaces; using Vevo.Domain.Discounts; using Vevo.Shared.Utilities; using Vevo.WebUI.Ajax; using Vevo.Base.Domain; public partial class AdminAdvanced_MainControls_QuantityDiscountList : AdminAdvancedBaseListControl { private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContext.DiscountGroupRepository.GetTableSchema(); uxSearchFilter.SetUpSchema( list ); } private string CurrentDiscountType { get { if (ViewState["CurrentDiscountType"] == null) return "Percentage"; else return ViewState["CurrentDiscountType"].ToString(); } set { ViewState["CurrentDiscountType"] = value; } } private string CurrentProductOptionDiscount { get { if (ViewState["CurrentProductOptionDiscount"] == null) return "False"; else return ViewState["CurrentProductOptionDiscount"].ToString(); } set { ViewState["CurrentProductOptionDiscount"] = value; } } private void DeleteVisible( bool value ) { uxDeleteButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDeleteConfirmButton.TargetControlID = "uxDeleteButton"; uxConfirmModalPopup.TargetControlID = "uxDeleteButton"; } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void SetCurrentDiscountType() { if (uxDiscountGroupGrid.EditIndex != -1) { Label discount = (Label) (uxDiscountGroupGrid.Rows[uxDiscountGroupGrid.EditIndex].Cells[3].FindControl( "uxDiscountTypeLabel" )); CurrentDiscountType = discount.Text; Label productOptionDiscount = (Label) (uxDiscountGroupGrid.Rows[uxDiscountGroupGrid.EditIndex].Cells[4].FindControl( "uxProductOptionDiscountLabel" )); CurrentProductOptionDiscount = productOptionDiscount.Text; } } private void PopulateControls() { if (!MainContext.IsPostBack) { RefreshGrid(); } } private void ApplyPermissions() { if (!IsAdminModifiable()) { uxAddButton.Visible = false; DeleteVisible( false ); } else { if (uxDiscountGroupGrid.Rows.Count > 0) DeleteVisible( true ); else DeleteVisible( false ); } } private bool IsContainingOnlyEmptyRow() { if (uxDiscountGroupGrid.Rows.Count == 1 && ConvertUtilities.ToInt32( uxDiscountGroupGrid.DataKeys[0]["DiscountGroupID"] ) == -1) return true; else return false; } private void SetFooterRowFocus() { Control textBox = uxDiscountGroupGrid.FooterRow.FindControl( "uxGroupNameText" ); AjaxUtilities.GetScriptManager( textBox ).SetFocus( textBox ); } private void SetUpGridSupportControls() { if (!MainContext.IsPostBack) { uxPagingControl.ItemsPerPages = AdminConfig.OptionItemsPerPage; SetUpSearchFilter(); } RegisterGridView( uxDiscountGroupGrid, "DiscountGroupID" ); RegisterSearchFilter( uxSearchFilter ); RegisterPagingControl( uxPagingControl ); uxSearchFilter.BubbleEvent += new EventHandler( uxSearchFilter_BubbleEvent ); uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent ); } private void CreateDummyRow( IList<DiscountGroup> list ) { DiscountGroup discountGroup = new DiscountGroup(); discountGroup.DiscountGroupID = "-1"; discountGroup.GroupName = ""; list.Add( discountGroup ); } private void ClearData( GridViewRow row ) { ((TextBox) row.FindControl( "uxGroupNameText" )).Text = ""; } private DiscountGroup.DiscountTypeEnum GetDiscountType( string discountType ) { return (DiscountGroup.DiscountTypeEnum) Enum.Parse( typeof( DiscountGroup.DiscountTypeEnum ), discountType ); } private DiscountGroup AddUnlimitedDiscountRule( DiscountGroup discountGroup ) { DiscountRule discountRule = new DiscountRule(); discountRule.ToItems = SystemConst.UnlimitedNumber; discountRule.Percentage = 0; discountRule.Amount = 0; discountGroup.DiscountRules.Add( discountRule ); return discountGroup; } private DiscountGroup GetDiscountGroupFromGrid( DiscountGroup discountGroup, GridViewRow row ) { string uxGroupNameText = ((TextBox) row.FindControl( "uxGroupNameText" )).Text; string uxDiscountType = ((DropDownList) row.FindControl( "uxDiscountTypeDrop" )).SelectedValue; string uxProductOptionDiscount = ((DropDownList) row.FindControl( "uxProductOptionDiscount" )).SelectedValue; discountGroup.GroupName = uxGroupNameText; discountGroup.DiscountType = GetDiscountType( uxDiscountType ); discountGroup.ProductOptionDiscount = ConvertUtilities.ToBoolean( uxProductOptionDiscount ); return discountGroup; } protected void uxDiscountTypeDrop_PreRender( object sender, EventArgs e ) { DropDownList typePrice = (DropDownList) sender; if (CurrentDiscountType == "Percentage") typePrice.SelectedValue = "Percentage"; else typePrice.SelectedValue = "Price"; } protected void uxProductOptionDiscountLabel_PreRender( object sender, EventArgs e ) { DropDownList productOption = (DropDownList) sender; if (CurrentProductOptionDiscount == "Yes") productOption.SelectedValue = "True"; else productOption.SelectedValue = "False"; } protected void Page_Load( object sender, EventArgs e ) { SetUpGridSupportControls(); if (!MainContext.IsPostBack) { uxDiscountGroupGrid.ShowFooter = false; } } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); ApplyPermissions(); //SetCurrentDiscountType(); } protected void uxEditLinkButton_PreRender( object sender, EventArgs e ) { if (!IsAdminModifiable()) { LinkButton linkButton = (LinkButton) sender; linkButton.Visible = false; } } protected void uxDiscountGroupGrid_DataBound( object sender, EventArgs e ) { if (IsContainingOnlyEmptyRow()) { uxDiscountGroupGrid.Rows[0].Visible = false; } } protected void uxAddButton_Click( object sender, EventArgs e ) { uxDiscountGroupGrid.EditIndex = -1; uxDiscountGroupGrid.ShowFooter = true; RefreshGrid(); uxAddButton.Visible = false; SetFooterRowFocus(); } protected void uxDiscountGroupGrid_RowCommand( object sender, GridViewCommandEventArgs e ) { if (e.CommandName == "Add") { GridViewRow rowAdd = uxDiscountGroupGrid.FooterRow; DiscountGroup discountGroup = new DiscountGroup(); discountGroup = GetDiscountGroupFromGrid( discountGroup, rowAdd ); if (String.IsNullOrEmpty( discountGroup.GroupName )) { uxMessage.DisplayMessage( Resources.DiscountGroupMessage.ItemAddErrorEmpty ); return; } discountGroup = AddUnlimitedDiscountRule( discountGroup ); DataAccessContext.DiscountGroupRepository.Save( discountGroup ); ClearData( rowAdd ); RefreshGrid(); uxMessage.DisplayMessage( Resources.DiscountGroupMessage.ItemAddSuccess ); uxStatusHidden.Value = "Added"; } } protected void uxDeleteButton_Click( object sender, EventArgs e ) { try { int totalDel = 0; bool containsProduct = false; foreach (GridViewRow row in uxDiscountGroupGrid.Rows) { CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" ); if (deleteCheck != null && deleteCheck.Checked) { totalDel += 1; string discountGroupID = uxDiscountGroupGrid.DataKeys[row.RowIndex]["DiscountGroupID"].ToString(); if (!DataAccessContext.CategoryRepository.HasCategoryInDiscountGroup( discountGroupID ) && !DataAccessContext.ProductRepository.HasProductInDiscountGroup( discountGroupID )) { DataAccessContext.DiscountGroupRepository.Delete( discountGroupID ); } else { containsProduct = true; } } } uxDiscountGroupGrid.EditIndex = -1; if (totalDel != 0) { if (!containsProduct) { uxMessage.DisplayMessage( Resources.DiscountGroupMessage.ItemDeleteSuccess ); uxStatusHidden.Value = "Deleted"; } else { uxMessage.DisplayError( Resources.DiscountGroupMessage.DeleteProductReferenceError ); } } } catch (Exception ex) { uxMessage.DisplayException( ex ); } RefreshGrid(); if (uxDiscountGroupGrid.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages) { uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages; RefreshGrid(); } } protected void uxDiscountGroupGrid_RowUpdating( object sender, GridViewUpdateEventArgs e ) { try { GridViewRow rowGrid = uxDiscountGroupGrid.Rows[e.RowIndex]; string discountGroupID = uxDiscountGroupGrid.DataKeys[e.RowIndex]["DiscountGroupID"].ToString(); DiscountGroup discountGroup = DataAccessContext.DiscountGroupRepository.GetOne( discountGroupID ); discountGroup = GetDiscountGroupFromGrid( discountGroup, rowGrid ); if (String.IsNullOrEmpty( discountGroup.GroupName )) throw new VevoException( Resources.DiscountGroupMessage.ItemUpdateErrorEmpty ); DataAccessContext.DiscountGroupRepository.Save( discountGroup ); uxDiscountGroupGrid.EditIndex = -1; RefreshGrid(); uxMessage.DisplayMessage( Resources.DiscountGroupMessage.ItemUpdateSuccess ); uxStatusHidden.Value = "Updated"; } finally { e.Cancel = true; } } protected override void RefreshGrid() { int totalItems = 0; IList<DiscountGroup> discountGroupList = DataAccessContext.DiscountGroupRepository.SearchDiscountGroup( GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, uxPagingControl.StartIndex, uxPagingControl.EndIndex, out totalItems ); if (discountGroupList == null || discountGroupList.Count == 0) { discountGroupList = new List<DiscountGroup>(); CreateDummyRow( discountGroupList ); } uxDiscountGroupGrid.DataSource = discountGroupList; uxDiscountGroupGrid.DataBind(); uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); } protected void uxDiscountGroupGrid_RowEditing( object sender, GridViewEditEventArgs e ) { uxDiscountGroupGrid.EditIndex = e.NewEditIndex; SetCurrentDiscountType(); RefreshGrid(); } protected void uxDiscountGroupGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e ) { uxDiscountGroupGrid.EditIndex = -1; RefreshGrid(); } }
using System; using System.IO; using System.Text.RegularExpressions; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Collections.Generic; namespace RoboSharp { internal static class ExtensionMethods { /// <summary> Encase the LogPath in quotes if needed </summary> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static string WrapPath(this string logPath) => (!logPath.StartsWith("\"") && logPath.Contains(" ")) ? $"\"{logPath}\"" : logPath; /// <remarks> Extension method provided by RoboSharp package </remarks> /// <inheritdoc cref="System.String.IsNullOrWhiteSpace(string)"/> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static bool IsNullOrWhiteSpace(this string value) => string.IsNullOrWhiteSpace(value); [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static long TryConvertLong(this string val) { try { return Convert.ToInt64(val); } catch { return 0; } } [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static int TryConvertInt(this string val) { try { return Convert.ToInt32(val); } catch { return 0; } } [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] public static string CleanOptionInput(this string option) { // Get rid of forward slashes option = option.Replace("/", ""); // Get rid of padding option = option.Trim(); return option; } public static string CleanDirectoryPath(this string path) { // Get rid of single and double quotes path = path?.Replace("\"", ""); path = path?.Replace("\'", ""); //Validate against null / empty strings. if (string.IsNullOrWhiteSpace(path)) return string.Empty; // Get rid of padding path = path.Trim(); // Get rid of trailing Directory Seperator Chars // Length greater than 3 because E:\ is the shortest valid path while (path.Length > 3 && path.EndsWithDirectorySeperator()) { path = path.Substring(0, path.Length - 1); } //Sanitize invalid paths -- Convert E: to E:\ if (path.Length <= 2) { if (DriveRootRegex.IsMatch(path)) return path.ToUpper() + '\\'; else return path; } // Fix UNC paths that are the root directory of a UNC drive if (Uri.TryCreate(path, UriKind.Absolute, out Uri URI) && URI.IsUnc) { if (path.EndsWith("$")) { path += '\\'; } } return path; } private static readonly Regex DriveRootRegex = new Regex("[A-Za-z]:", RegexOptions.Compiled); /// <summary> /// Check if the string ends with a directory seperator character /// </summary> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] public static bool EndsWithDirectorySeperator(this string path) => path.EndsWith(Path.DirectorySeparatorChar.ToString()) || path.EndsWith(Path.AltDirectorySeparatorChar.ToString()); /// <summary> /// Convert <paramref name="StrTwo"/> into a char[]. Perform a ForEach( Char in strTwo) loop, and append any characters in Str2 to the end of this string if they don't already exist within this string. /// </summary> /// <param name="StrOne"></param> /// <param name="StrTwo"></param> /// <returns></returns> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static string CombineCharArr(this string StrOne, string StrTwo) { if (String.IsNullOrWhiteSpace(StrTwo)) return StrOne; if (String.IsNullOrWhiteSpace(StrOne)) return StrTwo ?? StrOne; string ret = StrOne; char[] S2 = StrTwo.ToArray(); foreach (char c in S2) { if (!ret.Contains(c)) ret += c; } return ret; } /// <summary> /// Compare the current value to that of the supplied value, and take the greater of the two. /// </summary> /// <param name="i"></param> /// <param name="i2"></param> /// <returns></returns> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static int GetGreaterVal(this int i, int i2) => i >= i2 ? i : i2; /// <summary> /// Evaluate this string. If this string is null or empty, replace it with the supplied string. /// </summary> /// <param name="str1"></param> /// <param name="str2"></param> /// <returns></returns> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] [DebuggerHidden()] internal static string ReplaceIfEmpty(this string str1, string str2) => String.IsNullOrWhiteSpace(str1) ? str2 ?? String.Empty : str1; } } namespace System.Threading { /// <summary> /// Contains methods for CancelleableSleep and WaitUntil /// </summary> internal static class ThreadEx { /// <summary> /// Wait synchronously until this task has reached the specified <see cref="TaskStatus"/> /// </summary> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] public static void WaitUntil(this Task t, TaskStatus status) { while (t.Status < status) Thread.Sleep(100); } /// <summary> /// Wait asynchronously until this task has reached the specified <see cref="TaskStatus"/> <br/> /// Checks every 100ms /// </summary> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] public static async Task WaitUntilAsync(this Task t, TaskStatus status) { while (t.Status < status) await Task.Delay(100); } /// <summary> /// Wait synchronously until this task has reached the specified <see cref="TaskStatus"/><br/> /// Checks every <paramref name="interval"/> milliseconds /// </summary> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] public static async Task WaitUntilAsync(this Task t, TaskStatus status, int interval) { while (t.Status < status) await Task.Delay(interval); } /// <param name="timeSpan">TimeSpan to sleep the thread</param> /// <param name="token"><inheritdoc cref="CancellationToken"/></param> /// <inheritdoc cref="CancellableSleep(int, CancellationToken)"/> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] internal static Task<bool> CancellableSleep(TimeSpan timeSpan, CancellationToken token) { return CancellableSleep((int)timeSpan.TotalMilliseconds, token); } /// <inheritdoc cref="CancellableSleep(int, CancellationToken[])"/> /// <inheritdoc cref="CancellableSleep(int, CancellationToken)"/> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] internal static Task<bool> CancellableSleep(TimeSpan timeSpan, CancellationToken[] tokens) { return CancellableSleep((int)timeSpan.TotalMilliseconds, tokens); } /// <summary> /// Use await Task.Delay to sleep the thread. <br/> /// </summary> /// <returns>True if timer has expired (full duration slep), otherwise false.</returns> /// <param name="millisecondsTimeout">Number of milliseconds to wait"/></param> /// <param name="token"><inheritdoc cref="CancellationToken"/></param> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] internal static Task<bool> CancellableSleep(int millisecondsTimeout, CancellationToken token) { return Task.Delay(millisecondsTimeout, token).ContinueWith(t => t.Exception == default); } /// <summary> /// Use await Task.Delay to sleep the thread. <br/> /// Supplied tokens are used to create a LinkedToken that can cancel the sleep at any point. /// </summary> /// <returns>True if slept full duration, otherwise false.</returns> /// <param name="millisecondsTimeout">Number of milliseconds to wait"/></param> /// <param name="tokens">Use <see cref="CancellationTokenSource.CreateLinkedTokenSource(CancellationToken[])"/> to create the token used to cancel the delay</param> /// <inheritdoc cref="CancellableSleep(int, CancellationToken)"/> [MethodImpl(methodImplOptions: MethodImplOptions.AggressiveInlining)] internal static Task<bool> CancellableSleep(int millisecondsTimeout, CancellationToken[] tokens) { var token = CancellationTokenSource.CreateLinkedTokenSource(tokens).Token; return Task.Delay(millisecondsTimeout, token).ContinueWith(t => t.Exception == default); } } }
//--------------------------------------------------------------------- // <copyright file="Utils.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- using System.Collections.Generic; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Reflection; namespace System.Data.EntityModel.Emitters { /// <summary> /// Summary description for Utils /// </summary> internal static class Utils { #region Static Fields public const string WebFrameworkNamespace = "System.Data.Services.Client"; public const string WebFrameworkCommonNamespace = "System.Data.Services.Common"; public const string AdoFrameworkNamespace = "System.Data.Objects"; public const string AdoFrameworkDataClassesNamespace = "System.Data.Objects.DataClasses"; public const string AdoFrameworkMetadataEdmNamespace = "System.Data.Metadata.Edm"; public const string AdoEntityClientNamespace = "System.Data.EntityClient"; public const string SetValidValueMethodName = "SetValidValue"; public const string ReportPropertyChangingMethodName = "ReportPropertyChanging"; public const string ReportPropertyChangedMethodName = "ReportPropertyChanged"; public const string GetValidValueMethodName = "GetValidValue"; public const string VerifyComplexObjectIsNotNullName = "VerifyComplexObjectIsNotNull"; // this is the list of keywords we check against for names. // If a name matches this keyword we prefix it, this is only used when creating parameter names from property, etc. names(see FixKeyword) private static string[] _keywords = new string[] { "class", "event", }; // to guarantee uniqueness these must all be unique, begin with and end with an underscore and not contain internal underscores private static string[] _privateMemberPrefixes = new string[(int)PrivateMemberPrefixId.Count] { "_", "_Initialize_", "PropertyInfo", "_pi", }; // suffix that is added to field names to create a boolean field used to indicate whether or // not a complex property has been explicitly initialized private static string _complexPropertyInitializedSuffix = "Initialized"; private static List<KeyValuePair<string, Type>> _typeReservedNames = InitializeTypeReservedNames(); /// <summary> /// Initialize some statics that cannot be initialized in member declaration... /// </summary> static List<KeyValuePair<string, Type>> InitializeTypeReservedNames() { Dictionary<string, Type> typeReservedNames = new Dictionary<string, Type>(StringComparer.Ordinal); const BindingFlags bindingFlags = BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; foreach (MemberInfo member in typeof(object).GetMembers(bindingFlags)) { if (ShouldReserveName(member)) { if (!typeReservedNames.ContainsKey(member.Name)) { typeReservedNames.Add(member.Name, null); } } } List<KeyValuePair<string, Type>> pairs = new List<KeyValuePair<string, Type>>(); foreach (KeyValuePair<string, Type> pair in typeReservedNames) { pairs.Add(pair); } return pairs; } private static bool ShouldReserveName(MemberInfo member) { if (member is EventInfo) { return ShouldReserveName((EventInfo)member); } else if (member is FieldInfo) { return ShouldReserveName((FieldInfo)member); } else if (member is MethodBase) { return ShouldReserveName((MethodBase)member); } else if (member is PropertyInfo) { return ShouldReserveName((PropertyInfo)member); } else { Debug.Assert(member is Type, "Did you add a new type of member?"); return ShouldReserveName((Type)member); } } private static bool ShouldReserveName(EventInfo member) { bool hasNonPrivate = false; MethodInfo miAdd = member.GetAddMethod(); if (miAdd != null) { hasNonPrivate |= ShouldReserveName(miAdd, false); } MethodInfo miRemove = member.GetRemoveMethod(); if (miRemove != null) { hasNonPrivate |= ShouldReserveName(miRemove, false); } return hasNonPrivate; } private static bool ShouldReserveName(PropertyInfo member) { bool hasNonPrivate = false; MethodInfo miSet = member.GetSetMethod(); if (miSet != null) { hasNonPrivate |= ShouldReserveName(miSet, false); } MethodInfo miGet = member.GetGetMethod(); if (miGet != null) { hasNonPrivate |= ShouldReserveName(miGet, false); } return hasNonPrivate; } private static bool ShouldReserveName(FieldInfo member) { return !member.IsPrivate && !member.IsAssembly && !member.IsSpecialName; } private static bool ShouldReserveName(MethodBase member, bool checkForSpecial) { return !member.IsPrivate && !member.IsAssembly && (!checkForSpecial || !member.IsSpecialName); } private static bool ShouldReserveName(MethodBase member) { return ShouldReserveName(member, true); } private static bool ShouldReserveName(Type member) { // we don't want to keep types return false; } #endregion #region Public Methods /// <summary> /// /// </summary> /// <param name="text"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308", Justification = "required for this feature")] public static string CamelCase(string text) { if (string.IsNullOrEmpty(text)) return text; if (text.Length == 1) return text[0].ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant(); return text[0].ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant() + text.Substring(1); } /// <summary> /// /// </summary> /// <param name="text"></param> /// <returns></returns> public static string PascalCase(string text) { if (string.IsNullOrEmpty(text)) return text; if (text.Length == 1) return text[0].ToString(System.Globalization.CultureInfo.InvariantCulture).ToUpperInvariant(); return text[0].ToString(System.Globalization.CultureInfo.InvariantCulture).ToUpperInvariant() + text.Substring(1); } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="prefix"></param> /// <returns></returns> private static string FixKeyword(string name, string prefix) { foreach (string keyword in _keywords) { if (name == keyword) { return prefix + PascalCase(name); } } return name; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="prefix"></param> /// <returns></returns> public static string FixParameterName(string name, string prefix) { return CamelCase(FixKeyword(name, prefix)); } /// <summary> /// /// </summary> /// <param name="propName"></param> /// <returns></returns> public static string FieldNameFromPropName(string propName) { return PrivateMemberPrefix(PrivateMemberPrefixId.Field) + propName; } /// <summary> /// Generate the name of a field that is used to indicate whether a complex property has been explicitly initialized /// </summary> /// <param name="propName">Name of the property associated that with this field</param> /// <returns>Generated field name</returns> public static string ComplexPropertyInitializedNameFromPropName(string propName) { return FieldNameFromPropName(propName) + _complexPropertyInitializedSuffix; } /// <summary> /// get the prefix ussed for a private member /// </summary> /// <param name="id"></param> /// <returns></returns> public static string PrivateMemberPrefix(PrivateMemberPrefixId id) { return _privateMemberPrefixes[(int)id]; } /// <summary> /// /// </summary> /// <param name="element"></param> /// <param name="modelType"></param> /// <returns></returns> public static bool TryGetPrimitiveTypeKind(EdmType type, out PrimitiveTypeKind modelType) { if (!Helper.IsPrimitiveType(type)) { // set it to something bogus because I have to modelType = PrimitiveTypeKind.Binary; return false; } modelType = ((PrimitiveType)type).PrimitiveTypeKind; return true; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> public static string[] SplitName(string name) { Debug.Assert(!string.IsNullOrEmpty(name), "name parameter is null or empty"); if (name.Length > 0 && name[0] == '.') return name.Substring(1).Split('.'); return name.Split('.'); } public static string GetFullyQualifiedCodeGenerationAttributeName(string attribute) { return XmlConstants.CodeGenerationSchemaNamespace + ":" + attribute; } /// <summary> /// check if a name is reserved for a type /// </summary> /// <param name="type">the object representing the schema type being defined</param> /// <param name="name">the member name</param> /// <returns>true if the name is reserved by the type</returns> public static bool DoesTypeReserveMemberName(StructuralType type, string name, StringComparison comparison) { Type reservingType = null; if (!TryGetReservedName(name, comparison, out reservingType)) { return false; } // if reserving types is null it means the name is reserved for all types. if (reservingType == null) { return true; } return (reservingType == type.GetType()); } public static bool TryGetReservedName(string name, StringComparison comparison, out Type applyToSpecificType) { applyToSpecificType = null; foreach (KeyValuePair<string, Type> pair in _typeReservedNames) { if (pair.Key.Equals(name, comparison)) { applyToSpecificType = pair.Value; return true; } } return false; } public static string SetSpecialCaseForFxCopOnPropertyName(string propertyName) { // FxCop consider 'iD' as violation, we will change any property that is 'id'(case insensitive) to 'ID' if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, "id")) { return "ID"; } return propertyName; } #endregion } }
using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Collections.Generic; namespace MCEBuddy.ProgressODoom { /// <summary></summary> [ToolboxBitmapAttribute(typeof(ProgressODoom.FruityLoopsBackgroundPainter), "Icons.FruityLoopsBackgroundPainter.ico")] public class FruityLoopsBackgroundPainter : Component, IProgressBackgroundPainter, IDisposable { private IGlossPainter gloss; private FruityLoopsProgressPainter.FruityLoopsProgressType type; private Image img; private Color OffLit = Color.FromArgb(49, 69, 74); private Pen pOffLit; // = new Pen(new SolidBrush(OffLit),1f); private Color OffLitTop = Color.FromArgb(66, 85, 90); private Pen pOffLitTop; // = new Pen(new SolidBrush(OffLitTop),1f); private Color OffLitBot = Color.FromArgb(24, 48, 49); private Pen pOffLitBot; // = new Pen(new SolidBrush(OffLitBot),1f); private Color OffMid = Color.FromArgb(24, 48, 49); private Pen pOffMid; // = new Pen(new SolidBrush(OffMid),1f); private Color OffMidTop = Color.FromArgb(24, 48, 49); private Pen pOffMidTop; // = new Pen(new SolidBrush(OffMidTop),1f); private Color OffMidBot = Color.FromArgb(8, 28, 24); private Pen pOffMidBot; // = new Pen(new SolidBrush(OffMidBot),1f); private Color OffDrk = Color.FromArgb(0, 24, 24); private Pen pOffDrk; // = new Pen(new SolidBrush(OffDrk),1f); private Color OffDrkTop = Color.FromArgb(8, 28, 24); private Pen pOffDrkTop; // = new Pen(new SolidBrush(OffDrkTop),1f); private Color OffDrkBot = Color.FromArgb(0, 16, 16); private Pen pOffDrkBot; // = new Pen(new SolidBrush(OffDrkBot),1f); private EventHandler onPropertiesChanged; /// <summary></summary> public event EventHandler PropertiesChanged { add { if (onPropertiesChanged != null) { foreach (Delegate d in onPropertiesChanged.GetInvocationList()) { if (object.ReferenceEquals(d, value)) { return; } } } onPropertiesChanged = (EventHandler)Delegate.Combine(onPropertiesChanged, value); } remove { onPropertiesChanged = (EventHandler)Delegate.Remove(onPropertiesChanged, value); } } private void FireChange() { if (onPropertiesChanged != null) { onPropertiesChanged(this, EventArgs.Empty); } } /// <summary></summary> /// <param name="sender"></param> /// <param name="e"></param> protected virtual void component_PropertiesChanged(object sender, EventArgs e) { FireChange(); } /// <summary></summary> [Category("Painters"), Description("Gets or sets the chain of gloss painters"), Browsable(true)] public IGlossPainter GlossPainter { get { return this.gloss; } set { this.gloss = value; if (this.gloss != null) { this.gloss.PropertiesChanged += new EventHandler(component_PropertiesChanged); } FireChange(); } } /// <summary></summary> [Category("Appearance"), Description("Gets or sets the type of FruityLoops progress style"), Browsable(true)] public FruityLoopsProgressPainter.FruityLoopsProgressType FruityType { get { return type; } set { type = value; if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.DoubleLayer) { OffLit = Color.FromArgb(49, 69, 74); pOffLit = new Pen(new SolidBrush(OffLit), 1f); OffLitTop = Color.FromArgb(57, 77, 82); pOffLitTop = new Pen(new SolidBrush(OffLitTop), 1f); OffLitBot = Color.FromArgb(24, 48, 49); pOffLitBot = new Pen(new SolidBrush(OffLitBot), 1f); OffDrk = Color.FromArgb(24, 48, 49); pOffDrk = new Pen(new SolidBrush(OffDrk), 1f); OffDrkTop = Color.FromArgb(16, 40, 41); pOffDrkTop = new Pen(new SolidBrush(OffDrkTop), 1f); OffDrkBot = Color.FromArgb(8, 18, 24); pOffDrkBot = new Pen(new SolidBrush(OffDrkBot), 1f); } else if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.TripleLayer) { OffLit = Color.FromArgb(49, 69, 74); pOffLit = new Pen(new SolidBrush(OffLit), 1f); OffLitTop = Color.FromArgb(66, 85, 90); pOffLitTop = new Pen(new SolidBrush(OffLitTop), 1f); OffLitBot = Color.FromArgb(24, 48, 49); pOffLitBot = new Pen(new SolidBrush(OffLitBot), 1f); OffMid = Color.FromArgb(24, 48, 49); pOffMid = new Pen(new SolidBrush(OffMid), 1f); OffMidTop = Color.FromArgb(24, 48, 49); pOffMidTop = new Pen(new SolidBrush(OffMidTop), 1f); OffMidBot = Color.FromArgb(8, 28, 24); pOffMidBot = new Pen(new SolidBrush(OffMidBot), 1f); OffDrk = Color.FromArgb(0, 24, 24); pOffDrk = new Pen(new SolidBrush(OffDrk), 1f); OffDrkTop = Color.FromArgb(8, 28, 24); pOffDrkTop = new Pen(new SolidBrush(OffDrkTop), 1f); OffDrkBot = Color.FromArgb(0, 16, 16); pOffDrkBot = new Pen(new SolidBrush(OffDrkBot), 1f); } FireChange(); } } /// <summary></summary> /// <param name="box"></param> /// <param name="g"></param> public void PaintBackground(Rectangle box, Graphics g) { if (img == null) { if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.DoubleLayer) { PaintDouble(box, g); } else if (type == FruityLoopsProgressPainter.FruityLoopsProgressType.TripleLayer) { PaintTriple(box, g); } } g.DrawImageUnscaled(img, 0, 0); if (gloss != null) { gloss.PaintGloss(box, g); } } /// <summary></summary> /// <param name="r"></param> /// <param name="g"></param> protected virtual void PaintDouble(Rectangle r, Graphics g) { bool lite = true; img = new Bitmap(r.Width + 1, r.Height + 1); Graphics gi = Graphics.FromImage(img); for (int i = 1; i < r.Width + 1; i++) { if (lite) { gi.DrawLine(pOffLitTop, i, r.Y, i, r.Y + 1); gi.DrawLine(pOffLitBot, i, r.Height, i, r.Height - 1); gi.DrawLine(pOffLit, i, r.Y + 1, i, r.Height - 1); } else { gi.DrawLine(pOffDrkTop, i, r.Y, i, r.Y + 1); gi.DrawLine(pOffDrkBot, i, r.Height, i, r.Height - 1); gi.DrawLine(pOffDrk, i, r.Y + 1, i, r.Height - 1); } lite = !lite; } gi.Dispose(); } /// <summary></summary> /// <param name="r"></param> /// <param name="g"></param> protected virtual void PaintTriple(Rectangle r, Graphics g) { int lite = 1; img = new Bitmap(r.Width + 1, r.Height + 1); Graphics gi = Graphics.FromImage(img); for (int i = 1; i < r.Width + 1; i++) { if (lite == 2) { gi.DrawLine(pOffLitTop, i, r.Y, i, r.Y + 1); gi.DrawLine(pOffLitBot, i, r.Height, i, r.Height - 1); gi.DrawLine(pOffLit, i, r.Y + 1, i, r.Height - 1); lite = 0; } else if (lite == 1) { gi.DrawLine(pOffMidTop, i, r.Y, i, r.Y + 1); gi.DrawLine(pOffMidBot, i, r.Height, i, r.Height - 1); gi.DrawLine(pOffMid, i, r.Y + 1, i, r.Height - 1); lite = 2; } else if (lite == 0) { gi.DrawLine(pOffDrkTop, i, r.Y, i, r.Y + 1); gi.DrawLine(pOffDrkBot, i, r.Height, i, r.Height - 1); gi.DrawLine(pOffDrk, i, r.Y + 1, i, r.Height - 1); lite = 1; } } gi.Dispose(); } /// <summary></summary> public void Resize(Rectangle box) { img = null; } /// <summary></summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); if (img != null) { img.Dispose(); } if (pOffLit != null) { pOffLit.Dispose(); } if (pOffLitTop != null) { pOffLitTop.Dispose(); } if (pOffLitBot != null) { pOffLitBot.Dispose(); } if (pOffMid != null) { pOffMid.Dispose(); } if (pOffMidTop != null) { pOffMidTop.Dispose(); } if (pOffMidBot != null) { pOffMidBot.Dispose(); } if (pOffDrk != null) { pOffDrk.Dispose(); } if (pOffDrkTop != null) { pOffDrkTop.Dispose(); } if (pOffDrkBot != null) { pOffDrkBot.Dispose(); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.HttpRequest.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web { sealed public partial class HttpRequest { #region Methods and constructors public byte[] BinaryRead(int count) { return default(byte[]); } public void GetChannelBindingToken(out IntPtr token, out int size) { token = default(IntPtr); size = default(int); } public HttpRequest(string filename, string url, string queryString) { } public void InsertEntityBody(byte[] buffer, int offset, int count) { } public void InsertEntityBody() { } public int[] MapImageCoordinates(string imageFieldName) { return default(int[]); } public string MapPath(string virtualPath, string baseVirtualDir, bool allowCrossAppMapping) { return default(string); } public string MapPath(string virtualPath) { return default(string); } public void SaveAs(string filename, bool includeHeaders) { } public void ValidateInput() { } #endregion #region Properties and indexers public string[] AcceptTypes { get { return default(string[]); } } public string AnonymousID { get { return default(string); } } public string ApplicationPath { get { return default(string); } } public string AppRelativeCurrentExecutionFilePath { get { return default(string); } } public HttpBrowserCapabilities Browser { get { return default(HttpBrowserCapabilities); } set { } } public Stream BufferlessInputStream { get { return default(Stream); } } public HttpClientCertificate ClientCertificate { get { return default(HttpClientCertificate); } } public Encoding ContentEncoding { get { return default(Encoding); } set { } } public int ContentLength { get { return default(int); } } public string ContentType { get { return default(string); } set { } } public HttpCookieCollection Cookies { get { return default(HttpCookieCollection); } } public string CurrentExecutionFilePath { get { return default(string); } } public string CurrentExecutionFilePathExtension { get { return default(string); } } public string FilePath { get { return default(string); } } public HttpFileCollection Files { get { return default(HttpFileCollection); } } public Stream Filter { get { return default(Stream); } set { } } public System.Collections.Specialized.NameValueCollection Form { get { return default(System.Collections.Specialized.NameValueCollection); } } public System.Collections.Specialized.NameValueCollection Headers { get { return default(System.Collections.Specialized.NameValueCollection); } } public System.Security.Authentication.ExtendedProtection.ChannelBinding HttpChannelBinding { get { return default(System.Security.Authentication.ExtendedProtection.ChannelBinding); } } public string HttpMethod { get { return default(string); } } public Stream InputStream { get { return default(Stream); } } public bool IsAuthenticated { get { return default(bool); } } public bool IsLocal { get { return default(bool); } } public bool IsSecureConnection { get { return default(bool); } } public string this [string key] { get { return default(string); } } public System.Security.Principal.WindowsIdentity LogonUserIdentity { get { return default(System.Security.Principal.WindowsIdentity); } } public System.Collections.Specialized.NameValueCollection Params { get { return default(System.Collections.Specialized.NameValueCollection); } } public string Path { get { return default(string); } } public string PathInfo { get { return default(string); } } public string PhysicalApplicationPath { get { return default(string); } } public string PhysicalPath { get { return default(string); } } public System.Collections.Specialized.NameValueCollection QueryString { get { return default(System.Collections.Specialized.NameValueCollection); } } public string RawUrl { get { return default(string); } internal set { } } public System.Web.Routing.RequestContext RequestContext { get { return default(System.Web.Routing.RequestContext); } internal set { } } public string RequestType { get { return default(string); } set { } } public System.Collections.Specialized.NameValueCollection ServerVariables { get { return default(System.Collections.Specialized.NameValueCollection); } } public int TotalBytes { get { return default(int); } } public Uri Url { get { return default(Uri); } } public Uri UrlReferrer { get { return default(Uri); } } public string UserAgent { get { return default(string); } } public string UserHostAddress { get { return default(string); } } public string UserHostName { get { return default(string); } } public string[] UserLanguages { get { return default(string[]); } } #endregion } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Microsoft.DotNet.Internal.ProjectModel.Files; namespace Microsoft.DotNet.Internal.ProjectModel { internal class CommonCompilerOptions { public IEnumerable<string> Defines { get; set; } public string LanguageVersion { get; set; } public string Platform { get; set; } public bool? AllowUnsafe { get; set; } public bool? WarningsAsErrors { get; set; } public bool? Optimize { get; set; } public string KeyFile { get; set; } public bool? DelaySign { get; set; } public bool? PublicSign { get; set; } public string DebugType { get; set; } public bool? EmitEntryPoint { get; set; } public bool? PreserveCompilationContext { get; set; } public bool? GenerateXmlDocumentation { get; set; } public IEnumerable<string> SuppressWarnings { get; set; } public IEnumerable<string> AdditionalArguments { get; set; } public string OutputName { get; set; } public string CompilerName { get; set; } public IncludeContext CompileInclude { get; set; } public IncludeContext EmbedInclude { get; set; } public IncludeContext CopyToOutputInclude { get; set; } public override bool Equals(object obj) { var other = obj as CommonCompilerOptions; return other != null && LanguageVersion == other.LanguageVersion && Platform == other.Platform && AllowUnsafe == other.AllowUnsafe && WarningsAsErrors == other.WarningsAsErrors && Optimize == other.Optimize && KeyFile == other.KeyFile && DelaySign == other.DelaySign && PublicSign == other.PublicSign && DebugType == other.DebugType && EmitEntryPoint == other.EmitEntryPoint && GenerateXmlDocumentation == other.GenerateXmlDocumentation && PreserveCompilationContext == other.PreserveCompilationContext && EnumerableEquals(Defines, other.Defines) && EnumerableEquals(SuppressWarnings, other.SuppressWarnings) && EnumerableEquals(AdditionalArguments, other.AdditionalArguments) && OutputName == other.OutputName && CompilerName == other.CompilerName && IsEqual(CompileInclude, other.CompileInclude) && IsEqual(EmbedInclude, other.EmbedInclude) && IsEqual(CopyToOutputInclude, other.CopyToOutputInclude); } private static bool IsEqual(IncludeContext first, IncludeContext second) { if (first == null || second == null) { return first == second; } return first.Equals(second); } private static bool EnumerableEquals(IEnumerable<string> left, IEnumerable<string> right) => Enumerable.SequenceEqual(left ?? EmptyArray<string>.Value, right ?? EmptyArray<string>.Value); public override int GetHashCode() { return base.GetHashCode(); } private static IEnumerable<string> Combine(IEnumerable<string> @new, IEnumerable<string> old) { if (@new != null) { old = old ?? EmptyArray<string>.Value; return old.Concat(@new).Distinct().ToArray(); } return old; } public static CommonCompilerOptions Combine(params CommonCompilerOptions[] options) { var result = new CommonCompilerOptions(); foreach (var option in options) { // Skip null options if (option == null) { continue; } // Defines, suppressions, and additional arguments are always combined result.Defines = Combine(option.Defines, result.Defines); result.SuppressWarnings = Combine(option.SuppressWarnings, result.SuppressWarnings); result.AdditionalArguments = Combine(option.AdditionalArguments, result.AdditionalArguments); if (option.LanguageVersion != null) { result.LanguageVersion = option.LanguageVersion; } if (option.Platform != null) { result.Platform = option.Platform; } if (option.AllowUnsafe != null) { result.AllowUnsafe = option.AllowUnsafe; } if (option.WarningsAsErrors != null) { result.WarningsAsErrors = option.WarningsAsErrors; } if (option.Optimize != null) { result.Optimize = option.Optimize; } if (option.KeyFile != null) { result.KeyFile = option.KeyFile; } if (option.DelaySign != null) { result.DelaySign = option.DelaySign; } if (option.PublicSign != null) { result.PublicSign = option.PublicSign; } if (option.DebugType != null) { result.DebugType = option.DebugType; } if (option.EmitEntryPoint != null) { result.EmitEntryPoint = option.EmitEntryPoint; } if (option.PreserveCompilationContext != null) { result.PreserveCompilationContext = option.PreserveCompilationContext; } if (option.GenerateXmlDocumentation != null) { result.GenerateXmlDocumentation = option.GenerateXmlDocumentation; } if (option.OutputName != null) { result.OutputName = option.OutputName; } if (option.CompileInclude != null) { result.CompileInclude = option.CompileInclude; } if (option.EmbedInclude != null) { result.EmbedInclude = option.EmbedInclude; } if (option.CopyToOutputInclude != null) { result.CopyToOutputInclude = option.CopyToOutputInclude; } // compilerName set in the root cannot be overriden. if (result.CompilerName == null) { result.CompilerName = option.CompilerName; } } return result; } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature { public partial class ChangeSignatureTests : AbstractChangeSignatureTests { #region Methods [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void $$Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInParameterList() { var markup = @" using System; class MyClass { public void Foo(int x, $$string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeAfterParameterList() { var markup = @" using System; class MyClass { public void Foo(int x, string y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeBeforeMethodDeclaration() { var markup = @" using System; class MyClass { $$public void Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToSt$$ring(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { $$((System.IFormattable)null).ToString(""test"", null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToString(""test"",$$ null); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.The_member_is_defined_in_metadata); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() { var markup = @" class C { string s = ((System.IFormattable)null).ToString(""test"", null)$$; }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.You_can_only_change_the_signature_of_a_constructor_indexer_method_or_delegate); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeInMethodBody() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$ } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_ArgumentList() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls1() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar($$Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(Baz(y, x), y); } public void Bar(int x, string y) { } public int Baz(string y, int x) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls2() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar$$(Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_NestedCalls3() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar(Baz(x, y), $$y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_Attribute() { var markup = @" using System; [$$My(1, 2)] class MyAttribute : Attribute { public MyAttribute(int x, int y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; [My(2, 1)] class MyAttribute : Attribute { public MyAttribute(int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols() { var markup = @" class Test { void M(int x, string y) { } void M(int x, double y) { } void M2() { $$M(""s"", 1); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Test { void M(string y, int x) { } void M(int x, double y) { } void M2() { M(1, ""s""); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor() { var markup = @" class Program { public Program(int x, int y) : this(1, 2, 3)$$ { } public Program(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { public Program(int x, int y) : this(3, 2, 1) { } public Program(int z, int y, int x) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor() { var markup = @" class B { public B(int a, int b) { } } class D : B { public D(int x, int y) : base(1, 2)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public B(int b, int a) { } } class D : B { public D(int x, int y) : base(2, 1) { } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Indexers [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtBeginningOfDeclaration() { var markup = @" class Program { $$int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InParameters() { var markup = @" class Program { int this[int x, $$string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeAtEndOfDeclaration() { var markup = @" class Program { int this[int x, string y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeInAccessor() { var markup = @" class Program { int this[int x, string y] { get { return $$5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_BeforeTarget() { var markup = @" class Program { void M(Program p) { var t = $$p[5, ""test""]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderIndexerParameters_InvokeOnReference_InArgumentList() { var markup = @" class Program { void M(Program p) { var t = p[5, ""test""$$]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Delegates [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation1() { var markup = @" public class C { void T() { var d = new $$D((x, y) => { }); } public delegate void D(int x, int y); }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class C { void T() { var d = new D((y, x) => { }); } public delegate void D(int y, int x); }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderDelegateParameters_ObjectCreation2() { var markup = @" public class CD<T> { public delegate void D(T t, T u); } class Test { public void M() { var dele = new CD<int>.$$D((int x, int y) => { }); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" public class CD<T> { public delegate void D(T u, T t); } class Test { public void M() { var dele = new CD<int>.D((int y, int x) => { }); } }"; await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region CodeRefactoring [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void [||]Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInMethodBody() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { [||] } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_InLambda() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b)[||] => { return a; }; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int x) { System.Func<int, int, int> f = (b, a) => { return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_NotInLambdaBody() { var markup = @" class Program { void M(int x) { System.Func<int, int, int> f = (a, b) => { [||]return a; }; } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)] public async Task ReorderMethodParameters_CodeRefactoring_AtCallSite() { var markup = @" class Program { void M(int x, int y) { M([||]5, 6); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(int y, int x) { M(6, 5); } }"; await TestChangeSignatureViaCodeActionAsync(markup, expectedCodeAction: true, updatedSignature: permutation, expectedCode: updatedCode); } #endregion } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using pinch; using pinch.Http.Request; using pinch.Http.Response; using pinch.Http.Client; using pinch.Models; namespace pinch.Controllers { public partial class WebhookController: BaseController { #region Singleton Pattern //private static variables for the singleton pattern private static object syncObject = new object(); private static WebhookController instance = null; /// <summary> /// Singleton pattern implementation /// </summary> internal static WebhookController Instance { get { lock (syncObject) { if (null == instance) { instance = new WebhookController(); } } return instance; } } #endregion Singleton Pattern /// <summary> /// List the webhooks of the current user /// </summary> /// <return>Returns the List<Webhook> response from the API call</return> public List<Webhook> List() { Task<List<Webhook>> t = ListAsync(); Task.WaitAll(t); return t.Result; } /// <summary> /// List the webhooks of the current user /// </summary> /// <return>Returns the List<Webhook> response from the API call</return> public async Task<List<Webhook>> ListAsync() { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/webhooks"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" } }; _headers.Add("X-API-TOKEN", Configuration.XAPITOKEN); _headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl,_headers); //Custom Authentication to be added for authorization AuthUtility.AppendCustomAuthParams(_request); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //return null on 404 if (_response.StatusCode == 404) return null; //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<List<Webhook>>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="webhook">Required parameter: Example: </param> /// <return>Returns the Webhook response from the API call</return> public Webhook Create(Webhook webhook) { Task<Webhook> t = CreateAsync(webhook); Task.WaitAll(t); return t.Result; } /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="webhook">Required parameter: Example: </param> /// <return>Returns the Webhook response from the API call</return> public async Task<Webhook> CreateAsync(Webhook webhook) { //validating required parameters if (null == webhook) throw new ArgumentNullException("webhook", "The parameter \"webhook\" is a required parameter and cannot be null."); //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/webhooks"); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" }, { "content-type", "application/json; charset=utf-8" } }; _headers.Add("X-API-TOKEN", Configuration.XAPITOKEN); _headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL); //append body params var _body = APIHelper.JsonSerialize(webhook); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.PostBody(_queryUrl, _headers, _body); //Custom Authentication to be added for authorization AuthUtility.AppendCustomAuthParams(_request); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //return null on 404 if (_response.StatusCode == 404) return null; //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<Webhook>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="webhookId">Required parameter: Example: </param> /// <param name="webhook">Optional parameter: Example: </param> /// <return>Returns the Webhook response from the API call</return> public Webhook Update(int webhookId, Webhook webhook = null) { Task<Webhook> t = UpdateAsync(webhookId, webhook); Task.WaitAll(t); return t.Result; } /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="webhookId">Required parameter: Example: </param> /// <param name="webhook">Optional parameter: Example: </param> /// <return>Returns the Webhook response from the API call</return> public async Task<Webhook> UpdateAsync(int webhookId, Webhook webhook = null) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/webhooks/{webhook_id}"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>() { { "webhook_id", webhookId } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" }, { "content-type", "application/json; charset=utf-8" } }; _headers.Add("X-API-TOKEN", Configuration.XAPITOKEN); _headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL); //append body params var _body = APIHelper.JsonSerialize(webhook); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.PutBody(_queryUrl, _headers, _body); //Custom Authentication to be added for authorization AuthUtility.AppendCustomAuthParams(_request); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //return null on 404 if (_response.StatusCode == 404) return null; //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<Webhook>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="webhookId">Required parameter: Example: </param> /// <return>Returns the string response from the API call</return> public string Destroy(int webhookId) { Task<string> t = DestroyAsync(webhookId); Task.WaitAll(t); return t.Result; } /// <summary> /// TODO: type endpoint description here /// </summary> /// <param name="webhookId">Required parameter: Example: </param> /// <return>Returns the string response from the API call</return> public async Task<string> DestroyAsync(int webhookId) { //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/webhooks/{webhook_id}"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>() { { "webhook_id", webhookId } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "APIMATIC 2.0" } }; _headers.Add("X-API-TOKEN", Configuration.XAPITOKEN); _headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Delete(_queryUrl, _headers, null); //Custom Authentication to be added for authorization AuthUtility.AppendCustomAuthParams(_request); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //return null on 404 if (_response.StatusCode == 404) return null; //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return _response.Body; } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } /// <summary> /// Get a specific webhook by its id /// </summary> /// <param name="id">Required parameter: Example: </param> /// <return>Returns the Webhook response from the API call</return> public Webhook Get(string id) { Task<Webhook> t = GetAsync(id); Task.WaitAll(t); return t.Result; } /// <summary> /// Get a specific webhook by its id /// </summary> /// <param name="id">Required parameter: Example: </param> /// <return>Returns the Webhook response from the API call</return> public async Task<Webhook> GetAsync(string id) { //validating required parameters if (null == id) throw new ArgumentNullException("id", "The parameter \"id\" is a required parameter and cannot be null."); //the base uri for api requestss string _baseUri = Configuration.BaseUri; //prepare query string for API call StringBuilder _queryBuilder = new StringBuilder(_baseUri); _queryBuilder.Append("/webhooks/{id}"); //process optional template parameters APIHelper.AppendUrlWithTemplateParameters(_queryBuilder, new Dictionary<string, object>() { { "id", id } }); //validate and preprocess url string _queryUrl = APIHelper.CleanUrl(_queryBuilder); //append request with appropriate headers and parameters var _headers = new Dictionary<string,string>() { { "user-agent", "APIMATIC 2.0" }, { "accept", "application/json" } }; _headers.Add("X-API-TOKEN", Configuration.XAPITOKEN); _headers.Add("X-API-EMAIL", Configuration.XAPIEMAIL); //prepare the API call request to fetch the response HttpRequest _request = ClientInstance.Get(_queryUrl,_headers); //Custom Authentication to be added for authorization AuthUtility.AppendCustomAuthParams(_request); //invoke request and get response HttpStringResponse _response = (HttpStringResponse) await ClientInstance.ExecuteAsStringAsync(_request); HttpContext _context = new HttpContext(_request,_response); //return null on 404 if (_response.StatusCode == 404) return null; //handle errors defined at the API level base.ValidateResponse(_response, _context); try { return APIHelper.JsonDeserialize<Webhook>(_response.Body); } catch (Exception _ex) { throw new APIException("Failed to parse the response: " + _ex.Message, _context); } } } }
// 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.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace ILCompiler.DependencyAnalysisFramework { /// <summary> /// Implement a dependency analysis framework. This works much like a Garbage Collector's mark algorithm /// in that it finds a set of nodes from an initial root set. /// /// However, in contrast to a typical GC in addition to simple edges from a node, there may also /// be conditional edges where a node has a dependency if some other specific node exists in the /// graph, and dynamic edges in which a node has a dependency if some other node exists in the graph, /// but what that other node might be is not known until it may exist in the graph. /// /// This analyzer also attempts to maintain a serialized state of why nodes are in the graph /// with strings describing the reason a given node was added to the graph. The degree of logging /// is configurable via the MarkStrategy /// /// </summary> public sealed class DependencyAnalyzer<MarkStrategy, DependencyContextType> : DependencyAnalyzerBase<DependencyContextType> where MarkStrategy : struct, IDependencyAnalysisMarkStrategy<DependencyContextType> { private MarkStrategy _marker = new MarkStrategy(); private DependencyContextType _dependencyContext; private IComparer<DependencyNodeCore<DependencyContextType>> _resultSorter = null; private Stack<DependencyNodeCore<DependencyContextType>> _markStack = new Stack<DependencyNodeCore<DependencyContextType>>(); private List<DependencyNodeCore<DependencyContextType>> _markedNodes = new List<DependencyNodeCore<DependencyContextType>>(); private ImmutableArray<DependencyNodeCore<DependencyContextType>> _markedNodesFinal; private List<DependencyNodeCore<DependencyContextType>> _rootNodes = new List<DependencyNodeCore<DependencyContextType>>(); private List<DependencyNodeCore<DependencyContextType>> _deferredStaticDependencies = new List<DependencyNodeCore<DependencyContextType>>(); private List<DependencyNodeCore<DependencyContextType>> _dynamicDependencyInterestingList = new List<DependencyNodeCore<DependencyContextType>>(); private List<DynamicDependencyNode> _markedNodesWithDynamicDependencies = new List<DynamicDependencyNode>(); private bool _newDynamicDependenciesMayHaveAppeared = false; private Dictionary<DependencyNodeCore<DependencyContextType>, HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry>> _conditional_dependency_store = new Dictionary<DependencyNodeCore<DependencyContextType>, HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry>>(); private bool _markingCompleted = false; private Random _stackPopRandomizer = null; private struct DynamicDependencyNode { private DependencyNodeCore<DependencyContextType> _node; private int _next; public DynamicDependencyNode(DependencyNodeCore<DependencyContextType> node) { _node = node; _next = 0; } public void MarkNewDynamicDependencies(DependencyAnalyzer<MarkStrategy, DependencyContextType> analyzer) { foreach (DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry dependency in _node.SearchDynamicDependencies(analyzer._dynamicDependencyInterestingList, _next, analyzer._dependencyContext)) { analyzer.AddToMarkStack(dependency.Node, dependency.Reason, _node, dependency.OtherReasonNode); } _next = analyzer._dynamicDependencyInterestingList.Count; } } // Api surface public DependencyAnalyzer(DependencyContextType dependencyContext, IComparer<DependencyNodeCore<DependencyContextType>> resultSorter) { _dependencyContext = dependencyContext; _resultSorter = resultSorter; _marker.AttachContext(dependencyContext); if (int.TryParse(Environment.GetEnvironmentVariable("CoreRT_DeterminismSeed"), out int seed)) { _stackPopRandomizer = new Random(seed); } } /// <summary> /// Add a root node /// </summary> public override sealed void AddRoot(DependencyNodeCore<DependencyContextType> rootNode, string reason) { if (AddToMarkStack(rootNode, reason, null, null)) { _rootNodes.Add(rootNode); } } public override sealed ImmutableArray<DependencyNodeCore<DependencyContextType>> MarkedNodeList { get { if (!_markingCompleted) { throw new InvalidOperationException(); } return _markedNodesFinal; } } public override sealed event Action<DependencyNodeCore<DependencyContextType>> NewMarkedNode; public override sealed event Action<List<DependencyNodeCore<DependencyContextType>>> ComputeDependencyRoutine; private IEnumerable<DependencyNodeCore<DependencyContextType>> MarkedNodesEnumerable() { if (_markedNodesFinal != null) return _markedNodesFinal; else return _markedNodes; } public override sealed void VisitLogNodes(IDependencyAnalyzerLogNodeVisitor<DependencyContextType> logNodeVisitor) { foreach (DependencyNodeCore<DependencyContextType> node in MarkedNodesEnumerable()) { logNodeVisitor.VisitNode(node); } _marker.VisitLogNodes(MarkedNodesEnumerable(), logNodeVisitor); } public override sealed void VisitLogEdges(IDependencyAnalyzerLogEdgeVisitor<DependencyContextType> logEdgeVisitor) { _marker.VisitLogEdges(MarkedNodesEnumerable(), logEdgeVisitor); } /// <summary> /// Called by the algorithm to ensure that this set of nodes is processed such that static dependencies are computed. /// </summary> /// <param name="deferredStaticDependencies">List of nodes which must have static dependencies computed</param> private void ComputeDependencies(List<DependencyNodeCore<DependencyContextType>> deferredStaticDependencies) { if (ComputeDependencyRoutine != null) ComputeDependencyRoutine(deferredStaticDependencies); } // Internal details private void GetStaticDependenciesImpl(DependencyNodeCore<DependencyContextType> node) { IEnumerable<DependencyNodeCore<DependencyContextType>.DependencyListEntry> staticDependencies = node.GetStaticDependencies(_dependencyContext); if (staticDependencies != null) { foreach (DependencyNodeCore<DependencyContextType>.DependencyListEntry dependency in staticDependencies) { AddToMarkStack(dependency.Node, dependency.Reason, node, null); } } if (node.HasConditionalStaticDependencies) { foreach (DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry dependency in node.GetConditionalStaticDependencies(_dependencyContext)) { if (dependency.OtherReasonNode.Marked) { AddToMarkStack(dependency.Node, dependency.Reason, node, dependency.OtherReasonNode); } else { HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> storedDependencySet = null; if (!_conditional_dependency_store.TryGetValue(dependency.OtherReasonNode, out storedDependencySet)) { storedDependencySet = new HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry>(); _conditional_dependency_store.Add(dependency.OtherReasonNode, storedDependencySet); } // Swap out other reason node as we're storing that as the dictionary key DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry conditionalDependencyStoreEntry = new DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry(dependency.Node, node, dependency.Reason); storedDependencySet.Add(conditionalDependencyStoreEntry); } } } } private void GetStaticDependencies(DependencyNodeCore<DependencyContextType> node) { if (node.StaticDependenciesAreComputed) { GetStaticDependenciesImpl(node); } else { _deferredStaticDependencies.Add(node); } } private void ProcessMarkStack() { do { while (_markStack.Count > 0) { // Pop the top node of the mark stack DependencyNodeCore<DependencyContextType> currentNode = _markStack.Pop(); Debug.Assert(currentNode.Marked); // Only some marked objects are interesting for dynamic dependencies // store those in a seperate list to avoid excess scanning over non-interesting // nodes during dynamic dependency discovery if (currentNode.InterestingForDynamicDependencyAnalysis) { _dynamicDependencyInterestingList.Add(currentNode); _newDynamicDependenciesMayHaveAppeared = true; } // Add all static dependencies to the mark stack GetStaticDependencies(currentNode); // If there are dynamic dependencies, note for later if (currentNode.HasDynamicDependencies) { _newDynamicDependenciesMayHaveAppeared = true; _markedNodesWithDynamicDependencies.Add(new DynamicDependencyNode(currentNode)); } // If this new node satisfies any stored conditional dependencies, // add them to the mark stack HashSet<DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry> storedDependencySet = null; if (_conditional_dependency_store.TryGetValue(currentNode, out storedDependencySet)) { foreach (DependencyNodeCore<DependencyContextType>.CombinedDependencyListEntry newlySatisfiedDependency in storedDependencySet) { AddToMarkStack(newlySatisfiedDependency.Node, newlySatisfiedDependency.Reason, newlySatisfiedDependency.OtherReasonNode, currentNode); } _conditional_dependency_store.Remove(currentNode); } } // Find new dependencies introduced by dynamic depedencies if (_newDynamicDependenciesMayHaveAppeared) { _newDynamicDependenciesMayHaveAppeared = false; for (int i = 0; i < _markedNodesWithDynamicDependencies.Count; i++) { DynamicDependencyNode dynamicNode = _markedNodesWithDynamicDependencies[i]; dynamicNode.MarkNewDynamicDependencies(this); // Update the copy in the list _markedNodesWithDynamicDependencies[i] = dynamicNode; } } } while (_markStack.Count != 0); } public override void ComputeMarkedNodes() { using (PerfEventSource.StartStopEvents.GraphProcessingEvents()) { if (_markingCompleted) return; do { // Run mark stack algorithm as much as possible using (PerfEventSource.StartStopEvents.DependencyAnalysisEvents()) { ProcessMarkStack(); } // Compute all dependencies which were not ready during the ProcessMarkStack step ComputeDependencies(_deferredStaticDependencies); foreach (DependencyNodeCore<DependencyContextType> node in _deferredStaticDependencies) { Debug.Assert(node.StaticDependenciesAreComputed); GetStaticDependenciesImpl(node); } _deferredStaticDependencies.Clear(); } while (_markStack.Count != 0); if (_resultSorter != null) _markedNodes.Sort(_resultSorter); _markedNodesFinal = _markedNodes.ToImmutableArray(); _markedNodes = null; _markingCompleted = true; } } private bool AddToMarkStack(DependencyNodeCore<DependencyContextType> node, string reason, DependencyNodeCore<DependencyContextType> reason1, DependencyNodeCore<DependencyContextType> reason2) { if (_marker.MarkNode(node, reason1, reason2, reason)) { if (PerfEventSource.Log.IsEnabled()) PerfEventSource.Log.AddedNodeToMarkStack(); // Pop the top node of the mark stack if (_stackPopRandomizer == null) { _markStack.Push(node); } else { // // Expose output file determinism bugs in our system by randomizing the order nodes are pushed // on to the mark stack. // int randomNodeIndex = _stackPopRandomizer.Next(_markStack.Count); var tempStack = new Stack<DependencyNodeCore<DependencyContextType>>(); for (int i = 0; i < randomNodeIndex; i++) { tempStack.Push(_markStack.Pop()); } _markStack.Push(node); while (tempStack.Count > 0) { _markStack.Push(tempStack.Pop()); } } _markedNodes.Add(node); node.CallOnMarked(_dependencyContext); if (NewMarkedNode != null) NewMarkedNode(node); return true; } return false; } } }
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System; using System.Collections.Generic; using System.Text; namespace Facebook.CSSLayout { /** * Should measure the given node and put the result in the given MeasureOutput. */ public delegate MeasureOutput MeasureFunction(CSSNode node, float width, CSSMeasureMode widthMode, float height, CSSMeasureMode heightMode); /** * A CSS Node. It has a style object you can manipulate at {@link #style}. After calling * {@link #calculateLayout()}, {@link #layout} will be filled with the results of the layout. */ public class CSSNode { const int POSITION_LEFT = CSSLayout.POSITION_LEFT; const int POSITION_TOP = CSSLayout.POSITION_TOP; const int POSITION_RIGHT = CSSLayout.POSITION_RIGHT; const int POSITION_BOTTOM = CSSLayout.POSITION_BOTTOM; const int DIMENSION_WIDTH = CSSLayout.DIMENSION_WIDTH; const int DIMENSION_HEIGHT = CSSLayout.DIMENSION_HEIGHT; enum LayoutState { /** * Some property of this node or its children has changes and the current values in * {@link #layout} are not valid. */ DIRTY, /** * This node has a new layout relative to the last time {@link #MarkLayoutSeen()} was called. */ HAS_NEW_LAYOUT, /** * {@link #layout} is valid for the node's properties and this layout has been marked as * having been seen. */ UP_TO_DATE, } internal readonly CSSStyle style = new CSSStyle(); internal readonly CSSLayout layout = new CSSLayout(); internal readonly CachedCSSLayout lastLayout = new CachedCSSLayout(); internal int lineIndex = 0; internal /*package*/ CSSNode nextChild; // 4 is kinda arbitrary, but the default of 10 seems really high for an average View. readonly List<CSSNode> mChildren = new List<CSSNode>(4); [Nullable] CSSNode mParent; [Nullable] MeasureFunction mMeasureFunction = null; LayoutState mLayoutState = LayoutState.DIRTY; bool mIsTextNode = false; public int ChildCount { get { return mChildren.Count; } } public CSSNode this[int i] { get { return mChildren[i]; } } public IEnumerable<CSSNode> Children { get { return mChildren; } } public void AddChild(CSSNode child) { InsertChild(ChildCount, child); } public void InsertChild(int i, CSSNode child) { if (child.mParent != null) { throw new InvalidOperationException("Child already has a parent, it must be removed first."); } mChildren.Insert(i, child); child.mParent = this; dirty(); } public void RemoveChildAt(int i) { mChildren[i].mParent = null; mChildren.RemoveAt(i); dirty(); } public CSSNode Parent { [return: Nullable] get { return mParent; } } /** * @return the index of the given child, or -1 if the child doesn't exist in this node. */ public int IndexOf(CSSNode child) { return mChildren.IndexOf(child); } public MeasureFunction MeasureFunction { get { return mMeasureFunction; } set { if (!valuesEqual(mMeasureFunction, value)) { mMeasureFunction = value; dirty(); } } } public bool IsTextNode { get { return mIsTextNode; } set { mIsTextNode = value; } } public bool IsMeasureDefined { get { return mMeasureFunction != null; } } internal MeasureOutput measure(MeasureOutput measureOutput, float width, CSSMeasureMode widthMode, float height, CSSMeasureMode heightMode) { if (!IsMeasureDefined) { throw new Exception("Measure function isn't defined!"); } return Assertions.assertNotNull(mMeasureFunction)(this, width, widthMode, height, heightMode); } /** * Performs the actual layout and saves the results in {@link #layout} */ public void CalculateLayout() { LayoutEngine.layoutNode(DummyLayoutContext, this, CSSConstants.Undefined, CSSConstants.Undefined, null); } static readonly CSSLayoutContext DummyLayoutContext = new CSSLayoutContext(); /** * See {@link LayoutState#DIRTY}. */ public bool IsDirty { get { return mLayoutState == LayoutState.DIRTY; } } /** * See {@link LayoutState#HAS_NEW_LAYOUT}. */ public bool HasNewLayout { get { return mLayoutState == LayoutState.HAS_NEW_LAYOUT; } } internal protected virtual void dirty() { if (mLayoutState == LayoutState.DIRTY) { return; } else if (mLayoutState == LayoutState.HAS_NEW_LAYOUT) { throw new InvalidOperationException("Previous layout was ignored! MarkLayoutSeen() never called"); } mLayoutState = LayoutState.DIRTY; if (mParent != null) { mParent.dirty(); } } internal void markHasNewLayout() { mLayoutState = LayoutState.HAS_NEW_LAYOUT; } /** * Tells the node that the current values in {@link #layout} have been seen. Subsequent calls * to {@link #hasNewLayout()} will return false until this node is laid out with new parameters. * You must call this each time the layout is generated if the node has a new layout. */ public void MarkLayoutSeen() { if (!HasNewLayout) { throw new InvalidOperationException("Expected node to have a new layout to be seen!"); } mLayoutState = LayoutState.UP_TO_DATE; } void toStringWithIndentation(StringBuilder result, int level) { // Spaces and tabs are dropped by IntelliJ logcat integration, so rely on __ instead. StringBuilder indentation = new StringBuilder(); for (int i = 0; i < level; ++i) { indentation.Append("__"); } result.Append(indentation.ToString()); result.Append(layout.ToString()); if (ChildCount == 0) { return; } result.Append(", children: [\n"); for (var i = 0; i < ChildCount; i++) { this[i].toStringWithIndentation(result, level + 1); result.Append("\n"); } result.Append(indentation + "]"); } public override string ToString() { StringBuilder sb = new StringBuilder(); this.toStringWithIndentation(sb, 0); return sb.ToString(); } protected bool valuesEqual(float f1, float f2) { return FloatUtil.floatsEqual(f1, f2); } protected bool valuesEqual<T>([Nullable] T o1, [Nullable] T o2) { if (o1 == null) { return o2 == null; } return o1.Equals(o2); } public CSSDirection Direction { get { return style.direction; } set { updateDiscreteValue(ref style.direction, value); } } public CSSFlexDirection FlexDirection { get { return style.flexDirection; } set { updateDiscreteValue(ref style.flexDirection, value); } } public CSSJustify JustifyContent { get { return style.justifyContent; } set { updateDiscreteValue(ref style.justifyContent, value); } } public CSSAlign AlignContent { get { return style.alignContent; } set { updateDiscreteValue(ref style.alignContent, value); } } public CSSAlign AlignItems { get { return style.alignItems; } set { updateDiscreteValue(ref style.alignItems, value); } } public CSSAlign AlignSelf { get { return style.alignSelf; } set { updateDiscreteValue(ref style.alignSelf, value); } } public CSSPositionType PositionType { get { return style.positionType; } set { updateDiscreteValue(ref style.positionType, value); } } public CSSWrap Wrap { get { return style.flexWrap; } set { updateDiscreteValue(ref style.flexWrap, value); } } public float Flex { get { return style.flex; } set { updateFloatValue(ref style.flex, value); } } public CSSOverflow Overflow { get { return style.overflow; } set { updateDiscreteValue(ref style.overflow, value); } } public void SetMargin(CSSSpacingType spacingType, float margin) { if (style.margin.set((int)spacingType, margin)) dirty(); } public float GetMargin(CSSSpacingType spacingType) { return style.margin.getRaw((int)spacingType); } public void SetPadding(CSSSpacingType spacingType, float padding) { if (style.padding.set((int)spacingType, padding)) dirty(); } public float GetPadding(CSSSpacingType spacingType) { return style.padding.getRaw((int)spacingType); } public void SetBorder(CSSSpacingType spacingType, float border) { if (style.border.set((int)spacingType, border)) dirty(); } public float GetBorder(CSSSpacingType spacingType) { return style.border.getRaw((int)spacingType); } public float PositionTop { get { return style.position[POSITION_TOP]; } set { updateFloatValue(ref style.position[POSITION_TOP], value); } } public float PositionBottom { get { return style.position[POSITION_BOTTOM]; } set { updateFloatValue(ref style.position[POSITION_BOTTOM], value); } } public float PositionLeft { get { return style.position[POSITION_LEFT]; } set { updateFloatValue(ref style.position[POSITION_LEFT], value); } } public float PositionRight { get { return style.position[POSITION_RIGHT]; } set { updateFloatValue(ref style.position[POSITION_RIGHT], value); } } public float Width { get { return style.dimensions[DIMENSION_WIDTH]; } set { updateFloatValue(ref style.dimensions[DIMENSION_WIDTH], value); } } public float Height { get { return style.dimensions[DIMENSION_HEIGHT]; } set { updateFloatValue(ref style.dimensions[DIMENSION_HEIGHT], value); } } public float MinWidth { get { return style.minWidth; } set { updateFloatValue(ref style.minWidth, value); } } public float MinHeight { get { return style.minHeight; } set { updateFloatValue(ref style.minHeight, value); } } public float MaxWidth { get { return style.maxWidth; } set { updateFloatValue(ref style.maxWidth, value); } } public float MaxHeight { get { return style.maxHeight; } set { updateFloatValue(ref style.maxHeight, value); } } public float LayoutX { get { return layout.position[POSITION_LEFT]; } } public float LayoutY { get { return layout.position[POSITION_TOP]; } } public float LayoutWidth { get { return layout.dimensions[DIMENSION_WIDTH]; } } public float LayoutHeight { get { return layout.dimensions[DIMENSION_HEIGHT]; } } public CSSDirection LayoutDirection { get { return layout.direction; } } /** * Set a default padding (left/top/right/bottom) for this node. */ public void SetDefaultPadding(CSSSpacingType spacingType, float padding) { if (style.padding.setDefault((int)spacingType, padding)) dirty(); } void updateDiscreteValue<ValueT>(ref ValueT valueRef, ValueT newValue) { if (valuesEqual(valueRef, newValue)) return; valueRef = newValue; dirty(); } void updateFloatValue(ref float valueRef, float newValue) { if (valuesEqual(valueRef, newValue)) return; valueRef = newValue; dirty(); } } public static class CSSNodeExtensions { /* Explicitly mark this node as dirty. Calling this function is required when the measure function points to the same instance, but changes its behavior. For all other property changes, the node is automatically marked dirty. */ public static void MarkDirty(this CSSNode node) { node.dirty(); } } internal static class CSSNodeExtensionsInternal { public static CSSNode getParent(this CSSNode node) { return node.Parent; } public static int getChildCount(this CSSNode node) { return node.ChildCount; } public static CSSNode getChildAt(this CSSNode node, int i) { return node[i]; } public static void addChildAt(this CSSNode node, CSSNode child, int i) { node.InsertChild(i, child); } public static void removeChildAt(this CSSNode node, int i) { node.RemoveChildAt(i); } public static void setMeasureFunction(this CSSNode node, MeasureFunction measureFunction) { node.MeasureFunction = measureFunction; } public static void setIsTextNode(this CSSNode node, bool isTextNode) { node.IsTextNode = isTextNode; } public static void calculateLayout(this CSSNode node) { node.CalculateLayout(); } public static bool isDirty(this CSSNode node) { return node.IsDirty; } public static void setMargin(this CSSNode node, int spacingType, float margin) { node.SetMargin((CSSSpacingType)spacingType, margin); } public static void setPadding(this CSSNode node, int spacingType, float padding) { node.SetPadding((CSSSpacingType)spacingType, padding); } public static void setBorder(this CSSNode node, int spacingType, float border) { node.SetBorder((CSSSpacingType)spacingType, border); } } }
// 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 Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; namespace System.Threading { // // Windows-specific implementation of ThreadPool // public sealed class RegisteredWaitHandle : MarshalByRefObject { private readonly Lock _lock; private SafeWaitHandle _waitHandle; private readonly _ThreadPoolWaitOrTimerCallback _callbackHelper; private readonly uint _millisecondsTimeout; private bool _repeating; private bool _unregistering; // Handle to this object to keep it alive private GCHandle _gcHandle; // Pointer to the TP_WAIT structure private IntPtr _tpWait; internal RegisteredWaitHandle(SafeWaitHandle waitHandle, _ThreadPoolWaitOrTimerCallback callbackHelper, uint millisecondsTimeout, bool repeating) { _lock = new Lock(); // Protect the handle from closing while we are waiting on it (VSWhidbey 285642) waitHandle.DangerousAddRef(); _waitHandle = waitHandle; _callbackHelper = callbackHelper; _millisecondsTimeout = millisecondsTimeout; _repeating = repeating; // Allocate _gcHandle and _tpWait as the last step and make sure they are never leaked _gcHandle = GCHandle.Alloc(this); _tpWait = Interop.mincore.CreateThreadpoolWait( AddrofIntrinsics.AddrOf<Interop.mincore.WaitCallback>(RegisteredWaitCallback), (IntPtr)_gcHandle, IntPtr.Zero); if (_tpWait == IntPtr.Zero) { _gcHandle.Free(); throw new OutOfMemoryException(); } } [NativeCallable(CallingConvention = CallingConvention.StdCall)] internal static void RegisteredWaitCallback(IntPtr instance, IntPtr context, IntPtr wait, uint waitResult) { var wrapper = ThreadPoolCallbackWrapper.Enter(); GCHandle handle = (GCHandle)context; RegisteredWaitHandle registeredWaitHandle = (RegisteredWaitHandle)handle.Target; Debug.Assert((handle == registeredWaitHandle._gcHandle) && (wait == registeredWaitHandle._tpWait)); bool timedOut = (waitResult == (uint)Interop.Kernel32.WAIT_TIMEOUT); registeredWaitHandle.PerformCallback(timedOut); wrapper.Exit(); } private void PerformCallback(bool timedOut) { bool lockAcquired; var spinner = new SpinWait(); // Prevent the race condition with Unregister and the previous PerformCallback call, which may still be // holding the _lock. while (!(lockAcquired = _lock.TryAcquire(0)) && !Volatile.Read(ref _unregistering)) { spinner.SpinOnce(); } // If another thread is running Unregister, no need to restart the timer or clean up if (lockAcquired) { try { if (!_unregistering) { if (_repeating) { // Allow this wait to fire again. Restart the timer before executing the callback. RestartWait(); } else { // This wait will not be fired again. Free the GC handle to allow the GC to collect this object. Debug.Assert(_gcHandle.IsAllocated); _gcHandle.Free(); } } } finally { _lock.Release(); } } _ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(_callbackHelper, timedOut); } internal unsafe void RestartWait() { long timeout; long* pTimeout = null; // Null indicates infinite timeout if (_millisecondsTimeout != Timeout.UnsignedInfinite) { timeout = -10000L * _millisecondsTimeout; pTimeout = &timeout; } // We can use DangerousGetHandle because of DangerousAddRef in the constructor Interop.mincore.SetThreadpoolWait(_tpWait, _waitHandle.DangerousGetHandle(), (IntPtr)pTimeout); } public bool Unregister(WaitHandle waitObject) { // Hold the lock during the synchronous part of Unregister (as in CoreCLR) using (LockHolder.Hold(_lock)) { if (!_unregistering) { // Ensure callbacks will not call SetThreadpoolWait anymore _unregistering = true; // Cease queueing more callbacks Interop.mincore.SetThreadpoolWait(_tpWait, IntPtr.Zero, IntPtr.Zero); // Should we wait for callbacks synchronously? Note that we treat the zero handle as the asynchronous case. SafeWaitHandle safeWaitHandle = waitObject?.SafeWaitHandle; bool blocking = ((safeWaitHandle != null) && (safeWaitHandle.DangerousGetHandle() == new IntPtr(-1))); if (blocking) { FinishUnregistering(); } else { // Wait for callbacks and dispose resources asynchronously ThreadPool.QueueUserWorkItem(FinishUnregisteringAsync, safeWaitHandle); } return true; } } return false; } private void FinishUnregistering() { Debug.Assert(_unregistering); // Wait for outstanding wait callbacks to complete Interop.mincore.WaitForThreadpoolWaitCallbacks(_tpWait, false); // Now it is safe to dispose resources Interop.mincore.CloseThreadpoolWait(_tpWait); _tpWait = IntPtr.Zero; if (_gcHandle.IsAllocated) { _gcHandle.Free(); } Debug.Assert(_waitHandle != null); _waitHandle.DangerousRelease(); _waitHandle = null; GC.SuppressFinalize(this); } private void FinishUnregisteringAsync(object waitObject) { FinishUnregistering(); // Signal the provided wait object SafeWaitHandle safeWaitHandle = (SafeWaitHandle)waitObject; if ((safeWaitHandle != null) && !safeWaitHandle.IsInvalid) { Interop.Kernel32.SetEvent(safeWaitHandle); } } ~RegisteredWaitHandle() { // If _gcHandle is allocated, it points to this object, so this object must not be collected by the GC Debug.Assert(!_gcHandle.IsAllocated); // If this object gets resurrected and another thread calls Unregister, that creates a race condition. // Do not block the finalizer thread. If another thread is running Unregister, it will clean up for us. // The _lock may be null in case of OOM in the constructor. if ((_lock != null) && _lock.TryAcquire(0)) { try { if (!_unregistering) { _unregistering = true; if (_tpWait != IntPtr.Zero) { // There must be no in-flight callbacks; just dispose resources Interop.mincore.CloseThreadpoolWait(_tpWait); _tpWait = IntPtr.Zero; } if (_waitHandle != null) { _waitHandle.DangerousRelease(); _waitHandle = null; } } } finally { _lock.Release(); } } } } public static partial class ThreadPool { // Time in ms for which ThreadPoolWorkQueue.Dispatch keeps executing work items before returning to the OS private const uint DispatchQuantum = 30; /// <summary> /// The maximum number of threads in the default thread pool on Windows 10 as computed by /// TppComputeDefaultMaxThreads(TppMaxGlobalPool). /// </summary> /// <remarks> /// Note that Windows 8 and 8.1 used a different value: Math.Max(4 * ThreadPoolGlobals.processorCount, 512). /// </remarks> private static readonly int MaxThreadCount = Math.Max(8 * ThreadPoolGlobals.processorCount, 768); private static IntPtr s_work; // The number of threads executing work items in the Dispatch method private static volatile int numWorkingThreads; public static bool SetMaxThreads(int workerThreads, int completionPortThreads) { // Not supported at present return false; } public static void GetMaxThreads(out int workerThreads, out int completionPortThreads) { // Note that worker threads and completion port threads share the same thread pool. // The total number of threads cannot exceed MaxThreadCount. workerThreads = MaxThreadCount; completionPortThreads = MaxThreadCount; } public static bool SetMinThreads(int workerThreads, int completionPortThreads) { // Not supported at present return false; } public static void GetMinThreads(out int workerThreads, out int completionPortThreads) { workerThreads = 0; completionPortThreads = 0; } public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads) { // Make sure we return a non-negative value if thread pool defaults are changed int availableThreads = Math.Max(MaxThreadCount - numWorkingThreads, 0); workerThreads = availableThreads; completionPortThreads = availableThreads; } internal static bool KeepDispatching(int startTickCount) { // Note: this function may incorrectly return false due to TickCount overflow // if work item execution took around a multiple of 2^32 milliseconds (~49.7 days), // which is improbable. return ((uint)(Environment.TickCount - startTickCount) < DispatchQuantum); } internal static void NotifyWorkItemProgress() { } internal static bool NotifyWorkItemComplete() { return true; } [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static void DispatchCallback(IntPtr instance, IntPtr context, IntPtr work) { var wrapper = ThreadPoolCallbackWrapper.Enter(); Debug.Assert(s_work == work); Interlocked.Increment(ref numWorkingThreads); ThreadPoolWorkQueue.Dispatch(); int numWorkers = Interlocked.Decrement(ref numWorkingThreads); Debug.Assert(numWorkers >= 0); // We reset the thread after executing each callback wrapper.Exit(resetThread: false); } internal static void RequestWorkerThread() { if (s_work == IntPtr.Zero) { IntPtr nativeCallback = AddrofIntrinsics.AddrOf<Interop.mincore.WorkCallback>(DispatchCallback); IntPtr work = Interop.mincore.CreateThreadpoolWork(nativeCallback, IntPtr.Zero, IntPtr.Zero); if (work == IntPtr.Zero) throw new OutOfMemoryException(); if (Interlocked.CompareExchange(ref s_work, work, IntPtr.Zero) != IntPtr.Zero) Interop.mincore.CloseThreadpoolWork(work); } Interop.mincore.SubmitThreadpoolWork(s_work); } private static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce, bool flowExecutionContext) { if (waitObject == null) throw new ArgumentNullException(nameof(waitObject)); if (callBack == null) throw new ArgumentNullException(nameof(callBack)); var callbackHelper = new _ThreadPoolWaitOrTimerCallback(callBack, state, flowExecutionContext); var registeredWaitHandle = new RegisteredWaitHandle(waitObject.SafeWaitHandle, callbackHelper, millisecondsTimeOutInterval, !executeOnlyOnce); registeredWaitHandle.RestartWait(); return registeredWaitHandle; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using DemoREST.Areas.HelpPage.ModelDescriptions; using DemoREST.Areas.HelpPage.Models; namespace DemoREST.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using log4net; using Mono.Addins; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.CoreModules.World.Objects.Commands { /// <summary> /// A module that holds commands for manipulating objects in the scene. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ObjectCommandsModule")] public class ObjectCommandsModule : INonSharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private ICommandConsole m_console; public string Name { get { return "Object Commands Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[OBJECT COMMANDS MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[OBJECT COMMANDS MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[OBJECT COMMANDS MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[OBJECT COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); m_scene = scene; m_console = MainConsole.Instance; m_console.Commands.AddCommand( "Objects", false, "delete object owner", "delete object owner <UUID>", "Delete scene objects by owner", "Command will ask for confirmation before proceeding.", HandleDeleteObject); m_console.Commands.AddCommand( "Objects", false, "delete object creator", "delete object creator <UUID>", "Delete scene objects by creator", "Command will ask for confirmation before proceeding.", HandleDeleteObject); m_console.Commands.AddCommand( "Objects", false, "delete object id", "delete object id <UUID-or-localID>", "Delete a scene object by uuid or localID", HandleDeleteObject); m_console.Commands.AddCommand( "Objects", false, "delete object name", "delete object name [--regex] <name>", "Delete a scene object by name.", "Command will ask for confirmation before proceeding.\n" + "If --regex is specified then the name is treatead as a regular expression", HandleDeleteObject); m_console.Commands.AddCommand( "Objects", false, "delete object outside", "delete object outside", "Delete all scene objects outside region boundaries", "Command will ask for confirmation before proceeding.", HandleDeleteObject); m_console.Commands.AddCommand( "Objects", false, "delete object pos", "delete object pos <start-coord> to <end-coord>", "Delete scene objects within the given area.", ConsoleUtil.CoordHelp, HandleDeleteObject); m_console.Commands.AddCommand( "Objects", false, "show object id", "show object id [--full] <UUID-or-localID>", "Show details of a scene object with the given UUID or localID", "The --full option will print out information on all the parts of the object.\n" + "For yet more detailed part information, use the \"show part\" commands.", HandleShowObjectById); m_console.Commands.AddCommand( "Objects", false, "show object name", "show object name [--full] [--regex] <name>", "Show details of scene objects with the given name.", "The --full option will print out information on all the parts of the object.\n" + "For yet more detailed part information, use the \"show part\" commands.\n" + "If --regex is specified then the name is treatead as a regular expression.", HandleShowObjectByName); m_console.Commands.AddCommand( "Objects", false, "show object owner", "show object owner [--full] <OwnerID>", "Show details of scene objects with given owner.", "The --full option will print out information on all the parts of the object.\n", HandleShowObjectByOwnerID); m_console.Commands.AddCommand( "Objects", false, "show object pos", "show object pos [--full] <start-coord> to <end-coord>", "Show details of scene objects within the given area.", "The --full option will print out information on all the parts of the object.\n" + "For yet more detailed part information, use the \"show part\" commands.\n" + ConsoleUtil.CoordHelp, HandleShowObjectByPos); m_console.Commands.AddCommand( "Objects", false, "show part id", "show part id <UUID-or-localID>", "Show details of a scene object part with the given UUID or localID", HandleShowPartById); m_console.Commands.AddCommand( "Objects", false, "show part name", "show part name [--regex] <name>", "Show details of scene object parts with the given name.", "If --regex is specified then the name is treated as a regular expression", HandleShowPartByName); m_console.Commands.AddCommand( "Objects", false, "show part pos", "show part pos <start-coord> to <end-coord>", "Show details of scene object parts within the given area.", ConsoleUtil.CoordHelp, HandleShowPartByPos); m_console.Commands.AddCommand( "Objects", false, "dump object id", "dump object id <UUID-or-localID>", "Dump the formatted serialization of the given object to the file <UUID>.xml", "e.g. dump object uuid c1ed6809-cc24-4061-a4c2-93082a2d1f1d will dump serialization to c1ed6809-cc24-4061-a4c2-93082a2d1f1d.xml\n" + "To locate the UUID or localID in the first place, you need to use the other show object commands.\n" + "If a local ID is given then the filename used is still that for the UUID", HandleDumpObjectById); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[OBJECTS COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[OBJECTS COMMANDS MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); } /// <summary> /// Outputs the sogs to console. /// </summary> /// <param name='searchPredicate'></param> /// <param name='showFull'>If true then output all part details. If false then output summary.</param> private void OutputSogsToConsole(Predicate<SceneObjectGroup> searchPredicate, bool showFull) { List<SceneObjectGroup> sceneObjects = m_scene.GetSceneObjectGroups().FindAll(searchPredicate); StringBuilder sb = new StringBuilder(); foreach (SceneObjectGroup so in sceneObjects) { AddSceneObjectReport(sb, so, showFull); sb.Append("\n"); } sb.AppendFormat("{0} object(s) found in {1}\n", sceneObjects.Count, m_scene.Name); m_console.OutputFormat(sb.ToString()); } private void OutputSopsToConsole(Predicate<SceneObjectPart> searchPredicate, bool showFull) { List<SceneObjectGroup> sceneObjects = m_scene.GetSceneObjectGroups(); List<SceneObjectPart> parts = new List<SceneObjectPart>(); sceneObjects.ForEach(so => parts.AddRange(Array.FindAll<SceneObjectPart>(so.Parts, searchPredicate))); StringBuilder sb = new StringBuilder(); foreach (SceneObjectPart part in parts) { AddScenePartReport(sb, part, showFull); sb.Append("\n"); } sb.AppendFormat("{0} parts found in {1}\n", parts.Count, m_scene.Name); m_console.OutputFormat(sb.ToString()); } private void HandleShowObjectById(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; bool showFull = false; OptionSet options = new OptionSet().Add("full", v => showFull = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) { m_console.OutputFormat("Usage: show object uuid <uuid>"); return; } UUID uuid; uint localId; if (!ConsoleUtil.TryParseConsoleId(m_console, mainParams[3], out uuid, out localId)) return; SceneObjectGroup so; if (localId != ConsoleUtil.LocalIdNotFound) so = m_scene.GetSceneObjectGroup(localId); else so = m_scene.GetSceneObjectGroup(uuid); if (so == null) { // m_console.OutputFormat("No part found with uuid {0}", objectUuid); return; } StringBuilder sb = new StringBuilder(); AddSceneObjectReport(sb, so, showFull); m_console.OutputFormat(sb.ToString()); } private void HandleShowObjectByName(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; bool showFull = false; bool useRegex = false; OptionSet options = new OptionSet(); options.Add("full", v => showFull = v != null ); options.Add("regex", v => useRegex = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) { m_console.OutputFormat("Usage: show object name [--full] [--regex] <name>"); return; } string name = mainParams[3]; Predicate<SceneObjectGroup> searchPredicate; if (useRegex) { Regex nameRegex = new Regex(name); searchPredicate = so => nameRegex.IsMatch(so.Name); } else { searchPredicate = so => so.Name == name; } OutputSogsToConsole(searchPredicate, showFull); } private void HandleShowObjectByOwnerID(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; bool showFull = false; OptionSet options = new OptionSet().Add("full", v => showFull = v != null); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) { m_console.OutputFormat("Usage: show object owner <OwnerID>"); return; } UUID ownerID; if (!ConsoleUtil.TryParseConsoleUuid(m_console, mainParams[3], out ownerID)) return; Predicate<SceneObjectGroup> searchPredicate = so => so.OwnerID == ownerID && !so.IsAttachment; OutputSogsToConsole(searchPredicate, showFull); } private void HandleShowObjectByPos(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; bool showFull = false; OptionSet options = new OptionSet().Add("full", v => showFull = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 5) { m_console.OutputFormat("Usage: show object pos [--full] <start-coord> to <end-coord>"); return; } Vector3 startVector, endVector; if (!TryParseVectorRange(cmdparams.Skip(3).Take(3), out startVector, out endVector)) return; Predicate<SceneObjectGroup> searchPredicate = so => Util.IsInsideBox(so.AbsolutePosition, startVector, endVector); OutputSogsToConsole(searchPredicate, showFull); } private void HandleShowPartById(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; // bool showFull = false; OptionSet options = new OptionSet(); // options.Add("full", v => showFull = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) { //m_console.OutputFormat("Usage: show part id [--full] <UUID-or-localID>"); m_console.OutputFormat("Usage: show part id <UUID-or-localID>"); return; } UUID objectUuid; uint localId; if (!ConsoleUtil.TryParseConsoleId(m_console, mainParams[3], out objectUuid, out localId)) return; SceneObjectPart sop; if (localId == ConsoleUtil.LocalIdNotFound) sop = m_scene.GetSceneObjectPart(objectUuid); else sop = m_scene.GetSceneObjectPart(localId); if (sop == null) { // m_console.OutputFormat("No part found with uuid {0}", objectUuid); return; } StringBuilder sb = new StringBuilder(); AddScenePartReport(sb, sop, true); m_console.OutputFormat(sb.ToString()); } private void HandleShowPartByPos(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; // bool showFull = false; OptionSet options = new OptionSet(); // options.Add("full", v => showFull = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 5) { //m_console.OutputFormat("Usage: show part pos <start-coord> to <end-coord>"); m_console.OutputFormat("Usage: show part pos [--full] <start-coord> to <end-coord>"); return; } string rawConsoleStartVector = mainParams[3]; Vector3 startVector; if (!ConsoleUtil.TryParseConsoleMinVector(rawConsoleStartVector, out startVector)) { m_console.OutputFormat("Error: Start vector '{0}' does not have a valid format", rawConsoleStartVector); return; } string rawConsoleEndVector = mainParams[5]; Vector3 endVector; if (!ConsoleUtil.TryParseConsoleMaxVector(rawConsoleEndVector, out endVector)) { m_console.OutputFormat("Error: End vector '{0}' does not have a valid format", rawConsoleEndVector); return; } OutputSopsToConsole(sop => Util.IsInsideBox(sop.AbsolutePosition, startVector, endVector), true); } private void HandleShowPartByName(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; // bool showFull = false; bool useRegex = false; OptionSet options = new OptionSet(); // options.Add("full", v => showFull = v != null ); options.Add("regex", v => useRegex = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) { m_console.OutputFormat("Usage: show part name [--regex] <name>"); //m_console.OutputFormat("Usage: show part name [--full] [--regex] <name>"); return; } string name = mainParams[3]; Predicate<SceneObjectPart> searchPredicate; if (useRegex) { Regex nameRegex = new Regex(name); searchPredicate = sop => nameRegex.IsMatch(sop.Name); } else { searchPredicate = sop => sop.Name == name; } OutputSopsToConsole(searchPredicate, true); } private void HandleDumpObjectById(string module, string[] cmdparams) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; if (cmdparams.Length < 4) { m_console.OutputFormat("Usage: dump object id <UUID-or-localID>"); return; } UUID objectUuid; uint localId; if (!ConsoleUtil.TryParseConsoleId(m_console, cmdparams[3], out objectUuid, out localId)) return; SceneObjectGroup so; if (localId == ConsoleUtil.LocalIdNotFound) so = m_scene.GetSceneObjectGroup(objectUuid); else so = m_scene.GetSceneObjectGroup(localId); if (so == null) { // m_console.OutputFormat("No part found with uuid {0}", objectUuid); return; } // In case we found it via local ID. objectUuid = so.UUID; string fileName = string.Format("{0}.xml", objectUuid); if (!ConsoleUtil.CheckFileDoesNotExist(m_console, fileName)) return; using (XmlTextWriter xtw = new XmlTextWriter(fileName, Encoding.UTF8)) { xtw.Formatting = Formatting.Indented; SceneObjectSerializer.ToOriginalXmlFormat(so, xtw, true); } m_console.OutputFormat("Object dumped to file {0}", fileName); } /// <summary> /// Append a scene object report to an input StringBuilder /// </summary> /// <returns></returns> /// <param name='sb'></param> /// <param name='so'</param> /// <param name='showFull'> /// If true then information on all parts of an object is appended. /// If false then only summary information about an object is appended. /// </param> private StringBuilder AddSceneObjectReport(StringBuilder sb, SceneObjectGroup so, bool showFull) { if (showFull) { foreach (SceneObjectPart sop in so.Parts) { AddScenePartReport(sb, sop, false); sb.Append("\n"); } } else { AddSummarySceneObjectReport(sb, so); } return sb; } private StringBuilder AddSummarySceneObjectReport(StringBuilder sb, SceneObjectGroup so) { ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("Name", so.Name); cdl.AddRow("Description", so.Description); cdl.AddRow("Local ID", so.LocalId); cdl.AddRow("UUID", so.UUID); cdl.AddRow("Location", string.Format("{0} @ {1}", so.AbsolutePosition, so.Scene.Name)); cdl.AddRow("Parts", so.PrimCount); cdl.AddRow("Flags", so.RootPart.Flags); return sb.Append(cdl.ToString()); } /// <summary> /// Append a scene object part report to an input StringBuilder /// </summary> /// <returns></returns> /// <param name='sb'></param> /// <param name='sop'</param> /// <param name='showFull'> /// If true then information on each inventory item will be shown. /// If false then only summary inventory information is shown. /// </param> private StringBuilder AddScenePartReport(StringBuilder sb, SceneObjectPart sop, bool showFull) { ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("Name", sop.Name); cdl.AddRow("Description", sop.Description); cdl.AddRow("Local ID", sop.LocalId); cdl.AddRow("UUID", sop.UUID); cdl.AddRow("Location", string.Format("{0} @ {1}", sop.AbsolutePosition, sop.ParentGroup.Scene.Name)); cdl.AddRow( "Parent", sop.IsRoot ? "Is Root" : string.Format("{0} {1}", sop.ParentGroup.Name, sop.ParentGroup.UUID)); cdl.AddRow("Link number", sop.LinkNum); cdl.AddRow("Flags", sop.Flags); if (showFull) { PrimitiveBaseShape s = sop.Shape; cdl.AddRow("FlexiDrag", s.FlexiDrag); cdl.AddRow("FlexiEntry", s.FlexiEntry); cdl.AddRow("FlexiForce", string.Format("<{0},{1},{2}>", s.FlexiForceX, s.FlexiForceY, s.FlexiForceZ)); cdl.AddRow("FlexiGravity", s.FlexiGravity); cdl.AddRow("FlexiSoftness", s.FlexiSoftness); cdl.AddRow("HollowShape", s.HollowShape); cdl.AddRow( "LightColor", string.Format("<{0},{1},{2},{3}>", s.LightColorR, s.LightColorB, s.LightColorG, s.LightColorA)); cdl.AddRow("LightCutoff", s.LightCutoff); cdl.AddRow("LightEntry", s.LightEntry); cdl.AddRow("LightFalloff", s.LightFalloff); cdl.AddRow("LightIntensity", s.LightIntensity); cdl.AddRow("LightRadius", s.LightRadius); cdl.AddRow("Location (relative)", sop.RelativePosition); cdl.AddRow("Media", string.Format("{0} entries", s.Media != null ? s.Media.Count.ToString() : "n/a")); cdl.AddRow("PathBegin", s.PathBegin); cdl.AddRow("PathEnd", s.PathEnd); cdl.AddRow("PathCurve", s.PathCurve); cdl.AddRow("PathRadiusOffset", s.PathRadiusOffset); cdl.AddRow("PathRevolutions", s.PathRevolutions); cdl.AddRow("PathScale", string.Format("<{0},{1}>", s.PathScaleX, s.PathScaleY)); cdl.AddRow("PathSkew", string.Format("<{0},{1}>", s.PathShearX, s.PathShearY)); cdl.AddRow("FlexiDrag", s.PathSkew); cdl.AddRow("PathTaper", string.Format("<{0},{1}>", s.PathTaperX, s.PathTaperY)); cdl.AddRow("PathTwist", s.PathTwist); cdl.AddRow("PathTwistBegin", s.PathTwistBegin); cdl.AddRow("PCode", s.PCode); cdl.AddRow("ProfileBegin", s.ProfileBegin); cdl.AddRow("ProfileEnd", s.ProfileEnd); cdl.AddRow("ProfileHollow", s.ProfileHollow); cdl.AddRow("ProfileShape", s.ProfileShape); cdl.AddRow("ProjectionAmbiance", s.ProjectionAmbiance); cdl.AddRow("ProjectionEntry", s.ProjectionEntry); cdl.AddRow("ProjectionFocus", s.ProjectionFocus); cdl.AddRow("ProjectionFOV", s.ProjectionFOV); cdl.AddRow("ProjectionTextureUUID", s.ProjectionTextureUUID); cdl.AddRow("Rotation (Relative)", sop.RotationOffset); cdl.AddRow("Rotation (World)", sop.GetWorldRotation()); cdl.AddRow("Scale", s.Scale); cdl.AddRow( "SculptData", string.Format("{0} bytes", s.SculptData != null ? s.SculptData.Length.ToString() : "n/a")); cdl.AddRow("SculptEntry", s.SculptEntry); cdl.AddRow("SculptTexture", s.SculptTexture); cdl.AddRow("SculptType", s.SculptType); cdl.AddRow("State", s.State); // TODO, need to display more information about textures but in a compact format // to stop output becoming huge. for (int i = 0; i < sop.GetNumberOfSides(); i++) { Primitive.TextureEntryFace teFace = s.Textures.FaceTextures[i]; UUID textureID; if (teFace != null) textureID = teFace.TextureID; else textureID = s.Textures.DefaultTexture.TextureID; cdl.AddRow(string.Format("Face {0} texture ID", i), textureID); } //cdl.AddRow("Textures", string.Format("{0} entries", s.Textures. } object itemsOutput; if (showFull) { StringBuilder itemsSb = new StringBuilder("\n"); itemsOutput = AddScenePartItemsReport(itemsSb, sop.Inventory).ToString(); } else { itemsOutput = sop.Inventory.Count; } cdl.AddRow("Items", itemsOutput); return sb.Append(cdl.ToString()); } private StringBuilder AddScenePartItemsReport(StringBuilder sb, IEntityInventory inv) { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.Indent = 2; cdt.AddColumn("Name", 50); cdt.AddColumn("Type", 12); cdt.AddColumn("Running", 7); cdt.AddColumn("Item UUID", 36); cdt.AddColumn("Asset UUID", 36); foreach (TaskInventoryItem item in inv.GetInventoryItems()) { bool foundScriptInstance, scriptRunning; foundScriptInstance = SceneObjectPartInventory.TryGetScriptInstanceRunning(m_scene, item, out scriptRunning); cdt.AddRow( item.Name, ((InventoryType)item.InvType).ToString(), foundScriptInstance ? scriptRunning.ToString() : "n/a", item.ItemID.ToString(), item.AssetID.ToString()); } return sb.Append(cdt.ToString()); } private void HandleDeleteObject(string module, string[] cmd) { if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene)) return; if (cmd.Length < 3) return; string mode = cmd[2]; string o = ""; if (mode != "outside") { if (cmd.Length < 4) return; o = cmd[3]; } List<SceneObjectGroup> deletes = null; UUID match; bool requireConfirmation = true; switch (mode) { case "owner": if (!UUID.TryParse(o, out match)) return; deletes = new List<SceneObjectGroup>(); m_scene.ForEachSOG(delegate (SceneObjectGroup g) { if (g.OwnerID == match && !g.IsAttachment) deletes.Add(g); }); // if (deletes.Count == 0) // m_console.OutputFormat("No objects were found with owner {0}", match); break; case "creator": if (!UUID.TryParse(o, out match)) return; deletes = new List<SceneObjectGroup>(); m_scene.ForEachSOG(delegate (SceneObjectGroup g) { if (g.RootPart.CreatorID == match && !g.IsAttachment) deletes.Add(g); }); // if (deletes.Count == 0) // m_console.OutputFormat("No objects were found with creator {0}", match); break; case "id": UUID uuid; uint localId; if (!ConsoleUtil.TryParseConsoleId(m_console, o, out uuid, out localId)) return; requireConfirmation = false; deletes = new List<SceneObjectGroup>(); SceneObjectGroup so; if (localId == ConsoleUtil.LocalIdNotFound) so = m_scene.GetSceneObjectGroup(uuid); else so = m_scene.GetSceneObjectGroup(localId); if (so!= null && !so.IsAttachment) deletes.Add(so); // if (deletes.Count == 0) // m_console.OutputFormat("No objects were found with uuid {0}", match); break; case "name": deletes = GetDeleteCandidatesByName(module, cmd); break; case "outside": deletes = new List<SceneObjectGroup>(); m_scene.ForEachSOG(delegate (SceneObjectGroup g) { SceneObjectPart rootPart = g.RootPart; bool delete = false; if (rootPart.GroupPosition.Z < 0.0 || rootPart.GroupPosition.Z > 10000.0) { delete = true; } else { ILandObject parcel = m_scene.LandChannel.GetLandObject(rootPart.GroupPosition.X, rootPart.GroupPosition.Y); if (parcel == null || parcel.LandData.Name == "NO LAND") delete = true; } if (delete && !g.IsAttachment && !deletes.Contains(g)) deletes.Add(g); }); if (deletes.Count == 0) m_console.OutputFormat("No objects were found outside region bounds"); break; case "pos": deletes = GetDeleteCandidatesByPos(module, cmd); break; default: m_console.OutputFormat("Unrecognized mode {0}", mode); return; } if (deletes == null || deletes.Count <= 0) return; if (requireConfirmation) { string response = MainConsole.Instance.CmdPrompt( string.Format( "Are you sure that you want to delete {0} objects from {1}", deletes.Count, m_scene.RegionInfo.RegionName), "y/N"); if (response.ToLower() != "y") { MainConsole.Instance.OutputFormat( "Aborting delete of {0} objects from {1}", deletes.Count, m_scene.RegionInfo.RegionName); return; } } m_console.OutputFormat("Deleting {0} objects in {1}", deletes.Count, m_scene.RegionInfo.RegionName); foreach (SceneObjectGroup g in deletes) { m_console.OutputFormat("Deleting object {0} {1}", g.UUID, g.Name); m_scene.DeleteSceneObject(g, false); } } private List<SceneObjectGroup> GetDeleteCandidatesByName(string module, string[] cmdparams) { bool useRegex = false; OptionSet options = new OptionSet().Add("regex", v=> useRegex = v != null ); List<string> mainParams = options.Parse(cmdparams); if (mainParams.Count < 4) { m_console.OutputFormat("Usage: delete object name [--regex] <name>"); return null; } string name = mainParams[3]; List<SceneObjectGroup> sceneObjects = new List<SceneObjectGroup>(); Action<SceneObjectGroup> searchAction; if (useRegex) { Regex nameRegex = new Regex(name); searchAction = so => { if (nameRegex.IsMatch(so.Name)) { sceneObjects.Add(so); }}; } else { searchAction = so => { if (so.Name == name) { sceneObjects.Add(so); }}; } m_scene.ForEachSOG(searchAction); if (sceneObjects.Count == 0) m_console.OutputFormat("No objects with name {0} found in {1}", name, m_scene.RegionInfo.RegionName); return sceneObjects; } /// <summary> /// Get scene object delete candidates by position /// </summary> /// <param name='module'></param> /// <param name='cmdparams'></param> /// <returns>null if parsing failed on one of the arguments, otherwise a list of objects to delete. If there /// are no objects to delete then the list will be empty./returns> private List<SceneObjectGroup> GetDeleteCandidatesByPos(string module, string[] cmdparams) { if (cmdparams.Length < 5) { m_console.OutputFormat("Usage: delete object pos <start-coord> to <end-coord>"); return null; } Vector3 startVector, endVector; if (!TryParseVectorRange(cmdparams.Skip(3).Take(3), out startVector, out endVector)) return null; return m_scene.GetSceneObjectGroups().FindAll( so => !so.IsAttachment && Util.IsInsideBox(so.AbsolutePosition, startVector, endVector)); } private bool TryParseVectorRange(IEnumerable<string> rawComponents, out Vector3 startVector, out Vector3 endVector) { string rawConsoleStartVector = rawComponents.Take(1).Single(); if (!ConsoleUtil.TryParseConsoleMinVector(rawConsoleStartVector, out startVector)) { m_console.OutputFormat("Error: Start vector '{0}' does not have a valid format", rawConsoleStartVector); endVector = Vector3.Zero; return false; } string rawConsoleEndVector = rawComponents.Skip(1).Take(1).Single(); if (!ConsoleUtil.TryParseConsoleMaxVector(rawConsoleEndVector, out endVector)) { m_console.OutputFormat("Error: End vector '{0}' does not have a valid format", rawConsoleEndVector); return false; } return true; } } }
// DateWithOperators.cs (c) 2003 Kari Laitinen // The Date class in this file works in the same way as // class Date in Date.cs. In this version of the class // operators < and > are overloaded. These operators // replace the methods is_earlier_than() and is_later_than() // of the "real" class Date. // 04.09.2003 C# file created. // 04.09.2003 Last modification. using System ; class Date { protected int this_day = 1 ; protected int this_month = 1 ; protected int this_year = 1970 ; protected char date_print_format = 'E' ; public Date() {} public Date( int given_day, int given_month, int given_year, char given_print_format ) { this_day = given_day ; this_month = given_month ; this_year = given_year ; date_print_format = given_print_format ; } public Date( int given_day, int given_month, int given_year ) { this_day = given_day ; this_month = given_month ; this_year = given_year ; } public Date( string date_as_string ) { // This constructor accepts date strings in two formats: // // MM/DD/YYYY is the American format. // DD.MM.YYYY is the format used in Europe. // // Member variable date_print_format will be set either // to value 'A' or 'E'. This value will be used to select // correct print format when this date object is printed. if ( date_as_string[ 2 ] == '/' ) { date_print_format = 'A' ; // American format this_day = Convert.ToInt32( date_as_string.Substring( 3, 2 ) ) ; this_month = Convert.ToInt32( date_as_string.Substring( 0, 2 ) ) ; } else { date_print_format = 'E' ; // European format this_day = Convert.ToInt32( date_as_string.Substring( 0, 2 ) ) ; this_month = Convert.ToInt32( date_as_string.Substring( 3, 2 ) ) ; } this_year = Convert.ToInt32( date_as_string.Substring( 6, 4 ) ) ; } public int day() { return this_day ; } public int month() { return this_month ; } public int year() { return this_year ; } public char get_date_print_format() { return date_print_format ; } public bool is_last_day_of_month() { bool it_is_last_day_of_month = false ; if ( this_day > 27 ) { if ( this_day == 31 ) { it_is_last_day_of_month = true ; } else if ( ( this_day == 30 ) && ( this_month == 2 || this_month == 4 || this_month == 6 || this_month == 9 || this_month == 11 ) ) { it_is_last_day_of_month = true ; } else if ( this_day == 29 && this_month == 2 ) { it_is_last_day_of_month = true ; } else if ( this_day == 28 && this_month == 2 && ! this_is_a_leap_year() ) { it_is_last_day_of_month = true ; } } return it_is_last_day_of_month ; } public bool this_is_a_leap_year() { bool return_code = false ; if ( this_year % 4 == 0 ) { // Years which are equally divisible by 4 and which // are not full centuries are leap years. Centuries // equally divisible by 4 are, however, leap years. if ( this_year % 100 == 0 ) { int century = this_year / 100 ; if ( century % 4 == 0 ) { return_code = true ; } } else { return_code = true ; } } return return_code ; } public bool is_within_dates( Date earlier_date, Date later_date ) { return (( equals( earlier_date ) ) || ( equals( later_date ) ) || ( ( this > earlier_date ) && ( this < later_date ) ) ) ; } public int index_for_day_of_week() { // day_index will get a value in the range from 0 to 6, // 0 meaning Monday and 6 meaning Sunday. int day_index = 0 ; Date known_date = new Date( 6, 10, 1997 ) ; // Oct. 6, 1997 is Monday. if ( known_date > this ) { while ( known_date.is_not_equal_to( this ) ) { if ( day_index > 0 ) { day_index -- ; } else { day_index = 6 ; } known_date.decrement() ; } } else { while ( known_date.is_not_equal_to( this ) ) { if ( day_index < 6 ) { day_index ++ ; } else { day_index = 0 ; } known_date.increment() ; } } return day_index ; } public string get_day_of_week() { String[] days_of_week = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" } ; return days_of_week[ index_for_day_of_week() ] ; } public void increment() { if ( is_last_day_of_month() ) { this_day = 1 ; if ( this_month < 12 ) { this_month ++ ; } else { this_month = 1 ; this_year ++ ; } } else { this_day ++ ; } } public void decrement() { if ( this_day > 1 ) { this_day -- ; } else { if ( this_month == 5 || this_month == 7 || this_month == 10 || this_month == 12 ) { this_day = 30 ; this_month -- ; } else if ( this_month == 2 || this_month == 4 || this_month == 6 || this_month == 8 || this_month == 9 || this_month == 11 ) { this_day = 31 ; this_month -- ; } else if ( this_month == 1 ) { this_day = 31 ; this_month = 12 ; this_year -- ; } else if ( this_month == 3 ) { this_month = 2 ; if ( this_is_a_leap_year() ) { this_day = 29 ; } else { this_day = 28 ; } } } } public void get_distance_to( Date another_date, out int years_of_distance, out int months_of_distance, out int days_of_distance ) { Date start_date ; Date end_date ; int start_day, end_day ; if ( this < another_date ) { start_date = this ; end_date = another_date ; } else { start_date = another_date ; end_date = this ; } // We will suppose that day 30 is the last day of every // month. This way we minimize calculation errors. if ( start_date.is_last_day_of_month() || ( start_date.day() == 28 && start_date.month() == 2 ) ) { start_day = 30 ; } else { start_day = start_date.day() ; } if ( end_date.is_last_day_of_month() || ( end_date.day() == 28 && end_date.month() == 2 ) ) { end_day = 30 ; } else { end_day = end_date.day() ; } years_of_distance = end_date.year() - start_date.year() ; months_of_distance = end_date.month() - start_date.month() ; days_of_distance = end_day - start_day ; if ( days_of_distance < 0 ) { months_of_distance -- ; days_of_distance = days_of_distance + 30 ; } if ( months_of_distance < 0 ) { years_of_distance -- ; months_of_distance = months_of_distance + 12 ; } } public int get_week_number() { // January 1, 1883 was a Monday with week number 1. // January 1, 1990 was a Monday with week number 1. Date date_to_increment = new Date( 1, 1, 1883 ) ; int week_number = 1 ; int local_index_for_day_of_week = 0 ; // 0 means Monday while ( date_to_increment < this ) { date_to_increment.increment() ; if ( local_index_for_day_of_week == 6 ) // 6 means Sunday { local_index_for_day_of_week = 0 ; // back to Monday if ( week_number < 52 ) { week_number ++ ; } else if ( week_number == 52 ) { if ( date_to_increment.day() <= 28 && date_to_increment.month() == 12 ) { week_number = 53 ; } else { week_number = 1 ; } } else // must be week_number 53 { week_number = 1 ; } } else { local_index_for_day_of_week ++ ; } } return week_number ; } public bool equals( Date another_date ) { return ( this_day == another_date.day() && this_month == another_date.month() && this_year == another_date.year() ) ; } public bool is_not_equal_to( Date another_date ) { return ( this_day != another_date.day() || this_month != another_date.month() || this_year != another_date.year() ) ; } public static bool operator<( Date left_side_date, Date right_side_date ) { return (( left_side_date.year() < right_side_date.year() ) || ( ( left_side_date.year() == right_side_date.year() ) && ( left_side_date.month() < right_side_date.month() ) ) || ( ( left_side_date.year() == right_side_date.year() ) && ( left_side_date.month() == right_side_date.month() ) && ( left_side_date.day() < right_side_date.day() ) ) ) ; } public static bool operator>( Date left_side_date, Date right_side_date ) { return (( left_side_date.year() > right_side_date.year() ) || ( ( left_side_date.year() == right_side_date.year() ) && ( left_side_date.month() > right_side_date.month() ) ) || ( ( left_side_date.year() == right_side_date.year() ) && ( left_side_date.month() == right_side_date.month() ) && ( left_side_date.day() > right_side_date.day() ) ) ) ; } public override string ToString() { String day_as_string = this_day.ToString( "D2" ) ; String month_as_string = this_month.ToString( "D2" ) ; String year_as_string = this_year.ToString() ; string string_to_return ; if ( date_print_format == 'A' ) { string_to_return = month_as_string + "/" + day_as_string + "/" + year_as_string ; } else { string_to_return = day_as_string + "." + month_as_string + "." + year_as_string ; } return string_to_return ; } }
/* 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 System.IO; using System.Linq.Expressions; using System.Web.UI; using Sitecore.Data.Items; using Sitecore.Web.UI; namespace Glass.Mapper.Sc.Web.Ui { /// <summary> /// Class AbstractGlassUserControl /// </summary> public class AbstractGlassUserControl : UserControl { private TextWriter _writer; protected TextWriter Output { get { return _writer ?? this.Response.Output; } } /// <summary> /// Initializes a new instance of the <see cref="AbstractGlassUserControl"/> class. /// </summary> /// <param name="context">The context.</param> public AbstractGlassUserControl(ISitecoreContext context, IGlassHtml glassHtml) { _glassHtml = glassHtml; _sitecoreContext = context; } public AbstractGlassUserControl(ISitecoreContext context) : this(context, new GlassHtml(context)) { } /// <summary> /// Initializes a new instance of the <see cref="AbstractGlassUserControl"/> class. /// </summary> public AbstractGlassUserControl() : this(Sc.SitecoreContext.GetFromHttpContext()) { } private ISitecoreContext _sitecoreContext; private IGlassHtml _glassHtml; /// <summary> /// Gets a value indicating whether this instance is in editing mode. /// </summary> /// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value> public bool IsInEditingMode { get { return Sc.GlassHtml.IsInEditingMode; } } /// <summary> /// Represents the current Sitecore context /// </summary> /// <value>The sitecore context.</value> public ISitecoreContext SitecoreContext { get { return _sitecoreContext; } } /// <summary> /// Access to rendering helpers /// </summary> /// <value>The glass HTML.</value> protected virtual IGlassHtml GlassHtml { get { return _glassHtml; } set { _glassHtml = value; } } /// <summary> /// The custom data source for the sublayout /// </summary> /// <value>The data source.</value> public string DataSource { get { WebControl parent = Parent as WebControl; if (parent == null) return string.Empty; return parent.DataSource; } } /// <summary> /// Returns either the item specified by the DataSource or the current context item /// </summary> /// <value>The layout item.</value> public Item LayoutItem { get { if (DataSourceItem == null) return global::Sitecore.Context.Item; else return DataSourceItem; } } public Item DataSourceItem { get { if (DataSource.IsNullOrEmpty()) return null; else return global::Sitecore.Context.Database.GetItem(DataSource); } } /// <summary> /// Makes a field editable via the Page Editor. Use the Model property as the target item, e.g. model =&gt; model.Title where Title is field name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">The model.</param> /// <param name="field">The field.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public string Editable<T>(T model, Expression<Func<T, object>> field, object parameters = null) { return GlassHtml.Editable(model, field, parameters); } /// <summary> /// Makes a field editable via the Page Editor. Use the Model property as the target item, e.g. model =&gt; model.Title where Title is field name. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model">The model.</param> /// <param name="field">The field.</param> /// <param name="standardOutput">The standard output.</param> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public string Editable<T>(T model, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null) { return GlassHtml.Editable(model, field, standardOutput, parameters); } /// <summary> /// Renders an image allowing simple page editor support /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model that contains the image field</param> /// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param> /// <param name="parameters">Image parameters, e.g. width, height</param> /// <param name="isEditable">Indicates if the field should be editable</param> /// <param name="outputHeightWidth">Indicates if the height and width attributes should be outputted when rendering the image</param> /// <returns></returns> public virtual string RenderImage<T>(T model, Expression<Func<T, object>> field, object parameters = null, bool isEditable = false, bool outputHeightWidth = true) { return GlassHtml.RenderImage(model, field, parameters, isEditable, outputHeightWidth); } /// <summary> /// Render HTML for a link with contents /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <returns></returns> public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false) { return GlassHtml.BeginRenderLink(model, field, this.Output, attributes, isEditable); } /// <summary> /// Render HTML for a link /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="model">The model</param> /// <param name="field">The link field to user</param> /// <param name="attributes">Any additional link attributes</param> /// <param name="isEditable">Make the link editable</param> /// <param name="contents">Content to override the default decription or item name</param> /// <returns></returns> public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents=null) { return GlassHtml.RenderLink(model, field, attributes, isEditable, contents); } public override void RenderControl(HtmlTextWriter writer) { this._writer = writer; base.RenderControl(writer); } } }
using System; using System.Collections; using System.Data.SqlTypes; using System.Reflection; using System.Web; using Inform; namespace Xenosynth.Modules { /// <summary> /// Registration information for a Module that extends the Xenosynth Framework. This class supports the Xenosynth Framework and is not intended to be used directly from your code. /// </summary> [TypeMapping(TableName="xs_RegisteredModules")] public class RegisteredModule { [MemberMapping(PrimaryKey=true, ColumnName="ID")] private Guid id; [MemberMapping(ColumnName="Name", Length=250)] private string name; [MemberMapping(ColumnName="Description", Length=500)] private string description; [MemberMapping(ColumnName="ResourceFolder", Length=50)] private string resourceFolder; [MemberMapping(ColumnName="ClassName", Length=100)] private string className; [MemberMapping(ColumnName = "InitOrder")] private int initOrder; [MemberMapping(ColumnName = "Enabled")] private bool enabled; private static Hashtable modules = new Hashtable(); /// <summary> /// Constructs a new RegisteredModule. /// </summary> public RegisteredModule() { id = Guid.Empty; } /// <summary> /// A unique indentifier for the registered module. /// </summary> public Guid ID { get { return id; } } /// <summary> /// The user-friendly name of the module. /// </summary> public string Name { set { name = value; } get { return name; } } /// <summary> /// A description of the module. /// </summary> public string Description { set { description = value; } get { return description; } } /// <summary> /// The location of the resource folder for the module. /// </summary> public string ResourceFolder { set { resourceFolder = value; } get { return resourceFolder; } } /// <summary> /// The name of the class that implements IModule for this registered module. Modules that do not implement an <see cref="IModule"/> can leave this null. /// </summary> public string ClassName { set { className = value; } get { return className; } } /// <summary> /// The initiliation order for the module. Lower numbers are initialized first. /// </summary> public int InitOrder { set { initOrder = value; } get { return initOrder; } } /// <summary> /// Whether the module should be initialized. If false, the module will not get loaded or have its init and start methods called. /// </summary> public bool IsEnabled { set { enabled = value; } get { return enabled; } } /// <summary> /// If the module has been loaded and successfully initialized. /// </summary> public bool IsInitialized { get { return modules.ContainsKey(ID); } } /// <summary> /// Returns the actual instance of the IModule if initialized. /// </summary> public IModule Instance { get { IModule module = (IModule)modules[ID]; if(module == null){ throw new XenosynthException("Module '" + ID + "' not initialized."); } return module; } } /// <summary> /// Returns the url for the module's entry adminstration page. /// </summary> public string DefaultUrl { get { if (HasRegisteredModuleClass && IsInitialized) { return Instance.DefaultUrl; } else { return "~/Modules/" + ResourceFolder + "/default.aspx"; } } } /// <summary> /// Returns the url for the module's congifuration page. /// </summary> public string ConfigurationUrl { get { if (HasRegisteredModuleClass && IsInitialized) { return Instance.ConfigurationUrl; } else { return "~/Modules/" + ResourceFolder + "/default.aspx"; } } } /// <summary> /// The assembly name for the module. /// </summary> public string AssemblyName { get { return className.Substring(className.IndexOf(",")); } } /// <summary> /// Whether the registered module has an IModule. /// </summary> public bool HasRegisteredModuleClass { get { return ClassName != null && ClassName.Trim().Length > 0; } } private IModule CreateModuleInstance() { Type t = Type.GetType(ClassName); if (t == null) { throw new XenosynthException("Could not locate module class: " + ClassName); } return (IModule)Activator.CreateInstance(t); } /// <summary> /// Initializes the registered module. /// </summary> /// <param name="application"> /// A <see cref="HttpApplication"/> /// </param> public void Init(HttpApplication application){ if(HasRegisteredModuleClass){ IModule module = CreateModuleInstance(); modules[this.ID] = module; module.Init(application); } } /// <summary> /// Starts the registered module. /// </summary> public void Start(){ if(HasRegisteredModuleClass){ IModule module = CreateModuleInstance(); module.Start(); } } /// <summary> /// Inserts this registered module in to the database. /// </summary> public void Insert(){ DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); //TODO: Check ID is EmptyGuid? this.id = Guid.NewGuid(); ds.Insert(this); } /// <summary> /// Updates this registered module in the database. /// </summary> public void Update(){ DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); ds.Update(this); } /// <summary> /// Deletes this registered module from the database. /// </summary> public void Delete(){ DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); ds.Delete(this); } /// <summary> /// Finds the registered module from the database by ID. /// </summary> /// <param name="registeredModuleID"> /// A <see cref="Guid"/> /// </param> /// <returns> /// A <see cref="RegisteredModule"/> /// </returns> public static RegisteredModule FindByID(Guid registeredModuleID) { //TODO: Push internal and add cache? DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); return (RegisteredModule)ds.FindByPrimaryKey(typeof(RegisteredModule), registeredModuleID); } /// <summary> /// Finds all registered modules in the database. /// </summary> /// <returns> /// A <see cref="IList"/> of <see cref="RegisteredModule"/> of /// </returns> public static IList FindAll(){ DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); IFindCollectionCommand cmd = ds.CreateFindCollectionCommand(typeof(RegisteredModule), "ORDER BY InitOrder"); return cmd.Execute(); } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A virtual network /// First published in XenServer 4.0. /// </summary> public partial class Network : XenObject<Network> { #region Constructors public Network() { } public Network(string uuid, string name_label, string name_description, List<network_operations> allowed_operations, Dictionary<string, network_operations> current_operations, List<XenRef<VIF>> VIFs, List<XenRef<PIF>> PIFs, long MTU, Dictionary<string, string> other_config, string bridge, bool managed, Dictionary<string, XenRef<Blob>> blobs, string[] tags, network_default_locking_mode default_locking_mode, Dictionary<XenRef<VIF>, string> assigned_ips, List<network_purpose> purpose) { this.uuid = uuid; this.name_label = name_label; this.name_description = name_description; this.allowed_operations = allowed_operations; this.current_operations = current_operations; this.VIFs = VIFs; this.PIFs = PIFs; this.MTU = MTU; this.other_config = other_config; this.bridge = bridge; this.managed = managed; this.blobs = blobs; this.tags = tags; this.default_locking_mode = default_locking_mode; this.assigned_ips = assigned_ips; this.purpose = purpose; } /// <summary> /// Creates a new Network from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Network(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Network from a Proxy_Network. /// </summary> /// <param name="proxy"></param> public Network(Proxy_Network proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Network. /// </summary> public override void UpdateFrom(Network update) { uuid = update.uuid; name_label = update.name_label; name_description = update.name_description; allowed_operations = update.allowed_operations; current_operations = update.current_operations; VIFs = update.VIFs; PIFs = update.PIFs; MTU = update.MTU; other_config = update.other_config; bridge = update.bridge; managed = update.managed; blobs = update.blobs; tags = update.tags; default_locking_mode = update.default_locking_mode; assigned_ips = update.assigned_ips; purpose = update.purpose; } internal void UpdateFrom(Proxy_Network proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; name_label = proxy.name_label == null ? null : proxy.name_label; name_description = proxy.name_description == null ? null : proxy.name_description; allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<network_operations>(proxy.allowed_operations); current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_network_operations(proxy.current_operations); VIFs = proxy.VIFs == null ? null : XenRef<VIF>.Create(proxy.VIFs); PIFs = proxy.PIFs == null ? null : XenRef<PIF>.Create(proxy.PIFs); MTU = proxy.MTU == null ? 0 : long.Parse(proxy.MTU); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); bridge = proxy.bridge == null ? null : proxy.bridge; managed = (bool)proxy.managed; blobs = proxy.blobs == null ? null : Maps.convert_from_proxy_string_XenRefBlob(proxy.blobs); tags = proxy.tags == null ? new string[] {} : (string [])proxy.tags; default_locking_mode = proxy.default_locking_mode == null ? (network_default_locking_mode) 0 : (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)proxy.default_locking_mode); assigned_ips = proxy.assigned_ips == null ? null : Maps.convert_from_proxy_XenRefVIF_string(proxy.assigned_ips); purpose = proxy.purpose == null ? null : Helper.StringArrayToEnumList<network_purpose>(proxy.purpose); } public Proxy_Network ToProxy() { Proxy_Network result_ = new Proxy_Network(); result_.uuid = uuid ?? ""; result_.name_label = name_label ?? ""; result_.name_description = name_description ?? ""; result_.allowed_operations = allowed_operations == null ? new string[] {} : Helper.ObjectListToStringArray(allowed_operations); result_.current_operations = Maps.convert_to_proxy_string_network_operations(current_operations); result_.VIFs = VIFs == null ? new string[] {} : Helper.RefListToStringArray(VIFs); result_.PIFs = PIFs == null ? new string[] {} : Helper.RefListToStringArray(PIFs); result_.MTU = MTU.ToString(); result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.bridge = bridge ?? ""; result_.managed = managed; result_.blobs = Maps.convert_to_proxy_string_XenRefBlob(blobs); result_.tags = tags; result_.default_locking_mode = network_default_locking_mode_helper.ToString(default_locking_mode); result_.assigned_ips = Maps.convert_to_proxy_XenRefVIF_string(assigned_ips); result_.purpose = purpose == null ? new string[] {} : Helper.ObjectListToStringArray(purpose); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Network /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("name_label")) name_label = Marshalling.ParseString(table, "name_label"); if (table.ContainsKey("name_description")) name_description = Marshalling.ParseString(table, "name_description"); if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList<network_operations>(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) current_operations = Maps.convert_from_proxy_string_network_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VIFs")) VIFs = Marshalling.ParseSetRef<VIF>(table, "VIFs"); if (table.ContainsKey("PIFs")) PIFs = Marshalling.ParseSetRef<PIF>(table, "PIFs"); if (table.ContainsKey("MTU")) MTU = Marshalling.ParseLong(table, "MTU"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("bridge")) bridge = Marshalling.ParseString(table, "bridge"); if (table.ContainsKey("managed")) managed = Marshalling.ParseBool(table, "managed"); if (table.ContainsKey("blobs")) blobs = Maps.convert_from_proxy_string_XenRefBlob(Marshalling.ParseHashTable(table, "blobs")); if (table.ContainsKey("tags")) tags = Marshalling.ParseStringArray(table, "tags"); if (table.ContainsKey("default_locking_mode")) default_locking_mode = (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), Marshalling.ParseString(table, "default_locking_mode")); if (table.ContainsKey("assigned_ips")) assigned_ips = Maps.convert_from_proxy_XenRefVIF_string(Marshalling.ParseHashTable(table, "assigned_ips")); if (table.ContainsKey("purpose")) purpose = Helper.StringArrayToEnumList<network_purpose>(Marshalling.ParseStringArray(table, "purpose")); } public bool DeepEquals(Network other, bool ignoreCurrentOperations) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) return false; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._name_label, other._name_label) && Helper.AreEqual2(this._name_description, other._name_description) && Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && Helper.AreEqual2(this._VIFs, other._VIFs) && Helper.AreEqual2(this._PIFs, other._PIFs) && Helper.AreEqual2(this._MTU, other._MTU) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._bridge, other._bridge) && Helper.AreEqual2(this._managed, other._managed) && Helper.AreEqual2(this._blobs, other._blobs) && Helper.AreEqual2(this._tags, other._tags) && Helper.AreEqual2(this._default_locking_mode, other._default_locking_mode) && Helper.AreEqual2(this._assigned_ips, other._assigned_ips) && Helper.AreEqual2(this._purpose, other._purpose); } internal static List<Network> ProxyArrayToObjectList(Proxy_Network[] input) { var result = new List<Network>(); foreach (var item in input) result.Add(new Network(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Network server) { if (opaqueRef == null) { var reference = create(session, this); return reference == null ? null : reference.opaque_ref; } else { if (!Helper.AreEqual2(_name_label, server._name_label)) { Network.set_name_label(session, opaqueRef, _name_label); } if (!Helper.AreEqual2(_name_description, server._name_description)) { Network.set_name_description(session, opaqueRef, _name_description); } if (!Helper.AreEqual2(_MTU, server._MTU)) { Network.set_MTU(session, opaqueRef, _MTU); } if (!Helper.AreEqual2(_other_config, server._other_config)) { Network.set_other_config(session, opaqueRef, _other_config); } if (!Helper.AreEqual2(_tags, server._tags)) { Network.set_tags(session, opaqueRef, _tags); } return null; } } /// <summary> /// Get a record containing the current state of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Network get_record(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_record(session.opaque_ref, _network); else return new Network(session.proxy.network_get_record(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get a reference to the network instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Network> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Network>.Create(session.proxy.network_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Create a new network instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Network> create(Session session, Network _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_create(session.opaque_ref, _record); else return XenRef<Network>.Create(session.proxy.network_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Create a new network instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, Network _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_create(session.opaque_ref, _record); else return XenRef<Task>.Create(session.proxy.async_network_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified network instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static void destroy(Session session, string _network) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_destroy(session.opaque_ref, _network); else session.proxy.network_destroy(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Destroy the specified network instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static XenRef<Task> async_destroy(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_destroy(session.opaque_ref, _network); else return XenRef<Task>.Create(session.proxy.async_network_destroy(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get all the network instances with the given label. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_label">label of object to return</param> public static List<XenRef<Network>> get_by_name_label(Session session, string _label) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_by_name_label(session.opaque_ref, _label); else return XenRef<Network>.Create(session.proxy.network_get_by_name_label(session.opaque_ref, _label ?? "").parse()); } /// <summary> /// Get the uuid field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_uuid(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_uuid(session.opaque_ref, _network); else return session.proxy.network_get_uuid(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Get the name/label field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_name_label(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_name_label(session.opaque_ref, _network); else return session.proxy.network_get_name_label(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Get the name/description field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_name_description(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_name_description(session.opaque_ref, _network); else return session.proxy.network_get_name_description(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Get the allowed_operations field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<network_operations> get_allowed_operations(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_allowed_operations(session.opaque_ref, _network); else return Helper.StringArrayToEnumList<network_operations>(session.proxy.network_get_allowed_operations(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the current_operations field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<string, network_operations> get_current_operations(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_current_operations(session.opaque_ref, _network); else return Maps.convert_from_proxy_string_network_operations(session.proxy.network_get_current_operations(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the VIFs field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<XenRef<VIF>> get_VIFs(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_vifs(session.opaque_ref, _network); else return XenRef<VIF>.Create(session.proxy.network_get_vifs(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the PIFs field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<XenRef<PIF>> get_PIFs(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_pifs(session.opaque_ref, _network); else return XenRef<PIF>.Create(session.proxy.network_get_pifs(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the MTU field of the given network. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static long get_MTU(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_mtu(session.opaque_ref, _network); else return long.Parse(session.proxy.network_get_mtu(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the other_config field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<string, string> get_other_config(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_other_config(session.opaque_ref, _network); else return Maps.convert_from_proxy_string_string(session.proxy.network_get_other_config(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the bridge field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string get_bridge(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_bridge(session.opaque_ref, _network); else return session.proxy.network_get_bridge(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Get the managed field of the given network. /// First published in XenServer 7.2. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static bool get_managed(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_managed(session.opaque_ref, _network); else return (bool)session.proxy.network_get_managed(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Get the blobs field of the given network. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<string, XenRef<Blob>> get_blobs(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_blobs(session.opaque_ref, _network); else return Maps.convert_from_proxy_string_XenRefBlob(session.proxy.network_get_blobs(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the tags field of the given network. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static string[] get_tags(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_tags(session.opaque_ref, _network); else return (string [])session.proxy.network_get_tags(session.opaque_ref, _network ?? "").parse(); } /// <summary> /// Get the default_locking_mode field of the given network. /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static network_default_locking_mode get_default_locking_mode(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_default_locking_mode(session.opaque_ref, _network); else return (network_default_locking_mode)Helper.EnumParseDefault(typeof(network_default_locking_mode), (string)session.proxy.network_get_default_locking_mode(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the assigned_ips field of the given network. /// First published in XenServer 6.5. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static Dictionary<XenRef<VIF>, string> get_assigned_ips(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_assigned_ips(session.opaque_ref, _network); else return Maps.convert_from_proxy_XenRefVIF_string(session.proxy.network_get_assigned_ips(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Get the purpose field of the given network. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> public static List<network_purpose> get_purpose(Session session, string _network) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_purpose(session.opaque_ref, _network); else return Helper.StringArrayToEnumList<network_purpose>(session.proxy.network_get_purpose(session.opaque_ref, _network ?? "").parse()); } /// <summary> /// Set the name/label field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_label">New value to set</param> public static void set_name_label(Session session, string _network, string _label) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_set_name_label(session.opaque_ref, _network, _label); else session.proxy.network_set_name_label(session.opaque_ref, _network ?? "", _label ?? "").parse(); } /// <summary> /// Set the name/description field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_description">New value to set</param> public static void set_name_description(Session session, string _network, string _description) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_set_name_description(session.opaque_ref, _network, _description); else session.proxy.network_set_name_description(session.opaque_ref, _network ?? "", _description ?? "").parse(); } /// <summary> /// Set the MTU field of the given network. /// First published in XenServer 5.6. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_mtu">New value to set</param> public static void set_MTU(Session session, string _network, long _mtu) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_set_mtu(session.opaque_ref, _network, _mtu); else session.proxy.network_set_mtu(session.opaque_ref, _network ?? "", _mtu.ToString()).parse(); } /// <summary> /// Set the other_config field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _network, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_set_other_config(session.opaque_ref, _network, _other_config); else session.proxy.network_set_other_config(session.opaque_ref, _network ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given network. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _network, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_add_to_other_config(session.opaque_ref, _network, _key, _value); else session.proxy.network_add_to_other_config(session.opaque_ref, _network ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given network. If the key is not in that Map, then do nothing. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _network, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_remove_from_other_config(session.opaque_ref, _network, _key); else session.proxy.network_remove_from_other_config(session.opaque_ref, _network ?? "", _key ?? "").parse(); } /// <summary> /// Set the tags field of the given network. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_tags">New value to set</param> public static void set_tags(Session session, string _network, string[] _tags) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_set_tags(session.opaque_ref, _network, _tags); else session.proxy.network_set_tags(session.opaque_ref, _network ?? "", _tags).parse(); } /// <summary> /// Add the given value to the tags field of the given network. If the value is already in that Set, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">New value to add</param> public static void add_tags(Session session, string _network, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_add_tags(session.opaque_ref, _network, _value); else session.proxy.network_add_tags(session.opaque_ref, _network ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given value from the tags field of the given network. If the value is not in that Set, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">Value to remove</param> public static void remove_tags(Session session, string _network, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_remove_tags(session.opaque_ref, _network, _value); else session.proxy.network_remove_tags(session.opaque_ref, _network ?? "", _value ?? "").parse(); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_create_new_blob(session.opaque_ref, _network, _name, _mime_type); else return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "").parse()); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_create_new_blob(session.opaque_ref, _network, _name, _mime_type); else return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "").parse()); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> /// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param> public static XenRef<Blob> create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_create_new_blob(session.opaque_ref, _network, _name, _mime_type, _public); else return XenRef<Blob>.Create(session.proxy.network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse()); } /// <summary> /// Create a placeholder for a named binary blob of data that is associated with this pool /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_name">The name associated with the blob</param> /// <param name="_mime_type">The mime type for the data. Empty string translates to application/octet-stream</param> /// <param name="_public">True if the blob should be publicly available First published in XenServer 6.1.</param> public static XenRef<Task> async_create_new_blob(Session session, string _network, string _name, string _mime_type, bool _public) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_create_new_blob(session.opaque_ref, _network, _name, _mime_type, _public); else return XenRef<Task>.Create(session.proxy.async_network_create_new_blob(session.opaque_ref, _network ?? "", _name ?? "", _mime_type ?? "", _public).parse()); } /// <summary> /// Set the default locking mode for VIFs attached to this network /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The default locking mode for VIFs attached to this network.</param> public static void set_default_locking_mode(Session session, string _network, network_default_locking_mode _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_set_default_locking_mode(session.opaque_ref, _network, _value); else session.proxy.network_set_default_locking_mode(session.opaque_ref, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse(); } /// <summary> /// Set the default locking mode for VIFs attached to this network /// First published in XenServer 6.1. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The default locking mode for VIFs attached to this network.</param> public static XenRef<Task> async_set_default_locking_mode(Session session, string _network, network_default_locking_mode _value) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_set_default_locking_mode(session.opaque_ref, _network, _value); else return XenRef<Task>.Create(session.proxy.async_network_set_default_locking_mode(session.opaque_ref, _network ?? "", network_default_locking_mode_helper.ToString(_value)).parse()); } /// <summary> /// Give a network a new purpose (if not present already) /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to add</param> public static void add_purpose(Session session, string _network, network_purpose _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_add_purpose(session.opaque_ref, _network, _value); else session.proxy.network_add_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse(); } /// <summary> /// Give a network a new purpose (if not present already) /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to add</param> public static XenRef<Task> async_add_purpose(Session session, string _network, network_purpose _value) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_add_purpose(session.opaque_ref, _network, _value); else return XenRef<Task>.Create(session.proxy.async_network_add_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse()); } /// <summary> /// Remove a purpose from a network (if present) /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to remove</param> public static void remove_purpose(Session session, string _network, network_purpose _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.network_remove_purpose(session.opaque_ref, _network, _value); else session.proxy.network_remove_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse(); } /// <summary> /// Remove a purpose from a network (if present) /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_network">The opaque_ref of the given network</param> /// <param name="_value">The purpose to remove</param> public static XenRef<Task> async_remove_purpose(Session session, string _network, network_purpose _value) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_network_remove_purpose(session.opaque_ref, _network, _value); else return XenRef<Task>.Create(session.proxy.async_network_remove_purpose(session.opaque_ref, _network ?? "", network_purpose_helper.ToString(_value)).parse()); } /// <summary> /// Return a list of all the networks known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Network>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_all(session.opaque_ref); else return XenRef<Network>.Create(session.proxy.network_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the network Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Network>, Network> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.network_get_all_records(session.opaque_ref); else return XenRef<Network>.Create<Proxy_Network>(session.proxy.network_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// a human-readable name /// </summary> public virtual string name_label { get { return _name_label; } set { if (!Helper.AreEqual(value, _name_label)) { _name_label = value; Changed = true; NotifyPropertyChanged("name_label"); } } } private string _name_label = ""; /// <summary> /// a notes field containing human-readable description /// </summary> public virtual string name_description { get { return _name_description; } set { if (!Helper.AreEqual(value, _name_description)) { _name_description = value; Changed = true; NotifyPropertyChanged("name_description"); } } } private string _name_description = ""; /// <summary> /// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. /// </summary> public virtual List<network_operations> allowed_operations { get { return _allowed_operations; } set { if (!Helper.AreEqual(value, _allowed_operations)) { _allowed_operations = value; Changed = true; NotifyPropertyChanged("allowed_operations"); } } } private List<network_operations> _allowed_operations = new List<network_operations>() {}; /// <summary> /// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. /// </summary> public virtual Dictionary<string, network_operations> current_operations { get { return _current_operations; } set { if (!Helper.AreEqual(value, _current_operations)) { _current_operations = value; Changed = true; NotifyPropertyChanged("current_operations"); } } } private Dictionary<string, network_operations> _current_operations = new Dictionary<string, network_operations>() {}; /// <summary> /// list of connected vifs /// </summary> [JsonConverter(typeof(XenRefListConverter<VIF>))] public virtual List<XenRef<VIF>> VIFs { get { return _VIFs; } set { if (!Helper.AreEqual(value, _VIFs)) { _VIFs = value; Changed = true; NotifyPropertyChanged("VIFs"); } } } private List<XenRef<VIF>> _VIFs = new List<XenRef<VIF>>() {}; /// <summary> /// list of connected pifs /// </summary> [JsonConverter(typeof(XenRefListConverter<PIF>))] public virtual List<XenRef<PIF>> PIFs { get { return _PIFs; } set { if (!Helper.AreEqual(value, _PIFs)) { _PIFs = value; Changed = true; NotifyPropertyChanged("PIFs"); } } } private List<XenRef<PIF>> _PIFs = new List<XenRef<PIF>>() {}; /// <summary> /// MTU in octets /// First published in XenServer 5.6. /// </summary> public virtual long MTU { get { return _MTU; } set { if (!Helper.AreEqual(value, _MTU)) { _MTU = value; Changed = true; NotifyPropertyChanged("MTU"); } } } private long _MTU = 1500; /// <summary> /// additional configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// name of the bridge corresponding to this network on the local host /// </summary> public virtual string bridge { get { return _bridge; } set { if (!Helper.AreEqual(value, _bridge)) { _bridge = value; Changed = true; NotifyPropertyChanged("bridge"); } } } private string _bridge = ""; /// <summary> /// true if the bridge is managed by xapi /// First published in XenServer 7.2. /// </summary> public virtual bool managed { get { return _managed; } set { if (!Helper.AreEqual(value, _managed)) { _managed = value; Changed = true; NotifyPropertyChanged("managed"); } } } private bool _managed = true; /// <summary> /// Binary blobs associated with this network /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringXenRefMapConverter<Blob>))] public virtual Dictionary<string, XenRef<Blob>> blobs { get { return _blobs; } set { if (!Helper.AreEqual(value, _blobs)) { _blobs = value; Changed = true; NotifyPropertyChanged("blobs"); } } } private Dictionary<string, XenRef<Blob>> _blobs = new Dictionary<string, XenRef<Blob>>() {}; /// <summary> /// user-specified tags for categorization purposes /// First published in XenServer 5.0. /// </summary> public virtual string[] tags { get { return _tags; } set { if (!Helper.AreEqual(value, _tags)) { _tags = value; Changed = true; NotifyPropertyChanged("tags"); } } } private string[] _tags = {}; /// <summary> /// The network will use this value to determine the behaviour of all VIFs where locking_mode = default /// First published in XenServer 6.1. /// </summary> [JsonConverter(typeof(network_default_locking_modeConverter))] public virtual network_default_locking_mode default_locking_mode { get { return _default_locking_mode; } set { if (!Helper.AreEqual(value, _default_locking_mode)) { _default_locking_mode = value; Changed = true; NotifyPropertyChanged("default_locking_mode"); } } } private network_default_locking_mode _default_locking_mode = network_default_locking_mode.unlocked; /// <summary> /// The IP addresses assigned to VIFs on networks that have active xapi-managed DHCP /// First published in XenServer 6.5. /// </summary> [JsonConverter(typeof(XenRefStringMapConverter<VIF>))] public virtual Dictionary<XenRef<VIF>, string> assigned_ips { get { return _assigned_ips; } set { if (!Helper.AreEqual(value, _assigned_ips)) { _assigned_ips = value; Changed = true; NotifyPropertyChanged("assigned_ips"); } } } private Dictionary<XenRef<VIF>, string> _assigned_ips = new Dictionary<XenRef<VIF>, string>() {}; /// <summary> /// Set of purposes for which the server will use this network /// First published in XenServer 7.3. /// </summary> public virtual List<network_purpose> purpose { get { return _purpose; } set { if (!Helper.AreEqual(value, _purpose)) { _purpose = value; Changed = true; NotifyPropertyChanged("purpose"); } } } private List<network_purpose> _purpose = new List<network_purpose>() {}; } }
namespace Microsoft.Samples.RssPlatform.ScreenSaver { partial class OptionsForm : System.Windows.Forms.Form { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.okButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.applyButton = new System.Windows.Forms.Button(); this.rssGroupBox = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.rssFadePauseLength = new System.Windows.Forms.TrackBar(); this.imageGroupBox = new System.Windows.Forms.GroupBox(); this.label2 = new System.Windows.Forms.Label(); this.rootFolderTextBox = new System.Windows.Forms.TextBox(); this.backgroundImageLabel = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.rssGroupBox.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.rssFadePauseLength)).BeginInit(); this.imageGroupBox.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // okButton // this.okButton.Anchor = System.Windows.Forms.AnchorStyles.None; this.okButton.Location = new System.Drawing.Point(75, 3); this.okButton.Margin = new System.Windows.Forms.Padding(3, 3, 2, 3); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 3; this.okButton.Text = "OK"; this.okButton.Click += new System.EventHandler(this.btnOK_Click); // // cancelButton // this.cancelButton.Anchor = System.Windows.Forms.AnchorStyles.None; this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelButton.Location = new System.Drawing.Point(155, 3); this.cancelButton.Margin = new System.Windows.Forms.Padding(1, 3, 3, 3); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 4; this.cancelButton.Text = "Cancel"; this.cancelButton.Click += new System.EventHandler(this.btnCancel_Click); // // applyButton // this.applyButton.Anchor = System.Windows.Forms.AnchorStyles.None; this.applyButton.Enabled = false; this.applyButton.Location = new System.Drawing.Point(237, 3); this.applyButton.Name = "applyButton"; this.applyButton.Size = new System.Drawing.Size(75, 23); this.applyButton.TabIndex = 5; this.applyButton.Text = "Apply"; this.applyButton.Click += new System.EventHandler(this.btnApply_Click); // // rssGroupBox // this.rssGroupBox.Controls.Add(this.label4); this.rssGroupBox.Controls.Add(this.label3); this.rssGroupBox.Controls.Add(this.label1); this.rssGroupBox.Controls.Add(this.rssFadePauseLength); this.rssGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.rssGroupBox.Location = new System.Drawing.Point(3, 3); this.rssGroupBox.Name = "rssGroupBox"; this.rssGroupBox.Size = new System.Drawing.Size(315, 115); this.rssGroupBox.TabIndex = 4; this.rssGroupBox.TabStop = false; this.rssGroupBox.Text = "Fade Pause"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 72); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(27, 13); this.label4.TabIndex = 2; this.label4.Text = "Fast"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(201, 72); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(30, 13); this.label3.TabIndex = 2; this.label3.Text = "Slow"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 27); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(226, 13); this.label1.TabIndex = 1; this.label1.Text = "Number of seconds to pause between images:"; // // rssFadePauseLength // this.rssFadePauseLength.Location = new System.Drawing.Point(6, 43); this.rssFadePauseLength.Maximum = 30; this.rssFadePauseLength.Name = "rssFadePauseLength"; this.rssFadePauseLength.Size = new System.Drawing.Size(225, 42); this.rssFadePauseLength.TabIndex = 1; this.rssFadePauseLength.TickFrequency = 2; this.rssFadePauseLength.Value = 2; this.rssFadePauseLength.Scroll += new System.EventHandler(this.rssFadePauseLength_Scroll); // // imageGroupBox // this.imageGroupBox.Controls.Add(this.label2); this.imageGroupBox.Controls.Add(this.rootFolderTextBox); this.imageGroupBox.Controls.Add(this.backgroundImageLabel); this.imageGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.imageGroupBox.Location = new System.Drawing.Point(3, 124); this.imageGroupBox.Name = "imageGroupBox"; this.imageGroupBox.Size = new System.Drawing.Size(315, 115); this.imageGroupBox.TabIndex = 5; this.imageGroupBox.TabStop = false; this.imageGroupBox.Text = "Feed Folder"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 29); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(213, 13); this.label2.TabIndex = 2; this.label2.Text = "(Leave blank to search from the root folder.)"; // // rootFolderTextBox // this.rootFolderTextBox.Location = new System.Drawing.Point(6, 54); this.rootFolderTextBox.Name = "rootFolderTextBox"; this.rootFolderTextBox.Size = new System.Drawing.Size(301, 20); this.rootFolderTextBox.TabIndex = 2; this.rootFolderTextBox.TextChanged += new System.EventHandler(this.rootFolderTextBox_TextChanged); // // backgroundImageLabel // this.backgroundImageLabel.AutoSize = true; this.backgroundImageLabel.Location = new System.Drawing.Point(6, 16); this.backgroundImageLabel.Name = "backgroundImageLabel"; this.backgroundImageLabel.Size = new System.Drawing.Size(206, 13); this.backgroundImageLabel.TabIndex = 0; this.backgroundImageLabel.Text = "Choose a feed folder to search for images:"; // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.imageGroupBox, 0, 1); this.tableLayoutPanel1.Controls.Add(this.rssGroupBox, 0, 0); this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 2); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(9, 9); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 3; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 35F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(321, 278); this.tableLayoutPanel1.TabIndex = 6; // // tableLayoutPanel2 // this.tableLayoutPanel2.ColumnCount = 4; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 81F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 81F)); this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 81F)); this.tableLayoutPanel2.Controls.Add(this.applyButton, 3, 0); this.tableLayoutPanel2.Controls.Add(this.cancelButton, 2, 0); this.tableLayoutPanel2.Controls.Add(this.okButton, 1, 0); this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 245); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 1; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel2.Size = new System.Drawing.Size(315, 30); this.tableLayoutPanel2.TabIndex = 6; // // OptionsForm // 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(339, 296); this.Controls.Add(this.tableLayoutPanel1); this.Name = "OptionsForm"; this.Padding = new System.Windows.Forms.Padding(9); this.ShowIcon = false; this.Text = "Screen Saver Settings"; this.rssGroupBox.ResumeLayout(false); this.rssGroupBox.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.rssFadePauseLength)).EndInit(); this.imageGroupBox.ResumeLayout(false); this.imageGroupBox.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel2.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button applyButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.GroupBox rssGroupBox; private System.Windows.Forms.GroupBox imageGroupBox; private System.Windows.Forms.TextBox rootFolderTextBox; private System.Windows.Forms.Label backgroundImageLabel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.Label label1; private System.Windows.Forms.TrackBar rssFadePauseLength; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM [....] 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; // // Calendar ID Values. This is used to get data from calendar.nlp. // The order of calendar ID means the order of data items in the table. // internal const int CAL_GREGORIAN = 1 ; // Gregorian (localized) calendar internal const int CAL_GREGORIAN_US = 2 ; // Gregorian (U.S.) calendar internal const int CAL_JAPAN = 3 ; // Japanese Emperor Era calendar internal const int CAL_TAIWAN = 4 ; // Taiwan Era calendar internal const int CAL_KOREA = 5 ; // Korean Tangun Era calendar internal const int CAL_HIJRI = 6 ; // Hijri (Arabic Lunar) calendar internal const int CAL_THAI = 7 ; // Thai calendar internal const int CAL_HEBREW = 8 ; // Hebrew (Lunar) calendar internal const int CAL_GREGORIAN_ME_FRENCH = 9 ; // Gregorian Middle East French calendar internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar internal const int CAL_GREGORIAN_XLIT_FRENCH = 12; internal const int CAL_JULIAN = 13; internal const int CAL_JAPANESELUNISOLAR = 14; internal const int CAL_CHINESELUNISOLAR = 15; internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code internal const int CAL_KOREANLUNISOLAR = 20; internal const int CAL_TAIWANLUNISOLAR = 21; internal const int CAL_PERSIAN = 22; internal const int CAL_UMALQURA = 23; internal int m_currentEraValue = -1; [System.Runtime.Serialization.OptionalField(VersionAdded = 2)] private bool m_isReadOnly = false; // The minimum supported DateTime range for the calendar. [System.Runtime.InteropServices.ComVisible(false)] public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. [System.Runtime.InteropServices.ComVisible(false)] public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual int ID { get { return (-1); } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual int BaseCalendarID { get { return ID; } } // Returns the type of the calendar. // [System.Runtime.InteropServices.ComVisible(false)] public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public bool IsReadOnly { get { return (m_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of IColnable. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public virtual Object Clone() { object o = MemberwiseClone(); ((Calendar) o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// [System.Runtime.InteropServices.ComVisible(false)] public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException("calendar"); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (m_isReadOnly) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly")); } } internal void SetReadOnlyState(bool readOnly) { m_isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (m_currentEraValue == -1) { Contract.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0"); m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (m_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Argument_ResultCalendarRange"), minValue, maxValue)); } Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException("value", Environment.GetResourceString("ArgumentOutOfRange_AddValue")); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Contract.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day/7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( "firstDayOfWeek", Environment.GetResourceString("ArgumentOutOfRange_Range", DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( "rule", Environment.GetResourceString("ArgumentOutOfRange_Range", CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month=1; month<=monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax/100 - ( year > TwoDigitYearMax % 100 ? 1 : 0))*100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( "millisecond", String.Format( CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1)); } return TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond")); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue) { // Call nativeGetTwoDigitYearMax int twoDigitYearMax = CalendarData.nativeGetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
// // AdjustTimeDialog.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Larry Ewing <lewing@novell.com> // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2006 Larry Ewing // Copyright (C) 2006-2009 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Mono.Unix; using FSpot.Core; using FSpot.Database; using FSpot.Widgets; using Hyena; namespace FSpot.UI.Dialog { public class AdjustTimeDialog : BuilderDialog { [GtkBeans.Builder.Object] ScrolledWindow view_scrolled; [GtkBeans.Builder.Object] ScrolledWindow tray_scrolled; [GtkBeans.Builder.Object] Button ok_button; [GtkBeans.Builder.Object] Button cancel_button; [GtkBeans.Builder.Object] SpinButton photo_spin; [GtkBeans.Builder.Object] Label name_label; [GtkBeans.Builder.Object] Label old_label; [GtkBeans.Builder.Object] Label count_label; [GtkBeans.Builder.Object] Gnome.DateEdit date_edit; [GtkBeans.Builder.Object] Frame tray_frame; [GtkBeans.Builder.Object] Gtk.Entry offset_entry; [GtkBeans.Builder.Object] Gtk.CheckButton difference_check; [GtkBeans.Builder.Object] Gtk.Frame action_frame; [GtkBeans.Builder.Object] Gtk.Entry spacing_entry; [GtkBeans.Builder.Object] Gtk.Label starting_label; IBrowsableCollection collection; BrowsablePointer item; CollectionGridView tray; PhotoImageView view; Db db; TimeSpan gnome_dateedit_sucks; public AdjustTimeDialog (Db db, IBrowsableCollection collection) : base ("AdjustTimeDialog.ui", "time_dialog") { this.db = db; this.collection = collection; view = new PhotoImageView (collection); view_scrolled.Add (view); item = view.Item; item.Changed += HandleItemChanged; item.MoveFirst (); tray = new BrowseablePointerGridView (view.Item) { MaxColumns = 1, DisplayRatings = false, DisplayTags = false, DisplayDates = true }; tray_scrolled.Add (tray); //forward_button.Clicked += HandleForwardClicked; //back_button.Clicked += HandleBackClicked; ok_button.Clicked += HandleOkClicked; cancel_button.Clicked += HandleCancelClicked; photo_spin.ValueChanged += HandleSpinChanged; photo_spin.SetIncrements (1.0, 1.0); photo_spin.Adjustment.StepIncrement = 1.0; photo_spin.Wrap = true; date_edit.TimeChanged += HandleTimeChanged; date_edit.DateChanged += HandleTimeChanged; Gtk.Entry entry = (Gtk.Entry) date_edit.Children [0]; entry.Changed += HandleTimeChanged; entry = (Gtk.Entry) date_edit.Children [2]; entry.Changed += HandleTimeChanged; offset_entry.Changed += HandleOffsetChanged; ShowAll (); HandleCollectionChanged (collection); spacing_entry.Changed += HandleSpacingChanged; spacing_entry.Sensitive = ! difference_check.Active; difference_check.Toggled += HandleActionToggled; } DateTime EditTime { get { return date_edit.Time - gnome_dateedit_sucks; } } TimeSpan Offset { get { Log.DebugFormat ("{0} - {1} = {2}", date_edit.Time, item.Current.Time, date_edit.Time - item.Current.Time); return EditTime - item.Current.Time; } set { date_edit.Time = item.Current.Time - gnome_dateedit_sucks + value; } } void HandleTimeChanged (object sender, EventArgs args) { TimeSpan span = Offset; Log.DebugFormat ("time changed {0}", span); if (! offset_entry.HasFocus) offset_entry.Text = span.ToString (); starting_label.Text = "min."; difference_check.Label = String.Format (Catalog.GetString ("Shift all photos by {0}"), Offset); } void HandleItemChanged (object sender, BrowsablePointerChangedEventArgs args) { //back_button.Sensitive = (Item.Index > 0 && collection.Count > 0); //forward_button.Sensitive = (Item.Index < collection.Count - 1); if (item.IsValid) { IPhoto curr_item = item.Current; name_label.Text = System.Uri.UnescapeDataString(curr_item.Name); old_label.Text = (curr_item.Time).ToString (); int i = collection.Count > 0 ? item.Index + 1: 0; // Note for translators: This indicates the current photo is photo {0} of {1} out of photos count_label.Text = System.String.Format (Catalog.GetString ("{0} of {1}"), i, collection.Count); DateTime actual = curr_item.Time; date_edit.Time = actual; gnome_dateedit_sucks = date_edit.Time - actual; } HandleTimeChanged (this, System.EventArgs.Empty); photo_spin.Value = item.Index + 1; } private void ShiftByDifference () { TimeSpan span = Offset; Photo [] photos = new Photo [collection.Count]; for (int i = 0; i < collection.Count; i++) { Photo p = (Photo) collection [i]; DateTime time = p.Time; p.Time = time + span; photos [i] = p; Log.DebugFormat ("XXXXX old: {0} new: {1} span: {2}", time, p.Time, span); } db.Photos.Commit (photos); } private void SpaceByInterval () { DateTime date = EditTime; long ticks = (long) (double.Parse (spacing_entry.Text) * TimeSpan.TicksPerMinute); TimeSpan span = new TimeSpan (ticks); Photo [] photos = new Photo [collection.Count]; for (int i = 0; i < collection.Count; i++) { photos [i] = (Photo) collection [i]; } TimeSpan accum = new TimeSpan (0); for (int j = item.Index; j > 0; j--) { date -= span; } for (int i = 0; i < photos.Length; i++) { photos [i].Time = date + accum; accum += span; } db.Photos.Commit (photos); } void HandleSpinChanged (object sender, EventArgs args) { item.Index = photo_spin.ValueAsInt - 1; } void HandleOkClicked (object sender, EventArgs args) { if (! item.IsValid) throw new ApplicationException ("invalid item selected"); Sensitive = false; if (difference_check.Active) ShiftByDifference (); else SpaceByInterval (); Destroy (); } void HandleOffsetChanged (object sender, EventArgs args) { Log.DebugFormat ("offset = {0}", Offset); TimeSpan current = Offset; try { TimeSpan span = TimeSpan.Parse (offset_entry.Text); if (span != current) Offset = span; } catch (System.Exception) { Log.WarningFormat ("unparsable span {0}", offset_entry.Text); } } void HandleSpacingChanged (object sender, EventArgs args) { if (! spacing_entry.Sensitive) return; try { double.Parse (spacing_entry.Text); ok_button.Sensitive = true; } catch { ok_button.Sensitive = false; } } void HandleActionToggled (object sender, EventArgs args) { spacing_entry.Sensitive = ! difference_check.Active; HandleSpacingChanged (sender, args); } void HandleCancelClicked (object sender, EventArgs args) { Destroy (); } void HandleForwardClicked (object sender, EventArgs args) { view.Item.MoveNext (); } void HandleBackClicked (object sender, EventArgs args) { view.Item.MovePrevious (); } void HandleCollectionChanged (IBrowsableCollection collection) { bool multiple = collection.Count > 1; tray_frame.Visible = multiple; //forward_button.Visible = multiple; //back_button.Visible = multiple; count_label.Visible = multiple; photo_spin.Visible = multiple; action_frame.Visible = multiple; photo_spin.SetRange (1.0, (double) collection.Count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Reflection.Emit.Tests { public class TypeBuilderCreateType2 { private const int MinAsmName = 1; private const int MaxAsmName = 260; private const int MinModName = 1; private const int MaxModName = 260; private const int MinTypName = 1; private const int MaxTypName = 1024; private const int NumLoops = 5; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); private TypeAttributes[] _typesPos = new TypeAttributes[17] { TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.AnsiClass | TypeAttributes.NestedPublic, TypeAttributes.AutoClass | TypeAttributes.NestedPublic, TypeAttributes.AutoLayout | TypeAttributes.NestedPublic, TypeAttributes.BeforeFieldInit | TypeAttributes.NestedPublic, TypeAttributes.Class | TypeAttributes.NestedPublic, TypeAttributes.ClassSemanticsMask | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.ExplicitLayout | TypeAttributes.NestedPublic, TypeAttributes.Import | TypeAttributes.NestedPublic, TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.NestedPublic, TypeAttributes.Sealed | TypeAttributes.NestedPublic, TypeAttributes.SequentialLayout | TypeAttributes.NestedPublic, TypeAttributes.Serializable | TypeAttributes.NestedPublic, TypeAttributes.SpecialName | TypeAttributes.NestedPublic, TypeAttributes.StringFormatMask | TypeAttributes.NestedPublic, TypeAttributes.UnicodeClass | TypeAttributes.NestedPublic, TypeAttributes.VisibilityMask, }; [Fact] public void TestDefineNestedType() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName); for (int i = 0; i < NumLoops; i++) { nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (_generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestDefineNestedTypeWithEmbeddedNullsInName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; for (int i = 0; i < NumLoops; i++) { modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + _generator.GetString(true, MinTypName, MaxTypName / 4) + '\0' + _generator.GetString(true, MinTypName, MaxTypName / 4); typeBuilder = modBuilder.DefineType(typeName); // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.Abstract | TypeAttributes.NestedPublic); newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } } [Fact] public void TestDefineNestedTypeWithTypeAttributes() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; TypeBuilder nestedType = null; Type newType; string typeName = ""; string nestedTypeName = ""; TypeAttributes typeAttrib = (TypeAttributes)0; int i = 0; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls typeBuilder = modBuilder.DefineType(typeName, typeAttrib); for (i = 0; i < _typesPos.Length; i++) { typeAttrib = _typesPos[i]; nestedTypeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls // create nested type if (null != nestedType && 0 == (_generator.GetInt32() % 2)) { nestedType.DefineNestedType(nestedTypeName, _typesPos[i]); } else { nestedType = typeBuilder.DefineNestedType(nestedTypeName, _typesPos[i]); } } newType = typeBuilder.CreateTypeInfo().AsType(); Assert.True(newType.Name.Equals(typeName)); } [Fact] public void TestThrowsExceptionForNullName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = null; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentNullException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class); newType = typeBuilder.CreateTypeInfo().AsType(); }); } [Fact] public void TestThrowsExceptionForEmptyName() { ModuleBuilder modBuilder; TypeBuilder typeBuilder; Type newType; string typeName = ""; string nestedTypeName = ""; modBuilder = CreateModule( _generator.GetString(true, MinAsmName, MaxAsmName), _generator.GetString(false, MinModName, MaxModName)); typeName = _generator.GetString(true, MinTypName, MaxTypName); // name can not contain embedded nulls nestedTypeName = string.Empty; typeBuilder = modBuilder.DefineType(typeName); Assert.Throws<ArgumentException>(() => { // create nested type typeBuilder.DefineNestedType(nestedTypeName, TypeAttributes.NestedPublic | TypeAttributes.Class); newType = typeBuilder.CreateTypeInfo().AsType(); }); } public ModuleBuilder CreateModule(string assemblyName, string modName) { AssemblyName asmName; AssemblyBuilder asmBuilder; ModuleBuilder modBuilder; // create the dynamic module asmName = new AssemblyName(assemblyName); asmBuilder = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run); modBuilder = TestLibrary.Utilities.GetModuleBuilder(asmBuilder, "Module1"); return modBuilder; } } }
// 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.Data.Common; using System.Diagnostics; using System.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents the date and time data ranging in value /// from January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds /// to be stored in or retrieved from a database. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] [XmlSchemaProvider("GetXsdType")] public struct SqlDateTime : INullable, IComparable, IXmlSerializable { private bool _fNotNull; // false if null private int _day; // Day from 1900/1/1, could be negative. Range: Jan 1 1753 - Dec 31 9999. private int _time; // Time in the day in term of ticks // Constants // Number of (100ns) ticks per time unit private static readonly double s_SQLTicksPerMillisecond = 0.3; public static readonly int SQLTicksPerSecond = 300; public static readonly int SQLTicksPerMinute = SQLTicksPerSecond * 60; public static readonly int SQLTicksPerHour = SQLTicksPerMinute * 60; private static readonly int s_SQLTicksPerDay = SQLTicksPerHour * 24; private static readonly long s_ticksPerSecond = TimeSpan.TicksPerMillisecond * 1000; private static readonly DateTime s_SQLBaseDate = new DateTime(1900, 1, 1); private static readonly long s_SQLBaseDateTicks = s_SQLBaseDate.Ticks; private static readonly int s_minYear = 1753; // Jan 1 1753 private static readonly int s_maxYear = 9999; // Dec 31 9999 private static readonly int s_minDay = -53690; // Jan 1 1753 private static readonly int s_maxDay = 2958463; // Dec 31 9999 is this many days from Jan 1 1900 private static readonly int s_minTime = 0; // 00:00:0:000PM private static readonly int s_maxTime = s_SQLTicksPerDay - 1; // = 25919999, 11:59:59:997PM private static readonly int s_dayBase = 693595; // Jan 1 1900 is this many days from Jan 1 0001 private static readonly int[] s_daysToMonth365 = new int[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; private static readonly int[] s_daysToMonth366 = new int[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366}; private static readonly DateTime s_minDateTime = new DateTime(1753, 1, 1); private static readonly DateTime s_maxDateTime = DateTime.MaxValue; private static readonly TimeSpan s_minTimeSpan = s_minDateTime.Subtract(s_SQLBaseDate); private static readonly TimeSpan s_maxTimeSpan = s_maxDateTime.Subtract(s_SQLBaseDate); private static readonly string s_ISO8601_DateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fff"; // These formats are valid styles in SQL Server (style 9, 12, 13, 14) // but couldn't be recognized by the default parse. Needs to call // ParseExact in addition to recognize them. private static readonly string[] s_dateTimeFormats = { "MMM d yyyy hh:mm:ss:ffftt", "MMM d yyyy hh:mm:ss:fff", "d MMM yyyy hh:mm:ss:ffftt", "d MMM yyyy hh:mm:ss:fff", "hh:mm:ss:ffftt", "hh:mm:ss:fff", "yyMMdd", "yyyyMMdd" }; private const DateTimeStyles x_DateTimeStyle = DateTimeStyles.AllowWhiteSpaces; // construct a Null private SqlDateTime(bool fNull) { _fNotNull = false; _day = 0; _time = 0; } public SqlDateTime(DateTime value) { this = FromDateTime(value); } public SqlDateTime(int year, int month, int day) : this(year, month, day, 0, 0, 0, 0.0) { } public SqlDateTime(int year, int month, int day, int hour, int minute, int second) : this(year, month, day, hour, minute, second, 0.0) { } public SqlDateTime(int year, int month, int day, int hour, int minute, int second, double millisecond) { if (year >= s_minYear && year <= s_maxYear && month >= 1 && month <= 12) { int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365; if (day >= 1 && day <= days[month] - days[month - 1]) { int y = year - 1; int dayticks = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; dayticks -= s_dayBase; if (dayticks >= s_minDay && dayticks <= s_maxDay && hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60 && millisecond >= 0 && millisecond < 1000.0) { double ticksForMilisecond = millisecond * s_SQLTicksPerMillisecond + 0.5; int timeticks = hour * SQLTicksPerHour + minute * SQLTicksPerMinute + second * SQLTicksPerSecond + (int)ticksForMilisecond; if (timeticks > s_maxTime) { // Only rounding up could cause time to become greater than MaxTime. Debug.Assert(timeticks == s_maxTime + 1); // Make time to be zero, and increment day. timeticks = 0; dayticks++; } // Success. Call ctor here which will again check dayticks and timeticks are within range. // All other cases will throw exception below. this = new SqlDateTime(dayticks, timeticks); return; } } } throw new SqlTypeException(SQLResource.InvalidDateTimeMessage); } // constructor that take DBTIMESTAMP data members // Note: bilisecond is same as 'fraction' in DBTIMESTAMP public SqlDateTime(int year, int month, int day, int hour, int minute, int second, int bilisecond) : this(year, month, day, hour, minute, second, bilisecond / 1000.0) { } public SqlDateTime(int dayTicks, int timeTicks) { if (dayTicks < s_minDay || dayTicks > s_maxDay || timeTicks < s_minTime || timeTicks > s_maxTime) { _fNotNull = false; throw new OverflowException(SQLResource.DateTimeOverflowMessage); } _day = dayTicks; _time = timeTicks; _fNotNull = true; } internal SqlDateTime(double dblVal) { if ((dblVal < s_minDay) || (dblVal >= s_maxDay + 1)) throw new OverflowException(SQLResource.DateTimeOverflowMessage); int day = (int)dblVal; int time = (int)((dblVal - day) * s_SQLTicksPerDay); // Check if we need to borrow a day from the day portion. if (time < 0) { day--; time += s_SQLTicksPerDay; } else if (time >= s_SQLTicksPerDay) { // Deal with case where time portion = 24 hrs. // // ISSUE: Is this code reachable? For this code to be reached there // must be a value for dblVal such that: // dblVal - (long)dblVal = 1.0 // This seems odd, but there was a bug that resulted because // there was a negative value for dblVal such that dblVal + 1.0 = 1.0 // day++; time -= s_SQLTicksPerDay; } this = new SqlDateTime(day, time); } // INullable public bool IsNull { get { return !_fNotNull; } } private static TimeSpan ToTimeSpan(SqlDateTime value) { long millisecond = (long)(value._time / s_SQLTicksPerMillisecond + 0.5); return new TimeSpan(value._day * TimeSpan.TicksPerDay + millisecond * TimeSpan.TicksPerMillisecond); } private static DateTime ToDateTime(SqlDateTime value) { return s_SQLBaseDate.Add(ToTimeSpan(value)); } // Used by SqlBuffer in SqlClient. internal static DateTime ToDateTime(int daypart, int timepart) { if (daypart < s_minDay || daypart > s_maxDay || timepart < s_minTime || timepart > s_maxTime) { throw new OverflowException(SQLResource.DateTimeOverflowMessage); } long dayticks = daypart * TimeSpan.TicksPerDay; long timeticks = ((long)(timepart / s_SQLTicksPerMillisecond + 0.5)) * TimeSpan.TicksPerMillisecond; DateTime result = new DateTime(s_SQLBaseDateTicks + dayticks + timeticks); return result; } // Convert from TimeSpan, rounded to one three-hundredth second, due to loss of precision private static SqlDateTime FromTimeSpan(TimeSpan value) { if (value < s_minTimeSpan || value > s_maxTimeSpan) throw new SqlTypeException(SQLResource.DateTimeOverflowMessage); int day = value.Days; long ticks = value.Ticks - day * TimeSpan.TicksPerDay; if (ticks < 0L) { day--; ticks += TimeSpan.TicksPerDay; } int time = (int)((double)ticks / TimeSpan.TicksPerMillisecond * s_SQLTicksPerMillisecond + 0.5); if (time > s_maxTime) { // Only rounding up could cause time to become greater than MaxTime. Debug.Assert(time == s_maxTime + 1); // Make time to be zero, and increment day. time = 0; day++; } return new SqlDateTime(day, time); } private static SqlDateTime FromDateTime(DateTime value) { // SqlDateTime has smaller precision and range than DateTime. // Usually we round the DateTime value to the nearest SqlDateTime value. // but for DateTime.MaxValue, if we round it up, it will overflow. // Although the overflow would be the correct behavior, we simply // returned SqlDateTime.MaxValue in v1. In order not to break exisiting // code, we'll keep this logic. // if (value == DateTime.MaxValue) return SqlDateTime.MaxValue; return FromTimeSpan(value.Subtract(s_SQLBaseDate)); } /* internal static SqlDateTime FromDouble(double dblVal) { return new SqlDateTime(dblVal); } internal static double ToDouble(SqlDateTime x) { AssertValidSqlDateTime(x); return(double)x.m_day + ((double)x.m_time / (double)SQLTicksPerDay); } internal static int ToInt(SqlDateTime x) { AssertValidSqlDateTime(x); return x.m_time >= MaxTime / 2 ? x.m_day + 1 : x.m_day; } */ // do we still want to define a property of DateTime? If the user uses it often, it is expensive // property: Value public DateTime Value { get { if (_fNotNull) return ToDateTime(this); else throw new SqlNullValueException(); } } // Day ticks -- returns number of days since 1/1/1900 public int DayTicks { get { if (_fNotNull) return _day; else throw new SqlNullValueException(); } } // Time ticks -- return daily time in unit of 1/300 second public int TimeTicks { get { if (_fNotNull) return _time; else throw new SqlNullValueException(); } } // Implicit conversion from DateTime to SqlDateTime public static implicit operator SqlDateTime(DateTime value) { return new SqlDateTime(value); } // Explicit conversion from SqlDateTime to int. Returns 0 if x is Null. public static explicit operator DateTime(SqlDateTime x) { return ToDateTime(x); } // Return string representation of SqlDateTime public override string ToString() { if (IsNull) return SQLResource.NullString; DateTime dateTime = ToDateTime(this); return dateTime.ToString((IFormatProvider)null); } public static SqlDateTime Parse(string s) { DateTime dt; if (s == SQLResource.NullString) return SqlDateTime.Null; try { dt = DateTime.Parse(s, CultureInfo.InvariantCulture); } catch (FormatException) { DateTimeFormatInfo dtfi = (DateTimeFormatInfo)(CultureInfo.CurrentCulture.GetFormat(typeof(DateTimeFormatInfo))); dt = DateTime.ParseExact(s, s_dateTimeFormats, dtfi, x_DateTimeStyle); } return new SqlDateTime(dt); } // Binary operators // Arithmetic operators // Alternative method: SqlDateTime.Add public static SqlDateTime operator +(SqlDateTime x, TimeSpan t) { return x.IsNull ? Null : FromDateTime(ToDateTime(x) + t); } // Alternative method: SqlDateTime.Subtract public static SqlDateTime operator -(SqlDateTime x, TimeSpan t) { return x.IsNull ? Null : FromDateTime(ToDateTime(x) - t); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlDateTime Add(SqlDateTime x, TimeSpan t) { return x + t; } // Alternative method for operator - public static SqlDateTime Subtract(SqlDateTime x, TimeSpan t) { return x - t; } /* // Implicit conversions // Implicit conversion from SqlBoolean to SqlDateTime public static implicit operator SqlDateTime(SqlBoolean x) { return x.IsNull ? Null : new SqlDateTime(x.Value, 0); } // Implicit conversion from SqlInt32 to SqlDateTime public static implicit operator SqlDateTime(SqlInt32 x) { return x.IsNull ? Null : new SqlDateTime(x.Value, 0); } // Implicit conversion from SqlMoney to SqlDateTime public static implicit operator SqlDateTime(SqlMoney x) { return x.IsNull ? Null : SqlDateTime.FromDouble(x.ToDouble()); } // Explicit conversions // Explicit conversion from SqlDateTime to SqlInt32 public static explicit operator SqlInt32(SqlDateTime x) { if (x.IsNull) return SqlInt32.Null; return new SqlInt32(SqlDateTime.ToInt(x)); } // Explicit conversion from SqlDateTime to SqlBoolean public static explicit operator SqlBoolean(SqlDateTime x) { if (x.IsNull) return SqlBoolean.Null; return new SqlBoolean(x.m_day != 0 || x.m_time != 0, false); } // Explicit conversion from SqlDateTime to SqlMoney public static explicit operator SqlMoney(SqlDateTime x) { return x.IsNull ? SqlMoney.Null : new SqlMoney(SqlDateTime.ToDouble(x)); } // Implicit conversion from SqlDouble to SqlDateTime public static implicit operator SqlDateTime(SqlDouble x) { return x.IsNull ? Null : new SqlDateTime(x.Value); } // Explicit conversion from SqlDateTime to SqlDouble public static explicit operator SqlDouble(SqlDateTime x) { return x.IsNull ? SqlDouble.Null : new SqlDouble(SqlDateTime.ToDouble(x)); } // Implicit conversion from SqlDecimal to SqlDateTime public static implicit operator SqlDateTime(SqlDecimal x) { return x.IsNull ? SqlDateTime.Null : new SqlDateTime(SqlDecimal.ToDouble(x)); } // Explicit conversion from SqlDateTime to SqlDecimal public static explicit operator SqlDecimal(SqlDateTime x) { return x.IsNull ? SqlDecimal.Null : new SqlDecimal(SqlDateTime.ToDouble(x)); } */ // Explicit conversion from SqlString to SqlDateTime // Throws FormatException or OverflowException if necessary. public static explicit operator SqlDateTime(SqlString x) { return x.IsNull ? SqlDateTime.Null : SqlDateTime.Parse(x.Value); } // Builtin functions // utility functions /* private static void AssertValidSqlDateTime(SqlDateTime x) { Debug.Assert(!x.IsNull, "!x.IsNull", "Datetime: Null"); Debug.Assert(x.m_day >= MinDay && x.m_day <= MaxDay, "day >= MinDay && day <= MaxDay", "DateTime: Day out of range"); Debug.Assert(x.m_time >= MinTime && x.m_time <= MaxTime, "time >= MinTime && time <= MaxTime", "DateTime: Time out of range"); } */ // Checks whether a given year is a leap year. This method returns true if // "year" is a leap year, or false if not. // // @param year The year to check. // @return true if "year" is a leap year, false otherwise. // private static bool IsLeapYear(int year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); } // Overloading comparison operators public static SqlBoolean operator ==(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._day == y._day && x._time == y._time); } public static SqlBoolean operator !=(SqlDateTime x, SqlDateTime y) { return !(x == y); } public static SqlBoolean operator <(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._day < y._day || (x._day == y._day && x._time < y._time)); } public static SqlBoolean operator >(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._day > y._day || (x._day == y._day && x._time > y._time)); } public static SqlBoolean operator <=(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._day < y._day || (x._day == y._day && x._time <= y._time)); } public static SqlBoolean operator >=(SqlDateTime x, SqlDateTime y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._day > y._day || (x._day == y._day && x._time >= y._time)); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator == public static SqlBoolean Equals(SqlDateTime x, SqlDateTime y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlDateTime x, SqlDateTime y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlDateTime x, SqlDateTime y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlDateTime x, SqlDateTime y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlDateTime x, SqlDateTime y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlDateTime x, SqlDateTime y) { return (x >= y); } // Alternative method for conversions. public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlDateTime) { SqlDateTime i = (SqlDateTime)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlDateTime)); } public int CompareTo(SqlDateTime value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlDateTime)) { return false; } SqlDateTime i = (SqlDateTime)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); _fNotNull = false; } else { DateTime dt = XmlConvert.ToDateTime(reader.ReadElementString(), XmlDateTimeSerializationMode.RoundtripKind); // We do not support any kind of timezone information that is // possibly included in the CLR DateTime, since SQL Server // does not support TZ info. If any was specified, error out. // if (dt.Kind != System.DateTimeKind.Unspecified) { throw new SqlTypeException(SQLResource.TimeZoneSpecifiedMessage); } SqlDateTime st = FromDateTime(dt); _day = st.DayTicks; _time = st.TimeTicks; _fNotNull = true; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(Value, s_ISO8601_DateTimeFormat)); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("dateTime", XmlSchema.Namespace); } public static readonly SqlDateTime MinValue = new SqlDateTime(s_minDay, 0); public static readonly SqlDateTime MaxValue = new SqlDateTime(s_maxDay, s_maxTime); public static readonly SqlDateTime Null = new SqlDateTime(true); } // SqlDateTime } // namespace System.Data.SqlTypes
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Diagnostics; using System.Drawing; using System.IO; using mshtml; using OpenLiveWriter.Api; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.ImageEditing; namespace OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators { /// <summary> /// Summary description for Decorator. /// </summary> public class HtmlImageResizeDecorator : IImageDecorator, IImageDecoratorDefaultSettingsCustomizer { public const string Id = "ImageResizeRotate"; public HtmlImageResizeDecorator() { } public void Decorate(ImageDecoratorContext context) { bool useOriginalImage = true; HtmlImageResizeDecoratorSettings settings = new HtmlImageResizeDecoratorSettings(context.Settings, context.ImgElement); if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert || context.InvocationSource == ImageDecoratorInvocationSource.Reset) { // WinLive 96840 - Copying and pasting images within shared canvas should persist source // decorator settings. // If ImageSizeName is set, then use that instead of default values if (settings.IsImageSizeNameSet && context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert) { // We must be copying settings from another instance of the same image settings.SetImageSize(settings.ImageSize, settings.ImageSizeName); // WinLive 96840 - Copying and pasting images within shared canvas should persist source // decorator settings. // Also if we are copying settings, then use the image instance from context instead of the // original image. This ensures we use the cropped image (if any) to resize. useOriginalImage = false; } else { //calculate the default image size and rotation. If the camera has indicated that the //orientation of the photo is rotated (in the EXIF data), shift the rotation appropriately //to insert the image correctly. //Fix the image orientation based on the Exif data (added by digital cameras). RotateFlipType fixedRotation = ImageUtils.GetFixupRotateFlipFromExifOrientation(context.Image); settings.Rotation = fixedRotation; settings.BaseSize = context.Image.Size; //the default size is a scaled version of the image based on the default inline size constraints. Size defaultBoundsSize; if (settings.DefaultBoundsSizeName != ImageSizeName.Full) { defaultBoundsSize = settings.DefaultBoundsSize; } else //original size is default, so we aren't going to scale { defaultBoundsSize = context.Image.Size; } //calulate the base image size to scale from. If the image is rotated 90 degrees, then switch the height/width Size baseImageSize = context.Image.Size; if (ImageUtils.IsRotated90(settings.Rotation)) baseImageSize = new Size(baseImageSize.Height, baseImageSize.Width); //calculate and set the scaled default size using the defaultSizeBounds //Note: if the image dimensions are smaller than the default, don't scale that dimension (bug 419446) Size defaultSize = ImageUtils.GetScaledImageSize(Math.Min(baseImageSize.Width, defaultBoundsSize.Width), Math.Min(baseImageSize.Height, defaultBoundsSize.Height), baseImageSize); if (defaultSize.Width < defaultBoundsSize.Width && defaultSize.Height < defaultBoundsSize.Height) settings.SetImageSize(defaultSize, ImageSizeName.Full); else settings.SetImageSize(defaultSize, settings.DefaultBoundsSizeName); } } else if (settings.BaseSizeChanged(context.Image)) { Size newBaseSize = context.Image.Size; settings.SetImageSize(AdjustImageSizeForNewBaseSize(true, settings, newBaseSize, settings.Rotation, context), null); settings.BaseSize = newBaseSize; } //this decorator only applies to embedded images. if (context.ImageEmbedType == ImageEmbedType.Embedded && !ImageHelper2.IsAnimated(context.Image)) { Bitmap imageToResize = null; // To make image insertion faster, we've already created an initial resized image on a background thread. if (context.InvocationSource == ImageDecoratorInvocationSource.InitialInsert && useOriginalImage) { try { string imageSrc = context.ImgElement.getAttribute("src", 2) as string; if (!string.IsNullOrEmpty(imageSrc) && (UrlHelper.IsFileUrl(imageSrc) || File.Exists(new Uri(imageSrc).ToString()))) { Uri imageSrcUri = new Uri(imageSrc); imageToResize = (Bitmap)Image.FromFile(imageSrcUri.LocalPath); } } catch (Exception e) { Debug.Write("Failed to load pre-created initial image: " + e); } } if (imageToResize == null) imageToResize = context.Image; // Figure the desired image size by taking the size of the img element // and calculate what borderless image size we'd need to start with // to end up at that size. This is different than simply subtracting // the existing border size, since borders can be relative to the // size of the base image. Size desiredImageSize = settings.BorderMargin.ReverseCalculateImageSize(settings.ImageSizeWithBorder); //resize the image and update the image used by the context. if (desiredImageSize != imageToResize.Size || settings.Rotation != RotateFlipType.RotateNoneFlipNone) { context.Image = ResizeImage(imageToResize, desiredImageSize, settings.Rotation); } else { context.Image = imageToResize; } if (settings.ImageSize != context.Image.Size) settings.SetImageSize(context.Image.Size, settings.ImageSizeName); } } internal static Size AdjustImageSizeForNewBaseSize(bool allowEnlargement, IResizeDecoratorSettings s, Size newBaseSize, RotateFlipType rotation, ImageDecoratorContext context) { Size rotatedBaseSize = ImageUtils.IsRotated90(rotation) ? new Size(newBaseSize.Height, newBaseSize.Width) : newBaseSize; if (s.ImageSizeName != ImageSizeName.Custom) { // If a standard image size is being used, fit to that Size sizeBounds = ImageSizeHelper.GetSizeConstraints(s.ImageSizeName); if (!allowEnlargement) { sizeBounds.Width = Math.Min(rotatedBaseSize.Width, sizeBounds.Width); sizeBounds.Height = Math.Min(rotatedBaseSize.Height, sizeBounds.Height); } return ImageUtils.GetScaledImageSize(sizeBounds.Width, sizeBounds.Height, rotatedBaseSize); } else { // If custom size, but we know the base size, preserve // the aspect ratio "skew" (difference in x and y DPI) // and pixel area Size imageSize = s.ImageSize; // Need to get the image size to the non-rotated angle, // because s.BaseSize dimensions are always pre-rotation. // Although ImageSize has not been fully updated for this // decorator yet (that's what we're trying to do here), // the width/height gets flipped immediately when a // rotation is applied, so rotation is already taken // into account. if (ImageUtils.IsRotated90(rotation)) imageSize = new Size(imageSize.Height, imageSize.Width); // If the base size has not been set yet, we have to guess. // This basically means the image was inserted using an older // build of Writer that did not have the crop feature. Ideally // we would use the original image size, but this is expensive // to get from here. It just so happens that newBaseSize works // for now because the crop dialog defaults to the same aspect // ratio as the original image, but if that ever changes this // will break. #if DEBUG if (s.BaseSize == null) { using (Bitmap bitmap = (Bitmap)Bitmap.FromFile(context.SourceImageUri.LocalPath)) { Size size = new Size(Math.Max(1, bitmap.Width / 2), Math.Max(1, bitmap.Height / 2)); Debug.Assert(size.Equals(newBaseSize) || bitmap.Size.Equals(newBaseSize), "Check base size assumptions. Can't use 's.BaseSize ?? newBaseSize', instead must calculate original image size (context.SourceImageUri.LocalPath)."); } } #endif Size baseSize = s.BaseSize ?? newBaseSize; double xFactor = imageSize.Width / (double)baseSize.Width; double yFactor = imageSize.Height / (double)baseSize.Height; newBaseSize = new Size( (int)Math.Round(xFactor * newBaseSize.Width), (int)Math.Round(yFactor * newBaseSize.Height) ); // Need to re-apply the rotation if necessary. if (ImageUtils.IsRotated90(rotation)) newBaseSize = new Size(newBaseSize.Height, newBaseSize.Width); // At this point, newBaseSize has the right aspect ratio; we now // need to scale it so it uses about the same number of pixels // as it did before. double factor = (imageSize.Width * imageSize.Height) / (double)(newBaseSize.Width * newBaseSize.Height); factor = Math.Sqrt(factor); newBaseSize.Width = (int)Math.Round(newBaseSize.Width * factor); newBaseSize.Height = (int)Math.Round(newBaseSize.Height * factor); if (!allowEnlargement) { if (newBaseSize.Width > rotatedBaseSize.Width || newBaseSize.Height > rotatedBaseSize.Height) newBaseSize = ImageUtils.GetScaledImageSize(rotatedBaseSize.Width, rotatedBaseSize.Height, newBaseSize); } return newBaseSize; } } internal static Bitmap ResizeImage(Bitmap image, Size newSize, RotateFlipType rotation) { if (rotation != RotateFlipType.RotateNoneFlipNone) { image.RotateFlip(rotation); image = new Bitmap(image); } int newWidth = Math.Max(newSize.Width, 2); int newHeight = Math.Max(newSize.Height, 2); //resize the image (if its not already the correct size!) Bitmap bitmap; if (image.Width != newWidth || image.Height != newHeight) bitmap = ImageHelper2.CreateResizedBitmap(image, newWidth, newHeight, image.RawFormat); else bitmap = image; return bitmap; } public ImageDecoratorEditor CreateEditor(CommandManager commandManager) { return new HtmlImageResizeEditor(commandManager); } void IImageDecoratorDefaultSettingsCustomizer.CustomizeDefaultSettingsBeforeSave(ImageDecoratorEditorContext context, IProperties defaultSettings) { //clear all defaulted settings for this decorator foreach (string key in defaultSettings.Names) defaultSettings.Remove(key); HtmlImageResizeDecoratorSettings defaultResizeSettings = new HtmlImageResizeDecoratorSettings(defaultSettings, context.ImgElement); HtmlImageResizeDecoratorSettings resizeSettings = new HtmlImageResizeDecoratorSettings(context.Settings, context.ImgElement); //explicitly save the settings we want to support defaulting for. defaultResizeSettings.DefaultBoundsSizeName = resizeSettings.ImageSizeName; if (resizeSettings.ImageSizeName == ImageSizeName.Custom) { defaultResizeSettings.DefaultBoundsSize = resizeSettings.ImageSize; } } } internal interface IResizeDecoratorSettings { Size ImageSize { get; } /// <summary> /// The image size name used when determining the current image size. /// This value is used to decide what the best initial size should be for the image if the current /// size is saved as the default size. Rather than forcing all future images to be exactly the current /// size, the named size can be used for more flexibility. /// </summary> ImageSizeName ImageSizeName { get; } Size DefaultBoundsSize { get; } ImageSizeName DefaultBoundsSizeName { get; } Size? BaseSize { get; } } internal class HtmlImageResizeDecoratorSettings : IResizeDecoratorSettings { private readonly IProperties Settings; private readonly IHTMLElement ImgElement; private const string ROTATION = "Rotation"; private const string SIZE_NAME = "ImageSizeName"; private const string ASPECT_RATIO_LOCKED = "AspectRatioLocked"; private const string DEFAULT_WIDTH = "DefaultImageWidth"; private const string DEFAULT_HEIGHT = "DefaultImageHeight"; private const string DEFAULT_SIZE_NAME = "DefaultImageSizeName"; private const string IMAGE_WIDTH_OFFSET = "ImageWidthOffset"; private const string IMAGE_HEIGHT_OFFSET = "ImageHeightOffset"; private const string TARGET_ASPECT_RATIO_WIDTH = "TargetAspectRatioWidth"; private const string TARGET_ASPECT_RATIO_HEIGHT = "TargetAspectRatioHeight"; private const string BASE_WIDTH = "BaseWidth"; private const string BASE_HEIGHT = "BaseHeight"; private const string PREV_ROTATION = "PrevRotation"; private const string BORDER_INFO = "BorderInfo"; private const string BORDER_TOP = "BorderTop"; private const string BORDER_RIGHT = "BorderRight"; private const string BORDER_BOTTOM = "BorderBottom"; private const string BORDER_LEFT = "BorderLeft"; public HtmlImageResizeDecoratorSettings(IProperties settings, IHTMLElement imgElement) { Settings = settings; ImgElement = imgElement; } public Size ImageSize { get { ImageBorderMargin borderMargin = BorderMargin; Size imageSizeWithBorder = ImageSizeWithBorder; int width = imageSizeWithBorder.Width - borderMargin.Width; int height = imageSizeWithBorder.Height - borderMargin.Height; Size size = new Size(width, height); //Initialize the saved aspect ratio if it has no value if (TargetAspectRatioSize.Width == -1) TargetAspectRatioSize = size; return size; //return borderMargin.ReverseCalculateImageSize(imageSizeWithBorder); } } public Size ImageSizeWithBorder { get { IHTMLImgElement imgElement = (IHTMLImgElement)ImgElement; //get the true size of the image by removing size offsets that may be applied to the image by the CSS margin/padding int width = imgElement.width - Settings.GetInt(IMAGE_WIDTH_OFFSET, 0); int height = imgElement.height - Settings.GetInt(IMAGE_HEIGHT_OFFSET, 0); return new Size(width, height); } } /// <summary> /// Sets the new size of the image (not including the border) /// </summary> /// <param name="size"></param> /// <param name="sizeName"></param> public void SetImageSize(Size size, ImageSizeName? sizeName) { IHTMLImgElement imgElement = (IHTMLImgElement)ImgElement; ImageBorderMargin borderMargin = BorderMargin; // The next line is a little bit tortured, but // I'm trying to introduce the concept of "calculated image size" // for more complex border calculations without breaking any // existing logic. Size sizeWithBorder = ImageSize.Equals(size) ? ImageSizeWithBorder : borderMargin.CalculateImageSize(size); if (imgElement.width != sizeWithBorder.Width || imgElement.height != sizeWithBorder.Height) { imgElement.width = sizeWithBorder.Width; imgElement.height = sizeWithBorder.Height; } //remember the size offsets which are added by CSS margins/padding Settings.SetInt(IMAGE_WIDTH_OFFSET, imgElement.width - sizeWithBorder.Width); Settings.SetInt(IMAGE_HEIGHT_OFFSET, imgElement.height - sizeWithBorder.Height); if (sizeName != null) ImageSizeName = sizeName.Value; //Initialize the saved aspect ratio if it has no value //OR update it if the ratio has been changed Size targetSize = TargetAspectRatioSize; if (targetSize.Width == -1 || (size.Width != Math.Round((targetSize.Width * (float)size.Height) / targetSize.Height) && size.Height != Math.Round((targetSize.Height * (float)size.Width) / targetSize.Width))) { TargetAspectRatioSize = size; } } public ImageBorderMargin BorderMargin { get { if (Settings.ContainsSubProperties(BORDER_INFO)) { return new ImageBorderMargin(Settings.GetSubProperties(BORDER_INFO)); } // backwards compatibility with previous releases int top = Settings.GetInt(BORDER_TOP, 0); int right = Settings.GetInt(BORDER_RIGHT, 0); int bottom = Settings.GetInt(BORDER_BOTTOM, 0); int left = Settings.GetInt(BORDER_LEFT, 0); return new ImageBorderMargin(right + left, bottom + top, new BorderCalculation(right + left, bottom + top)); } set { value.Save(Settings.GetSubProperties(BORDER_INFO)); Settings.SetInt(BORDER_TOP, value.Height); Settings.SetInt(BORDER_RIGHT, value.Width); Settings.SetInt(BORDER_BOTTOM, 0); Settings.SetInt(BORDER_LEFT, 0); } } /// <summary> /// The image size name used when determining the current image size. /// This value is used to decide what the best initial size should be for the image if the current /// size is saved as the default size. Rather than forcing all future images to be exactly the current /// size, the named size can be used for more flexibility. /// </summary> public ImageSizeName ImageSizeName { get { ImageSizeName bounds = (ImageSizeName)ImageSizeName.Parse( typeof(ImageSizeName), Settings.GetString(SIZE_NAME, ImageSizeName.Full.ToString())); return bounds; } set { Settings.SetString(SIZE_NAME, value.ToString()); } } public bool IsImageSizeNameSet { get { return Settings.GetString(SIZE_NAME, null) != null; } } public bool AspectRatioLocked { get { return Settings.GetBoolean(ASPECT_RATIO_LOCKED, true); } set { Settings.SetBoolean(ASPECT_RATIO_LOCKED, value); } } public Size TargetAspectRatioSize { get { return new Size(Settings.GetInt(TARGET_ASPECT_RATIO_WIDTH, -1), Settings.GetInt(TARGET_ASPECT_RATIO_HEIGHT, -1)); } set { Settings.SetInt(TARGET_ASPECT_RATIO_WIDTH, value.Width); Settings.SetInt(TARGET_ASPECT_RATIO_HEIGHT, value.Height); } } public Size DefaultBoundsSize { get { return GetDefaultImageSize(Settings); } set { Settings.SetInt(DEFAULT_WIDTH, value.Width); Settings.SetInt(DEFAULT_HEIGHT, value.Height); } } public static Size GetDefaultImageSize(IProperties settings) { ImageSizeName boundsSize = GetDefaultBoundsSizeName(settings); Size defaultBoundsSize; if (boundsSize != ImageSizeName.Custom) defaultBoundsSize = ImageSizeHelper.GetSizeConstraints(boundsSize); else { int defaultWidth = settings.GetInt(DEFAULT_WIDTH, 240); int defaultHeight = settings.GetInt(DEFAULT_HEIGHT, 240); defaultBoundsSize = new Size(defaultWidth, defaultHeight); } return defaultBoundsSize; } // This will callback to the hosting application, so we lazy load it. private static readonly LazyLoader<string> DefaultSizeName = new LazyLoader<string>(() => GlobalEditorOptions.GetSetting<string>(ContentEditorSetting.ImageDefaultSize)); public static ImageSizeName GetDefaultBoundsSizeName(IProperties settings) { string defaultSizeName = DefaultSizeName; if (!Enum.IsDefined(typeof(ImageSizeName), defaultSizeName)) { // This is our fallback if the hosting application returns a bad value. defaultSizeName = ImageSizeName.Small.ToString(); } return (ImageSizeName)Enum.Parse(typeof(ImageSizeName), settings.GetString(DEFAULT_SIZE_NAME, defaultSizeName)); } public ImageSizeName DefaultBoundsSizeName { get { return GetDefaultBoundsSizeName(Settings); } set { Settings.SetString(DEFAULT_SIZE_NAME, value.ToString()); } } public string ImageUrl { get { return (string)ImgElement.getAttribute("src", 2); } set { ImgElement.setAttribute("src", value, 0); } } public RotateFlipType Rotation { get { string rotation = Settings.GetString(ROTATION, RotateFlipType.RotateNoneFlipNone.ToString()); try { return (RotateFlipType)RotateFlipType.Parse(typeof(RotateFlipType), rotation); } catch (Exception) { return RotateFlipType.RotateNoneFlipNone; } } set { Settings.SetString(ROTATION, value.ToString()); } } // The base size is used to quickly determine whether the image has // been cropped since the last time the default bounds were calculated. public Size? BaseSize { get { if (!Settings.Contains(BASE_WIDTH) || !Settings.Contains(BASE_HEIGHT)) return null; try { return new Size(Settings.GetInt(BASE_WIDTH, -1), Settings.GetInt(BASE_HEIGHT, -1)); } catch { return null; } } set { if (value == null) { Settings.Remove(BASE_WIDTH); Settings.Remove(BASE_HEIGHT); } else { Settings.SetInt(BASE_WIDTH, value.Value.Width); Settings.SetInt(BASE_HEIGHT, value.Value.Height); } } } public RotateFlipType? PrevRotation { get { return (RotateFlipType)Enum.Parse(typeof(RotateFlipType), Settings.GetString(PREV_ROTATION, RotateFlipType.RotateNoneFlipNone.ToString())); } set { Settings.SetString(PREV_ROTATION, value.ToString()); } } public bool BaseSizeChanged(Bitmap image) { Size? baseSize = BaseSize; if (baseSize == null) return true; return !baseSize.Equals(image.Size); } } }
//------------------------------------------------------------------------------ // <copyright file="DbConnectionStringBuilder.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Data.SqlClient; namespace System.Data.Common { /* internal sealed class NamedConnectionStringConverter : StringConverter { public NamedConnectionStringConverter() { } public override bool GetStandardValuesSupported(ITypeDescriptorContext context) { return true; } public override bool GetStandardValuesExclusive(ITypeDescriptorContext context) { // Although theoretically this could be true, some people may want to just type in a name return false; } public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) { StandardValuesCollection standardValues = null; if (null != context) { DbConnectionStringBuilder instance = (context.Instance as DbConnectionStringBuilder); if (null != instance) { string myProviderName = instance.GetType().Namespace; List<string> myConnectionNames = new List<string>(); foreach(System.Configuration.ConnectionStringSetting setting in System.Configuration.ConfigurationManager.ConnectionStrings) { if (myProviderName.EndsWith(setting.ProviderName)) { myConnectionNames.Add(setting.ConnectionName); } } standardValues = new StandardValuesCollection(myConnectionNames); } } return standardValues; } } */ internal class DbConnectionStringBuilderDescriptor : PropertyDescriptor { private Type _componentType; private Type _propertyType; private bool _isReadOnly; private bool _refreshOnChange; internal DbConnectionStringBuilderDescriptor(string propertyName, Type componentType, Type propertyType, bool isReadOnly, Attribute[] attributes) : base(propertyName, attributes) { //Bid.Trace("<comm.DbConnectionStringBuilderDescriptor|INFO> propertyName='%ls', propertyType='%ls'\n", propertyName, propertyType.Name); _componentType = componentType; _propertyType = propertyType; _isReadOnly = isReadOnly; } internal bool RefreshOnChange { get { return _refreshOnChange; } set { _refreshOnChange = value; } } public override Type ComponentType { get { return _componentType; } } public override bool IsReadOnly { get { return _isReadOnly; } } public override Type PropertyType { get { return _propertyType; } } public override bool CanResetValue(object component) { DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); return ((null != builder) && builder.ShouldSerialize(DisplayName)); } public override object GetValue(object component) { DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); if (null != builder) { object value; if (builder.TryGetValue(DisplayName, out value)) { return value; } } return null; } public override void ResetValue(object component) { DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); if (null != builder) { builder.Remove(DisplayName); if (RefreshOnChange) { builder.ClearPropertyDescriptors(); } } } public override void SetValue(object component, object value) { DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); if (null != builder) { // via the editor, empty string does a defacto Reset if ((typeof(string) == PropertyType) && String.Empty.Equals(value)) { value = null; } builder[DisplayName] = value; if (RefreshOnChange) { builder.ClearPropertyDescriptors(); } } } public override bool ShouldSerializeValue(object component) { DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); return ((null != builder) && builder.ShouldSerialize(DisplayName)); } } [Serializable()] internal sealed class ReadOnlyCollection<T> : System.Collections.ICollection, ICollection<T> { private T[] _items; internal ReadOnlyCollection(T[] items) { _items = items; #if DEBUG for(int i = 0; i < items.Length; ++i) { Debug.Assert(null != items[i], "null item"); } #endif } public void CopyTo(T[] array, int arrayIndex) { Array.Copy(_items, 0, array, arrayIndex, _items.Length); } void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { Array.Copy(_items, 0, array, arrayIndex, _items.Length); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator<T>(_items); } public System.Collections.IEnumerator GetEnumerator() { return new Enumerator<T>(_items); } bool System.Collections.ICollection.IsSynchronized { get { return false; } } Object System.Collections.ICollection.SyncRoot { get { return _items; } } bool ICollection<T>.IsReadOnly { get { return true;} } void ICollection<T>.Add(T value) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T value) { return Array.IndexOf(_items, value) >= 0; } bool ICollection<T>.Remove(T value) { throw new NotSupportedException(); } public int Count { get { return _items.Length; } } [Serializable()] internal struct Enumerator<K> : IEnumerator<K>, System.Collections.IEnumerator { // based on List<T>.Enumerator private K[] _items; private int _index; internal Enumerator(K[] items) { _items = items; _index = -1; } public void Dispose() { } public bool MoveNext() { return (++_index < _items.Length); } public K Current { get { return _items[_index]; } } Object System.Collections.IEnumerator.Current { get { return _items[_index]; } } void System.Collections.IEnumerator.Reset() { _index = -1; } } } internal static class DbConnectionStringBuilderUtil { internal static bool ConvertToBoolean(object value) { Debug.Assert(null != value, "ConvertToBoolean(null)"); string svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) return false; else { string tmp = svalue.Trim(); // Remove leading & trailing white space. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) return false; } return Boolean.Parse(svalue); } try { return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e); } } internal static bool ConvertToIntegratedSecurity(object value) { Debug.Assert(null != value, "ConvertToIntegratedSecurity(null)"); string svalue = (value as string); if (null != svalue) { if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "true") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(svalue, "false") || StringComparer.OrdinalIgnoreCase.Equals(svalue, "no")) return false; else { string tmp = svalue.Trim(); // Remove leading & trailing white space. if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "sspi") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "true") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "yes")) return true; else if (StringComparer.OrdinalIgnoreCase.Equals(tmp, "false") || StringComparer.OrdinalIgnoreCase.Equals(tmp, "no")) return false; } return Boolean.Parse(svalue); } try { return ((IConvertible)value).ToBoolean(CultureInfo.InvariantCulture); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Boolean), e); } } internal static int ConvertToInt32(object value) { try { return ((IConvertible)value).ToInt32(CultureInfo.InvariantCulture); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(Int32), e); } } internal static string ConvertToString(object value) { try { return ((IConvertible)value).ToString(CultureInfo.InvariantCulture); } catch (InvalidCastException e) { throw ADP.ConvertFailed(value.GetType(), typeof(String), e); } } const string ApplicationIntentReadWriteString = "ReadWrite"; const string ApplicationIntentReadOnlyString = "ReadOnly"; internal static bool TryConvertToApplicationIntent(string value, out ApplicationIntent result) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); Debug.Assert(null != value, "TryConvertToApplicationIntent(null,...)"); if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadOnlyString)) { result = ApplicationIntent.ReadOnly; return true; } else if (StringComparer.OrdinalIgnoreCase.Equals(value, ApplicationIntentReadWriteString)) { result = ApplicationIntent.ReadWrite; return true; } else { result = DbConnectionStringDefaults.ApplicationIntent; return false; } } internal static bool IsValidApplicationIntentValue(ApplicationIntent value) { Debug.Assert(Enum.GetNames(typeof(ApplicationIntent)).Length == 2, "ApplicationIntent enum has changed, update needed"); return value == ApplicationIntent.ReadOnly || value == ApplicationIntent.ReadWrite; } internal static string ApplicationIntentToString(ApplicationIntent value) { Debug.Assert(IsValidApplicationIntentValue(value)); if (value == ApplicationIntent.ReadOnly) { return ApplicationIntentReadOnlyString; } else { return ApplicationIntentReadWriteString; } } /// <summary> /// This method attempts to convert the given value tp ApplicationIntent enum. The algorithm is: /// * if the value is from type string, it will be matched against ApplicationIntent enum names only, using ordinal, case-insensitive comparer /// * if the value is from type ApplicationIntent, it will be used as is /// * if the value is from integral type (SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, or UInt64), it will be converted to enum /// * if the value is another enum or any other type, it will be blocked with an appropriate ArgumentException /// /// in any case above, if the conerted value is out of valid range, the method raises ArgumentOutOfRangeException. /// </summary> /// <returns>applicaiton intent value in the valid range</returns> internal static ApplicationIntent ConvertToApplicationIntent(string keyword, object value) { Debug.Assert(null != value, "ConvertToApplicationIntent(null)"); string sValue = (value as string); ApplicationIntent result; if (null != sValue) { // We could use Enum.TryParse<ApplicationIntent> here, but it accepts value combinations like // "ReadOnly, ReadWrite" which are unwelcome here // Also, Enum.TryParse is 100x slower than plain StringComparer.OrdinalIgnoreCase.Equals method. if (TryConvertToApplicationIntent(sValue, out result)) { return result; } // try again after remove leading & trailing whitespaces. sValue = sValue.Trim(); if (TryConvertToApplicationIntent(sValue, out result)) { return result; } // string values must be valid throw ADP.InvalidConnectionOptionValue(keyword); } else { // the value is not string, try other options ApplicationIntent eValue; if (value is ApplicationIntent) { // quick path for the most common case eValue = (ApplicationIntent)value; } else if (value.GetType().IsEnum) { // explicitly block scenarios in which user tries to use wrong enum types, like: // builder["ApplicationIntent"] = EnvironmentVariableTarget.Process; // workaround: explicitly cast non-ApplicationIntent enums to int throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), null); } else { try { // Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest eValue = (ApplicationIntent)Enum.ToObject(typeof(ApplicationIntent), value); } catch (ArgumentException e) { // to be consistent with the messages we send in case of wrong type usage, replace // the error with our exception, and keep the original one as inner one for troubleshooting throw ADP.ConvertFailed(value.GetType(), typeof(ApplicationIntent), e); } } // ensure value is in valid range if (IsValidApplicationIntentValue(eValue)) { return eValue; } else { throw ADP.InvalidEnumerationValue(typeof(ApplicationIntent), (int)eValue); } } } const string SqlPasswordString = "Sql Password"; const string ActiveDirectoryPasswordString = "Active Directory Password"; const string ActiveDirectoryIntegratedString = "Active Directory Integrated"; internal static bool TryConvertToAuthenticationType(string value, out SqlAuthenticationMethod result) { Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 4, "SqlAuthenticationMethod enum has changed, update needed"); bool isSuccess = false; if (StringComparer.InvariantCultureIgnoreCase.Equals(value, SqlPasswordString)) { result = SqlAuthenticationMethod.SqlPassword; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryPasswordString)) { result = SqlAuthenticationMethod.ActiveDirectoryPassword; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ActiveDirectoryIntegratedString)) { result = SqlAuthenticationMethod.ActiveDirectoryIntegrated; isSuccess = true; } else { result = DbConnectionStringDefaults.Authentication; } return isSuccess; } /// <summary> /// Column Encryption Setting. /// </summary> const string ColumnEncryptionSettingEnabledString = "Enabled"; const string ColumnEncryptionSettingDisabledString = "Disabled"; /// <summary> /// Convert a string value to the corresponding SqlConnectionColumnEncryptionSetting. /// </summary> /// <param name="value"></param> /// <param name="result"></param> /// <returns></returns> internal static bool TryConvertToColumnEncryptionSetting(string value, out SqlConnectionColumnEncryptionSetting result) { bool isSuccess = false; if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingEnabledString)) { result = SqlConnectionColumnEncryptionSetting.Enabled; isSuccess = true; } else if (StringComparer.InvariantCultureIgnoreCase.Equals(value, ColumnEncryptionSettingDisabledString)) { result = SqlConnectionColumnEncryptionSetting.Disabled; isSuccess = true; } else { result = DbConnectionStringDefaults.ColumnEncryptionSetting; } return isSuccess; } /// <summary> /// Is it a valid connection level column encryption setting ? /// </summary> /// <param name="value"></param> /// <returns></returns> internal static bool IsValidColumnEncryptionSetting(SqlConnectionColumnEncryptionSetting value) { Debug.Assert(Enum.GetNames(typeof(SqlConnectionColumnEncryptionSetting)).Length == 2, "SqlConnectionColumnEncryptionSetting enum has changed, update needed"); return value == SqlConnectionColumnEncryptionSetting.Enabled || value == SqlConnectionColumnEncryptionSetting.Disabled; } /// <summary> /// Convert connection level column encryption setting value to string. /// </summary> /// <param name="value"></param> /// <returns></returns> internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryptionSetting value) { Debug.Assert(IsValidColumnEncryptionSetting(value), "value is not a valid connection level column encryption setting."); switch (value) { case SqlConnectionColumnEncryptionSetting.Enabled: return ColumnEncryptionSettingEnabledString; case SqlConnectionColumnEncryptionSetting.Disabled: return ColumnEncryptionSettingDisabledString; default: return null; } } internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value) { Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 4, "SqlAuthenticationMethod enum has changed, update needed"); return value == SqlAuthenticationMethod.SqlPassword || value == SqlAuthenticationMethod.ActiveDirectoryPassword || value == SqlAuthenticationMethod.ActiveDirectoryIntegrated || value == SqlAuthenticationMethod.NotSpecified; } internal static string AuthenticationTypeToString(SqlAuthenticationMethod value) { Debug.Assert(IsValidAuthenticationTypeValue(value)); switch (value) { case SqlAuthenticationMethod.SqlPassword: return SqlPasswordString; case SqlAuthenticationMethod.ActiveDirectoryPassword: return ActiveDirectoryPasswordString; case SqlAuthenticationMethod.ActiveDirectoryIntegrated: return ActiveDirectoryIntegratedString; default: return null; } } internal static SqlAuthenticationMethod ConvertToAuthenticationType(string keyword, object value) { if (null == value) { return DbConnectionStringDefaults.Authentication; } string sValue = (value as string); SqlAuthenticationMethod result; if (null != sValue) { if (TryConvertToAuthenticationType(sValue, out result)) { return result; } // try again after remove leading & trailing whitespaces. sValue = sValue.Trim(); if (TryConvertToAuthenticationType(sValue, out result)) { return result; } // string values must be valid throw ADP.InvalidConnectionOptionValue(keyword); } else { // the value is not string, try other options SqlAuthenticationMethod eValue; if (value is SqlAuthenticationMethod) { // quick path for the most common case eValue = (SqlAuthenticationMethod)value; } else if (value.GetType().IsEnum) { // explicitly block scenarios in which user tries to use wrong enum types, like: // builder["ApplicationIntent"] = EnvironmentVariableTarget.Process; // workaround: explicitly cast non-ApplicationIntent enums to int throw ADP.ConvertFailed(value.GetType(), typeof(SqlAuthenticationMethod), null); } else { try { // Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest eValue = (SqlAuthenticationMethod)Enum.ToObject(typeof(SqlAuthenticationMethod), value); } catch (ArgumentException e) { // to be consistent with the messages we send in case of wrong type usage, replace // the error with our exception, and keep the original one as inner one for troubleshooting throw ADP.ConvertFailed(value.GetType(), typeof(SqlAuthenticationMethod), e); } } // ensure value is in valid range if (IsValidAuthenticationTypeValue(eValue)) { return eValue; } else { throw ADP.InvalidEnumerationValue(typeof(SqlAuthenticationMethod), (int)eValue); } } } /// <summary> /// Convert the provided value to a SqlConnectionColumnEncryptionSetting. /// </summary> /// <param name="keyword"></param> /// <param name="value"></param> /// <returns></returns> internal static SqlConnectionColumnEncryptionSetting ConvertToColumnEncryptionSetting(string keyword, object value) { if (null == value) { return DbConnectionStringDefaults.ColumnEncryptionSetting; } string sValue = (value as string); SqlConnectionColumnEncryptionSetting result; if (null != sValue) { if (TryConvertToColumnEncryptionSetting(sValue, out result)) { return result; } // try again after remove leading & trailing whitespaces. sValue = sValue.Trim(); if (TryConvertToColumnEncryptionSetting(sValue, out result)) { return result; } // string values must be valid throw ADP.InvalidConnectionOptionValue(keyword); } else { // the value is not string, try other options SqlConnectionColumnEncryptionSetting eValue; if (value is SqlConnectionColumnEncryptionSetting) { // quick path for the most common case eValue = (SqlConnectionColumnEncryptionSetting)value; } else if (value.GetType().IsEnum) { // explicitly block scenarios in which user tries to use wrong enum types, like: // builder["SqlConnectionColumnEncryptionSetting"] = EnvironmentVariableTarget.Process; // workaround: explicitly cast non-SqlConnectionColumnEncryptionSetting enums to int throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionColumnEncryptionSetting), null); } else { try { // Enum.ToObject allows only integral and enum values (enums are blocked above), rasing ArgumentException for the rest eValue = (SqlConnectionColumnEncryptionSetting)Enum.ToObject(typeof(SqlConnectionColumnEncryptionSetting), value); } catch (ArgumentException e) { // to be consistent with the messages we send in case of wrong type usage, replace // the error with our exception, and keep the original one as inner one for troubleshooting throw ADP.ConvertFailed(value.GetType(), typeof(SqlConnectionColumnEncryptionSetting), e); } } // ensure value is in valid range if (IsValidColumnEncryptionSetting(eValue)) { return eValue; } else { throw ADP.InvalidEnumerationValue(typeof(SqlConnectionColumnEncryptionSetting), (int)eValue); } } } } internal static class DbConnectionStringDefaults { // all // internal const string NamedConnection = ""; // Odbc internal const string Driver = ""; internal const string Dsn = ""; // OleDb internal const bool AdoNetPooler = false; internal const string FileName = ""; internal const int OleDbServices = ~(/*DBPROPVAL_OS_AGR_AFTERSESSION*/0x00000008 | /*DBPROPVAL_OS_CLIENTCURSOR*/0x00000004); // -13 internal const string Provider = ""; // OracleClient internal const bool Unicode = false; internal const bool OmitOracleConnectionName = false; // SqlClient internal const ApplicationIntent ApplicationIntent = System.Data.SqlClient.ApplicationIntent.ReadWrite; internal const string ApplicationName = ".Net SqlClient Data Provider"; internal const bool AsynchronousProcessing = false; internal const string AttachDBFilename = ""; internal const int ConnectTimeout = 15; internal const bool ConnectionReset = true; internal const bool ContextConnection = false; internal const string CurrentLanguage = ""; internal const string DataSource = ""; internal const bool Encrypt = false; internal const bool Enlist = true; internal const string FailoverPartner = ""; internal const string InitialCatalog = ""; internal const bool IntegratedSecurity = false; internal const int LoadBalanceTimeout = 0; // default of 0 means don't use internal const bool MultipleActiveResultSets = false; internal const bool MultiSubnetFailover = false; internal const bool TransparentNetworkIPResolution = true; internal const int MaxPoolSize = 100; internal const int MinPoolSize = 0; internal const string NetworkLibrary = ""; internal const int PacketSize = 8000; internal const string Password = ""; internal const bool PersistSecurityInfo = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string TypeSystemVersion = "Latest"; internal const string UserID = ""; internal const bool UserInstance = false; internal const bool Replication = false; internal const string WorkstationID = ""; internal const string TransactionBinding = "Implicit Unbind"; internal const int ConnectRetryCount = 1; internal const int ConnectRetryInterval = 10; internal static readonly SqlAuthenticationMethod Authentication = SqlAuthenticationMethod.NotSpecified; internal static readonly SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Disabled; } internal static class DbConnectionOptionKeywords { // Odbc internal const string Driver = "driver"; internal const string Pwd = "pwd"; internal const string UID = "uid"; // OleDb internal const string DataProvider = "data provider"; internal const string ExtendedProperties = "extended properties"; internal const string FileName = "file name"; internal const string Provider = "provider"; internal const string RemoteProvider = "remote provider"; // common keywords (OleDb, OracleClient, SqlClient) internal const string Password = "password"; internal const string UserID = "user id"; } internal static class DbConnectionStringKeywords { // all // internal const string NamedConnection = "Named Connection"; // Odbc internal const string Driver = "Driver"; internal const string Dsn = "Dsn"; internal const string FileDsn = "FileDsn"; internal const string SaveFile = "SaveFile"; // OleDb internal const string FileName = "File Name"; internal const string OleDbServices = "OLE DB Services"; internal const string Provider = "Provider"; // OracleClient internal const string Unicode = "Unicode"; internal const string OmitOracleConnectionName = "Omit Oracle Connection Name"; // SqlClient internal const string ApplicationIntent = "ApplicationIntent"; internal const string ApplicationName = "Application Name"; internal const string AsynchronousProcessing = "Asynchronous Processing"; internal const string AttachDBFilename = "AttachDbFilename"; internal const string ConnectTimeout = "Connect Timeout"; internal const string ConnectionReset = "Connection Reset"; internal const string ContextConnection = "Context Connection"; internal const string CurrentLanguage = "Current Language"; internal const string Encrypt = "Encrypt"; internal const string FailoverPartner = "Failover Partner"; internal const string InitialCatalog = "Initial Catalog"; internal const string MultipleActiveResultSets = "MultipleActiveResultSets"; internal const string MultiSubnetFailover = "MultiSubnetFailover"; internal const string TransparentNetworkIPResolution = "TransparentNetworkIPResolution"; internal const string NetworkLibrary = "Network Library"; internal const string PacketSize = "Packet Size"; internal const string Replication = "Replication"; internal const string TransactionBinding = "Transaction Binding"; internal const string TrustServerCertificate = "TrustServerCertificate"; internal const string TypeSystemVersion = "Type System Version"; internal const string UserInstance = "User Instance"; internal const string WorkstationID = "Workstation ID"; internal const string ConnectRetryCount = "ConnectRetryCount"; internal const string ConnectRetryInterval = "ConnectRetryInterval"; internal const string Authentication = "Authentication"; internal const string Certificate = "Certificate"; internal const string ColumnEncryptionSetting = "Column Encryption Setting"; // common keywords (OleDb, OracleClient, SqlClient) internal const string DataSource = "Data Source"; internal const string IntegratedSecurity = "Integrated Security"; internal const string Password = "Password"; internal const string PersistSecurityInfo = "Persist Security Info"; internal const string UserID = "User ID"; // managed pooling (OracleClient, SqlClient) internal const string Enlist = "Enlist"; internal const string LoadBalanceTimeout = "Load Balance Timeout"; internal const string MaxPoolSize = "Max Pool Size"; internal const string Pooling = "Pooling"; internal const string MinPoolSize = "Min Pool Size"; } internal static class DbConnectionStringSynonyms { //internal const string AsynchronousProcessing = Async; internal const string Async = "async"; //internal const string ApplicationName = APP; internal const string APP = "app"; //internal const string AttachDBFilename = EXTENDEDPROPERTIES+","+INITIALFILENAME; internal const string EXTENDEDPROPERTIES = "extended properties"; internal const string INITIALFILENAME = "initial file name"; //internal const string ConnectTimeout = CONNECTIONTIMEOUT+","+TIMEOUT; internal const string CONNECTIONTIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; //internal const string CurrentLanguage = LANGUAGE; internal const string LANGUAGE = "language"; //internal const string OraDataSource = SERVER; //internal const string SqlDataSource = ADDR+","+ADDRESS+","+SERVER+","+NETWORKADDRESS; internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORKADDRESS = "network address"; //internal const string InitialCatalog = DATABASE; internal const string DATABASE = "database"; //internal const string IntegratedSecurity = TRUSTEDCONNECTION; internal const string TRUSTEDCONNECTION = "trusted_connection"; // underscore introduced in everett //internal const string LoadBalanceTimeout = ConnectionLifetime; internal const string ConnectionLifetime = "connection lifetime"; //internal const string NetworkLibrary = NET+","+NETWORK; internal const string NET = "net"; internal const string NETWORK = "network"; internal const string WorkaroundOracleBug914652 = "Workaround Oracle Bug 914652"; //internal const string Password = Pwd; internal const string Pwd = "pwd"; //internal const string PersistSecurityInfo = PERSISTSECURITYINFO; internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; //internal const string UserID = UID+","+User; internal const string UID = "uid"; internal const string User = "user"; //internal const string WorkstationID = WSID; internal const string WSID = "wsid"; } }
using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { //Console.Write("Enter First Number:"); //string a = Console.ReadLine(); //Console.Write("Enter Second Number:"); //string b = Console.ReadLine(); //int c = Convert.ToInt32(a) + Convert.ToInt32(b); // Console.WriteLine("Sum:"+c.ToString()); Program o = new Program(); o.Start(); Console.Read(); } void Start() { List<Person> lstPredictPerson = new List<Person>(); double outVal = 0; int outShortVal = 0; Console.Write("Enter Height:"); var height = double.TryParse(Console.ReadLine(), out outVal) == true ? outVal : 0; Console.Write("Enter Weight:"); var weight = double.TryParse(Console.ReadLine(), out outVal) == true ? outVal : 0; Console.Write("Enter FootSize:"); var footSize = double.TryParse(Console.ReadLine(), out outVal) == true ? outVal : 0; Console.Write("Enter Age:"); int age = int.TryParse(Console.ReadLine(), out outShortVal) == true ? outShortVal : 0; lstPredictPerson.Add(new Person { Height = height, Weight = weight, FootSize = footSize, Age = age }); List<Person> lstPerson = new List<Person>(); //training data. lstPerson.Add(new Person { Sex = "male", Height = 6, Weight = 90, FootSize = 12, Age = 25 }); lstPerson.Add(new Person { Sex = "male", Height = 5.92, Weight = 95, FootSize = 11, Age = 30 }); lstPerson.Add(new Person { Sex = "male", Height = 5.58, Weight = 85, FootSize = 12, Age = 40 }); lstPerson.Add(new Person { Sex = "male", Height = 5.92, Weight = 82, FootSize = 10, Age = 20 }); lstPerson.Add(new Person { Sex = "male", Height = 5, Weight = 50, FootSize = 6, Age = 15 }); lstPerson.Add(new Person { Sex = "male", Height = 5, Weight = 40, FootSize = 5, Age = 10 }); lstPerson.Add(new Person { Sex = "male", Height = 2, Weight = 20, FootSize = 3, Age = 4 }); lstPerson.Add(new Person { Sex = "female", Height = 5.5, Weight = 75, FootSize = 8, Age = 40 }); lstPerson.Add(new Person { Sex = "female", Height = 5.42, Weight = 65, FootSize = 7, Age = 30 }); lstPerson.Add(new Person { Sex = "female", Height = 5.75, Weight = 75, FootSize = 9, Age = 20 }); lstPerson.Add(new Person { Sex = "female", Height = 2, Weight = 15, FootSize = 2, Age = 3 }); lstPerson.Add(new Person { Sex = "transgender", Height = 4, Weight = 100, FootSize = 5, Age = 35 }); lstPerson.Add(new Person { Sex = "transgender", Height = 4.10, Weight = 75, FootSize = 8, Age = 30 }); lstPerson.Add(new Person { Sex = "transgender", Height = 5.42, Weight = 95, FootSize = 7, Age = 25 }); lstPerson.Add(new Person { Sex = "transgender", Height = 5.50, Weight = 75, FootSize = 9, Age = 20 }); TrainClassifier(lstPerson, lstPredictPerson); //output would be transgender. //Console.WriteLine(classifier.Classify(new double[] { 4, 150, 12 })); } void TrainClassifier(List<Person> lstPerson, List<Person> lstPredictPerson) { try { List<MeanPerson> lstMeanPerson = new List<MeanPerson>(); //calc data var results = (from singlePerson in lstPerson group singlePerson by singlePerson.Sex into g select new { Sex = g.Key, Count = g.Count() }).ToList(); for (int j = 0; j < results.Count; j++) { var selectedSex = results[j].Sex; var commonSetData = from commonSet in lstPerson where commonSet.Sex == selectedSex select commonSet; if (commonSetData.Any()) { var sumHeight = commonSetData.Sum(a => a.Height); var sumWeight = commonSetData.Sum(a => a.Weight); var sumFootSize = commonSetData.Sum(a => a.FootSize); var sumAge = commonSetData.Sum(a => a.Age); var noOfRecords = commonSetData.Count(); lstMeanPerson.Add(new MeanPerson { Sex = selectedSex, HeightMean = sumHeight > 0 ? sumHeight / noOfRecords : 0, WeightMean = sumWeight > 0 ? sumWeight / noOfRecords : 0, FootSizeMean = sumFootSize > 0 ? sumFootSize / noOfRecords : 0, AgeMean = sumAge > 0 ? sumAge / noOfRecords : 0 }); } } //int a = 1; //for (int i = 1; i < 4; i++) //{ // row[a] = Helper.Mean(SelectRows(table, i, string.Format("{0} = '{1}'", // table.Columns[0].ColumnName, results[j].Name))); // // row[++a] = Helper.Variance(SelectRows(table, i, // // string.Format("{0} = '{1}'", // // table.Columns[0].ColumnName, results[j].Name))); // a++; //} var height = lstPredictPerson[0].Height; var weight = lstPredictPerson[0].Weight; var footSize = lstPredictPerson[0].FootSize; var age = lstPredictPerson[0].Age; List<Height> llstHeight = new List<Height>(); List<Weight> llstWeight = new List<Weight>(); List<FootSize> llstFootSize = new List<FootSize>(); List<Age> llstAge = new List<Age>(); foreach (var x in lstMeanPerson) { var diffH = x.HeightMean - height; var diffW = x.WeightMean - weight; var diffFS = x.FootSizeMean - footSize; var diffA = x.AgeMean - age; diffH = diffH > 0 ? diffH : diffH * -1; diffW = diffW > 0 ? diffW : diffW * -1; diffFS = diffFS > 0 ? diffFS : diffFS * -1; diffA = diffA > 0 ? diffA : diffA * -1; llstHeight.Add(new Height { Sex = x.Sex, diff = diffH }); llstWeight.Add(new Weight { Sex = x.Sex, diff = diffW }); llstFootSize.Add(new FootSize { Sex = x.Sex, diff = diffFS }); llstAge.Add(new Age { Sex = x.Sex, diff = diffA }); //Console.WriteLine("Sex:{0}, H:{1}, W:{2}, F:{3}, A:{4}", x.Sex, x.HeightMean, x.WeightMean, x.FootSizeMean,x.AgeMean); } var minH = (from singleVal in llstHeight where singleVal.diff == llstHeight.Min(a => a.diff) select singleVal.Sex).FirstOrDefault().ToString(); var minW = (from singleVal in llstWeight where singleVal.diff == llstWeight.Min(a => a.diff) select singleVal.Sex).FirstOrDefault().ToString(); var minFS = (from singleVal in llstFootSize where singleVal.diff == llstFootSize.Min(a => a.diff) select singleVal.Sex).FirstOrDefault().ToString(); var minA = (from singleVal in llstAge where singleVal.diff == llstAge.Min(a => a.diff) select singleVal.Sex).FirstOrDefault().ToString(); List<PredictSex> llstPredictSex = new List<PredictSex>(); llstPredictSex.Add(new PredictSex { Sex = minH, diff = llstHeight.Min(a => a.diff) }); llstPredictSex.Add(new PredictSex { Sex = minW, diff = llstWeight.Min(a => a.diff) }); llstPredictSex.Add(new PredictSex { Sex = minFS, diff = llstFootSize.Min(a => a.diff) }); llstPredictSex.Add(new PredictSex { Sex = minA, diff = llstAge.Min(a => a.diff) }); var predict = (from singleSex in llstPredictSex group singleSex by singleSex.Sex into g select new { Name = g.Key, Count = g.Count() }).ToList(); //Console.WriteLine(minH); //Console.WriteLine(minW); //Console.WriteLine(minFS); if (predict.Any()) { var bestOfAll = (from singlePredict in predict where singlePredict.Count == predict.Max(a => a.Count) select singlePredict.Name).FirstOrDefault().ToString(); Console.WriteLine(bestOfAll); } else { var minDiffAll = (from singleVal in llstPredictSex where singleVal.diff == llstPredictSex.Min(a => a.diff) select singleVal.Sex).FirstOrDefault().ToString(); Console.WriteLine(minDiffAll); } } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } //static string Classify(double[] obj) //{ // Dictionary<string,double> score = new Dictionary<string,double>(); // var results = (from myRow in dataSet.Tables[0].AsEnumerable() // group myRow by myRow.Field<string>( // dataSet.Tables[0].Columns[0].ColumnName) into g // select new { Name = g.Key, Count = g.Count() }).ToList(); // for (int i = 0; i < results.Count; i++) // { // List<double> subScoreList = new List<double>(); // int a = 1, b = 1; // for (int k = 1; k < dataSet.Tables["Gaussian"].Columns.Count; k = k + 2) // { // double mean = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][a]); // double variance = Convert.ToDouble(dataSet.Tables["Gaussian"].Rows[i][++a]); // double result = Helper.NormalDist(obj[b - 1], mean, Helper.SquareRoot(variance)); // subScoreList.Add(result); // a++; b++; // } // double finalScore = 0; // for (int z = 0; z < subScoreList.Count; z++) // { // if (finalScore == 0) // { // finalScore = subScoreList[z]; // continue; // } // finalScore = finalScore * subScoreList[z]; // } // score.Add(results[i].Name, finalScore * 0.5); // } // double maxOne = score.Max(c => c.Value); // var name = (from c in score // where c.Value == maxOne // select c.Key).First(); // return name; //} public class Person { public string Sex { get; set; } public double Height { get; set; } public double Weight { get; set; } public double FootSize { get; set; } public int Age { get; set; } } public class MeanPerson { public string Sex { get; set; } public double HeightMean { get; set; } public double WeightMean { get; set; } public double FootSizeMean { get; set; } public int AgeMean { get; set; } } public class Height { public string Sex { get; set; } public double diff { get; set; } } public class Weight { public string Sex { get; set; } public double diff { get; set; } } public class FootSize { public string Sex { get; set; } public double diff { get; set; } } public class Age { public string Sex { get; set; } public double diff { get; set; } } public class PredictSex { public string Sex { get; set; } public double diff { get; set; } }
#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: ErrorTweetModule.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Web; using System.Collections.Generic; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// HTTP module implementation that posts tweets (short messages /// usually limited to 140 characters) about unhandled exceptions in /// an ASP.NET Web application to a Twitter account. /// </summary> /// <remarks> /// This module requires that the hosting application has permissions /// send HTTP POST requests to another Internet domain. /// </remarks> public class ErrorTweetModule : HttpModuleBase, IExceptionFiltering { public event ExceptionFilterEventHandler Filtering; private ICredentials _credentials; private string _statusFormat; private Uri _url; private int _maxStatusLength; private string _ellipsis; private string _formFormat; private List<WebRequest> _requests; /// <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. // IDictionary config = (IDictionary) GetConfig(); if (config == null) return; string userName = GetSetting(config, "userName", string.Empty); string password = GetSetting(config, "password", string.Empty); string statusFormat = GetSetting(config, "statusFormat", "{Message}"); int maxStatusLength = int.Parse(GetSetting(config, "maxStatusLength", "140"), NumberStyles.None, CultureInfo.InvariantCulture); string ellipsis = GetSetting(config, "ellipsis", /* ... */ "\x2026"); string formFormat = GetSetting(config, "formFormat", "status={0}"); Uri url = new Uri(GetSetting(config, "url", "http://twitter.com/statuses/update.xml"), UriKind.Absolute); _credentials = new NetworkCredential(userName, password); _statusFormat = statusFormat; _url = url; _maxStatusLength = maxStatusLength; _ellipsis = ellipsis; _formFormat = formFormat; _requests = new List<WebRequest>(); // TODO Synchronization application.Error += new EventHandler(OnError); ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled); } /// <summary> /// Gets the <see cref="ErrorLog"/> instance to which the module /// will log exceptions. /// </summary> protected virtual ErrorLog GetErrorLog(HttpContextBase context) { return ErrorLog.GetDefault(context); } /// <summary> /// The handler called when an unhandled exception bubbles up to /// the module. /// </summary> protected virtual void OnError(object sender, EventArgs args) { HttpApplication application = (HttpApplication) sender; LogException(application.Server.GetLastError(), new HttpContextWrapper(application.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)) LogException(args.Exception, args.Context); } /// <summary> /// Logs an exception and its context to the error log. /// </summary> protected virtual void LogException(Exception e, HttpContextBase context) { if (e == null) throw new ArgumentNullException("e"); // // Fire an event to check if listeners want to filter out // logging of the uncaught exception. // ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context); OnFiltering(args); if (args.Dismissed) return; // // Tweet away... // HttpWebRequest request = null; try { string status = StringFormatter.Format(_statusFormat, new Error(e, context)); // // Apply ellipsis if status is too long. If the trimmed // status plus ellipsis yields nothing then just use // the trimmed status without ellipsis. This can happen if // someone gives an ellipsis that is ridiculously long. // int maxLength = _maxStatusLength; if (status.Length > maxLength) { string ellipsis = _ellipsis; int trimmedStatusLength = maxLength - ellipsis.Length; status = trimmedStatusLength >= 0 ? status.Substring(0, trimmedStatusLength) + ellipsis : status.Substring(0, maxLength); } // // Submit the status by posting form data as typically down // by browsers for forms found in HTML. // request = (HttpWebRequest) WebRequest.Create(_url); request.Method = "POST"; // WebRequestMethods.Http.Post; request.ContentType = "application/x-www-form-urlencoded"; if (_credentials != null) // Need Basic authentication? { request.Credentials = _credentials; request.PreAuthenticate = true; } // See http://blogs.msdn.com/shitals/archive/2008/12/27/9254245.aspx request.ServicePoint.Expect100Continue = false; // // URL-encode status into the form and get the bytes to // determine and set the content length. // string encodedForm = string.Format(_formFormat, HttpUtility.UrlEncode(status)); byte[] data = Encoding.ASCII.GetBytes(encodedForm); Debug.Assert(data.Length > 0); request.ContentLength = data.Length; // // Get the request stream into which the form data is to // be written. This is done asynchronously to free up this // thread. // // NOTE: We maintain a (possibly paranoid) list of // outstanding requests and add the request to it so that // it does not get treated as garbage by GC. In effect, // we are creating an explicit root. It is also possible // for this module to get disposed before a request // completes. During the callback, no other member should // be touched except the requests list! // _requests.Add(request); IAsyncResult ar = request.BeginGetRequestStream( new AsyncCallback(OnGetRequestStreamCompleted), AsyncArgs(request, data)); } catch (Exception localException) { // // IMPORTANT! We swallow any exception raised during the // logging and send them out to the trace . The idea // here is that logging of exceptions by itself should not // be critical to the overall operation of the application. // The bad thing is that we catch ANY kind of exception, // even system ones and potentially let them slip by. // OnWebPostError(request, localException); } } private void OnWebPostError(WebRequest request, Exception e) { Debug.Assert(e != null); Trace.WriteLine(e); if (request != null) _requests.Remove(request); } private static object[] AsyncArgs(params object[] args) { return args; } private void OnGetRequestStreamCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); object[] args = (object[]) ar.AsyncState; OnGetRequestStreamCompleted(ar, (WebRequest) args[0], (byte[]) args[1]); } private void OnGetRequestStreamCompleted(IAsyncResult ar, WebRequest request, byte[] data) { Debug.Assert(ar != null); Debug.Assert(request != null); Debug.Assert(data != null); Debug.Assert(data.Length > 0); try { using (Stream output = request.EndGetRequestStream(ar)) output.Write(data, 0, data.Length); request.BeginGetResponse(new AsyncCallback(OnGetResponseCompleted), request); } catch (Exception e) { OnWebPostError(request, e); } } private void OnGetResponseCompleted(IAsyncResult ar) { if (ar == null) throw new ArgumentNullException("ar"); OnGetResponseCompleted(ar, (WebRequest) ar.AsyncState); } private void OnGetResponseCompleted(IAsyncResult ar, WebRequest request) { Debug.Assert(ar != null); Debug.Assert(request != null); try { Debug.Assert(request != null); request.EndGetResponse(ar).Close(); // Not interested; assume OK _requests.Remove(request); } catch (Exception e) { OnWebPostError(request, e); } } /// <summary> /// Raises the <see cref="Filtering"/> event. /// </summary> protected virtual void OnFiltering(ExceptionFilterEventArgs args) { ExceptionFilterEventHandler handler = Filtering; if (handler != null) handler(this, args); } /// <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 configuration object used by <see cref="OnInit"/> to read /// the settings for module. /// </summary> protected virtual object GetConfig() { return Configuration.GetSubsection("errorTweet"); } private static string GetSetting(IDictionary config, string name, string defaultValue) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(name); string 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 tweeting module.", name)); } value = defaultValue; } return value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; namespace Vsts.Cli { public class VstsApiHelper : IVstsApiHelper { private readonly HttpClient _httpClient; private readonly string _pat; public VstsApiHelper(Uri baseAddress, string token) { _httpClient = new HttpClient { BaseAddress = baseAddress }; _pat = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format($"{String.Empty}:{token}"))); } public IEnumerable<Repository> GetRepositories() { string uri = "DefaultCollection/_apis/git/repositories?api-version=1.0"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<Repository>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<RepositoryResource>(result); return resource.Value.AsEnumerable(); } public IEnumerable<PullRequest> GetPullRequests(string repositoryId) { string uri = "DefaultCollection/_apis/git/repositories/{0}/pullRequests?api-version=3.0"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(String.Format(uri, repositoryId)).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<PullRequest>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<PullRequesetResource>(result); return resource.Value.AsEnumerable(); } public PullRequest CreatePullRequest(string repositoryId, string title, string description, string source, string target) { string uri = $"DefaultCollection/_apis/git/repositories/{repositoryId}/pullRequests?api-version=3.0"; var document = new { title = title, description = description, sourceRefName = $"refs/heads/{source}", targetRefName = $"refs/heads/{target}" }; var json = JsonConvert.SerializeObject(document); var jsonContent = new StringContent(json, Encoding.UTF8, "application/json"); _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); var method = new HttpMethod("POST"); var request = new HttpRequestMessage(method, uri) { Content = jsonContent }; var response = _httpClient.SendAsync(request).Result; if (!response.IsSuccessStatusCode) { var error = response.Content.ReadAsStringAsync().Result; var pullRequestErrorResource = JsonConvert.DeserializeObject<PullRequestErrorResource>(error); Console.WriteLine(pullRequestErrorResource.message, ConsoleColor.Red); return null; } var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<PullRequest>(result); return resource; } public IEnumerable<WorkItem> SearchWorkItems(SearchQuery searchQuery) { string uri = $"DefaultCollection/{searchQuery.ProjectName}/_apis/wit/wiql?api-version=1.0"; var workItemSearchResource = JsonConvert.SerializeObject(new WorkItemSearchResource { Query = searchQuery.Query }); _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient .PostAsync(uri, new StringContent(workItemSearchResource, Encoding.ASCII, "application/json")).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<WorkItem>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<WorkItemResource>(result); return resource.WorkItems.AsEnumerable(); } public IEnumerable<Fields> GetWorkItemDetail(int workItemId) { return GetWorkItemDetail(new[] { workItemId }); } public IEnumerable<Fields> GetWorkItemDetail(IEnumerable<int> workItemIds) { string workItemIdString = String.Join(",", workItemIds.Select(x => x.ToString())); var uri = $"DefaultCollection/_apis/wit/WorkItems?ids={workItemIdString}&$expand=all&api-version=1.0"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<Fields>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<WorkItemDetailResource>(result); return resource.Value.Select(x => x.Fields); } public NewWorkItemResource CreateWorkItem(string projectName, string workItemType, IEnumerable<object> document) { string uri = $"{projectName}/_apis/wit/workitems/${workItemType.Normalize()}?api-version=2.2"; //serialize the fields array into a json string var patchValue = new StringContent(JsonConvert.SerializeObject(document), Encoding.UTF8, "application/json-patch+json"); _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); var method = new HttpMethod("PATCH"); var request = new HttpRequestMessage(method, uri) { Content = patchValue }; var response = _httpClient.SendAsync(request).Result; if (!response.IsSuccessStatusCode) return null; var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<NewWorkItemResource>(result); return resource; } public BuildListItem QueueBuildDefinition(string projectName, BuildDefinitionQueueResource buildDefinitionQueueResource) { var uri = $"/DefaultCollection/{projectName}/_apis/build/builds?api-version=2.0"; //serialize the fields array into a json string var serializeObject = JsonConvert.SerializeObject(buildDefinitionQueueResource); var content = new StringContent(serializeObject, Encoding.UTF8, "application/json"); _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); var method = new HttpMethod("POST"); var request = new HttpRequestMessage(method, uri) { Content = content }; var response = _httpClient.SendAsync(request).Result; if (!response.IsSuccessStatusCode) return null; var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<BuildListItem>(result); return resource; } public IEnumerable<BuildDefinition> GetBuildList(string projectName) { var uri = $"DefaultCollection/{projectName}/_apis/build/definitions"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<BuildDefinition>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<BuildDefinitionResource>(result); return resource.value.AsEnumerable(); } public IEnumerable<BuildListItem> GetBuildListDetails(string projectName) { var uri = $"DefaultCollection/{projectName}/_apis/build/builds"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<BuildListItem>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<BuildListResource>(result); return resource.value.AsEnumerable(); } public BuildListItem GetBuildDetail(string projectName, int buildDefinitionId) { var uri = $"DefaultCollection/{projectName}/_apis/build/builds?definitions={buildDefinitionId}&statusFilter=completed&$top=1&api-version=2.0"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return null; var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<BuildListResource>(result); return resource.value.FirstOrDefault(); } public IEnumerable<Record> GetBuildTimeline(string projectName, int buildId) { var uri = $"DefaultCollection/{projectName}/_apis/build/builds/{buildId}/Timeline"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<Record>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<TimelineResource>(result); return resource.records.OrderBy(x => x.order); } public IEnumerable<string> GetBuildLogEntry(string projectName, int buildId, int logId) { var uri = $"DefaultCollection/{projectName}/_apis/build/builds/{buildId}/logs/{logId}"; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", _pat); HttpResponseMessage response = _httpClient.GetAsync(uri).Result; if (!response.IsSuccessStatusCode) return Enumerable.Empty<string>(); var result = response.Content.ReadAsStringAsync().Result; var resource = JsonConvert.DeserializeObject<LogResource>(result); return resource.value; } } }
namespace ReallyEasyResize { partial class frmMain { /// <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(frmMain)); this.btnSelFiles = new System.Windows.Forms.Button(); this.btnSelFolder = new System.Windows.Forms.Button(); this.btnClearQueue = new System.Windows.Forms.Button(); this.lstQueue = new System.Windows.Forms.ListView(); this.grpQueue = new System.Windows.Forms.GroupBox(); this.diaSelFiles = new System.Windows.Forms.OpenFileDialog(); this.diaSaveDest = new System.Windows.Forms.FolderBrowserDialog(); this.diaSelFolder = new System.Windows.Forms.FolderBrowserDialog(); this.grpSettings = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); this.txtJpegQty = new System.Windows.Forms.TextBox(); this.txtHeight = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtWidth = new System.Windows.Forms.TextBox(); this.grpSave = new System.Windows.Forms.GroupBox(); this.txtSaveDest = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.btnSaveDest = new System.Windows.Forms.Button(); this.btnBeginResize = new System.Windows.Forms.Button(); this.btnAbout = new System.Windows.Forms.Button(); this.grpQueue.SuspendLayout(); this.grpSettings.SuspendLayout(); this.grpSave.SuspendLayout(); this.SuspendLayout(); // // btnSelFiles // this.btnSelFiles.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnSelFiles.Location = new System.Drawing.Point(516, 19); this.btnSelFiles.Name = "btnSelFiles"; this.btnSelFiles.Size = new System.Drawing.Size(128, 23); this.btnSelFiles.TabIndex = 2; this.btnSelFiles.Text = "Add &files..."; this.btnSelFiles.UseVisualStyleBackColor = true; this.btnSelFiles.Click += new System.EventHandler(this.btnSelFiles_Click); // // btnSelFolder // this.btnSelFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnSelFolder.Location = new System.Drawing.Point(516, 48); this.btnSelFolder.Name = "btnSelFolder"; this.btnSelFolder.Size = new System.Drawing.Size(128, 23); this.btnSelFolder.TabIndex = 3; this.btnSelFolder.Text = "Add fo&lder..."; this.btnSelFolder.UseVisualStyleBackColor = true; this.btnSelFolder.Click += new System.EventHandler(this.btnSelFolder_Click); // // btnClearQueue // this.btnClearQueue.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnClearQueue.Location = new System.Drawing.Point(516, 77); this.btnClearQueue.Name = "btnClearQueue"; this.btnClearQueue.Size = new System.Drawing.Size(128, 23); this.btnClearQueue.TabIndex = 3; this.btnClearQueue.Text = "&Clear list"; this.btnClearQueue.UseVisualStyleBackColor = true; this.btnClearQueue.Click += new System.EventHandler(this.btnClearQueue_Click); // // lstQueue // this.lstQueue.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstQueue.Location = new System.Drawing.Point(8, 21); this.lstQueue.Margin = new System.Windows.Forms.Padding(5); this.lstQueue.Name = "lstQueue"; this.lstQueue.Size = new System.Drawing.Size(500, 229); this.lstQueue.TabIndex = 1; this.lstQueue.UseCompatibleStateImageBehavior = false; this.lstQueue.View = System.Windows.Forms.View.List; // // grpQueue // this.grpQueue.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpQueue.Controls.Add(this.btnSelFiles); this.grpQueue.Controls.Add(this.lstQueue); this.grpQueue.Controls.Add(this.btnSelFolder); this.grpQueue.Controls.Add(this.btnClearQueue); this.grpQueue.Location = new System.Drawing.Point(12, 12); this.grpQueue.Name = "grpQueue"; this.grpQueue.Size = new System.Drawing.Size(650, 258); this.grpQueue.TabIndex = 0; this.grpQueue.TabStop = false; this.grpQueue.Text = "&Images to resize"; // // diaSelFiles // this.diaSelFiles.Multiselect = true; // // diaSelFolder // this.diaSelFolder.ShowNewFolderButton = false; // // grpSettings // this.grpSettings.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpSettings.Controls.Add(this.label4); this.grpSettings.Controls.Add(this.txtJpegQty); this.grpSettings.Controls.Add(this.txtHeight); this.grpSettings.Controls.Add(this.label3); this.grpSettings.Controls.Add(this.label2); this.grpSettings.Controls.Add(this.txtWidth); this.grpSettings.Location = new System.Drawing.Point(12, 276); this.grpSettings.Name = "grpSettings"; this.grpSettings.Size = new System.Drawing.Size(650, 81); this.grpSettings.TabIndex = 4; this.grpSettings.TabStop = false; this.grpSettings.Text = "&Resize settings"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(268, 31); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(101, 13); this.label4.TabIndex = 5; this.label4.Text = "&JPEG image quality:"; // // txtJpegQty // this.txtJpegQty.Location = new System.Drawing.Point(271, 47); this.txtJpegQty.Name = "txtJpegQty"; this.txtJpegQty.Size = new System.Drawing.Size(86, 20); this.txtJpegQty.TabIndex = 4; this.txtJpegQty.Text = "80"; // // txtHeight // this.txtHeight.Location = new System.Drawing.Point(138, 47); this.txtHeight.Name = "txtHeight"; this.txtHeight.Size = new System.Drawing.Size(87, 20); this.txtHeight.TabIndex = 3; this.txtHeight.Text = "1800"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(135, 31); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(93, 13); this.label3.TabIndex = 2; this.label3.Text = "Max image &height:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 31); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(89, 13); this.label2.TabIndex = 1; this.label2.Text = "Max image &width:"; // // txtWidth // this.txtWidth.Location = new System.Drawing.Point(9, 47); this.txtWidth.Name = "txtWidth"; this.txtWidth.Size = new System.Drawing.Size(87, 20); this.txtWidth.TabIndex = 0; this.txtWidth.Text = "1800"; // // grpSave // this.grpSave.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpSave.Controls.Add(this.txtSaveDest); this.grpSave.Controls.Add(this.label1); this.grpSave.Controls.Add(this.btnSaveDest); this.grpSave.Location = new System.Drawing.Point(12, 363); this.grpSave.Name = "grpSave"; this.grpSave.Size = new System.Drawing.Size(650, 74); this.grpSave.TabIndex = 5; this.grpSave.TabStop = false; this.grpSave.Text = "&Save resized images"; // // txtSaveDest // this.txtSaveDest.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtSaveDest.Location = new System.Drawing.Point(9, 42); this.txtSaveDest.Name = "txtSaveDest"; this.txtSaveDest.Size = new System.Drawing.Size(499, 20); this.txtSaveDest.TabIndex = 7; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(6, 26); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(207, 13); this.label1.TabIndex = 6; this.label1.Text = "Resized images will be saved in this folder:"; // // btnSaveDest // this.btnSaveDest.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnSaveDest.Location = new System.Drawing.Point(514, 39); this.btnSaveDest.Name = "btnSaveDest"; this.btnSaveDest.Size = new System.Drawing.Size(130, 24); this.btnSaveDest.TabIndex = 8; this.btnSaveDest.Text = "S&elect folder..."; this.btnSaveDest.UseVisualStyleBackColor = true; this.btnSaveDest.Click += new System.EventHandler(this.btnSaveDest_Click); // // btnBeginResize // this.btnBeginResize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnBeginResize.Location = new System.Drawing.Point(526, 467); this.btnBeginResize.Name = "btnBeginResize"; this.btnBeginResize.Size = new System.Drawing.Size(136, 34); this.btnBeginResize.TabIndex = 9; this.btnBeginResize.Text = "&Begin resize"; this.btnBeginResize.UseVisualStyleBackColor = true; this.btnBeginResize.Click += new System.EventHandler(this.btnBeginResize_Click); // // btnAbout // this.btnAbout.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAbout.Location = new System.Drawing.Point(12, 477); this.btnAbout.Name = "btnAbout"; this.btnAbout.Size = new System.Drawing.Size(95, 24); this.btnAbout.TabIndex = 10; this.btnAbout.Text = "&About..."; this.btnAbout.UseVisualStyleBackColor = true; this.btnAbout.Click += new System.EventHandler(this.btnAbout_Click); // // frmMain // this.AllowDrop = true; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(674, 513); this.Controls.Add(this.btnAbout); this.Controls.Add(this.btnBeginResize); this.Controls.Add(this.grpSave); this.Controls.Add(this.grpSettings); this.Controls.Add(this.grpQueue); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(483, 393); this.Name = "frmMain"; this.Text = "Resiz-o-Tron"; this.DragDrop += new System.Windows.Forms.DragEventHandler(this.frmMain_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.frmMain_DragEnter); this.grpQueue.ResumeLayout(false); this.grpSettings.ResumeLayout(false); this.grpSettings.PerformLayout(); this.grpSave.ResumeLayout(false); this.grpSave.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnSelFolder; private System.Windows.Forms.Button btnSelFiles; private System.Windows.Forms.Button btnClearQueue; private System.Windows.Forms.ListView lstQueue; private System.Windows.Forms.GroupBox grpQueue; private System.Windows.Forms.OpenFileDialog diaSelFiles; private System.Windows.Forms.FolderBrowserDialog diaSaveDest; private System.Windows.Forms.FolderBrowserDialog diaSelFolder; private System.Windows.Forms.GroupBox grpSettings; private System.Windows.Forms.GroupBox grpSave; private System.Windows.Forms.Button btnSaveDest; private System.Windows.Forms.TextBox txtSaveDest; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnBeginResize; private System.Windows.Forms.TextBox txtHeight; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtWidth; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtJpegQty; private System.Windows.Forms.Button btnAbout; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Services_Common.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using ClipperLib; using MatterHackers.Agg.Transform; using MatterHackers.Agg.UI; using MatterHackers.Agg.VertexSource; using MatterHackers.VectorMath; using System; using System.Collections.Generic; using MatterHackers.DataConverters2D; namespace MatterHackers.Agg { public class PolygonClippingDemo : GuiWidget { private PathStorage CombinePaths(IVertexSource a, IVertexSource b, ClipType clipType) { List<List<IntPoint>> aPolys = VertexSourceToClipperPolygons.CreatePolygons(a); List<List<IntPoint>> bPolys = VertexSourceToClipperPolygons.CreatePolygons(b); Clipper clipper = new Clipper(); clipper.AddPaths(aPolys, PolyType.ptSubject, true); clipper.AddPaths(bPolys, PolyType.ptClip, true); List<List<IntPoint>> intersectedPolys = new List<List<IntPoint>>(); clipper.Execute(clipType, intersectedPolys); PathStorage output = VertexSourceToClipperPolygons.CreatePathStorage(intersectedPolys); output.Add(0, 0, ShapePath.FlagsAndCommand.CommandStop); return output; } private double m_x; private double m_y; private RadioButtonGroup m_operation = new RadioButtonGroup(new Vector2(555, 5), new Vector2(80, 130)) { HAnchor = HAnchor.ParentRight | HAnchor.FitToChildren, VAnchor = VAnchor.ParentBottom | VAnchor.FitToChildren, Margin = new BorderDouble(5), }; private RadioButtonGroup m_polygons = new RadioButtonGroup(new Vector2(5, 5), new Vector2(205, 110)) { HAnchor = HAnchor.ParentLeft | HAnchor.FitToChildren, VAnchor = VAnchor.ParentBottom | VAnchor.FitToChildren, Margin = new BorderDouble(5), }; public PolygonClippingDemo() { BackgroundColor = RGBA_Bytes.White; m_operation.AddRadioButton("None"); m_operation.AddRadioButton("OR"); m_operation.AddRadioButton("AND"); m_operation.AddRadioButton("XOR"); m_operation.AddRadioButton("A-B"); m_operation.AddRadioButton("B-A"); m_operation.SelectedIndex = 2; AddChild(m_operation); m_polygons.AddRadioButton("Two Simple Paths"); m_polygons.AddRadioButton("Closed Stroke"); m_polygons.AddRadioButton("Great Britain and Arrows"); m_polygons.AddRadioButton("Great Britain and Spiral"); m_polygons.AddRadioButton("Spiral and Glyph"); m_polygons.SelectedIndex = 3; AddChild(m_polygons); AnchorAll(); } private void render_gpc(Graphics2D graphics2D) { switch (m_polygons.SelectedIndex) { case 0: { //------------------------------------ // Two simple paths // PathStorage ps1 = new PathStorage(); PathStorage ps2 = new PathStorage(); double x = m_x - Width / 2 + 100; double y = m_y - Height / 2 + 100; ps1.MoveTo(x + 140, y + 145); ps1.LineTo(x + 225, y + 44); ps1.LineTo(x + 296, y + 219); ps1.ClosePolygon(); ps1.LineTo(x + 226, y + 289); ps1.LineTo(x + 82, y + 292); ps1.MoveTo(x + 220, y + 222); ps1.LineTo(x + 363, y + 249); ps1.LineTo(x + 265, y + 331); ps1.MoveTo(x + 242, y + 243); ps1.LineTo(x + 268, y + 309); ps1.LineTo(x + 325, y + 261); ps1.MoveTo(x + 259, y + 259); ps1.LineTo(x + 273, y + 288); ps1.LineTo(x + 298, y + 266); ps2.MoveTo(100 + 32, 100 + 77); ps2.LineTo(100 + 473, 100 + 263); ps2.LineTo(100 + 351, 100 + 290); ps2.LineTo(100 + 354, 100 + 374); graphics2D.Render(ps1, new RGBA_Floats(0, 0, 0, 0.1).GetAsRGBA_Bytes()); graphics2D.Render(ps2, new RGBA_Floats(0, 0.6, 0, 0.1).GetAsRGBA_Bytes()); CreateAndRenderCombined(graphics2D, ps1, ps2); } break; case 1: { //------------------------------------ // Closed stroke // PathStorage ps1 = new PathStorage(); PathStorage ps2 = new PathStorage(); Stroke stroke = new Stroke(ps2); stroke.width(10.0); double x = m_x - Width / 2 + 100; double y = m_y - Height / 2 + 100; ps1.MoveTo(x + 140, y + 145); ps1.LineTo(x + 225, y + 44); ps1.LineTo(x + 296, y + 219); ps1.ClosePolygon(); ps1.LineTo(x + 226, y + 289); ps1.LineTo(x + 82, y + 292); ps1.MoveTo(x + 220 - 50, y + 222); ps1.LineTo(x + 265 - 50, y + 331); ps1.LineTo(x + 363 - 50, y + 249); ps1.close_polygon(ShapePath.FlagsAndCommand.FlagCCW); ps2.MoveTo(100 + 32, 100 + 77); ps2.LineTo(100 + 473, 100 + 263); ps2.LineTo(100 + 351, 100 + 290); ps2.LineTo(100 + 354, 100 + 374); ps2.ClosePolygon(); graphics2D.Render(ps1, new RGBA_Floats(0, 0, 0, 0.1).GetAsRGBA_Bytes()); graphics2D.Render(stroke, new RGBA_Floats(0, 0.6, 0, 0.1).GetAsRGBA_Bytes()); CreateAndRenderCombined(graphics2D, ps1, stroke); } break; case 2: { //------------------------------------ // Great Britain and Arrows // PathStorage gb_poly = new PathStorage(); PathStorage arrows = new PathStorage(); GreatBritanPathStorage.Make(gb_poly); make_arrows(arrows); Affine mtx1 = Affine.NewIdentity(); Affine mtx2 = Affine.NewIdentity(); mtx1 *= Affine.NewTranslation(-1150, -1150); mtx1 *= Affine.NewScaling(2.0); mtx2 = mtx1; mtx2 *= Affine.NewTranslation(m_x - Width / 2, m_y - Height / 2); VertexSourceApplyTransform trans_gb_poly = new VertexSourceApplyTransform(gb_poly, mtx1); VertexSourceApplyTransform trans_arrows = new VertexSourceApplyTransform(arrows, mtx2); graphics2D.Render(trans_gb_poly, new RGBA_Floats(0.5, 0.5, 0, 0.1).GetAsRGBA_Bytes()); Stroke stroke_gb_poly = new Stroke(trans_gb_poly); stroke_gb_poly.Width = 0.1; graphics2D.Render(stroke_gb_poly, new RGBA_Floats(0, 0, 0).GetAsRGBA_Bytes()); graphics2D.Render(trans_arrows, new RGBA_Floats(0.0, 0.5, 0.5, 0.1).GetAsRGBA_Bytes()); CreateAndRenderCombined(graphics2D, trans_gb_poly, trans_arrows); } break; case 3: { //------------------------------------ // Great Britain and a Spiral // spiral sp = new spiral(m_x, m_y, 10, 150, 30, 0.0); Stroke stroke = new Stroke(sp); stroke.width(15.0); PathStorage gb_poly = new PathStorage(); GreatBritanPathStorage.Make(gb_poly); Affine mtx = Affine.NewIdentity(); ; mtx *= Affine.NewTranslation(-1150, -1150); mtx *= Affine.NewScaling(2.0); VertexSourceApplyTransform trans_gb_poly = new VertexSourceApplyTransform(gb_poly, mtx); graphics2D.Render(trans_gb_poly, new RGBA_Floats(0.5, 0.5, 0, 0.1).GetAsRGBA_Bytes()); Stroke stroke_gb_poly = new Stroke(trans_gb_poly); stroke_gb_poly.width(0.1); graphics2D.Render(stroke_gb_poly, new RGBA_Floats(0, 0, 0).GetAsRGBA_Bytes()); graphics2D.Render(stroke, new RGBA_Floats(0.0, 0.5, 0.5, 0.1).GetAsRGBA_Bytes()); CreateAndRenderCombined(graphics2D, trans_gb_poly, stroke); } break; case 4: { //------------------------------------ // Spiral and glyph // spiral sp = new spiral(m_x, m_y, 10, 150, 30, 0.0); Stroke stroke = new Stroke(sp); stroke.width(15.0); PathStorage glyph = new PathStorage(); glyph.MoveTo(28.47, 6.45); glyph.curve3(21.58, 1.12, 19.82, 0.29); glyph.curve3(17.19, -0.93, 14.21, -0.93); glyph.curve3(9.57, -0.93, 6.57, 2.25); glyph.curve3(3.56, 5.42, 3.56, 10.60); glyph.curve3(3.56, 13.87, 5.03, 16.26); glyph.curve3(7.03, 19.58, 11.99, 22.51); glyph.curve3(16.94, 25.44, 28.47, 29.64); glyph.LineTo(28.47, 31.40); glyph.curve3(28.47, 38.09, 26.34, 40.58); glyph.curve3(24.22, 43.07, 20.17, 43.07); glyph.curve3(17.09, 43.07, 15.28, 41.41); glyph.curve3(13.43, 39.75, 13.43, 37.60); glyph.LineTo(13.53, 34.77); glyph.curve3(13.53, 32.52, 12.38, 31.30); glyph.curve3(11.23, 30.08, 9.38, 30.08); glyph.curve3(7.57, 30.08, 6.42, 31.35); glyph.curve3(5.27, 32.62, 5.27, 34.81); glyph.curve3(5.27, 39.01, 9.57, 42.53); glyph.curve3(13.87, 46.04, 21.63, 46.04); glyph.curve3(27.59, 46.04, 31.40, 44.04); glyph.curve3(34.28, 42.53, 35.64, 39.31); glyph.curve3(36.52, 37.21, 36.52, 30.71); glyph.LineTo(36.52, 15.53); glyph.curve3(36.52, 9.13, 36.77, 7.69); glyph.curve3(37.01, 6.25, 37.57, 5.76); glyph.curve3(38.13, 5.27, 38.87, 5.27); glyph.curve3(39.65, 5.27, 40.23, 5.62); glyph.curve3(41.26, 6.25, 44.19, 9.18); glyph.LineTo(44.19, 6.45); glyph.curve3(38.72, -0.88, 33.74, -0.88); glyph.curve3(31.35, -0.88, 29.93, 0.78); glyph.curve3(28.52, 2.44, 28.47, 6.45); glyph.ClosePolygon(); glyph.MoveTo(28.47, 9.62); glyph.LineTo(28.47, 26.66); glyph.curve3(21.09, 23.73, 18.95, 22.51); glyph.curve3(15.09, 20.36, 13.43, 18.02); glyph.curve3(11.77, 15.67, 11.77, 12.89); glyph.curve3(11.77, 9.38, 13.87, 7.06); glyph.curve3(15.97, 4.74, 18.70, 4.74); glyph.curve3(22.41, 4.74, 28.47, 9.62); glyph.ClosePolygon(); Affine mtx = Affine.NewIdentity(); mtx *= Affine.NewScaling(4.0); mtx *= Affine.NewTranslation(220, 200); VertexSourceApplyTransform trans = new VertexSourceApplyTransform(glyph, mtx); FlattenCurves curve = new FlattenCurves(trans); CreateAndRenderCombined(graphics2D, stroke, curve); graphics2D.Render(stroke, new RGBA_Floats(0, 0, 0, 0.1).GetAsRGBA_Bytes()); graphics2D.Render(curve, new RGBA_Floats(0, 0.6, 0, 0.1).GetAsRGBA_Bytes()); } break; } } private void CreateAndRenderCombined(Graphics2D graphics2D, IVertexSource ps1, IVertexSource ps2) { PathStorage combined = null; switch (m_operation.SelectedIndex) { case 1: combined = CombinePaths(ps1, ps2, ClipType.ctUnion); break; case 2: combined = CombinePaths(ps1, ps2, ClipType.ctIntersection); break; case 3: combined = CombinePaths(ps1, ps2, ClipType.ctXor); break; case 4: combined = CombinePaths(ps1, ps2, ClipType.ctDifference); break; case 5: combined = CombinePaths(ps2, ps1, ClipType.ctDifference); break; } if (combined != null) { graphics2D.Render(combined, new RGBA_Floats(0.5, 0.0, 0, 0.5).GetAsRGBA_Bytes()); } } public override void OnBoundsChanged(EventArgs e) { m_x = Width / 2.0; m_y = Height / 2.0; base.OnBoundsChanged(e); } public override void OnDraw(Graphics2D graphics2D) { render_gpc(graphics2D); base.OnDraw(graphics2D); } public override void OnMouseDown(MouseEventArgs mouseEvent) { base.OnMouseDown(mouseEvent); if (mouseEvent.Button == MouseButtons.Left && FirstWidgetUnderMouse) { m_x = mouseEvent.X; m_y = mouseEvent.Y; Invalidate(); } } public override void OnMouseMove(MouseEventArgs mouseEvent) { if (MouseCaptured) { m_x = mouseEvent.X; m_y = mouseEvent.Y; Invalidate(); } base.OnMouseMove(mouseEvent); } [STAThread] public static void Main(string[] args) { AppWidgetFactory appWidget = new PolygonClippingFactory(); appWidget.CreateWidgetAndRunInWindow(); } private void make_arrows(PathStorage ps) { ps.remove_all(); ps.MoveTo(1330.599999999999909, 1282.399999999999864); ps.LineTo(1377.400000000000091, 1282.399999999999864); ps.LineTo(1361.799999999999955, 1298.000000000000000); ps.LineTo(1393.000000000000000, 1313.599999999999909); ps.LineTo(1361.799999999999955, 1344.799999999999955); ps.LineTo(1346.200000000000045, 1313.599999999999909); ps.LineTo(1330.599999999999909, 1329.200000000000045); ps.ClosePolygon(); ps.MoveTo(1330.599999999999909, 1266.799999999999955); ps.LineTo(1377.400000000000091, 1266.799999999999955); ps.LineTo(1361.799999999999955, 1251.200000000000045); ps.LineTo(1393.000000000000000, 1235.599999999999909); ps.LineTo(1361.799999999999955, 1204.399999999999864); ps.LineTo(1346.200000000000045, 1235.599999999999909); ps.LineTo(1330.599999999999909, 1220.000000000000000); ps.ClosePolygon(); ps.MoveTo(1315.000000000000000, 1282.399999999999864); ps.LineTo(1315.000000000000000, 1329.200000000000045); ps.LineTo(1299.400000000000091, 1313.599999999999909); ps.LineTo(1283.799999999999955, 1344.799999999999955); ps.LineTo(1252.599999999999909, 1313.599999999999909); ps.LineTo(1283.799999999999955, 1298.000000000000000); ps.LineTo(1268.200000000000045, 1282.399999999999864); ps.ClosePolygon(); ps.MoveTo(1268.200000000000045, 1266.799999999999955); ps.LineTo(1315.000000000000000, 1266.799999999999955); ps.LineTo(1315.000000000000000, 1220.000000000000000); ps.LineTo(1299.400000000000091, 1235.599999999999909); ps.LineTo(1283.799999999999955, 1204.399999999999864); ps.LineTo(1252.599999999999909, 1235.599999999999909); ps.LineTo(1283.799999999999955, 1251.200000000000045); ps.ClosePolygon(); } } public class PolygonClippingFactory : AppWidgetFactory { public override GuiWidget NewWidget() { return new PolygonClippingDemo(); } public override AppWidgetInfo GetAppParameters() { AppWidgetInfo appWidgetInfo = new AppWidgetInfo( "Clipping", "PolygonClipping", "Demonstration of general polygon clipping using the clipper library.", 640, 520); return appWidgetInfo; } } public class spiral : IVertexSource { private double m_x; private double m_y; private double m_r1; private double m_r2; private double m_step; private double m_start_angle; private double m_angle; private double m_curr_r; private double m_da; private double m_dr; private bool m_start; public spiral(double x, double y, double r1, double r2, double step, double start_angle = 0) { m_x = x; m_y = y; m_r1 = r1; m_r2 = r2; m_step = step; m_start_angle = start_angle; m_angle = start_angle; m_da = agg_basics.deg2rad(4.0); m_dr = m_step / 90.0; } public IEnumerable<VertexData> Vertices() { throw new NotImplementedException(); } public void rewind(int index) { m_angle = m_start_angle; m_curr_r = m_r1; m_start = true; } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { x = 0; y = 0; if (m_curr_r > m_r2) { return ShapePath.FlagsAndCommand.CommandStop; } x = m_x + Math.Cos(m_angle) * m_curr_r; y = m_y + Math.Sin(m_angle) * m_curr_r; m_curr_r += m_dr; m_angle += m_da; if (m_start) { m_start = false; return ShapePath.FlagsAndCommand.CommandMoveTo; } return ShapePath.FlagsAndCommand.CommandLineTo; } } internal class conv_poly_counter { private int m_contours; private int m_points; private conv_poly_counter(IVertexSource src) { m_contours = 0; m_points = 0; foreach (VertexData vertexData in src.Vertices()) { if (ShapePath.is_vertex(vertexData.command)) { ++m_points; } if (ShapePath.is_move_to(vertexData.command)) { ++m_contours; } } } } }
// -------------------------------------------------------------------------------------------------------------------- // <summary> // Methods for constructing controllers. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WebStreams.Server { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reactive.Linq; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; /// <summary> /// Methods for constructing controllers /// </summary> internal static class ControllerBuilder { /// <summary> /// The body parameter name. /// </summary> public const string BodyParameterName = "$body"; /// <summary> /// Returns the steam controller routes for the provided <paramref name="controller"/>. /// </summary> /// <param name="controller"> /// The controller type. /// </param> /// <param name="settings"> /// The settings. /// </param> /// <returns> /// The steam controller routes for the provided <paramref name="controller"/>. /// </returns> public static IDictionary<string, ControllerRoute> GetRoutes(Type controller, WebStreamsSettings settings) { var methodRoutePrefix = JoinRouteParts(settings.RoutePrefix, GetRoutePrefix(controller)); return GetStreamMethods(controller) .Select(method => GetControllerMethod(method, settings, methodRoutePrefix)) .ToDictionary(_ => _.Route, _ => _); } /// <summary> /// Returns the <see cref="RoutePrefixAttribute"/> value for the provided <paramref name="type"/>. /// </summary> /// <param name="type"> /// The type. /// </param> /// <returns> /// The <see cref="RoutePrefixAttribute"/> value for the provided <paramref name="type"/>. /// </returns> private static string GetRoutePrefix(Type type) { var attr = type.GetCustomAttribute<RoutePrefixAttribute>(); return attr != null ? attr.Prefix : string.Empty; } /// <summary> /// Returns the <see cref="RouteAttribute.Route"/> value for the provided <paramref name="method"/>. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// The <see cref="RouteAttribute.Route"/> value for the provided <paramref name="method"/>. /// </returns> private static string GetRouteSuffixTemplate(MethodInfo method) { var attr = method.GetCustomAttribute<RouteAttribute>(); return attr != null ? attr.Route : string.Empty; } /// <summary> /// Returns the steam controller methods for the provided <paramref name="type"/>. /// </summary> /// <param name="type"> /// The type. /// </param> /// <returns> /// The steam controller methods for the provided <paramref name="type"/>. /// </returns> private static IEnumerable<MethodInfo> GetStreamMethods(Type type) { var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public); return methods.Where(IsStreamMethod); } /// <summary> /// Returns <see langword="true"/> if the provided <paramref name="method"/> is a stream controller method, /// <see langword="false"/> otherwise. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// <see langword="true"/> if the provided <paramref name="method"/> is a stream controller method, /// <see langword="false"/> otherwise. /// </returns> private static bool IsStreamMethod(MethodInfo method) { var isObservable = method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(IObservable<>); var hasRouteTemplate = GetRouteSuffixTemplate(method) != null; return isObservable && hasRouteTemplate; } /// <summary> /// Returns the joined route for the provided values. /// </summary> /// <param name="parts"> /// The route parts. /// </param> /// <returns> /// The joined route for the provided values. /// </returns> private static string JoinRouteParts(params string[] parts) { return '/' + string.Join("/", parts.Where(_ => !string.IsNullOrWhiteSpace(_)).Select(_ => _.Trim('/'))); } /// <summary> /// Returns the <see cref="ControllerRoute.Invoker"/> for the provided <paramref name="method"/>. /// </summary> /// <param name="method"> /// The method. /// </param> /// <param name="settings"> /// The settings. /// </param> /// <param name="methodRoutePrefix"> /// The route prefix for the controller. /// </param> /// <returns> /// The <see cref="ControllerRoute"/> for the provided <paramref name="method"/>. /// </returns> private static ControllerRoute GetControllerMethod(MethodInfo method, WebStreamsSettings settings, string methodRoutePrefix) { var observableParameters = new HashSet<string>(); var hasBodyParameter = false; // Define the parameters of the resulting invoker. var controllerParameter = Expression.Parameter(typeof(object), "controller"); var parametersParameter = Expression.Parameter(typeof(IDictionary<string, string>), "parameters"); var getObservableParameter = Expression.Parameter(typeof(Func<string, IObservable<string>>), "getObservable"); // Reflect the methods being which are used below. var tryGetValue = typeof(IDictionary<string, string>).GetMethod("TryGetValue"); var deserialize = typeof(JsonConvert).GetMethod("DeserializeObject", new[] { typeof(string), typeof(Type), typeof(JsonSerializerSettings) }); var invokeFunc = typeof(Func<string, IObservable<string>>).GetMethod("Invoke"); // Construct expressions to retrieve each of the controller method's parameters. var parameterDictionaryVar = Expression.Variable(typeof(string), "paramVal"); var allVariables = new List<ParameterExpression> { parameterDictionaryVar }; var parameters = new List<ParameterExpression>(); var parameterAssignments = new List<Expression>(); foreach (var parameter in method.GetParameters()) { // Resulting parameter value. var paramType = parameter.ParameterType; var paramVar = Expression.Variable(paramType, parameter.Name); parameters.Add(paramVar); Expression parameterAssignment; // Check if this parameter is derived from the request body. var isBody = parameter.GetCustomAttribute<BodyAttribute>() != null; if (isBody) { if (hasBodyParameter) { throw new InvalidAttributeUsageException( "BodyAttribute cannot be used with multiple parameters."); } hasBodyParameter = true; } // If the parameter is an observable, get the incoming stream using the "getObservable" parameter. var serializerSettingsConst = Expression.Constant(settings.JsonSerializerSettings); if (paramType.IsGenericType && paramType.GetGenericTypeDefinition() == typeof(IObservable<>)) { if (isBody) { throw new InvalidAttributeUsageException($"{nameof(BodyAttribute)} cannot be used with observable parameters."); } // Add the observable parameter to the stream controller definition. observableParameters.Add(parameter.Name); // This is an incoming observable, get the proxy observable to pass in. var incomingObservable = Expression.Call(getObservableParameter, invokeFunc, Expression.Constant(parameter.Name)); // Select the proxy observable into the correct shape. var paramTypeArg = paramType.GenericTypeArguments[0]; var selectIncomingObservable = typeof(Observable).GetGenericMethod( "Select", new[] { typeof(IObservable<string>), typeof(Func<,>).MakeGenericType(typeof(string), paramTypeArg) }, new[] { typeof(string), paramTypeArg }); var next = Expression.Parameter(typeof(string), "next"); var observableType = paramTypeArg; var selector = Expression.Lambda( Expression.Convert( Expression.Call( null, deserialize, new Expression[] { next, Expression.Constant(observableType), serializerSettingsConst }), observableType), next); // Pass the converted observable in for the current parameter. parameterAssignment = Expression.Assign( paramVar, Expression.Call(null, selectIncomingObservable, new Expression[] { incomingObservable, selector })); } else { // Try to get the parameter from the parameters dictionary and convert it if neccessary. var paramName = isBody ? BodyParameterName : parameter.Name; Expression convertParam; var tryGetParam = Expression.Call( parametersParameter, tryGetValue, new Expression[] { Expression.Constant(paramName), parameterDictionaryVar }); if (paramType == typeof(string)) { // Strings need no conversion, just pluck the value from the parameter list. convertParam = parameterDictionaryVar; } else { // Determine whether or not the standard if (paramType.ShouldUseStaticTryParseMthod()) { // Parse the value using the "TryParse" method of the parameter type. var tryParseMethod = paramType.GetMethod("TryParse", new[] { typeof(string), paramType.MakeByRefType() }); var tryParseExp = Expression.Call(tryParseMethod, parameterDictionaryVar, paramVar); // Use the default value if parsing failed. convertParam = Expression.Block(tryParseExp, paramVar); } else { // Determine whether or not the value is a JSON primitive. var contract = JsonSerializer.Create(settings.JsonSerializerSettings).ContractResolver.ResolveContract(paramType); var isPrimitive = contract.GetType() == typeof(JsonPrimitiveContract); // Use the provided serializer to deserialize the parameter value. var paramTypeConst = Expression.Constant(paramType); if (isPrimitive) { // String-based primitives such as DateTime need to be wrapped in quotes before deserialization. var quoteConst = Expression.Constant("\""); var stringConcatMethod = typeof(string).GetMethod("Concat", new[] { typeof(object), typeof(object), typeof(object) }); var quotedParameterValue = Expression.Call( null, stringConcatMethod, new Expression[] { quoteConst, parameterDictionaryVar, quoteConst }); // Deserialize the quoted value. var deserialized = Expression.Call( null, deserialize, new Expression[] { quotedParameterValue, paramTypeConst, serializerSettingsConst }); convertParam = Expression.Convert(deserialized, paramType); } else { // Serialize raw value for non-primitive types, bools, and numeric types. var deserialized = Expression.Call( null, deserialize, new Expression[] { parameterDictionaryVar, paramTypeConst, serializerSettingsConst }); convertParam = Expression.Convert(deserialized, paramType); } } } parameterAssignment = Expression.IfThen(tryGetParam, Expression.Assign(paramVar, convertParam)); } parameterAssignments.Add(parameterAssignment); } // Cast the controller into its native type and invoke it to get the outgoing observable. if (method.ReflectedType == null) { throw new NullReferenceException("method.ReflectedType is null"); } var controller = (!method.IsStatic) ? Expression.Convert(controllerParameter, method.ReflectedType) : null; var outgoingObservable = Expression.Call(controller, method, parameters); // Convert the outgoing observable into an observable of strings. var selectToString = typeof(Observable).GetGenericMethod( "Select", new[] { method.ReturnType, typeof(Func<,>).MakeGenericType(method.ReturnType.GenericTypeArguments[0], typeof(string)) }, new[] { method.ReturnType.GenericTypeArguments[0], typeof(string) }); Expression<Func<object, string>> serialize = input => JsonConvert.SerializeObject(input, settings.JsonSerializerSettings); var outgoingStringObservable = Expression.Call(null, selectToString, new Expression[] { outgoingObservable, serialize }); parameterAssignments.Add(outgoingStringObservable); allVariables.AddRange(parameters); var body = Expression.Block(allVariables.ToArray(), parameterAssignments); var lambda = Expression.Lambda<ControllerRoute.Invoker>(body, controllerParameter, parametersParameter, getObservableParameter); var route = JoinRouteParts(methodRoutePrefix, GetRouteSuffixTemplate(method)); return new ControllerRoute(route, method.DeclaringType, lambda.Compile(), observableParameters, hasBodyParameter); } } }
// 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.Reflection; using System.Windows.Forms; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.PythonTools.Profiling { /// <summary> /// Top level node for our UI Hierarchy which includes all of the various performance sessions. /// /// We need one top-level node which we'll add the other nodes to. We treat the other nodes /// as nested hierarchies. /// </summary> class SessionsNode : BaseHierarchyNode, IVsHierarchyDeleteHandler { private readonly List<SessionNode> _sessions = new List<SessionNode>(); internal readonly EventSinkCollection _sessionsCollection = new EventSinkCollection(); private readonly IServiceProvider _serviceProvider; private readonly IVsUIHierarchyWindow _window; internal uint _activeSession = VSConstants.VSITEMID_NIL; internal static ImageList _imageList = InitImageList(); internal SessionsNode(IServiceProvider serviceProvider, IVsUIHierarchyWindow window) { _serviceProvider = serviceProvider; _window = window; } internal SessionNode AddTarget(ProfilingTarget target, string filename, bool save) { Debug.Assert(filename.EndsWithOrdinal(".pyperf", ignoreCase: true)); // ensure a unique name string newBaseName = Path.GetFileNameWithoutExtension(filename); string tempBaseName = newBaseName; int append = 0; bool dupFound; do { dupFound = false; for (int i = 0; i < _sessions.Count; i++) { if (Path.GetFileNameWithoutExtension(_sessions[i].Filename) == newBaseName) { dupFound = true; } } if (dupFound) { append++; newBaseName = tempBaseName + append; } } while (dupFound); string newFilename = newBaseName + ".pyperf"; // add directory name back if present... string dirName = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(dirName)) { newFilename = Path.Combine(dirName, newFilename); } filename = newFilename; // save to the unique item if desired (we save whenever we have an active solution as we have a place to put it)... if (save) { using (var fs = new FileStream(filename, FileMode.Create)) { ProfilingTarget.Serializer.Serialize(fs, target); } } var node = OpenTarget(target, filename); if (!save) { node.MarkDirty(); node._neverSaved = true; } return node; } internal SessionNode OpenTarget(ProfilingTarget target, string filename) { for (int i = 0; i < _sessions.Count; i++) { if (_sessions[i].Filename == filename) { throw new InvalidOperationException(Strings.PerformanceSessionAlreadyOpen.FormatUI(filename)); } } uint prevSibl; if (_sessions.Count > 0) { prevSibl = _sessions[_sessions.Count - 1].ItemId; } else { prevSibl = VSConstants.VSITEMID_NIL; } var node = new SessionNode(_serviceProvider, this, target, filename); _sessions.Add(node); OnItemAdded(VSConstants.VSITEMID_ROOT, prevSibl, node.ItemId); if (_activeSession == VSConstants.VSITEMID_NIL) { SetActiveSession(node); } return node; } internal void SetActiveSession(SessionNode node) { uint oldItem = _activeSession; if (oldItem != VSConstants.VSITEMID_NIL) { _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_UnBoldItem); } _activeSession = node.ItemId; _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_BoldItem); } #region IVsUIHierarchy Members public override int GetNestedHierarchy(uint itemid, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pitemidNested) { var item = _sessionsCollection[itemid]; if (item != null) { if (iidHierarchyNested == typeof(IVsHierarchy).GUID || iidHierarchyNested == typeof(IVsUIHierarchy).GUID) { ppHierarchyNested = System.Runtime.InteropServices.Marshal.GetComInterfaceForObject(item, typeof(IVsUIHierarchy)); pitemidNested = VSConstants.VSITEMID_ROOT; return VSConstants.S_OK; } } return base.GetNestedHierarchy(itemid, ref iidHierarchyNested, out ppHierarchyNested, out pitemidNested); } public override int GetProperty(uint itemid, int propid, out object pvar) { // GetProperty is called many many times for this particular property pvar = null; var prop = (__VSHPROPID)propid; switch (prop) { case __VSHPROPID.VSHPROPID_CmdUIGuid: pvar = new Guid(GuidList.guidPythonProfilingPkgString); break; case __VSHPROPID.VSHPROPID_Parent: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = VSConstants.VSITEMID_ROOT; } break; case __VSHPROPID.VSHPROPID_FirstChild: if (itemid == VSConstants.VSITEMID_ROOT && _sessions.Count > 0) pvar = _sessions[0].ItemId; else pvar = VSConstants.VSITEMID_NIL; break; case __VSHPROPID.VSHPROPID_NextSibling: pvar = VSConstants.VSITEMID_NIL; for(int i = 0; i<_sessions.Count; i++) { if (_sessions[i].ItemId == itemid && i < _sessions.Count - 1) { pvar = _sessions[i + 1].ItemId; } } break; case __VSHPROPID.VSHPROPID_Expandable: pvar = true; break; case __VSHPROPID.VSHPROPID_ExpandByDefault: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = true; } break; case __VSHPROPID.VSHPROPID_IconImgList: case __VSHPROPID.VSHPROPID_OpenFolderIconHandle: pvar = (IntPtr)_imageList.Handle; break; case __VSHPROPID.VSHPROPID_IconIndex: case __VSHPROPID.VSHPROPID_OpenFolderIconIndex: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = 0; } else { pvar = (IntPtr)TreeViewIconIndex.PerformanceSession; } break; case __VSHPROPID.VSHPROPID_SaveName: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = GetItem(itemid).Filename; } break; case __VSHPROPID.VSHPROPID_Caption: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = GetItem(itemid).Caption; } break; case __VSHPROPID.VSHPROPID_ParentHierarchy: if (_sessionsCollection[itemid] != null) { pvar = this as IVsHierarchy; } break; } if (pvar != null) return VSConstants.S_OK; return VSConstants.DISP_E_MEMBERNOTFOUND; } #endregion #region IVsHierarchyDeleteHandler Members public int DeleteItem(uint dwDelItemOp, uint itemid) { var item = GetItem(itemid); if (item != null) { switch ((__VSDELETEITEMOPERATION)dwDelItemOp) { case __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage: File.Delete(item.Filename); goto case __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject; case __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject: item.Removed(); _sessions.Remove(item); _sessionsCollection.RemoveAt(itemid); OnItemDeleted(itemid); // our itemids have all changed, invalidate them OnInvalidateItems(VSConstants.VSITEMID_ROOT); break; } if (itemid == _activeSession) { if (_sessions.Count > 0) { SetActiveSession(_sessions[0]); } else { _activeSession = VSConstants.VSITEMID_NIL; } } return VSConstants.S_OK; } return VSConstants.E_FAIL; } public int QueryDeleteItem(uint dwDelItemOp, uint itemid, out int pfCanDelete) { pfCanDelete = 1; return VSConstants.S_OK; } #endregion private static ImageList InitImageList() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.PythonTools.ProfilingTreeView.bmp"); return Utilities.GetImageList( stream ); } private SessionNode GetItem(uint itemid) { return (SessionNode)_sessionsCollection[itemid]; } internal void StartProfiling() { if (_activeSession != VSConstants.VSITEMID_NIL) { GetItem(_activeSession).StartProfiling(); } } public List<SessionNode> Sessions { get { return _sessions; } } } }
using System; using System.Collections.Generic; using System.IO; using Lucene.Net.Index; namespace Lucene.Net.Store { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IOUtils = Lucene.Net.Util.IOUtils; /// <summary> /// A Directory is a flat list of files. Files may be written once, when they /// are created. Once a file is created it may only be opened for read, or /// deleted. Random access is permitted both when reading and writing. /// /// Java's i/o APIs not used directly, but rather all i/o is /// through this API. this permits things such as: <ul> /// <li> implementation of RAM-based indices;</li> /// <li> implementation indices stored in a database, via JDBC;</li> /// <li> implementation of an index as a single file;</li> /// </ul> /// /// Directory locking is implemented by an instance of {@link /// LockFactory}, and can be changed for each Directory /// instance using <seealso cref="setLockFactory"/>. /// /// </summary> public abstract class Directory : IDisposable { protected volatile bool isOpen = true; /// <summary> /// Returns an array of strings, one for each file in the directory. /// </summary> /// <exception cref="NoSuchDirectoryException"> if the directory is not prepared for any /// write operations (such as <seealso cref="#createOutput(String, IOContext)"/>). </exception> /// <exception cref="System.IO.IOException"> in case of other IO errors </exception> public abstract string[] ListAll(); /// <summary> /// Returns true iff a file with the given name exists. /// </summary> /// @deprecated this method will be removed in 5.0 public abstract bool FileExists(string name); /// <summary> /// Removes an existing file in the directory. </summary> public abstract void DeleteFile(string name); /// <summary> /// Returns the length of a file in the directory. this method follows the /// following contract: /// <ul> /// <li>Throws <seealso cref="FileNotFoundException"/> or <seealso cref="NoSuchFileException"/> /// if the file does not exist.</li> /// <li>Returns a value &gt;=0 if the file exists, which specifies its length.</li> /// </ul> /// </summary> /// <param name="name"> the name of the file for which to return the length. </param> /// <exception cref="System.IO.IOException"> if there was an IO error while retrieving the file's /// length. </exception> public abstract long FileLength(string name); /// <summary> /// Creates a new, empty file in the directory with the given name. /// Returns a stream writing this file. /// </summary> public abstract IndexOutput CreateOutput(string name, IOContext context); /// <summary> /// Ensure that any writes to these files are moved to /// stable storage. Lucene uses this to properly commit /// changes to the index, to prevent a machine/OS crash /// from corrupting the index.<br/> /// <br/> /// NOTE: Clients may call this method for same files over /// and over again, so some impls might optimize for that. /// For other impls the operation can be a noop, for various /// reasons. /// </summary> public abstract void Sync(ICollection<string> names); /// <summary> /// Returns a stream reading an existing file, with the /// specified read buffer size. The particular Directory /// implementation may ignore the buffer size. Currently /// the only Directory implementations that respect this /// parameter are <seealso cref="FSDirectory"/> and {@link /// CompoundFileDirectory}. /// <p>Throws <seealso cref="FileNotFoundException"/> or <seealso cref="NoSuchFileException"/> /// if the file does not exist. /// </summary> public abstract IndexInput OpenInput(string name, IOContext context); /// <summary> /// Returns a stream reading an existing file, computing checksum as it reads </summary> public virtual ChecksumIndexInput OpenChecksumInput(string name, IOContext context) { return new BufferedChecksumIndexInput(OpenInput(name, context)); } /// <summary> /// Construct a <seealso cref="Lock"/>. </summary> /// <param name="name"> the name of the lock file </param> public abstract Lock MakeLock(string name); /// <summary> /// Attempt to clear (forcefully unlock and remove) the /// specified lock. Only call this at a time when you are /// certain this lock is no longer in use. </summary> /// <param name="name"> name of the lock to be cleared. </param> public abstract void ClearLock(string name); /// <summary> /// Closes the store. </summary> public abstract void Dispose(); /// <summary> /// Set the LockFactory that this Directory instance should /// use for its locking implementation. Each * instance of /// LockFactory should only be used for one directory (ie, /// do not share a single instance across multiple /// Directories). /// </summary> /// <param name="lockFactory"> instance of <seealso cref="LockFactory"/>. </param> public abstract LockFactory LockFactory { set; get; } /// <summary> /// Return a string identifier that uniquely differentiates /// this Directory instance from other Directory instances. /// this ID should be the same if two Directory instances /// (even in different JVMs and/or on different machines) /// are considered "the same index". this is how locking /// "scopes" to the right index. /// </summary> public virtual string LockID { get { return this.ToString(); } } public override string ToString() { return this.GetType().Name + '@' + GetHashCode().ToString("x") + " lockFactory=" + LockFactory; } /// <summary> /// Copies the file <i>src</i> to <seealso cref="Directory"/> <i>to</i> under the new /// file name <i>dest</i>. /// <p> /// If you want to copy the entire source directory to the destination one, you /// can do so like this: /// /// <pre class="prettyprint"> /// Directory to; // the directory to copy to /// for (String file : dir.listAll()) { /// dir.copy(to, file, newFile, IOContext.DEFAULT); // newFile can be either file, or a new name /// } /// </pre> /// <p> /// <b>NOTE:</b> this method does not check whether <i>dest</i> exist and will /// overwrite it if it does. /// </summary> public virtual void Copy(Directory to, string src, string dest, IOContext context) { IndexOutput os = null; IndexInput @is = null; System.IO.IOException priorException = null; try { os = to.CreateOutput(dest, context); @is = OpenInput(src, context); os.CopyBytes(@is, @is.Length()); } catch (System.IO.IOException ioe) { priorException = ioe; } finally { bool success = false; try { IOUtils.CloseWhileHandlingException(priorException, os, @is); success = true; } finally { if (!success) { try { to.DeleteFile(dest); } catch (Exception) { } } } } } /// <summary> /// Creates an <seealso cref="IndexInputSlicer"/> for the given file name. /// IndexInputSlicer allows other <seealso cref="Directory"/> implementations to /// efficiently open one or more sliced <seealso cref="IndexInput"/> instances from a /// single file handle. The underlying file handle is kept open until the /// <seealso cref="IndexInputSlicer"/> is closed. /// <p>Throws <seealso cref="FileNotFoundException"/> or <seealso cref="NoSuchFileException"/> /// if the file does not exist. /// </summary> /// <exception cref="System.IO.IOException"> /// if an <seealso cref="System.IO.IOException"/> occurs /// @lucene.internal /// @lucene.experimental </exception> public virtual IndexInputSlicer CreateSlicer(string name, IOContext context) { EnsureOpen(); return new IndexInputSlicerAnonymousInnerClassHelper(this, name, context); } private class IndexInputSlicerAnonymousInnerClassHelper : IndexInputSlicer { private readonly Directory OuterInstance; private string Name; private IOContext Context; public IndexInputSlicerAnonymousInnerClassHelper(Directory outerInstance, string name, IOContext context) : base(outerInstance) { this.OuterInstance = outerInstance; this.Name = name; this.Context = context; @base = outerInstance.OpenInput(name, context); } private readonly IndexInput @base; public override IndexInput OpenSlice(string sliceDescription, long offset, long length) { return new SlicedIndexInput("SlicedIndexInput(" + sliceDescription + " in " + @base + ")", @base, offset, length); } public override void Dispose(bool disposing) { @base.Dispose(); } [Obsolete] public override IndexInput OpenFullSlice() { return (IndexInput)@base.Clone(); } } /// <exception cref="AlreadyClosedException"> if this Directory is closed </exception> public virtual void EnsureOpen() { if (!isOpen) throw new AlreadyClosedException("this Directory is closed"); } /// <summary> /// Allows to create one or more sliced <seealso cref="IndexInput"/> instances from a single /// file handle. Some <seealso cref="Directory"/> implementations may be able to efficiently map slices of a file /// into memory when only certain parts of a file are required. /// @lucene.internal /// @lucene.experimental /// </summary> public abstract class IndexInputSlicer : IDisposable { private readonly Directory OuterInstance; public IndexInputSlicer(Directory outerInstance) { this.OuterInstance = outerInstance; } /// <summary> /// Returns an <seealso cref="IndexInput"/> slice starting at the given offset with the given length. /// </summary> public abstract IndexInput OpenSlice(string sliceDescription, long offset, long length); /// <summary> /// Returns an <seealso cref="IndexInput"/> slice starting at offset <i>0</i> with a /// length equal to the length of the underlying file </summary> /// @deprecated Only for reading CFS files from 3.x indexes. [Obsolete("Only for reading CFS files from 3.x indexes.")] public abstract IndexInput OpenFullSlice(); // can we remove this somehow? public abstract void Dispose(bool disposing); public void Dispose() { Dispose(true); } } /// <summary> /// Implementation of an IndexInput that reads from a portion of /// a file. /// </summary> private sealed class SlicedIndexInput : BufferedIndexInput { private IndexInput @base; private long FileOffset; private long Length_Renamed; internal SlicedIndexInput(string sliceDescription, IndexInput @base, long fileOffset, long length) : this(sliceDescription, @base, fileOffset, length, BufferedIndexInput.BUFFER_SIZE) { } internal SlicedIndexInput(string sliceDescription, IndexInput @base, long fileOffset, long length, int readBufferSize) : base("SlicedIndexInput(" + sliceDescription + " in " + @base + " slice=" + fileOffset + ":" + (fileOffset + length) + ")", readBufferSize) { this.@base = (IndexInput)@base.Clone(); this.FileOffset = fileOffset; this.Length_Renamed = length; } public override object Clone() { SlicedIndexInput clone = (SlicedIndexInput)base.Clone(); clone.@base = (IndexInput)@base.Clone(); clone.FileOffset = FileOffset; clone.Length_Renamed = Length_Renamed; return clone; } /// <summary> /// Expert: implements buffer refill. Reads bytes from the current /// position in the input. </summary> /// <param name="b"> the array to read bytes into </param> /// <param name="offset"> the offset in the array to start storing bytes </param> /// <param name="len"> the number of bytes to read </param> protected internal override void ReadInternal(byte[] b, int offset, int len) { long start = FilePointer; if (start + len > Length_Renamed) { throw new Exception("read past EOF: " + this); } @base.Seek(FileOffset + start); @base.ReadBytes(b, offset, len, false); } /// <summary> /// Expert: implements seek. Sets current position in this file, where /// the next <seealso cref="#readInternal(byte[],int,int)"/> will occur. </summary> /// <seealso> cref= #readInternal(byte[],int,int) </seealso> protected override void SeekInternal(long pos) { } public override void Dispose() { @base.Dispose(); } public override long Length() { return Length_Renamed; } } public virtual bool IsOpen { get { return isOpen; }} } }
using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.Data.Interfaces; using JoinRpg.Data.Interfaces.Claims; using JoinRpg.Interfaces; using JoinRpg.Portal.Controllers.Common; using JoinRpg.Portal.Infrastructure.Authorization; using JoinRpg.Services.Interfaces; using JoinRpg.Web.Models; using JoinRpg.Web.Models.Masters; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace JoinRpg.Portal.Controllers { [RequireMasterOrAdmin()] [Route("{projectId}/masters")] public class AclController : ControllerGameBase { private readonly ICurrentUserAccessor currentUserAccessor; private IClaimsRepository ClaimRepository { get; } private IUriService UriService { get; } [HttpGet("add/{userId}")] [MasterAuthorize(Permission.CanGrantRights)] public async Task<ActionResult> Add(int projectId, int userId) { var project = await ProjectRepository.GetProjectAsync(projectId); var currentUser = await UserRepository.GetById(currentUserAccessor.UserId); var targetUser = await UserRepository.GetById(userId); var projectAcl = project.ProjectAcls.Single(acl => acl.UserId == currentUserAccessor.UserId); return View(AclViewModel.New(projectAcl, currentUser, targetUser)); } [HttpPost("add/{userId}")] [MasterAuthorize(Permission.CanGrantRights)] public async Task<ActionResult> Add(AclViewModel viewModel) { try { await ProjectService.GrantAccess(new GrantAccessRequest() { ProjectId = viewModel.ProjectId, UserId = viewModel.UserId, CanGrantRights = viewModel.CanGrantRights, CanChangeFields = viewModel.CanChangeFields, CanChangeProjectProperties = viewModel.CanChangeProjectProperties, CanManageClaims = viewModel.CanManageClaims, CanEditRoles = viewModel.CanEditRoles, CanManageMoney = viewModel.CanManageMoney, CanSendMassMails = viewModel.CanSendMassMails, CanManagePlots = viewModel.CanManagePlots, CanManageAccommodation = viewModel.CanManageAccommodation, CanSetPlayersAccommodations = viewModel.CanSetPlayersAccommodations, }); } catch { //TODO Fix this. ModelState.AddModelError("", "Error!"); return RedirectToAction("Details", "User", new { viewModel.UserId }); } return RedirectToAction("Index", "Acl", new { viewModel.ProjectId }); } public AclController( IProjectRepository projectRepository, IProjectService projectService, IClaimsRepository claimRepository, IUriService uriService, IUserRepository userRepository, ICurrentUserAccessor currentUserAccessor) : base(projectRepository, projectService, userRepository) { ClaimRepository = claimRepository; UriService = uriService; this.currentUserAccessor = currentUserAccessor; } [RequireMasterOrAdmin()] [HttpGet] public async Task<ActionResult> Index(int projectId) { var project = await ProjectRepository.GetProjectWithDetailsAsync(projectId); var claims = await ClaimRepository.GetClaimsCountByMasters(projectId, ClaimStatusSpec.Active); var groups = await ProjectRepository.GetGroupsWithResponsible(projectId); var currentUser = await GetCurrentUserAsync(); return View(new MastersListViewModel(project, claims, groups, currentUser, UriService)); } [HttpGet("delete")] [MasterAuthorize(Permission.CanGrantRights)] public async Task<ActionResult> Delete(int projectId, int projectaclid) { var project = await ProjectRepository.GetProjectAsync(projectId); var projectAcl = project.ProjectAcls.Single(acl => acl.ProjectAclId == projectaclid); var claims = await ClaimRepository.GetClaimsForMaster(projectId, projectAcl.UserId, ClaimStatusSpec.Any); var groups = await ProjectRepository.GetGroupsWithResponsible(projectId); var viewModel = DeleteAclViewModel.FromAcl(projectAcl, claims.Count, groups.Where(gr => gr.ResponsibleMasterUserId == projectAcl.UserId).ToList(), UriService); if (viewModel.UserId == CurrentUserId) { viewModel.SelfRemove = true; } return View("Delete", viewModel); } [HttpPost("delete")] [ValidateAntiForgeryToken, MasterAuthorize(Permission.CanGrantRights)] public async Task<ActionResult> Delete(DeleteAclViewModel viewModel) { try { await ProjectService.RemoveAccess(viewModel.ProjectId, viewModel.UserId, viewModel.ResponsibleMasterId); } catch { return View(viewModel); } if (viewModel.UserId == CurrentUserId) { //We are removing ourself, need to redirect to public page return await RedirectToProject(viewModel.ProjectId); } return RedirectToAction("Index", "Acl", new { viewModel.ProjectId }); } [HttpGet("leave")] [RequireMaster()] public async Task<ActionResult> RemoveYourself(int projectId, int projectAclId) => await Delete(projectId, projectAclId); [HttpPost("leave")] [ValidateAntiForgeryToken, RequireMaster()] public async Task<ActionResult> RemoveYourself(DeleteAclViewModel viewModel) => await Delete(viewModel); [HttpGet("edit")] [MasterAuthorize(Permission.CanGrantRights)] public async Task<ActionResult> Edit(int projectId, int? projectaclid) { var project = await ProjectRepository.GetProjectAsync(projectId); var groups = await ProjectRepository.GetGroupsWithResponsible(projectId); var projectAcl = project.ProjectAcls.Single(acl => acl.ProjectAclId == projectaclid); var currentUser = await GetCurrentUserAsync(); return View(AclViewModel.FromAcl(projectAcl, 0, groups.Where(gr => gr.ResponsibleMasterUserId == projectAcl.UserId).ToList(), currentUser, UriService)); } [HttpPost("edit")] [ValidateAntiForgeryToken, MasterAuthorize(Permission.CanGrantRights)] public async Task<ActionResult> Edit(ChangeAclViewModel viewModel) { try { await ProjectService.ChangeAccess(new ChangeAccessRequest() { ProjectId = viewModel.ProjectId, UserId = viewModel.UserId, CanGrantRights = viewModel.CanGrantRights, CanChangeFields = viewModel.CanChangeFields, CanChangeProjectProperties = viewModel.CanChangeProjectProperties, CanManageClaims = viewModel.CanManageClaims, CanEditRoles = viewModel.CanEditRoles, CanManageMoney = viewModel.CanManageMoney, CanSendMassMails = viewModel.CanSendMassMails, CanManagePlots = viewModel.CanManagePlots, CanManageAccommodation = viewModel.CanManageAccommodation, CanSetPlayersAccommodations = viewModel.CanSetPlayersAccommodations, }); } catch { //TODO Fix this return RedirectToAction("Index", "Acl", new { viewModel.ProjectId }); } return RedirectToAction("Index", "Acl", new { viewModel.ProjectId }); } [AdminAuthorize] [HttpGet("force-admin-access")] public ActionResult ForceSet(int projectid) => View(); [AdminAuthorize] [HttpPost("force-admin-access")] public async Task<ActionResult> ForceSet(int projectId, [UsedImplicitly] IFormCollection unused) { await ProjectService.GrantAccessAsAdmin(projectId); return RedirectToAction("Details", "Game", new { projectId }); } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections.Generic; using System.Text; using OpenADK.Library.Tools.Mapping; using System.Collections; namespace OpenADK.Library.Tools.Queries { /// <summary> An implementation of a QueryFormatter that formats queries for inclusion in /// an SQL <c>WHERE</c> clause.</summary> /// <remarks> /// /// When preparing a dictionary to be passed to the <c>SQLQueryFormatter.format</c> /// method, the caller must map ElementDef constants to instances of the <c>SQLField</c> /// class. The constructor to that class requires two parameters: the application- /// defined name of the field, and a constant from the <see cref="System.Data.DbType"/> class, /// which instructs the SQLQueryFormatter how to render the field value in the /// query string (e.g. strings are quoted with a single quote, numeric fields /// are rendered as-is, etc.) /// </remarks> /// <example> /// For example, /// /// <code> /// IDictionary m = new Hashtable(); /// m[ SIFDTD.STUDENTPERSONAL_REFID ] = /// new SQLField( "Students.Foreign_ID", DbType.String ) ; /// m[ SIFDTD.NAME_LASTNAME ], /// new SQLField( "Students.Last_Name", DbType.String ) ; /// m[ SIFDTD.NAME_FIRSTNAME ], /// new SQLField( "First_Name", DbType.String ) ; /// m[ SIFDTD.DEMOGRAPHICS_CITIZENSHIPSTATUS ], /// new SQLField( "Students.US_Citizen_Bool{04=1,=0}", DbType.Int32 ) ; /// </code> /// /// The above example might result in a string such as "( Students.US_Citizen_Bool = 0 )" /// or "( Students.Foreign_ID = '898' ) OR ( Students.Last_Name = 'Cortez' AND First_Name = 'Robert' )" /// </example> public class SQLQueryFormatter : QueryFormatter { private IDictionary fFields; /// <summary> Return the text that should be inserted for an opening brace</summary> protected internal override string OpenBrace { get { return "( "; } } /// <summary> Return the text that should be inserted for a closing brace</summary> protected internal override string CloseBrace { get { return " )"; } } /// <summary> Return the text that should be inserted for a logical <c>AND</c> operation</summary> public override string GetOperator( ComparisonOperators op ) { switch (op) { case ComparisonOperators.EQ: return " = "; case ComparisonOperators.NE: return " != "; case ComparisonOperators.GT: return " > "; case ComparisonOperators.LT: return " < "; case ComparisonOperators.GE: return " >= "; case ComparisonOperators.LE: return " <= "; } return ""; } public override string GetOperator( GroupOperator op ) { switch ( op ) { case GroupOperator.And: return " AND "; case GroupOperator.Or: return " OR "; } return ""; } public String Format( Query query, bool isExplicit ) { if ( fFields == null && query.HasConditions ) { throw new QueryFormatterException( "Agent is not configured to respond to query conditions" ); } return Format(query, fFields, isExplicit); } /// <summary> Return the text for a field name</summary> /// <param name="field">The field /// </param> /// <param name="def">The corresponding field definition from the Map passed to /// the <c>format</c> method /// </param> /// <returns> The implementation returns the field name in whatever form is /// appropriate to the implementation, using the supplied <i>def</i> /// Object if necessary to obtain additional field information. /// </returns> public override string RenderField( IElementDef field, Object def ) { try { return ExtractFieldName( ((SQLField) def).Name ); } catch ( InvalidCastException cce ) { throw new QueryFormatterException ( "SQLQueryFormatter requires that the Map passed to the format method consist of SQLField instances (not " + cce.Message + " instances)" ); } } /// <summary> Return the text for a field value</summary> /// <param name="valu">The field value</param> /// <param name="def">The corresponding field definition from the Map passed to /// the <c>format</c> method /// </param> /// <returns> The implementation returns the field value in whatever form is /// appropriate to the implementation, using the supplied <i>def</i> /// Object if necessary to obtain additional field information /// </returns> public override string RenderValue(string valu, Object def) { try { // The elements in the Map are expected to be SQLField instances SQLField f = (SQLField) def; return f.Render( DoValueSubstitution( valu, f.Name ) ); } catch ( InvalidCastException cce ) { throw new QueryFormatterException ( "SQLQueryFormatter requires that the Map passed to the format method consist of SQLField instances (not " + cce.Message + " instances)", cce ); } } /// <summary> /// /// </summary> /// <param name="def"></param> /// <param name="field"></param> public void AddField(IElementDef def, SQLField field) { if (fFields == null) { fFields = new Dictionary<Object, Object>(); } fFields[def] = field; } /// <summary> /// /// </summary> /// <param name="xPath"></param> /// <param name="field"></param> public void AddField(String xPath, SQLField field) { if (fFields == null) { fFields = new Dictionary<Object, Object>(); } fFields[xPath] = field; } /// <summary> /// Adds an SQLField to use for rendering an SQL Where clause using /// the <see cref="SQLQueryFormatter#Query"/> method. /// </summary> /// <param name="def"> The ElementDef that is represented by the field</param> /// <param name="field">The SQL representation of the field</param> public void AddField(IElementDef def, IQueryField field) { if (fFields == null) { fFields = new Dictionary<Object, Object>(); } fFields[def] = field; } /// <summary> /// Adds a QueryField to use for rendering an SQL Where clause /// </summary> /// <param name="xPath"></param> /// <param name="field"></param> public void AddField(String xPath, IQueryField field) { if (fFields == null) { fFields = new Dictionary<Object, Object>(); } fFields[xPath] = field; } /// <summary> /// Adds SQLFields to represent each field rule in the specified MappingsContext. /// </summary> /// <param name="context"></param> public void AddFields(MappingsContext context) { AddFields(context, SqlDialect.DEFAULT); } /// <summary> /// Adds SQLFields to represent each field rule in the specified MappingsContext /// </summary> /// <param name="context"></param> /// <param name="dialect"></param> public void AddFields( MappingsContext context, Dialect dialect ) { foreach ( FieldMapping mapping in context.FieldMappings ) { Rule rule = mapping.fRule; if ( rule is XPathRule ) { TypeConverter converter = null; XPathRule xRule = (XPathRule) rule; IElementDef targetDef = xRule.LookupTargetDef( context.ObjectDef ); if ( targetDef != null ) { converter = targetDef.TypeConverter; } if ( converter == null ) { converter = SifTypeConverters.STRING; } if ( mapping.ValueSetID != null ) { ValueSet vs = context.Mappings.GetValueSet( mapping.ValueSetID, true ); if ( vs != null ) { //Create the lookup table for generating the SQL lookup StringBuilder buffer = new StringBuilder(); // e.g. CircRecord.PatronType{StudentPersonal=1;StaffPersonal=2} //buffer.Append( tablePrefix ); buffer.Append( mapping.FieldName ); buffer.Append( '{' ); ValueSetEntry[] entries = vs.Entries; for ( int a = 0; a < entries.Length; a++ ) { if ( a > 0 ) { buffer.Append( ';' ); } buffer.Append( entries[a].Value ); buffer.Append( '=' ); ; buffer.Append( entries[a].Name ); } buffer.Append( '}' ); SQLField f = new SQLField( buffer.ToString(), converter.DbType, dialect ); AddField( xRule.XPath, f ); continue; } } SQLField field = new SQLField( mapping.FieldName, converter.DbType, dialect ); AddField( xRule.XPath, field ); } } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System.ComponentModel; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; using System.Globalization; using System.Windows.Threading; using System.Windows.Data; using System.Windows.Input; using System.Windows; using System.Windows.Automation.Peers; using System.Windows.Media; using System.Windows.Controls.Primitives; using System.Windows.Markup; using MS.Utility; using System; namespace System.Windows.Controls { /// <summary> /// TabControl allows a developer to arrange visual content in a compacted and organized form. /// The real-world analog of the control might be a tabbed notebook, /// in which visual content is displayed in discreet pages which are accessed /// by selecting the appropriate tab. Each tab/page is encapsulated by a TabItem, /// the generated item of TabControl. /// A TabItem has a Header property which corresponds to the content in the tab button /// and a Content property which corresponds to the content in the tab page. /// This control is useful for minimizing screen space usage while allowing an application to expose a large amount of data. /// The user navigates through TabItems by clicking on a tab button using the mouse or by using the keyboard. /// </summary> [StyleTypedProperty(Property = "ItemContainerStyle", StyleTargetType = typeof(TabItem))] [TemplatePart(Name = "PART_SelectedContentHost", Type = typeof(ContentPresenter))] public class TabControl : Selector { #region Constructors static TabControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(TabControl), new FrameworkPropertyMetadata(typeof(TabControl))); _dType = DependencyObjectType.FromSystemTypeInternal(typeof(TabControl)); IsTabStopProperty.OverrideMetadata(typeof(TabControl), new FrameworkPropertyMetadata(MS.Internal.KnownBoxes.BooleanBoxes.FalseBox)); KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(TabControl), new FrameworkPropertyMetadata(KeyboardNavigationMode.Contained)); IsEnabledProperty.OverrideMetadata(typeof(TabControl), new UIPropertyMetadata(new PropertyChangedCallback(OnVisualStatePropertyChanged))); } /// <summary> /// Default TabControl constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> public TabControl() : base() { } #endregion #region Properties /// <summary> /// The DependencyProperty for the TabStripPlacement property. /// Flags: None /// Default Value: Dock.Top /// </summary> public static readonly DependencyProperty TabStripPlacementProperty = DependencyProperty.Register( "TabStripPlacement", typeof(Dock), typeof(TabControl), new FrameworkPropertyMetadata( Dock.Top, new PropertyChangedCallback(OnTabStripPlacementPropertyChanged)), new ValidateValueCallback(DockPanel.IsValidDock)); // When TabControl TabStripPlacement is changing we need to invalidate its TabItem TabStripPlacement private static void OnTabStripPlacementPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { TabControl tc = (TabControl)d; ItemCollection tabItemCollection = tc.Items; for (int i = 0; i < tabItemCollection.Count; i++) { TabItem ti = tc.ItemContainerGenerator.ContainerFromIndex(i) as TabItem; if (ti != null) ti.CoerceValue(TabItem.TabStripPlacementProperty); } } /// <summary> /// TabStripPlacement specify how tab headers align relatively to content /// </summary> [Bindable(true), Category("Behavior")] public Dock TabStripPlacement { get { return (Dock)GetValue(TabStripPlacementProperty); } set { SetValue(TabStripPlacementProperty, value); } } private static readonly DependencyPropertyKey SelectedContentPropertyKey = DependencyProperty.RegisterReadOnly("SelectedContent", typeof(object), typeof(TabControl), new FrameworkPropertyMetadata((object)null)); /// <summary> /// The DependencyProperty for the SelectedContent property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty SelectedContentProperty = SelectedContentPropertyKey.DependencyProperty; /// <summary> /// SelectedContent is the Content of current SelectedItem. /// This property is updated whenever the selection is changed. /// It always keeps a reference to active TabItem.Content /// Used for aliasing in default TabControl Style /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public object SelectedContent { get { return GetValue(SelectedContentProperty); } internal set { SetValue(SelectedContentPropertyKey, value); } } private static readonly DependencyPropertyKey SelectedContentTemplatePropertyKey = DependencyProperty.RegisterReadOnly("SelectedContentTemplate", typeof(DataTemplate), typeof(TabControl), new FrameworkPropertyMetadata((DataTemplate)null)); /// <summary> /// The DependencyProperty for the SelectedContentTemplate property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty SelectedContentTemplateProperty = SelectedContentTemplatePropertyKey.DependencyProperty; /// <summary> /// SelectedContentTemplate is the ContentTemplate of current SelectedItem. /// This property is updated whenever the selection is changed. /// It always keeps a reference to active TabItem.ContentTemplate /// It is used for aliasing in default TabControl Style /// </summary> /// <value></value> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataTemplate SelectedContentTemplate { get { return (DataTemplate)GetValue(SelectedContentTemplateProperty); } internal set { SetValue(SelectedContentTemplatePropertyKey, value); } } private static readonly DependencyPropertyKey SelectedContentTemplateSelectorPropertyKey = DependencyProperty.RegisterReadOnly("SelectedContentTemplateSelector", typeof(DataTemplateSelector), typeof(TabControl), new FrameworkPropertyMetadata((DataTemplateSelector)null)); /// <summary> /// The DependencyProperty for the SelectedContentTemplateSelector property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty SelectedContentTemplateSelectorProperty = SelectedContentTemplateSelectorPropertyKey.DependencyProperty; /// <summary> /// SelectedContentTemplateSelector allows the app writer to provide custom style selection logic. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataTemplateSelector SelectedContentTemplateSelector { get { return (DataTemplateSelector)GetValue(SelectedContentTemplateSelectorProperty); } internal set { SetValue(SelectedContentTemplateSelectorPropertyKey, value); } } private static readonly DependencyPropertyKey SelectedContentStringFormatPropertyKey = DependencyProperty.RegisterReadOnly("SelectedContentStringFormat", typeof(String), typeof(TabControl), new FrameworkPropertyMetadata((String)null)); /// <summary> /// The DependencyProperty for the SelectedContentStringFormat property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty SelectedContentStringFormatProperty = SelectedContentStringFormatPropertyKey.DependencyProperty; /// <summary> /// ContentStringFormat is the format used to display the content of /// the control as a string. This arises only when no template is /// available. /// </summary> public String SelectedContentStringFormat { get { return (String) GetValue(SelectedContentStringFormatProperty); } internal set { SetValue(SelectedContentStringFormatPropertyKey, value); } } /// <summary> /// The DependencyProperty for the ContentTemplate property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty ContentTemplateProperty = DependencyProperty.Register("ContentTemplate", typeof(DataTemplate), typeof(TabControl), new FrameworkPropertyMetadata((DataTemplate)null)); /// <summary> /// ContentTemplate is the ContentTemplate to apply to TabItems /// that do not have the ContentTemplate or ContentTemplateSelector properties /// defined /// </summary> /// <value></value> public DataTemplate ContentTemplate { get { return (DataTemplate)GetValue(ContentTemplateProperty); } set { SetValue(ContentTemplateProperty, value); } } /// <summary> /// The DependencyProperty for the ContentTemplateSelector property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty ContentTemplateSelectorProperty = DependencyProperty.Register("ContentTemplateSelector", typeof(DataTemplateSelector), typeof(TabControl), new FrameworkPropertyMetadata((DataTemplateSelector)null)); /// <summary> /// ContentTemplateSelector allows the app writer to provide custom style selection logic. /// </summary> public DataTemplateSelector ContentTemplateSelector { get { return (DataTemplateSelector)GetValue(ContentTemplateSelectorProperty); } set { SetValue(ContentTemplateSelectorProperty, value); } } /// <summary> /// The DependencyProperty for the ContentStringFormat property. /// Flags: None /// Default Value: null /// </summary> public static readonly DependencyProperty ContentStringFormatProperty = DependencyProperty.Register( "ContentStringFormat", typeof(String), typeof(TabControl), new FrameworkPropertyMetadata((String) null)); /// <summary> /// ContentStringFormat is the format used to display the content of /// the control as a string. This arises only when no template is /// available. /// </summary> public String ContentStringFormat { get { return (String) GetValue(ContentStringFormatProperty); } set { SetValue(ContentStringFormatProperty, value); } } #endregion #region Overrided Methods internal override void ChangeVisualState(bool useTransitions) { if (!IsEnabled) { VisualStates.GoToState(this, useTransitions, VisualStates.StateDisabled, VisualStates.StateNormal); } else { VisualStateManager.GoToState(this, VisualStates.StateNormal, useTransitions); } base.ChangeVisualState(useTransitions); } /// <summary> /// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>) /// </summary> protected override AutomationPeer OnCreateAutomationPeer() { return new TabControlAutomationPeer(this); } /// <summary> /// This virtual method in called when IsInitialized is set to true and it raises an Initialized event /// </summary> protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); CanSelectMultiple = false; ItemContainerGenerator.StatusChanged += new EventHandler(OnGeneratorStatusChanged); } /// <summary> /// Called when the Template's tree has been generated. When Template gets expanded we ensure that SelectedContent is in [....] /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); UpdateSelectedContent(); } /// <summary> /// A virtual function that is called when the selection is changed. Default behavior /// is to raise a SelectionChangedEvent /// </summary> /// <param name="e">The inputs for this event. Can be raised (default behavior) or processed /// in some other way.</param> protected override void OnSelectionChanged(SelectionChangedEventArgs e) { base.OnSelectionChanged(e); if (IsKeyboardFocusWithin) { // If keyboard focus is within the control, make sure it is going to the correct place TabItem item = GetSelectedTabItem(); if (item != null) { item.SetFocus(); } } UpdateSelectedContent(); if ( AutomationPeer.ListenerExists(AutomationEvents.SelectionPatternOnInvalidated) || AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementSelected) || AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementAddedToSelection) || AutomationPeer.ListenerExists(AutomationEvents.SelectionItemPatternOnElementRemovedFromSelection) ) { TabControlAutomationPeer peer = UIElementAutomationPeer.CreatePeerForElement(this) as TabControlAutomationPeer; if (peer != null) peer.RaiseSelectionEvents(e); } } /// <summary> /// Updates the current selection when Items has changed /// </summary> /// <param name="e">Information about what has changed</param> protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e) { base.OnItemsChanged(e); if (e.Action == NotifyCollectionChangedAction.Remove && SelectedIndex == -1) { // If we remove the selected item we should select the previous item int startIndex = e.OldStartingIndex + 1; if (startIndex > Items.Count) startIndex = 0; TabItem nextTabItem = FindNextTabItem(startIndex, -1); if (nextTabItem != null) nextTabItem.SetCurrentValueInternal(TabItem.IsSelectedProperty, MS.Internal.KnownBoxes.BooleanBoxes.TrueBox); } } /// <summary> /// This is the method that responds to the KeyDown event. /// </summary> /// <param name="e"></param> protected override void OnKeyDown(KeyEventArgs e) { TabItem nextTabItem = null; // Handle [Ctrl][Shift]Tab, Home and End cases // We have special handling here because if focus is inside the TabItem content we cannot // cycle through TabItem because the content is not part of the TabItem visual tree int direction = 0; int startIndex = -1; switch (e.Key) { case Key.Tab: if ((e.KeyboardDevice.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { startIndex = ItemContainerGenerator.IndexFromContainer(ItemContainerGenerator.ContainerFromItem(SelectedItem)); if ((e.KeyboardDevice.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift) direction = -1; else direction = 1; } break; case Key.Home: direction = 1; startIndex = -1; break; case Key.End: direction = -1; startIndex = Items.Count; break; } nextTabItem = FindNextTabItem(startIndex, direction); if (nextTabItem != null && nextTabItem != SelectedItem) { e.Handled = nextTabItem.SetFocus(); } if (!e.Handled) base.OnKeyDown(e); } private TabItem FindNextTabItem(int startIndex, int direction) { TabItem nextTabItem = null; if (direction != 0) { int index = startIndex; for (int i = 0; i < Items.Count; i++) { index += direction; if (index >= Items.Count) index = 0; else if (index < 0) index = Items.Count - 1; TabItem tabItem = ItemContainerGenerator.ContainerFromIndex(index) as TabItem; if (tabItem != null && tabItem.IsEnabled && tabItem.Visibility == Visibility.Visible) { nextTabItem = tabItem; break; } } } return nextTabItem; } /// <summary> /// Return true if the item is (or is eligible to be) its own ItemUI /// </summary> protected override bool IsItemItsOwnContainerOverride(object item) { return (item is TabItem); } /// <summary> Create or identify the element used to display the given item. </summary> protected override DependencyObject GetContainerForItemOverride() { return new TabItem(); } #endregion #region private helpers internal ContentPresenter SelectedContentPresenter { get { return GetTemplateChild(SelectedContentHostTemplateName) as ContentPresenter; } } private void OnGeneratorStatusChanged(object sender, EventArgs e) { if (ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated) { if (HasItems && _selectedItems.Count == 0) { SetCurrentValueInternal(SelectedIndexProperty, 0); } UpdateSelectedContent(); } } private TabItem GetSelectedTabItem() { object selectedItem = SelectedItem; if (selectedItem != null) { // Check if the selected item is a TabItem TabItem tabItem = selectedItem as TabItem; if (tabItem == null) { // It is a data item, get its TabItem container tabItem = ItemContainerGenerator.ContainerFromIndex(SelectedIndex) as TabItem; // Due to event leapfrogging, we may have the wrong container. // If so, re-fetch the right container using a more expensive method. // (BTW, the previous line will cause a debug assert in this case) [Dev10 452711] if (tabItem == null || !Object.Equals(selectedItem, ItemContainerGenerator.ItemFromContainer(tabItem))) { tabItem = ItemContainerGenerator.ContainerFromItem(selectedItem) as TabItem; } } return tabItem; } return null; } // When selection is changed we need to copy the active TabItem content in SelectedContent property // SelectedContent is aliased in the TabControl style private void UpdateSelectedContent() { if (SelectedIndex < 0) { SelectedContent = null; SelectedContentTemplate = null; SelectedContentTemplateSelector = null; SelectedContentStringFormat = null; return; } TabItem tabItem = GetSelectedTabItem(); if (tabItem != null) { FrameworkElement visualParent = VisualTreeHelper.GetParent(tabItem) as FrameworkElement; if (visualParent != null) { KeyboardNavigation.SetTabOnceActiveElement(visualParent, tabItem); KeyboardNavigation.SetTabOnceActiveElement(this, visualParent); } SelectedContent = tabItem.Content; ContentPresenter scp = SelectedContentPresenter; if (scp != null) { scp.HorizontalAlignment = tabItem.HorizontalContentAlignment; scp.VerticalAlignment = tabItem.VerticalContentAlignment; } // Use tabItem's template or selector if specified, otherwise use TabControl's if (tabItem.ContentTemplate != null || tabItem.ContentTemplateSelector != null || tabItem.ContentStringFormat != null) { SelectedContentTemplate = tabItem.ContentTemplate; SelectedContentTemplateSelector = tabItem.ContentTemplateSelector; SelectedContentStringFormat = tabItem.ContentStringFormat; } else { SelectedContentTemplate = ContentTemplate; SelectedContentTemplateSelector = ContentTemplateSelector; SelectedContentStringFormat = ContentStringFormat; } } } #endregion private helpers #region private data // Part name used in the style. The class TemplatePartAttribute should use the same name private const string SelectedContentHostTemplateName = "PART_SelectedContentHost"; #endregion #region DTypeThemeStyleKey // Returns the DependencyObjectType for the registered ThemeStyleKey's default // value. Controls will override this method to return approriate types. internal override DependencyObjectType DTypeThemeStyleKey { get { return _dType; } } private static DependencyObjectType _dType; #endregion DTypeThemeStyleKey } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.11.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyComplex { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class PrimitiveExtensions { /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IntWrapper GetInt(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetIntAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IntWrapper> GetIntAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IntWrapper> result = await operations.GetIntWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> public static void PutInt(this IPrimitive operations, IntWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutIntAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with integer properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put -1 and 2 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutIntAsync( this IPrimitive operations, IntWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutIntWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static LongWrapper GetLong(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetLongAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LongWrapper> GetLongAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<LongWrapper> result = await operations.GetLongWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> public static void PutLong(this IPrimitive operations, LongWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutLongAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with long properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1099511627775 and -999511627788 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutLongAsync( this IPrimitive operations, LongWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutLongWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static FloatWrapper GetFloat(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FloatWrapper> GetFloatAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<FloatWrapper> result = await operations.GetFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> public static void PutFloat(this IPrimitive operations, FloatWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutFloatAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with float properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 1.05 and -0.003 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutFloatAsync( this IPrimitive operations, FloatWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutFloatWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DoubleWrapper GetDouble(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DoubleWrapper> GetDoubleAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DoubleWrapper> result = await operations.GetDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> public static void PutDouble(this IPrimitive operations, DoubleWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutDoubleAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with double properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 3e-100 and /// -0.000000000000000000000000000000000000000000000000000000005 /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDoubleAsync( this IPrimitive operations, DoubleWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDoubleWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static BooleanWrapper GetBool(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetBoolAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BooleanWrapper> GetBoolAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<BooleanWrapper> result = await operations.GetBoolWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put true and false /// </param> public static void PutBool(this IPrimitive operations, BooleanWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutBoolAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with bool properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put true and false /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutBoolAsync( this IPrimitive operations, BooleanWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutBoolWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static StringWrapper GetString(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetStringAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<StringWrapper> GetStringAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<StringWrapper> result = await operations.GetStringWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> public static void PutString(this IPrimitive operations, StringWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutStringAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with string properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put 'goodrequest', '', and null /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutStringAsync( this IPrimitive operations, StringWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutStringWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DateWrapper GetDate(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DateWrapper> GetDateAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DateWrapper> result = await operations.GetDateWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> public static void PutDate(this IPrimitive operations, DateWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutDateAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with date properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01' and '2016-02-29' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateAsync( this IPrimitive operations, DateWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDateWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static DatetimeWrapper GetDateTime(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetDateTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<DatetimeWrapper> GetDateTimeAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<DatetimeWrapper> result = await operations.GetDateTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' /// </param> public static void PutDateTime(this IPrimitive operations, DatetimeWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutDateTimeAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with datetime properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutDateTimeAsync( this IPrimitive operations, DatetimeWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutDateTimeWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static ByteWrapper GetByte(this IPrimitive operations) { return Task.Factory.StartNew(s => ((IPrimitive)s).GetByteAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ByteWrapper> GetByteAsync( this IPrimitive operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<ByteWrapper> result = await operations.GetByteWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6) /// </param> public static void PutByte(this IPrimitive operations, ByteWrapper complexBody) { Task.Factory.StartNew(s => ((IPrimitive)s).PutByteAsync(complexBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put complex types with byte properties /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='complexBody'> /// Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6) /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutByteAsync( this IPrimitive operations, ByteWrapper complexBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutByteWithHttpMessagesAsync(complexBody, null, cancellationToken).ConfigureAwait(false); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using System.Xml; using Nini.Config; using OpenMetaverse; using Aurora.Framework.Servers.HttpServer; using log4net.Core; namespace Aurora.Framework { public class ConsoleConnection { public int last; public long lastLineSeen; public bool newConnection = true; } // A console that uses REST interfaces // public class RemoteConsole : CommandConsole { private readonly Dictionary<UUID, ConsoleConnection> m_Connections = new Dictionary<UUID, ConsoleConnection>(); private readonly ManualResetEvent m_DataEvent = new ManualResetEvent(false); private readonly List<string> m_InputData = new List<string>(); private readonly List<string> m_Scrollback = new List<string>(); private long m_LineNumber; private string m_Password = String.Empty; private IHttpServer m_Server; private string m_UserName = String.Empty; public override string Name { get { return "RemoteConsole"; } } public override void Initialize(IConfigSource source, ISimulationBase baseOpenSim) { uint m_consolePort = 0; if (source.Configs["Console"] != null) { if (source.Configs["Console"].GetString("Console", String.Empty) != Name) return; m_consolePort = (uint) source.Configs["Console"].GetInt("remote_console_port", 0); m_UserName = source.Configs["Console"].GetString("RemoteConsoleUser", String.Empty); m_Password = source.Configs["Console"].GetString("RemoteConsolePass", String.Empty); } else return; baseOpenSim.ApplicationRegistry.RegisterModuleInterface<ICommandConsole>(this); MainConsole.Instance = this; SetServer(m_consolePort == 0 ? MainServer.Instance : baseOpenSim.GetHttpServer(m_consolePort)); m_Commands.AddCommand("help", "help", "Get a general command list", base.Help); } public void SetServer(IHttpServer server) { m_Server = server; m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession); m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession); m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand); } public override void Output(string text, string level) { lock (m_Scrollback) { while (m_Scrollback.Count >= 1000) m_Scrollback.RemoveAt(0); m_LineNumber++; m_Scrollback.Add(String.Format("{0}", m_LineNumber) + ":" + level + ":" + text); } Console.WriteLine(text.Trim()); } public override void Output(string text) { Output(text, "Info"); } public override string ReadLine(string p, bool isCommand, bool e) { if (isCommand) Output("+++" + p); else Output("-++" + p); m_DataEvent.WaitOne(); string cmdinput; lock (m_InputData) { if (m_InputData.Count == 0) { m_DataEvent.Reset(); return ""; } cmdinput = m_InputData[0]; m_InputData.RemoveAt(0); if (m_InputData.Count == 0) m_DataEvent.Reset(); } if (isCommand) { string[] cmd = Commands.Resolve(Parser.Parse(cmdinput)); if (cmd.Length != 0) { int i; for (i = 0; i < cmd.Length; i++) { if (cmd[i].Contains(" ")) cmd[i] = "\"" + cmd[i] + "\""; } return String.Empty; } } return cmdinput; } private void DoExpire() { List<UUID> expired = new List<UUID>(); lock (m_Connections) { expired.AddRange(from kvp in m_Connections where Environment.TickCount - kvp.Value.last > 500000 select kvp.Key); foreach (UUID id in expired) { m_Connections.Remove(id); CloseConnection(id); } } } private Hashtable HandleHttpStartSession(Hashtable request) { DoExpire(); Hashtable post = DecodePostString(request["body"].ToString()); Hashtable reply = new Hashtable(); reply["str_response_string"] = ""; reply["int_response_code"] = 401; reply["content_type"] = "text/plain"; if (m_UserName == String.Empty) return reply; if (post["USER"] == null || post["PASS"] == null) return reply; if (m_UserName != post["USER"].ToString() || m_Password != post["PASS"].ToString()) { return reply; } ConsoleConnection c = new ConsoleConnection {last = Environment.TickCount, lastLineSeen = 0}; UUID sessionID = UUID.Random(); lock (m_Connections) { m_Connections[sessionID] = c; } string uri = "/ReadResponses/" + sessionID.ToString() + "/"; m_Server.AddPollServiceHTTPHandler(uri, HandleHttpPoll, new PollServiceEventArgs(null, HasEvents, GetEvents, NoEvents, Valid, sessionID)); XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", ""); xmldoc.AppendChild(rootElement); XmlElement id = xmldoc.CreateElement("", "SessionID", ""); id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString())); rootElement.AppendChild(id); XmlElement prompt = xmldoc.CreateElement("", "Prompt", ""); prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt)); rootElement.AppendChild(prompt); reply["str_response_string"] = xmldoc.InnerXml; reply["int_response_code"] = 200; reply["content_type"] = "text/xml"; return reply; } private bool Valid() { return true; } private Hashtable HandleHttpPoll(Hashtable request) { return new Hashtable(); } private Hashtable HandleHttpCloseSession(Hashtable request) { DoExpire(); Hashtable post = DecodePostString(request["body"].ToString()); Hashtable reply = new Hashtable(); reply["str_response_string"] = ""; reply["int_response_code"] = 404; reply["content_type"] = "text/plain"; if (post["ID"] == null) return reply; UUID id; if (!UUID.TryParse(post["ID"].ToString(), out id)) return reply; lock (m_Connections) { if (m_Connections.ContainsKey(id)) { m_Connections.Remove(id); CloseConnection(id); } } XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", ""); xmldoc.AppendChild(rootElement); XmlElement res = xmldoc.CreateElement("", "Result", ""); res.AppendChild(xmldoc.CreateTextNode("OK")); rootElement.AppendChild(res); reply["str_response_string"] = xmldoc.InnerXml; reply["int_response_code"] = 200; reply["content_type"] = "text/xml"; return reply; } private Hashtable HandleHttpSessionCommand(Hashtable request) { DoExpire(); Hashtable post = DecodePostString(request["body"].ToString()); Hashtable reply = new Hashtable(); reply["str_response_string"] = ""; reply["int_response_code"] = 404; reply["content_type"] = "text/plain"; if (post["ID"] == null) return reply; UUID id; if (!UUID.TryParse(post["ID"].ToString(), out id)) return reply; lock (m_Connections) { if (!m_Connections.ContainsKey(id)) return reply; } if (post["COMMAND"] == null) return reply; lock (m_InputData) { m_DataEvent.Set(); m_InputData.Add(post["COMMAND"].ToString()); } XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", ""); xmldoc.AppendChild(rootElement); XmlElement res = xmldoc.CreateElement("", "Result", ""); res.AppendChild(xmldoc.CreateTextNode("OK")); rootElement.AppendChild(res); reply["str_response_string"] = xmldoc.InnerXml; reply["int_response_code"] = 200; reply["content_type"] = "text/xml"; return reply; } private Hashtable DecodePostString(string data) { Hashtable result = new Hashtable(); string[] terms = data.Split(new[] {'&'}); foreach (string term in terms) { string[] elems = term.Split(new[] {'='}); if (elems.Length == 0) continue; string name = HttpUtility.UrlDecode(elems[0]); string value = String.Empty; if (elems.Length > 1) value = HttpUtility.UrlDecode(elems[1]); result[name] = value; } return result; } public void CloseConnection(UUID id) { try { string uri = "/ReadResponses/" + id.ToString() + "/"; m_Server.RemovePollServiceHTTPHandler("", uri); } catch (Exception) { } } private bool HasEvents(UUID RequestID, UUID sessionID) { ConsoleConnection c = null; lock (m_Connections) { if (!m_Connections.ContainsKey(sessionID)) return false; c = m_Connections[sessionID]; } c.last = Environment.TickCount; if (c.lastLineSeen < m_LineNumber) return true; return false; } private Hashtable GetEvents(UUID RequestID, UUID sessionID, string request) { ConsoleConnection c = null; lock (m_Connections) { if (!m_Connections.ContainsKey(sessionID)) return NoEvents(RequestID, UUID.Zero); c = m_Connections[sessionID]; } c.last = Environment.TickCount; if (c.lastLineSeen >= m_LineNumber) return NoEvents(RequestID, UUID.Zero); Hashtable result = new Hashtable(); XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", ""); if (c.newConnection) { c.newConnection = false; Output("+++" + DefaultPrompt); } lock (m_Scrollback) { long startLine = m_LineNumber - m_Scrollback.Count; long sendStart = startLine; if (sendStart < c.lastLineSeen) sendStart = c.lastLineSeen; for (long i = sendStart; i < m_LineNumber; i++) { XmlElement res = xmldoc.CreateElement("", "Line", ""); long line = i + 1; res.SetAttribute("Number", line.ToString()); res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int) (i - startLine)])); rootElement.AppendChild(res); } } c.lastLineSeen = m_LineNumber; xmldoc.AppendChild(rootElement); result["str_response_string"] = xmldoc.InnerXml; result["int_response_code"] = 200; result["content_type"] = "application/xml"; result["keepalive"] = false; result["reusecontext"] = false; return result; } private Hashtable NoEvents(UUID RequestID, UUID id) { Hashtable result = new Hashtable(); XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", ""); xmldoc.AppendChild(rootElement); result["str_response_string"] = xmldoc.InnerXml; result["int_response_code"] = 200; result["content_type"] = "text/xml"; result["keepalive"] = false; result["reusecontext"] = false; return result; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// RestoresOperations operations. /// </summary> internal partial class RestoresOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IRestoresOperations { /// <summary> /// Initializes a new instance of the RestoresOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RestoresOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Restores the specified backed up data. This is an asynchronous operation. /// To know the status of this API call, use GetProtectedItemOperationResult /// API. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up items. /// </param> /// <param name='containerName'> /// Container name associated with the backed up items. /// </param> /// <param name='protectedItemName'> /// Backed up item to be restored. /// </param> /// <param name='recoveryPointId'> /// Recovery point ID which represents the backed up data to be restored. /// </param> /// <param name='resourceRestoreRequest'> /// resource restore request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> TriggerWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, RestoreRequestResource resourceRestoreRequest, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "protectedItemName"); } if (recoveryPointId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "recoveryPointId"); } if (resourceRestoreRequest == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceRestoreRequest"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("resourceRestoreRequest", resourceRestoreRequest); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Trigger", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/restore").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } 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; if(resourceRestoreRequest != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(resourceRestoreRequest, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using System.Xml; using log4net; using Nini.Config; namespace OpenSim.Tools.Configger { /// <summary> /// Loads the Configuration files into nIni /// </summary> public class ConfigurationLoader { /// <summary> /// A source of Configuration data /// </summary> protected IConfigSource m_config; /// <summary> /// Console logger /// </summary> private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); public ConfigurationLoader() { } /// <summary> /// Loads the region configuration /// </summary> /// <param name="argvSource">Parameters passed into the process when started</param> /// <param name="configSettings"></param> /// <param name="networkInfo"></param> /// <returns>A configuration that gets passed to modules</returns> public IConfigSource LoadConfigSettings() { bool iniFileExists = false; List<string> sources = new List<string>(); string iniFileName = "OpenSim.ini"; string iniFilePath = Path.Combine(".", iniFileName); if (IsUri(iniFileName)) { if (!sources.Contains(iniFileName)) sources.Add(iniFileName); } else { if (File.Exists(iniFilePath)) { if (!sources.Contains(iniFilePath)) sources.Add(iniFilePath); } } m_config = new IniConfigSource(); m_config.Merge(DefaultConfig()); m_log.Info("[CONFIG] Reading configuration settings"); if (sources.Count == 0) { m_log.FatalFormat("[CONFIG] Could not load any configuration"); m_log.FatalFormat("[CONFIG] Did you copy the OpenSim.ini.example file to OpenSim.ini?"); Environment.Exit(1); } for (int i = 0 ; i < sources.Count ; i++) { if (ReadConfig(sources[i])) iniFileExists = true; AddIncludes(sources); } if (!iniFileExists) { m_log.FatalFormat("[CONFIG] Could not load any configuration"); m_log.FatalFormat("[CONFIG] Configuration exists, but there was an error loading it!"); Environment.Exit(1); } return m_config; } /// <summary> /// Adds the included files as ini configuration files /// </summary> /// <param name="sources">List of URL strings or filename strings</param> private void AddIncludes(List<string> sources) { //loop over config sources foreach (IConfig config in m_config.Configs) { // Look for Include-* in the key name string[] keys = config.GetKeys(); foreach (string k in keys) { if (k.StartsWith("Include-")) { // read the config file to be included. string file = config.GetString(k); if (IsUri(file)) { if (!sources.Contains(file)) sources.Add(file); } else { string basepath = Path.GetFullPath("."); string path = Path.Combine(basepath, file); string[] paths = Util.Glob(path); foreach (string p in paths) { if (!sources.Contains(p)) sources.Add(p); } } } } } } /// <summary> /// Check if we can convert the string to a URI /// </summary> /// <param name="file">String uri to the remote resource</param> /// <returns>true if we can convert the string to a Uri object</returns> bool IsUri(string file) { Uri configUri; return Uri.TryCreate(file, UriKind.Absolute, out configUri) && configUri.Scheme == Uri.UriSchemeHttp; } /// <summary> /// Provide same ini loader functionality for standard ini and master ini - file system or XML over http /// </summary> /// <param name="iniPath">Full path to the ini</param> /// <returns></returns> private bool ReadConfig(string iniPath) { bool success = false; if (!IsUri(iniPath)) { m_log.InfoFormat("[CONFIG] Reading configuration file {0}", Path.GetFullPath(iniPath)); m_config.Merge(new IniConfigSource(iniPath)); success = true; } else { m_log.InfoFormat("[CONFIG] {0} is a http:// URI, fetching ...", iniPath); // The ini file path is a http URI // Try to read it // try { XmlReader r = XmlReader.Create(iniPath); XmlConfigSource cs = new XmlConfigSource(r); m_config.Merge(cs); success = true; } catch (Exception e) { m_log.FatalFormat("[CONFIG] Exception reading config from URI {0}\n" + e.ToString(), iniPath); Environment.Exit(1); } } return success; } /// <summary> /// Setup a default config values in case they aren't present in the ini file /// </summary> /// <returns>A Configuration source containing the default configuration</returns> private static IConfigSource DefaultConfig() { IConfigSource defaultConfig = new IniConfigSource(); { IConfig config = defaultConfig.Configs["Startup"]; if (null == config) config = defaultConfig.AddConfig("Startup"); config.Set("region_info_source", "filesystem"); config.Set("gridmode", false); config.Set("physics", "OpenDynamicsEngine"); config.Set("meshing", "Meshmerizer"); config.Set("physical_prim", true); config.Set("see_into_this_sim_from_neighbor", true); config.Set("serverside_object_permissions", false); config.Set("storage_plugin", "OpenSim.Data.SQLite.dll"); config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3"); config.Set("storage_prim_inventories", true); config.Set("startup_console_commands_file", String.Empty); config.Set("shutdown_console_commands_file", String.Empty); config.Set("DefaultScriptEngine", "XEngine"); config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll"); // life doesn't really work without this config.Set("EventQueue", true); } { IConfig config = defaultConfig.Configs["StandAlone"]; if (null == config) config = defaultConfig.AddConfig("StandAlone"); config.Set("accounts_authenticate", true); config.Set("welcome_message", "Welcome to OpenSimulator"); config.Set("inventory_plugin", "OpenSim.Data.SQLite.dll"); config.Set("inventory_source", ""); config.Set("userDatabase_plugin", "OpenSim.Data.SQLite.dll"); config.Set("user_source", ""); config.Set("LibrariesXMLFile", string.Format(".{0}inventory{0}Libraries.xml", Path.DirectorySeparatorChar)); } { IConfig config = defaultConfig.Configs["Network"]; if (null == config) config = defaultConfig.AddConfig("Network"); config.Set("default_location_x", 1000); config.Set("default_location_y", 1000); config.Set("grid_send_key", "null"); config.Set("grid_recv_key", "null"); config.Set("user_send_key", "null"); config.Set("user_recv_key", "null"); config.Set("secure_inventory_server", "true"); } return defaultConfig; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; public abstract class CloningContext { // // State // protected readonly ControlFlowGraphState m_cfgDestination; protected readonly ControlFlowGraphState m_cfgSource; protected readonly InstantiationContext m_ic; protected readonly GrowOnlyHashTable< object, object > m_cloned = HashTableFactory.New< object, object >(); // // Constructor Methods // protected CloningContext( ControlFlowGraphState cfgSource , ControlFlowGraphState cfgDestination , InstantiationContext ic ) { m_cfgSource = cfgSource; m_cfgDestination = cfgDestination; m_ic = ic; } //--// public T ConvertType<T>( T td ) where T : TypeRepresentation { if(m_ic != null) { td = (T)m_ic.Instantiate( td ); } return td; } public T ConvertField<T>( T fd ) where T : FieldRepresentation { if(m_ic != null) { fd = (T)m_ic.Instantiate( fd ); } return fd; } public T[] ConvertFields<T>( T[] fdArray ) where T : FieldRepresentation { if(m_ic != null && fdArray != null) { fdArray = (T[])m_ic.Instantiate( fdArray ); } return fdArray; } public T ConvertMethod<T>( T md ) where T : MethodRepresentation { if(m_ic != null) { md = (T)m_ic.Instantiate( md ); } return md; } public T[] ConvertMethods<T>( T[] mdArray ) where T : MethodRepresentation { if(m_ic != null && mdArray != null) { mdArray = (T[])m_ic.Instantiate( mdArray ); } return mdArray; } //--// protected virtual void RegisterInner( object from , object to ) { m_cloned[from] = to; } public void Register( BasicBlock from , BasicBlock to ) { RegisterInner( from, to ); } public void Register( Expression from , Expression to ) { RegisterInner( from, to ); } public void Register( Operator from , Operator to ) { RegisterInner( from, to ); } public void Register( Annotation from , Annotation to ) { RegisterInner( from, to ); } public void Register( ExceptionClause from , ExceptionClause to ) { RegisterInner( from, to ); } public T LookupRegistered<T>( T key ) { object val; m_cloned.TryGetValue( key, out val ); return (T)val; } //--// protected virtual bool FoundInCache( object from , out object to ) { return m_cloned.TryGetValue( from, out to ); } private bool ShouldClone<T>( ref T from ) { object o; if(from == null) return false; if(FoundInCache( from, out o )) { from = (T)o; return false; } return true; } private bool ShouldClone<T>( ref T[] from ) { object o; if(from == null) return false; if(from.Length == 0) return false; if(FoundInCache( from, out o )) { from = (T[])o; return false; } return true; } //--// public BasicBlock Clone( BasicBlock from ) { if(!ShouldClone( ref from )) return from; BasicBlock clone = from.Clone( this ); return clone; } public BasicBlock[] Clone( BasicBlock[] from ) { if(!ShouldClone( ref from )) return from; BasicBlock[] clone = new BasicBlock[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } public ExceptionHandlerBasicBlock[] Clone( ExceptionHandlerBasicBlock[] from ) { if(!ShouldClone( ref from )) return from; ExceptionHandlerBasicBlock[] clone = new ExceptionHandlerBasicBlock[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = (ExceptionHandlerBasicBlock)Clone( from[i] ); } return clone; } //--// public Expression Clone( Expression from ) { if(!ShouldClone( ref from )) return from; if(m_cfgSource == m_cfgDestination) { // // Same flow graph, we don't create new local and argument variables. // if(from is ArgumentVariableExpression) { return from; } if(from is LocalVariableExpression) { return from; } } Expression clone = from.Clone( this ); return clone; } public Expression[] Clone( Expression[] from ) { if(!ShouldClone( ref from )) return from; Expression[] clone = new Expression[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } public VariableExpression[] Clone( VariableExpression[] from ) { if(!ShouldClone( ref from )) return from; VariableExpression[] clone = new VariableExpression[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = (VariableExpression)Clone( from[i] ); } return clone; } //--// public Operator Clone( Operator from ) { if(!ShouldClone( ref from )) return from; Operator clone = from.Clone( this ); return clone; } public Operator[] Clone( Operator[] from ) { if(!ShouldClone( ref from )) return from; Operator[] clone = new Operator[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } //--// public Annotation Clone( Annotation from ) { if(!ShouldClone( ref from )) return from; Annotation clone = from.Clone( this ); return clone; } public Annotation[] Clone( Annotation[] from ) { if(!ShouldClone( ref from )) return from; Annotation[] clone = new Annotation[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } //--// public ExceptionClause Clone( ExceptionClause from ) { if(!ShouldClone( ref from )) return from; ExceptionClause clone = from.Clone( this ); return clone; } public ExceptionClause[] Clone( ExceptionClause[] from ) { if(!ShouldClone( ref from )) return from; ExceptionClause[] clone = new ExceptionClause[from.Length]; m_cloned[from] = clone; for(int i = 0; i < from.Length; i++) { clone[i] = Clone( from[i] ); } return clone; } //--// // // Access Methods // public ControlFlowGraphState ControlFlowGraphSource { get { return m_cfgSource; } } public ControlFlowGraphState ControlFlowGraphDestination { get { return m_cfgDestination; } } public TypeSystemForIR TypeSystem { get { return m_cfgDestination.TypeSystemForIR; } } } }
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Base { public static class PasswordHashAlgorithmTests { public static readonly TheoryData<PasswordBasedKeyDerivationAlgorithm> PasswordHashAlgorithms = Registry.PasswordHashAlgorithms; private const string s_password = "passw0rd123"; #region Properties [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void Properties(PasswordBasedKeyDerivationAlgorithm a) { Assert.InRange(a.MaxCount, 0, int.MaxValue); Assert.InRange(a.MinSaltSize, 0, a.MaxSaltSize); Assert.InRange(a.MaxSaltSize, a.MinSaltSize, int.MaxValue); } #endregion #region DeriveBytes #1 [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSaltTooShort(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..(a.MinSaltSize - 1)], 0)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSaltTooLarge(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..(a.MaxSaltSize + 1)], 0)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithNegativeCount(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentOutOfRangeException>("count", () => a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], -1)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSmallCount(PasswordBasedKeyDerivationAlgorithm a) { var b = a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], 3); Assert.NotNull(b); Assert.Equal(3, b.Length); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesSuccess(PasswordBasedKeyDerivationAlgorithm a) { var b = a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], 32); Assert.NotNull(b); Assert.Equal(32, b.Length); } #endregion #region DeriveBytes #2 [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSpanWithSaltTooShort(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..(a.MinSaltSize - 1)], Span<byte>.Empty)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSpanWithSaltTooLarge(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..(a.MaxSaltSize + 1)], Span<byte>.Empty)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSpanWithSmallCount(PasswordBasedKeyDerivationAlgorithm a) { a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], new byte[3]); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveBytesWithSpanSuccess(PasswordBasedKeyDerivationAlgorithm a) { a.DeriveBytes(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], new byte[32]); } #endregion #region DeriveKey [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveKeyWithSaltTooShort(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveKey(Utilities.RandomBytes[..13], Utilities.RandomBytes[..(a.MinSaltSize - 1)], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveKeyWithSaltTooLarge(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveKey(Utilities.RandomBytes[..13], Utilities.RandomBytes[..(a.MaxSaltSize + 1)], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveKeyWithNullAlgorithm(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentNullException>("algorithm", () => a.DeriveKey(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void DeriveKeySuccess(PasswordBasedKeyDerivationAlgorithm a) { var x = AeadAlgorithm.ChaCha20Poly1305; using var k = a.DeriveKey(Utilities.RandomBytes[..13], Utilities.RandomBytes[..a.MinSaltSize], x); Assert.NotNull(k); Assert.Same(x, k.Algorithm); } #endregion #region DeriveBytes #1 [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesNull(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentNullException>("password", () => a.DeriveBytes((string)null!, Utilities.RandomBytes[..a.MinSaltSize], 0)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSaltTooShort(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(s_password, Utilities.RandomBytes[..(a.MinSaltSize - 1)], 0)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSaltTooLarge(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(s_password, Utilities.RandomBytes[..(a.MaxSaltSize + 1)], 0)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithNegativeCount(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentOutOfRangeException>("count", () => a.DeriveBytes(s_password, Utilities.RandomBytes[..a.MinSaltSize], -1)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSmallCount(PasswordBasedKeyDerivationAlgorithm a) { var b = a.DeriveBytes(s_password, Utilities.RandomBytes[..a.MinSaltSize], 3); Assert.NotNull(b); Assert.Equal(3, b.Length); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesSuccess(PasswordBasedKeyDerivationAlgorithm a) { var b = a.DeriveBytes(s_password, Utilities.RandomBytes[..a.MinSaltSize], 32); Assert.NotNull(b); Assert.Equal(32, b.Length); } #endregion #region DeriveBytes #2 [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSpanNull(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentNullException>("password", () => a.DeriveBytes((string)null!, Utilities.RandomBytes[..a.MinSaltSize], Span<byte>.Empty)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSpanWithSaltTooShort(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(s_password, Utilities.RandomBytes[..(a.MinSaltSize - 1)], Span<byte>.Empty)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSpanWithSaltTooLarge(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveBytes(s_password, Utilities.RandomBytes[..(a.MaxSaltSize + 1)], Span<byte>.Empty)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSpanWithSmallCount(PasswordBasedKeyDerivationAlgorithm a) { a.DeriveBytes(s_password, Utilities.RandomBytes[..a.MinSaltSize], new byte[3]); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveBytesWithSpanSuccess(PasswordBasedKeyDerivationAlgorithm a) { a.DeriveBytes(s_password, Utilities.RandomBytes[..a.MinSaltSize], new byte[32]); } #endregion #region DeriveKey [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveKeyNull(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentNullException>("password", () => a.DeriveKey((string)null!, Utilities.RandomBytes[..a.MinSaltSize], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveKeyWithSaltTooShort(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveKey(s_password, Utilities.RandomBytes[..(a.MinSaltSize - 1)], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveKeyWithSaltTooLarge(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentException>("salt", () => a.DeriveKey(s_password, Utilities.RandomBytes[..(a.MaxSaltSize + 1)], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveKeyWithNullAlgorithm(PasswordBasedKeyDerivationAlgorithm a) { Assert.Throws<ArgumentNullException>("algorithm", () => a.DeriveKey(s_password, Utilities.RandomBytes[..a.MinSaltSize], null!)); } [Theory] [MemberData(nameof(PasswordHashAlgorithms))] public static void StringDeriveKeySuccess(PasswordBasedKeyDerivationAlgorithm a) { var x = AeadAlgorithm.ChaCha20Poly1305; using var k = a.DeriveKey(s_password, Utilities.RandomBytes[..a.MinSaltSize], x); Assert.NotNull(k); Assert.Same(x, k.Algorithm); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using PhotoStoryToBloomConverter.BloomModel; using PhotoStoryToBloomConverter.PS3Model; using PhotoStoryToBloomConverter.Utilities; using SIL.Extensions; namespace PhotoStoryToBloomConverter { class Project { private readonly string _projectXmlPath; private readonly AudioHelper _audioHelper = new AudioHelper(); public Project(string projectXmlPath) { _projectXmlPath = projectXmlPath; } public bool Convert(string destinationFolder, string projectName, string projectCode, IEnumerable<string> docxPaths, string bloomPath, bool overwrite, PhotoStoryProject photoStoryProject = null, bool alsoZip = false) { if (docxPaths == null) docxPaths = new List<string>(); if (photoStoryProject == null) { photoStoryProject = Ps3AndBloomSerializer.DeserializePhotoStoryXml(_projectXmlPath); if (String.IsNullOrEmpty(projectName)) projectName = photoStoryProject.GetProjectName(); } var textByLanguage = new Dictionary<Language, IList<SourceText>>(); foreach (var docxPath in docxPaths) { var language = Path.GetFileNameWithoutExtension(docxPath).GetLanguageFromFileNameWithoutExtension(); if (language != Language.Unknown && textByLanguage.ContainsKey(language)) continue; if (TextExtractor.TryExtractText(docxPath, out var languageText)) textByLanguage.Add(language, languageText); else Console.WriteLine($@"Error: Could not process {language.ToString()} Word document for {projectName}."); } if (!textByLanguage.ContainsKey(Language.English)) { Console.WriteLine($@"Error: Could not find document with corresponding English text for {projectName}."); return false; } var allPagesInAllLanguages = new List<List<KeyValuePair<Language, SourceText>>>(); // Perhaps a bad assumption, but for now we will assume that if a non-English language // has the same number of elements as the English, that it is up-to-date. If not, don't include it. var englishTextElementCount = textByLanguage[Language.English].Count; var languagesToExclude = new List<Language>(); foreach (var language in textByLanguage) { if (language.Value.Count != englishTextElementCount) { Console.WriteLine($@"Excluding {language.Key} because it is out of sync with English"); languagesToExclude.Add(language.Key); } } textByLanguage.RemoveAll(l => languagesToExclude.Contains(l.Key)); SpAppMetadata spAppMetadata = null; for (int index = 0; index < textByLanguage[Language.English].Count; index++) { var allTranslationsOfThisPage = new List<KeyValuePair<Language, SourceText>>(6); foreach (var language in textByLanguage) { var sourceText = language.Value[index]; if (sourceText.TextType == TextType.Title && !string.IsNullOrWhiteSpace(projectCode)) { if (!sourceText.Text.StartsWith(projectCode)) sourceText.Text = $"{projectCode} {sourceText.Text}"; if (language.Key.GetCode() == Program.PrimaryOutputLanguage) { // We decided to give preference to the title in the docx rather than the original PhotoStory project projectName = sourceText.Text; } } if (sourceText.TextType == TextType.AlternateTitlesAndScrRef) { if (Program.SpAppOutput && language.Key.GetCode() == Program.PrimaryOutputLanguage) spAppMetadata = CreateSpAppMetadata(sourceText); allTranslationsOfThisPage = null; continue; } allTranslationsOfThisPage.Add(new KeyValuePair<Language, SourceText>(language.Key, sourceText)); } if (allTranslationsOfThisPage != null) allPagesInAllLanguages.Add(allTranslationsOfThisPage); } var convertedProjectDirectory = Path.Combine(destinationFolder, IOHelper.SanitizeFileOrDirectoryName(projectName)); if (Directory.Exists(convertedProjectDirectory) && !overwrite) { Console.WriteLine($@"Error: A book already exists with the name {projectName}."); return false; } if (Directory.Exists(convertedProjectDirectory) && overwrite) Program.DeleteAllFilesAndFoldersInDirectory(convertedProjectDirectory); else Directory.CreateDirectory(convertedProjectDirectory); //Three things needed for a bloom book: // book assets (images, narration audio, background audio) // bloom book css and images // the actual book, a generated html file built from the photostory project CopyAssetsAndResources(Path.GetDirectoryName(_projectXmlPath), convertedProjectDirectory); ConvertToBloom(photoStoryProject, Path.Combine(convertedProjectDirectory, $"{projectName}.htm"), projectName, allPagesInAllLanguages, spAppMetadata); var hydrationArguments = $"hydrate --preset shellbook --bookpath \"{convertedProjectDirectory}\" --vernacularisocode {Program.PrimaryOutputLanguage}"; bool hydrateSuccessful; try { using (var process = Process.Start(bloomPath, hydrationArguments)) { process.WaitForExit(); hydrateSuccessful = process.ExitCode == 0; } } catch { hydrateSuccessful = false; } if (!hydrateSuccessful) Console.WriteLine($@"ERROR: Unable to hydrate {projectName}"); else { Console.WriteLine($@"Successfully converted {projectName}"); Console.WriteLine($@" Languages: {string.Join(", ", textByLanguage.Keys)}"); } if (alsoZip) { var parentDir = Path.GetDirectoryName(convertedProjectDirectory); var outputPath = Path.Combine(parentDir, $"{projectName}.bloom"); ZipHelper.Zip(convertedProjectDirectory, outputPath); Console.WriteLine($@" Also created {outputPath}"); } Console.WriteLine(); return true; } private SpAppMetadata CreateSpAppMetadata(SourceText sourceText) { string titleIdeaHeading = null; var titleIdeas = new List<string>(); var titleIdeaInfo = sourceText.Text.Split('\n'); foreach (var line in titleIdeaInfo) { if (titleIdeaInfo.IndexOf(line) == 0) titleIdeaHeading = line; else titleIdeas.Add(line); } return new SpAppMetadata(sourceText.Reference, titleIdeaHeading, titleIdeas); } //The assumption is that the wp3 archive only contains assets and a project.xml file. We convert the .xml file and copy the images and audio tracks. private void CopyAssetsAndResources(string sourceFolderPath, string destinationFolderPath) { var audioFiles = new List<Tuple<string, bool>>(); foreach (var filePath in Directory.EnumerateFiles(sourceFolderPath)) { var filename = Path.GetFileName(filePath); if (filename.Equals("project.xml")) continue; if (AudioHelper.AudioFileNeedsConversion(filename)) audioFiles.Add(new Tuple<string, bool>(filename, true)); else if (AudioHelper.IsAudioFile(filename)) audioFiles.Add(new Tuple<string, bool>(filename, false)); else // should be image assets File.Copy(Path.Combine(sourceFolderPath, filename), Path.Combine(destinationFolderPath, filename)); } if (audioFiles.Count > 0) _audioHelper.ProcessAudioFiles(sourceFolderPath, destinationFolderPath, audioFiles); } //Pulls in all the gathered information for the project and creates a single bloom book html file at destinationFile private void ConvertToBloom(PhotoStoryProject project, string destinationFile, string bookName, IList<List<KeyValuePair<Language, SourceText>>> allPagesInAllLanguages, SpAppMetadata spAppMetadata) { var destinationDirectory = Path.GetDirectoryName(destinationFile); var document = new BloomDocument(project, bookName, destinationDirectory, allPagesInAllLanguages, _audioHelper.Duplicates, spAppMetadata); Ps3AndBloomSerializer.SerializeBloomHtml(document.ConvertToHtml(), destinationFile); AddMetaJson(destinationDirectory); } private void AddMetaJson(string destinationDirectory) { // Adding these tags was our plan at one point, but we are just leaving them off for now. // TODO: If we include narration audio in any templates we create, we should include the 'media:audio' tag as well. //File.WriteAllText(Path.Combine(destinationDirectory, "meta.json"), "{tags:['media:fulltext', 'media:kbanimation', 'media:music', 'tag:BibleStoryMultimedia']}"); var subBookshelf = Program.SpAppOutput ? "SPApp" : "IMS-IBS"; // TODO: If we include narration audio in any templates we create, we should include the talkingBook tag as well. File.WriteAllText(Path.Combine(destinationDirectory, "meta.json"), $@"{{features:['motion']}},tags{{bookshelf:Wycliffe/{subBookshelf},bookshelf:Bible/{subBookshelf}}}"); } } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Factories; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Persistence.Repositories { /// <summary> /// Represents a repository for doing CRUD operations for <see cref="Language"/> /// </summary> internal class LanguageRepository : PetaPocoRepositoryBase<int, ILanguage>, ILanguageRepository { public LanguageRepository(IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { } #region Overrides of RepositoryBase<int,Language> protected override ILanguage PerformGet(int id) { var sql = GetBaseQuery(false); sql.Where(GetBaseWhereClause(), new { Id = id }); var languageDto = Database.FirstOrDefault<LanguageDto>(sql); if (languageDto == null) return null; var entity = ConvertFromDto(languageDto); //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 ((Entity)entity).ResetDirtyProperties(false); return entity; } protected override IEnumerable<ILanguage> PerformGetAll(params int[] ids) { var sql = GetBaseQuery(false).Where("umbracoLanguage.id > 0"); if (ids.Any()) { sql.Where("umbracoLanguage.id in (@ids)", new { ids = ids }); } //this needs to be sorted since that is the way legacy worked - default language is the first one!! //even though legacy didn't sort, it should be by id sql.OrderBy<LanguageDto>(dto => dto.Id, SqlSyntax); return Database.Fetch<LanguageDto>(sql).Select(ConvertFromDto); } protected override IEnumerable<ILanguage> PerformGetByQuery(IQuery<ILanguage> query) { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator<ILanguage>(sqlClause, query); var sql = translator.Translate(); return Database.Fetch<LanguageDto>(sql).Select(ConvertFromDto); } #endregion #region Overrides of PetaPocoRepositoryBase<int,Language> protected override Sql GetBaseQuery(bool isCount) { var sql = new Sql(); sql.Select(isCount ? "COUNT(*)" : "*") .From<LanguageDto>(SqlSyntax); return sql; } protected override string GetBaseWhereClause() { return "umbracoLanguage.id = @Id"; } protected override IEnumerable<string> GetDeleteClauses() { var list = new List<string> { //NOTE: There is no constraint between the Language and cmsDictionary/cmsLanguageText tables (?) // but we still need to remove them "DELETE FROM cmsLanguageText WHERE languageId = @Id", "DELETE FROM umbracoLanguage WHERE id = @Id" }; return list; } protected override Guid NodeObjectTypeId { get { throw new NotImplementedException(); } } #endregion #region Unit of Work Implementation protected override void PersistNewItem(ILanguage entity) { ((Entity)entity).AddingEntity(); var factory = new LanguageFactory(); var dto = factory.BuildDto(entity); var id = Convert.ToInt32(Database.Insert(dto)); entity.Id = id; entity.ResetDirtyProperties(); } protected override void PersistUpdatedItem(ILanguage entity) { ((Entity)entity).UpdatingEntity(); var factory = new LanguageFactory(); var dto = factory.BuildDto(entity); Database.Update(dto); entity.ResetDirtyProperties(); //Clear the cache entries that exist by key/iso RuntimeCache.ClearCacheItem(GetCacheIdKey<ILanguage>(entity.IsoCode)); RuntimeCache.ClearCacheItem(GetCacheIdKey<ILanguage>(entity.CultureName)); } protected override void PersistDeletedItem(ILanguage entity) { base.PersistDeletedItem(entity); //Clear the cache entries that exist by key/iso RuntimeCache.ClearCacheItem(GetCacheIdKey<ILanguage>(entity.IsoCode)); RuntimeCache.ClearCacheItem(GetCacheIdKey<ILanguage>(entity.CultureName)); } #endregion protected ILanguage ConvertFromDto(LanguageDto dto) { var factory = new LanguageFactory(); var entity = factory.BuildEntity(dto); return entity; } public ILanguage GetByCultureName(string cultureName) { var cultureNameRepo = new LanguageByCultureNameRepository(this, UnitOfWork, RepositoryCache, Logger, SqlSyntax); return cultureNameRepo.Get(cultureName); } public ILanguage GetByIsoCode(string isoCode) { var isoRepo = new LanguageByIsoCodeRepository(this, UnitOfWork, RepositoryCache, Logger, SqlSyntax); return isoRepo.Get(isoCode); } /// <summary> /// Inner repository for looking up languages by ISO code, this deals with caching by a string key /// </summary> private class LanguageByIsoCodeRepository : SimpleGetRepository<string, ILanguage, LanguageDto> { private readonly LanguageRepository _languageRepository; public LanguageByIsoCodeRepository(LanguageRepository languageRepository, IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { _languageRepository = languageRepository; } protected override Sql GetBaseQuery(bool isCount) { return _languageRepository.GetBaseQuery(isCount); } protected override string GetBaseWhereClause() { return "umbracoLanguage.languageISOCode = @Id"; } protected override ILanguage ConvertToEntity(LanguageDto dto) { var factory = new LanguageFactory(); return factory.BuildEntity(dto); } protected override object GetBaseWhereClauseArguments(string id) { return new {Id = id}; } protected override string GetWhereInClauseForGetAll() { return "umbracoLanguage.languageISOCode in (@ids)"; } } /// <summary> /// Inner repository for looking up languages by culture name, this deals with caching by a string key /// </summary> private class LanguageByCultureNameRepository : SimpleGetRepository<string, ILanguage, LanguageDto> { private readonly LanguageRepository _languageRepository; public LanguageByCultureNameRepository(LanguageRepository languageRepository, IDatabaseUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { _languageRepository = languageRepository; } protected override Sql GetBaseQuery(bool isCount) { return _languageRepository.GetBaseQuery(isCount); } protected override string GetBaseWhereClause() { return "umbracoLanguage.languageCultureName = @Id"; } protected override ILanguage ConvertToEntity(LanguageDto dto) { var factory = new LanguageFactory(); return factory.BuildEntity(dto); } protected override object GetBaseWhereClauseArguments(string id) { return new {Id = id}; } protected override string GetWhereInClauseForGetAll() { return "umbracoLanguage.languageCultureName in (@ids)"; } } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net; using System.Text; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Logging; using Microsoft.Rest.Generator.Properties; using Microsoft.Rest.Generator.Utilities; namespace Microsoft.Rest.Generator { public abstract class CodeNamer { private static readonly IDictionary<char, string> basicLaticCharacters; protected CodeNamer() { ReservedWords = new HashSet<string>(); } /// <summary> /// Gets collection of reserved words. /// </summary> public HashSet<string> ReservedWords { get; private set; } /// <summary> /// Formats segments of a string split by underscores or hyphens into "Camel" case strings. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public static string CamelCase(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return name.Split('_', '-', ' ') .Where(s => !string.IsNullOrEmpty(s)) .Select((s, i) => FormatCase(s, i == 0)) // Pass true/toLower for just the first element. .DefaultIfEmpty("") .Aggregate(string.Concat); } /// <summary> /// Formats segments of a string split by underscores or hyphens into "Pascal" case. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public static string PascalCase(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return name.Split('_', '-', ' ') .Where(s => !string.IsNullOrEmpty(s)) .Select(s => FormatCase(s, false)) .DefaultIfEmpty("") .Aggregate(string.Concat); } /// <summary> /// Recursively normalizes names in the client model /// </summary> /// <param name="client"></param> public virtual void NormalizeClientModel(ServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } client.Name = GetTypeName(client.Name); client.Namespace = GetNamespaceName(client.Namespace); foreach (var property in client.Properties) { property.Name = GetPropertyName(property.Name); property.Type = NormalizeType(property.Type); } var normalizedModels = new List<CompositeType>(); foreach (var modelType in client.ModelTypes) { normalizedModels.Add(NormalizeType(modelType) as CompositeType); } client.ModelTypes.Clear(); normalizedModels.ForEach( (item) => client.ModelTypes.Add(item)); var normalizedEnums = new List<EnumType>(); foreach (var enumType in client.EnumTypes) { var normalizedType = NormalizeType(enumType) as EnumType; if (normalizedType != null) { normalizedEnums.Add(NormalizeType(enumType) as EnumType); } } client.EnumTypes.Clear(); normalizedEnums.ForEach((item) => client.EnumTypes.Add(item)); foreach (var method in client.Methods) { method.Name = GetMethodName(method.Name); method.Group = GetTypeName(method.Group); method.ReturnType = NormalizeType(method.ReturnType); method.DefaultResponse = NormalizeType(method.DefaultResponse); var normalizedResponses = new Dictionary<HttpStatusCode, IType>(); foreach (var statusCode in method.Responses.Keys) { normalizedResponses[statusCode] = NormalizeType(method.Responses[statusCode]); } method.Responses.Clear(); foreach (var statusCode in normalizedResponses.Keys) { method.Responses[statusCode] = normalizedResponses[statusCode]; } foreach (var parameter in method.Parameters) { parameter.Name = GetParameterName(parameter.Name); parameter.Type = NormalizeType(parameter.Type); } } } /// <summary> /// Formats a string for naming members of an enum using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetEnumMemberName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(name)); } /// <summary> /// Formats a string for naming fields using a prefix '_' and VariableName Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetFieldName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return '_' + GetVariableName(name); } /// <summary> /// Formats a string for naming interfaces using a prefix 'I' and Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetInterfaceName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return "I" + PascalCase(RemoveInvalidCharacters(name)); } /// <summary> /// Formats a string for naming a method using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetMethodName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Operation"))); } /// <summary> /// Formats a string for identifying a namespace using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetNamespaceName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharactersNamespace(name)); } /// <summary> /// Formats a string for naming method parameters using GetVariableName Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetParameterName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return GetVariableName(GetEscapedReservedName(name, "Parameter")); } /// <summary> /// Formats a string for naming properties using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetPropertyName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Property"))); } /// <summary> /// Formats a string for naming a Type or Object using Pascal case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetTypeName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return PascalCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Model"))); } /// <summary> /// Formats a string for naming a local variable using Camel case by default. /// </summary> /// <param name="name"></param> /// <returns>The formatted string.</returns> public virtual string GetVariableName(string name) { if (string.IsNullOrWhiteSpace(name)) { return name; } return CamelCase(RemoveInvalidCharacters(GetEscapedReservedName(name, "Variable"))); } /// <summary> /// Returns language specific type name. /// </summary> /// <param name="type"></param> /// <returns></returns> protected abstract IType NormalizeType(IType type); /// <summary> /// Formats a string as upper or lower case. Two-letter inputs that are all upper case are both lowered. /// Example: ID = > id, Ex => ex /// </summary> /// <param name="name"></param> /// <param name="toLower"></param> /// <returns>The formatted string.</returns> private static string FormatCase(string name, bool toLower) { if (!string.IsNullOrEmpty(name)) { if (name.Length < 2 || (name.Length == 2 && char.IsUpper(name[0]) && char.IsUpper(name[1]))) { name = toLower ? name.ToLowerInvariant() : name.ToUpperInvariant(); } else { name = (toLower ? char.ToLowerInvariant(name[0]) : char.ToUpperInvariant(name[0])) + name.Substring(1, name.Length - 1); } } return name; } /// <summary> /// Removes invalid characters from the name. Everything but alpha-numeral, underscore, /// and dash. /// </summary> /// <param name="name">String to parse.</param> /// <returns>Name with invalid characters removed.</returns> public static string RemoveInvalidCharacters(string name) { return GetValidName(name, '_', '-'); } /// <summary> /// Removes invalid characters from the namespace. Everything but alpha-numeral, underscore, /// period, and dash. /// </summary> /// <param name="name">String to parse.</param> /// <returns>Namespace with invalid characters removed.</returns> protected virtual string RemoveInvalidCharactersNamespace(string name) { return GetValidName(name, '_', '-', '.'); } /// <summary> /// Gets valid name for the identifier. /// </summary> /// <param name="name">String to parse.</param> /// <param name="allowerCharacters">Allowed characters.</param> /// <returns>Name with invalid characters removed.</returns> private static string GetValidName(string name, params char[] allowerCharacters) { var correctName = RemoveInvalidCharacters(name, allowerCharacters); // here we have only letters and digits or an empty string if (string.IsNullOrEmpty(correctName) || basicLaticCharacters.ContainsKey(correctName[0])) { var sb = new StringBuilder(); foreach (char symbol in name) { if (basicLaticCharacters.ContainsKey(symbol)) { sb.Append(basicLaticCharacters[symbol]); } else { sb.Append(symbol); } } correctName = RemoveInvalidCharacters(sb.ToString(), allowerCharacters); } // if it is still empty string, throw if (correctName.IsNullOrEmpty()) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidIdentifierName, name)); } return correctName; } /// <summary> /// Removes invalid characters from the name. /// </summary> /// <param name="name">String to parse.</param> /// <param name="allowerCharacters">Allowed characters.</param> /// <returns>Name with invalid characters removed.</returns> private static string RemoveInvalidCharacters(string name, params char[] allowerCharacters) { return new string(name.Replace("[]", "Sequence") .Where(c => char.IsLetterOrDigit(c) || allowerCharacters.Contains(c)) .ToArray()); } /// <summary> /// If the provided name is a reserved word in a programming language then the method converts the /// name by appending the provided appendValue /// </summary> /// <param name="name">Name.</param> /// <param name="appendValue">String to append.</param> /// <returns>The transformed reserved name</returns> protected virtual string GetEscapedReservedName(string name, string appendValue) { if (name == null) { throw new ArgumentNullException("name"); } if (appendValue == null) { throw new ArgumentNullException("appendValue"); } if (ReservedWords.Contains(name, StringComparer.OrdinalIgnoreCase)) { name += appendValue; } return name; } /// <summary> /// Resolves name collisions in the client model by iterating over namespaces (if provided, /// model names, client name, and client method groups. /// </summary> /// <param name="serviceClient">Service client to process.</param> /// <param name="clientNamespace">Client namespace or null.</param> /// <param name="modelNamespace">Client model namespace or null.</param> public virtual void ResolveNameCollisions(ServiceClient serviceClient, string clientNamespace, string modelNamespace) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } // take all namespaces of Models var exclusionListQuery = SplitNamespaceAndIgnoreLast(modelNamespace) .Union(SplitNamespaceAndIgnoreLast(clientNamespace)); var exclusionDictionary = new Dictionary<string, string>(exclusionListQuery .Where(s => !string.IsNullOrWhiteSpace(s)) .ToDictionary(s => s, v => "namespace"), StringComparer.OrdinalIgnoreCase); var models = new List<CompositeType>(serviceClient.ModelTypes); serviceClient.ModelTypes.Clear(); foreach (var model in models) { model.Name = ResolveNameConflict( exclusionDictionary, model.Name, "Schema definition", "Model"); serviceClient.ModelTypes.Add(model); foreach (var property in model.Properties) { if (property.Name.Equals(model.Name, StringComparison.OrdinalIgnoreCase)) { property.Name += "Property"; } } } var enumTypes = new List<EnumType>(serviceClient.EnumTypes); serviceClient.EnumTypes.Clear(); foreach (var enumType in enumTypes) { enumType.Name = ResolveNameConflict( exclusionDictionary, enumType.Name, "Enum name", "Enum"); serviceClient.EnumTypes.Add(enumType); } serviceClient.Name = ResolveNameConflict( exclusionDictionary, serviceClient.Name, "Client", "Client"); ResolveMethodGroupNameCollision(serviceClient, exclusionDictionary); } /// <summary> /// Resolves name collisions in the client model for method groups (operations). /// </summary> /// <param name="serviceClient"></param> /// <param name="exclusionDictionary"></param> protected virtual void ResolveMethodGroupNameCollision(ServiceClient serviceClient, Dictionary<string, string> exclusionDictionary) { if (serviceClient == null) { throw new ArgumentNullException("serviceClient"); } if (exclusionDictionary == null) { throw new ArgumentNullException("exclusionDictionary"); } var methodGroups = serviceClient.MethodGroups.ToList(); foreach (var methodGroup in methodGroups) { var resolvedName = ResolveNameConflict( exclusionDictionary, methodGroup, "Client operation", "Operations"); foreach (var method in serviceClient.Methods) { if (method.Group == methodGroup) { method.Group = resolvedName; } } } } private static string ResolveNameConflict( Dictionary<string, string> exclusionDictionary, string typeName, string type, string suffix) { string resolvedName = typeName; var sb = new StringBuilder(); sb.AppendLine(); while (exclusionDictionary.ContainsKey(resolvedName)) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, Resources.NamespaceConflictReasonMessage, resolvedName, exclusionDictionary[resolvedName])); resolvedName += suffix; } if (!string.Equals(resolvedName, typeName, StringComparison.OrdinalIgnoreCase)) { sb.AppendLine(Resources.NamingConflictsSuggestion); Logger.LogWarning( string.Format( CultureInfo.InvariantCulture, Resources.EntityConflictTitleMessage, type, typeName, resolvedName, sb)); } exclusionDictionary.Add(resolvedName, type); return resolvedName; } private static IEnumerable<string> SplitNamespaceAndIgnoreLast(string nameSpace) { if (string.IsNullOrEmpty(nameSpace)) { return Enumerable.Empty<string>(); } var namespaceWords = nameSpace.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); if (namespaceWords.Length < 1) { return Enumerable.Empty<string>(); } // else we do not need the last part of the namespace return namespaceWords.Take(namespaceWords.Length - 1); } [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static CodeNamer() { basicLaticCharacters = new Dictionary<char, string>(); basicLaticCharacters[(char)32] = "Space"; basicLaticCharacters[(char)33] = "ExclamationMark"; basicLaticCharacters[(char)34] = "QuotationMark"; basicLaticCharacters[(char)35] = "NumberSign"; basicLaticCharacters[(char)36] = "DollarSign"; basicLaticCharacters[(char)37] = "PercentSign"; basicLaticCharacters[(char)38] = "Ampersand"; basicLaticCharacters[(char)39] = "Apostrophe"; basicLaticCharacters[(char)40] = "LeftParenthesis"; basicLaticCharacters[(char)41] = "RightParenthesis"; basicLaticCharacters[(char)42] = "Asterisk"; basicLaticCharacters[(char)43] = "PlusSign"; basicLaticCharacters[(char)44] = "Comma"; basicLaticCharacters[(char)45] = "HyphenMinus"; basicLaticCharacters[(char)46] = "FullStop"; basicLaticCharacters[(char)47] = "Slash"; basicLaticCharacters[(char)48] = "Zero"; basicLaticCharacters[(char)49] = "One"; basicLaticCharacters[(char)50] = "Two"; basicLaticCharacters[(char)51] = "Three"; basicLaticCharacters[(char)52] = "Four"; basicLaticCharacters[(char)53] = "Five"; basicLaticCharacters[(char)54] = "Six"; basicLaticCharacters[(char)55] = "Seven"; basicLaticCharacters[(char)56] = "Eight"; basicLaticCharacters[(char)57] = "Nine"; basicLaticCharacters[(char)58] = "Colon"; basicLaticCharacters[(char)59] = "Semicolon"; basicLaticCharacters[(char)60] = "LessThanSign"; basicLaticCharacters[(char)61] = "EqualSign"; basicLaticCharacters[(char)62] = "GreaterThanSign"; basicLaticCharacters[(char)63] = "QuestionMark"; basicLaticCharacters[(char)64] = "AtSign"; basicLaticCharacters[(char)91] = "LeftSquareBracket"; basicLaticCharacters[(char)92] = "Backslash"; basicLaticCharacters[(char)93] = "RightSquareBracket"; basicLaticCharacters[(char)94] = "CircumflexAccent"; basicLaticCharacters[(char)95] = "LowLine"; basicLaticCharacters[(char)96] = "GraveAccent"; basicLaticCharacters[(char)123] = "LeftCurlyBracket"; basicLaticCharacters[(char)124] = "VerticalBar"; basicLaticCharacters[(char)125] = "RightCurlyBracket"; basicLaticCharacters[(char)126] = "Tilde"; } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Net; using System.Text; using System.Collections; using System.Net.Sockets; using OpenSource.UPnP; using System.Collections.Generic; namespace UPnPStackBuilder { /// <summary> /// Summary description for EmbeddedCGenerator. /// </summary> public class DotNetGenerator : CodeGenerator { private string nspace = "OpenSource.Sample"; public Hashtable Settings = new Hashtable(); public ArrayList AllServices = new ArrayList(); public Hashtable ServiceNames; public string StartupPath; private static string cl = "\r\n"; public string CodeNewLine { get {return cl;} set {cl = value;} } public DotNetGenerator(string ns,ServiceGenerator.StackConfiguration Config):base(Config) { if (ns!="") { nspace = ns; } } private void AddAllServices(UPnPDevice device) { foreach (UPnPService s in device.Services) AllServices.Add(s); foreach (UPnPDevice d in device.EmbeddedDevices) AddAllServices(d); } int gendevnumber = 0; private void GenerateAddDevice(CodeProcessor cs, UPnPDevice device) { string dev = gendevnumber.ToString(); if (gendevnumber == 0) dev = ""; if (device.ParentDevice == null) { cs.Append("device = UPnPDevice.CreateRootDevice(1800,1.0,\"\\\\\");"+cl); } else { cs.Append("UPnPDevice device"+dev+" = UPnPDevice.CreateEmbeddedDevice(1,System.Guid.NewGuid().ToString());"+cl); } // // Add Custom Tags // foreach (string ns in device.GetCustomFieldFromDescription_Namespaces()) { foreach (KeyValuePair<string, string> tag in device.GetCustomFieldsFromDescription(ns)) { cs.Append("device" + dev + ".AddCustomFieldInDescription(\"" + tag.Key + "\", \"" + tag.Value + "\", \"" + ns + "\");" + cl); } } cs.Append(cl); cs.Append("device"+dev+".FriendlyName = \""+device.FriendlyName+"\";"+cl); if (device.Manufacturer != null) cs.Append("device"+dev+".Manufacturer = \""+device.Manufacturer+"\";"+cl); if (device.ManufacturerURL != null) cs.Append("device"+dev+".ManufacturerURL = \""+device.ManufacturerURL+"\";"+cl); if (device.ModelName != null) cs.Append("device"+dev+".ModelName = \""+device.ModelName+"\";"+cl); if (device.ModelDescription != null) cs.Append("device"+dev+".ModelDescription = \""+device.ModelDescription+"\";"+cl); if (device.ModelURL != null) cs.Append("device"+dev+".ModelURL = new Uri(\""+device.ModelURL.ToString()+"\");"+cl); if (device.ModelNumber != null) cs.Append("device"+dev+".ModelNumber = \""+device.ModelNumber+"\";"+cl); cs.Append("device"+dev+".HasPresentation = false;"+cl); cs.Append("device"+dev+".DeviceURN = \""+device.DeviceURN+"\";"+cl); foreach (UPnPService service in device.Services) { string servicename = (string)ServiceNames[service]; cs.Append(nspace+".Dv" + servicename + " " + servicename + " = new "+nspace+".Dv" + servicename + "();" + cl); //ConnectionManager.External_ConnectionComplete(new OpenSource.DeviceBuilder.ConnectionManager.Delegate_ConnectionComplete(ConnectionCompleteAction)); foreach (UPnPAction action in service.Actions) { cs.Append(servicename + ".External_" + action.Name + " = new "+nspace+".Dv" + servicename + ".Delegate_" + action.Name + "(" + servicename + "_" + action.Name + ");" + cl); } cs.Append("device"+dev+".AddService(" + servicename + ");" + cl); } gendevnumber++; foreach (UPnPDevice embeddeddevice in device.EmbeddedDevices) { int dn = gendevnumber; GenerateAddDevice(cs,embeddeddevice); cs.Append("device"+dev+".AddDevice(device" + dn + ");" + cl); gendevnumber++; } cs.Append(cl); } public override bool Generate(UPnPDevice[] devices, DirectoryInfo outputDirectory) { bool ok = false; bool RetVal = false; foreach(UPnPDevice device in devices) { if (((ServiceGenerator.Configuration)device.User).ConfigType==ServiceGenerator.ConfigurationType.DEVICE) { ok = true; if (Configuration.UPNP_1dot1) { device.ArchitectureVersion = "1.1"; } else { device.ArchitectureVersion = "1.0"; } device.ClearCustomFieldsInDescription(); ((ServiceGenerator.Configuration)device.User).AddAllCustomFieldsToDevice(device); RetVal = GenerateEx(device,outputDirectory,GetServiceNameTable(device)); if (!RetVal){break;} } } return(ok?RetVal:true); } protected bool GenerateEx(UPnPDevice device,DirectoryInfo outputDirectory, Hashtable serviceNames) { AllServices.Clear(); AddAllServices(device); StreamWriter writer; ServiceNames = serviceNames; // *** Generate Main Code Log("Writing main stack module..."); foreach (UPnPService service in AllServices) { string servicename = (string)serviceNames[service]; string servicexml = new UTF8Encoding().GetString(service.GetSCPDXml()); Log("Generating service class for " + servicename); OpenSource.UPnP.ServiceGenerator.Generate("Dv"+servicename,nspace,outputDirectory.FullName + "\\Dv" + servicename + ".cs",service.ServiceID,service.ServiceURN,servicexml); } CodeProcessor cs = new CodeProcessor(new StringBuilder(),true); StringBuilder cs2; cs.Comment("UPnP .NET Framework Device Stack, Device Module"); cs.Comment(VersionString); cs.Append(cl); cs.Append("using System;" + cl); cs.Append("using OpenSource.UPnP;" + cl); cs.Append("using "+nspace+";" + cl); cs.Append(cl); cs.Append("namespace "+nspace+cl); cs.Append("{"+cl); cs.Append(" /// <summary>"+cl); cs.Append(" /// Summary description for SampleDevice."+cl); cs.Append(" /// </summary>"+cl); cs.Append(" class SampleDevice"+cl); cs.Append(" {"+cl); cs.Append(" private UPnPDevice device;" + cl); cs.Append(cl); cs.Append(" public SampleDevice()"+cl); cs.Append(" {"+cl); gendevnumber = 0; GenerateAddDevice(cs,device); cs.Comment("Setting the initial value of evented variables"); foreach (UPnPService service in AllServices) { string servicename = (string)ServiceNames[service]; foreach (UPnPStateVariable variable in service.GetStateVariables()) { if (variable.SendEvent == true) { cs.Append(servicename + ".Evented_" + variable.Name + " = " + this.ToSampleValue(variable.GetNetType().ToString()) + ";" + cl); } } } cs.Append(" }"+cl); cs.Append(cl); cs.Append(" public void Start()"+cl); cs.Append(" {"+cl); cs.Append(" device.StartDevice();"+cl); cs.Append(" }"+cl); cs.Append(cl); cs.Append(" public void Stop()"+cl); cs.Append(" {"+cl); cs.Append(" device.StopDevice();"+cl); cs.Append(" }"+cl); cs.Append(cl); foreach (UPnPService service in AllServices) { string servicename = (string)serviceNames[service]; // Build MethodDelegates foreach(UPnPAction action in service.Actions) { cs.Append("public "); if (action.HasReturnValue==false) { cs.Append("void "); } else { cs.Append(action.GetRetArg().RelatedStateVar.GetNetType().FullName + " "); } cs.Append(servicename + "_" + action.Name + "("); UPnPArgument[] Args = action.ArgumentList; for(int i=0;i<Args.Length;++i) { UPnPArgument arg = Args[i]; if (arg.IsReturnValue==false) { if (arg.Direction=="out") { cs.Append("out "); } if (arg.RelatedStateVar.AllowedStringValues==null) { cs.Append(arg.RelatedStateVar.GetNetType().FullName + " "); } else { cs.Append("Dv"+servicename + ".Enum_" + arg.RelatedStateVar.Name + " "); } cs.Append(arg.Name); if (i<Args.Length-1) { cs.Append(", "); } } } cs.Append(")" + cl); cs.Append("{" + cl); foreach (UPnPArgument arg in action.Arguments) { if (arg.Direction == "out" && arg.IsReturnValue==false) { if (arg.RelatedStateVar.AllowedStringValues==null) { cs.Append(arg.Name + " = " + ToSampleValue(arg.RelatedStateVar.GetNetType().ToString()) + ";" + cl); } else { string t = arg.RelatedStateVar.AllowedStringValues[0].ToUpper(); t = t.Replace("-","_"); t = t.Replace("+","_"); t = t.Replace(" ","_"); t = t.Replace(":","_"); if (IsNumeric(t[0])==true) t = "_" + t; cs.Append(arg.Name + " = Dv" + servicename + ".Enum_" + arg.RelatedStateVar.Name + "." + t + ";" + cl); } } } cs.Append("Console.WriteLine(\"" + servicename + "_" + action.Name + "(\""); foreach (UPnPArgument arg in action.ArgumentList) { if (arg.Direction == "in") { cs.Append(" + " + arg.Name + ".ToString()"); } } cs.Append(" + \")\");" + cl); if (action.GetRetArg() != null) { cs.Append(cl); cs.Append("return " + ToSampleValue(action.GetRetArg().RelatedStateVar.GetNetType().ToString()) + ";" + cl); } cs.Append("}" + cl); cs.Append(cl); } } cs.Append(" }"+cl); cs.Append("}"+cl); cs.Append(cl); writer = File.CreateText(outputDirectory.FullName + "\\SampleDevice.cs"); writer.Write(cs.ToString()); writer.Close(); cs = new CodeProcessor(new StringBuilder(),true); cs.Comment("UPnP .NET Framework Device Stack, Core Module"); cs.Comment(VersionString); cs.Append(cl); cs.Append("using System;" + cl); cs.Append("using OpenSource.UPnP;" + cl); cs.Append("using "+nspace+";" + cl); cs.Append(cl); cs.Append("namespace "+nspace+cl); cs.Append("{"+cl); cs.Append(" /// <summary>"+cl); cs.Append(" /// Summary description for Main."+cl); cs.Append(" /// </summary>"+cl); cs.Append(" class SampleDeviceMain"+cl); cs.Append(" {"+cl); cs.Append(" /// <summary>"+cl); cs.Append(" /// The main entry point for the application."+cl); cs.Append(" /// </summary>"+cl); cs.Append(" [STAThread]"+cl); cs.Append(" static void Main(string[] args)"+cl); cs.Append(" {"+cl); cs.Comment("Starting UPnP Device"); cs.Append(" System.Console.WriteLine(\"UPnP .NET Framework Stack\");"+cl); cs.Append(" System.Console.WriteLine(\""+VersionString+"\");"+cl); cs.Append(" SampleDevice device = new SampleDevice();"+cl); cs.Append(" device.Start();"+cl); cs.Append(" System.Console.WriteLine(\"Press return to stop device.\");"+cl); cs.Append(" System.Console.ReadLine();"+cl); cs.Append(" device.Stop();"+cl); cs.Append(" }"+cl); cs.Append(cl); cs.Append(" }"+cl); cs.Append("}"+cl); cs.Append(cl); writer = File.CreateText(outputDirectory.FullName + "\\Main.cs"); writer.Write(cs.ToString()); writer.Close(); Log("Generating Visual Studio 7 Solution"); cs2 = new StringBuilder(); cs2.Append("Microsoft Visual Studio Solution File, Format Version 7.00" + cl); cs2.Append("Project(\"{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\") = \"SampleDevice\", \"SampleDevice.csproj\", \"{FE5FA3F9-E2EA-40BE-8CF4-27F33CF6454E}\"" + cl); cs2.Append("EndProject" + cl); cs2.Append("Global" + cl); cs2.Append(" GlobalSection(SolutionConfiguration) = preSolution" + cl); cs2.Append(" ConfigName.0 = Debug" + cl); cs2.Append(" ConfigName.1 = Release" + cl); cs2.Append(" EndGlobalSection" + cl); cs2.Append(" GlobalSection(ProjectDependencies) = postSolution" + cl); cs2.Append(" EndGlobalSection" + cl); cs2.Append(" GlobalSection(ProjectConfiguration) = postSolution" + cl); cs2.Append(" {FE5FA3F9-E2EA-40BE-8CF4-27F33CF6454E}.Debug.ActiveCfg = Debug|.NET" + cl); cs2.Append(" {FE5FA3F9-E2EA-40BE-8CF4-27F33CF6454E}.Debug.Build.0 = Debug|.NET" + cl); cs2.Append(" {FE5FA3F9-E2EA-40BE-8CF4-27F33CF6454E}.Release.ActiveCfg = Release|.NET" + cl); cs2.Append(" {FE5FA3F9-E2EA-40BE-8CF4-27F33CF6454E}.Release.Build.0 = Release|.NET" + cl); cs2.Append(" EndGlobalSection" + cl); cs2.Append(" GlobalSection(ExtensibilityGlobals) = postSolution" + cl); cs2.Append(" EndGlobalSection" + cl); cs2.Append(" GlobalSection(ExtensibilityAddIns) = postSolution" + cl); cs2.Append(" EndGlobalSection" + cl); cs2.Append("EndGlobal" + cl); writer = File.CreateText(outputDirectory.FullName + "\\SampleDevice.sln"); writer.Write(cs2.ToString()); writer.Close(); Log("Generating Assembly Info"); cs2 = new StringBuilder(); cs2.Append("using System.Reflection;" + cl); cs2.Append("using System.Runtime.CompilerServices;" + cl); cs2.Append(cl); cs2.Append("[assembly: AssemblyTitle(\"\")]" + cl); cs2.Append("[assembly: AssemblyDescription(\"\")]" + cl); cs2.Append("[assembly: AssemblyConfiguration(\"\")]" + cl); cs2.Append("[assembly: AssemblyCompany(\"\")]" + cl); cs2.Append("[assembly: AssemblyProduct(\"\")]" + cl); cs2.Append("[assembly: AssemblyCopyright(\"\")]" + cl); cs2.Append("[assembly: AssemblyTrademark(\"\")]" + cl); cs2.Append("[assembly: AssemblyCulture(\"\")]" + cl); cs2.Append("[assembly: AssemblyVersion(\"1.0.*\")]" + cl); cs2.Append("[assembly: AssemblyDelaySign(false)]" + cl); cs2.Append("[assembly: AssemblyKeyFile(\"\")]" + cl); cs2.Append("[assembly: AssemblyKeyName(\"\")]" + cl); writer = File.CreateText(outputDirectory.FullName + "\\AssemblyInfo.cs"); writer.Write(cs2.ToString()); writer.Close(); Log("Generating Visual Studio 7 Project"); cs2 = new StringBuilder(); cs2.Append("<VisualStudioProject>" + cl); cs2.Append(" <CSHARP" + cl); cs2.Append(" ProjectType = \"Local\"" + cl); cs2.Append(" ProductVersion = \"7.0.9466\"" + cl); cs2.Append(" SchemaVersion = \"1.0\"" + cl); cs2.Append(" ProjectGuid = \"{FE5FA3F9-E2EA-40BE-8CF4-27F33CF6454E}\"" + cl); cs2.Append(" >" + cl); cs2.Append(" <Build>" + cl); cs2.Append(" <Settings" + cl); cs2.Append(" ApplicationIcon = \"\"" + cl); cs2.Append(" AssemblyKeyContainerName = \"\"" + cl); cs2.Append(" AssemblyName = \"SampleDevice\"" + cl); cs2.Append(" AssemblyOriginatorKeyFile = \"\"" + cl); cs2.Append(" DefaultClientScript = \"JScript\"" + cl); cs2.Append(" DefaultHTMLPageLayout = \"Grid\"" + cl); cs2.Append(" DefaultTargetSchema = \"IE50\"" + cl); cs2.Append(" DelaySign = \"false\"" + cl); cs2.Append(" OutputType = \"Exe\"" + cl); cs2.Append(" RootNamespace = \"SampleDevice\"" + cl); cs2.Append(" StartupObject = \"\"" + cl); cs2.Append(" >" + cl); cs2.Append(" <Config" + cl); cs2.Append(" Name = \"Debug\"" + cl); cs2.Append(" AllowUnsafeBlocks = \"false\"" + cl); cs2.Append(" BaseAddress = \"285212672\"" + cl); cs2.Append(" CheckForOverflowUnderflow = \"false\"" + cl); cs2.Append(" ConfigurationOverrideFile = \"\"" + cl); cs2.Append(" DefineConstants = \"DEBUG;TRACE\"" + cl); cs2.Append(" DocumentationFile = \"\"" + cl); cs2.Append(" DebugSymbols = \"true\"" + cl); cs2.Append(" FileAlignment = \"4096\"" + cl); cs2.Append(" IncrementalBuild = \"true\"" + cl); cs2.Append(" Optimize = \"false\"" + cl); cs2.Append(" OutputPath = \"bin\\Debug\\\"" + cl); cs2.Append(" RegisterForComInterop = \"false\"" + cl); cs2.Append(" RemoveIntegerChecks = \"false\"" + cl); cs2.Append(" TreatWarningsAsErrors = \"false\"" + cl); cs2.Append(" WarningLevel = \"4\"" + cl); cs2.Append(" />" + cl); cs2.Append(" <Config" + cl); cs2.Append(" Name = \"Release\"" + cl); cs2.Append(" AllowUnsafeBlocks = \"false\"" + cl); cs2.Append(" BaseAddress = \"285212672\"" + cl); cs2.Append(" CheckForOverflowUnderflow = \"false\"" + cl); cs2.Append(" ConfigurationOverrideFile = \"\"" + cl); cs2.Append(" DefineConstants = \"TRACE\"" + cl); cs2.Append(" DocumentationFile = \"\"" + cl); cs2.Append(" DebugSymbols = \"false\"" + cl); cs2.Append(" FileAlignment = \"4096\"" + cl); cs2.Append(" IncrementalBuild = \"false\"" + cl); cs2.Append(" Optimize = \"true\"" + cl); cs2.Append(" OutputPath = \"bin\\Release\\\"" + cl); cs2.Append(" RegisterForComInterop = \"false\"" + cl); cs2.Append(" RemoveIntegerChecks = \"false\"" + cl); cs2.Append(" TreatWarningsAsErrors = \"false\"" + cl); cs2.Append(" WarningLevel = \"4\"" + cl); cs2.Append(" />" + cl); cs2.Append(" </Settings>" + cl); cs2.Append(" <References>" + cl); cs2.Append(" <Reference" + cl); cs2.Append(" Name = \"System\"" + cl); cs2.Append(" AssemblyName = \"System\"" + cl); cs2.Append(" HintPath = \"..\\..\\WINDOWS\\Microsoft.NET\\Framework\\v1.0.3705\\System.dll\"" + cl); cs2.Append(" />" + cl); cs2.Append(" <Reference" + cl); cs2.Append(" Name = \"System.Data\"" + cl); cs2.Append(" AssemblyName = \"System.Data\"" + cl); cs2.Append(" HintPath = \"..\\..\\WINDOWS\\Microsoft.NET\\Framework\\v1.0.3705\\System.Data.dll\"" + cl); cs2.Append(" />" + cl); cs2.Append(" <Reference" + cl); cs2.Append(" Name = \"System.XML\"" + cl); cs2.Append(" AssemblyName = \"System.Xml\"" + cl); cs2.Append(" HintPath = \"..\\..\\WINDOWS\\Microsoft.NET\\Framework\\v1.0.3705\\System.XML.dll\"" + cl); cs2.Append(" />" + cl); cs2.Append(" <Reference" + cl); cs2.Append(" Name = \"UPnP\"" + cl); cs2.Append(" AssemblyName = \"UPnP\"" + cl); cs2.Append(" HintPath = \"UPnP.dll\"" + cl); cs2.Append(" />" + cl); cs2.Append(" </References>" + cl); cs2.Append(" </Build>" + cl); cs2.Append(" <Files>" + cl); cs2.Append(" <Include>" + cl); cs2.Append(" <File" + cl); cs2.Append(" RelPath = \"AssemblyInfo.cs\"" + cl); cs2.Append(" SubType = \"Code\"" + cl); cs2.Append(" BuildAction = \"Compile\"" + cl); cs2.Append(" />" + cl); foreach (UPnPService service in AllServices) { cs2.Append(" <File" + cl); cs2.Append(" RelPath = \"Dv"+(string)serviceNames[service]+".cs\"" + cl); cs2.Append(" SubType = \"Code\"" + cl); cs2.Append(" BuildAction = \"Compile\"" + cl); cs2.Append(" />" + cl); } cs2.Append(" <File" + cl); cs2.Append(" RelPath = \"SampleDevice.cs\"" + cl); cs2.Append(" SubType = \"Code\"" + cl); cs2.Append(" BuildAction = \"Compile\"" + cl); cs2.Append(" />" + cl); cs2.Append(" <File" + cl); cs2.Append(" RelPath = \"Main.cs\"" + cl); cs2.Append(" SubType = \"Code\"" + cl); cs2.Append(" BuildAction = \"Compile\"" + cl); cs2.Append(" />" + cl); cs2.Append(" </Include>" + cl); cs2.Append(" </Files>" + cl); cs2.Append(" </CSHARP>" + cl); cs2.Append("</VisualStudioProject>" + cl); writer = File.CreateText(outputDirectory.FullName + "\\SampleDevice.csproj"); writer.Write(cs2.ToString()); writer.Close(); Log("Copying UPnP.dll."); System.IO.File.Copy(AppStartPath + "\\UPnP.dll",outputDirectory.FullName + "\\UPnP.dll",true); Log("UPnP Stack Generation Complete."); return true; } public string ToSampleValue(string t) { switch (t) { case "System.Boolean": return "false"; case "System.Byte[]": case "System.String": return "\"Sample String\""; case "System.Uri": return "\"http://opentools.homeip.net\""; case "System.Byte": return "0"; case "System.UInt16": return "0"; case "System.UInt32": return "0"; case "System.Char": case "System.SByte": return "0"; case "System.Int16": return "0"; case "System.Int32": return "0"; case "System.Single": case "System.Double": return "0"; case "System.DateTime": return("DateTime.Now"); default: return "NULL"; } } private static bool IsNumeric(char c) { int x = (int)c; if ((x>=48)&&(x<=57)) { return(true); } else { return(false); } } } }
// Copyright (c) 2006-2007 Frank Laub // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. The name of the author may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Text; using System.Runtime.InteropServices; using System.IO; using OpenSSL.Core; namespace OpenSSL.Crypto { #region Cipher /// <summary> /// Wraps the EVP_CIPHER object. /// </summary> public class Cipher : Base { private EVP_CIPHER raw; internal Cipher(IntPtr ptr, bool owner) : base(ptr, owner) { this.raw = (EVP_CIPHER)Marshal.PtrToStructure(this.ptr, typeof(EVP_CIPHER)); } /// <summary> /// Prints the LongName of this cipher. /// </summary> /// <param name="bio"></param> public override void Print(BIO bio) { bio.Write(this.LongName); } /// <summary> /// Not implemented, these objects should never be disposed /// </summary> protected override void OnDispose() { throw new NotImplementedException(); } /// <summary> /// Returns EVP_get_cipherbyname() /// </summary> /// <param name="name"></param> /// <returns></returns> public static Cipher CreateByName(string name) { byte[] buf = Encoding.ASCII.GetBytes(name); IntPtr ptr = Native.EVP_get_cipherbyname(buf); if(ptr == IntPtr.Zero) return null; return new Cipher(ptr, false); } /// <summary> /// Calls OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH) /// </summary> public static string[] AllNamesSorted { get { return new NameCollector(Native.OBJ_NAME_TYPE_CIPHER_METH, true).Result.ToArray(); } } /// <summary> /// Calls OBJ_NAME_do_all(OBJ_NAME_TYPE_CIPHER_METH) /// </summary> public static string[] AllNames { get { return new NameCollector(Native.OBJ_NAME_TYPE_CIPHER_METH, false).Result.ToArray(); } } #region EVP_CIPHER [StructLayout(LayoutKind.Sequential)] struct EVP_CIPHER { public int nid; public int block_size; public int key_len; public int iv_len; public uint flags; public IntPtr init; public IntPtr do_cipher; public IntPtr cleanup; public int ctx_size; public IntPtr set_asn1_parameters; public IntPtr get_asn1_parameters; public IntPtr ctrl; public IntPtr app_data; } #endregion #region Ciphers /// <summary> /// EVP_enc_null() /// </summary> public static Cipher Null = new Cipher(Native.EVP_enc_null(), false); /// <summary> /// EVP_des_ecb() /// </summary> public static Cipher DES_ECB = new Cipher(Native.EVP_des_ecb(), false); /// <summary> /// EVP_des_ede() /// </summary> public static Cipher DES_EDE = new Cipher(Native.EVP_des_ede(), false); /// <summary> /// EVP_des_ede3() /// </summary> public static Cipher DES_EDE3 = new Cipher(Native.EVP_des_ede3(), false); /// <summary> /// EVP_des_ede_ecb() /// </summary> public static Cipher DES_EDE_ECB = new Cipher(Native.EVP_des_ede_ecb(), false); /// <summary> /// EVP_des_ede3_ecb() /// </summary> public static Cipher DES_EDE3_ECB = new Cipher(Native.EVP_des_ede3_ecb(), false); /// <summary> /// EVP_des_cfb64() /// </summary> public static Cipher DES_CFB64 = new Cipher(Native.EVP_des_cfb64(), false); /// <summary> /// EVP_des_cfb1() /// </summary> public static Cipher DES_CFB1 = new Cipher(Native.EVP_des_cfb1(), false); /// <summary> /// EVP_des_cfb8() /// </summary> public static Cipher DES_CFB8 = new Cipher(Native.EVP_des_cfb8(), false); /// <summary> /// EVP_des_ede_cfb64() /// </summary> public static Cipher DES_EDE_CFB64 = new Cipher(Native.EVP_des_ede_cfb64(), false); /// <summary> /// EVP_des_ede3_cfb64() /// </summary> public static Cipher DES_EDE3_CFB64 = new Cipher(Native.EVP_des_ede3_cfb64(), false); /// <summary> /// EVP_des_ede3_cfb1() /// </summary> // public static Cipher DES_EDE3_CFB1 = new Cipher(Native.EVP_des_ede3_cfb1(), false); /// <summary> /// EVP_des_ede3_cfb8() /// </summary> public static Cipher DES_EDE3_CFB8 = new Cipher(Native.EVP_des_ede3_cfb8(), false); /// <summary> /// EVP_des_ofb() /// </summary> public static Cipher DES_OFB = new Cipher(Native.EVP_des_ofb(), false); /// <summary> /// EVP_ded_ede_ofb() /// </summary> public static Cipher DES_EDE_OFB = new Cipher(Native.EVP_des_ede_ofb(), false); /// <summary> /// EVP_des_ede3_ofb() /// </summary> public static Cipher DES_EDE3_OFB = new Cipher(Native.EVP_des_ede3_ofb(), false); /// <summary> /// EVP_des_cbc() /// </summary> public static Cipher DES_CBC = new Cipher(Native.EVP_des_cbc(), false); /// <summary> /// EVP_des_ede_cbc() /// </summary> public static Cipher DES_EDE_CBC = new Cipher(Native.EVP_des_ede_cbc(), false); /// <summary> /// EVP_des_ede3_cbc() /// </summary> public static Cipher DES_EDE3_CBC = new Cipher(Native.EVP_des_ede3_cbc(), false); /// <summary> /// EVP_desx_cbc() /// </summary> public static Cipher DESX_CBC = new Cipher(Native.EVP_desx_cbc(), false); /// <summary> /// EVP_rc4() /// </summary> public static Cipher RC4 = new Cipher(Native.EVP_rc4(), false); /// <summary> /// EVP_rc4_40() /// </summary> public static Cipher RC4_40 = new Cipher(Native.EVP_rc4_40(), false); /// <summary> /// EVP_idea_ecb() /// </summary> public static Cipher Idea_ECB = new Cipher(Native.EVP_idea_ecb(), false); /// <summary> /// EVP_idea_cfb64() /// </summary> public static Cipher Idea_CFB64 = new Cipher(Native.EVP_idea_cfb64(), false); /// <summary> /// EVP_idea_ofb() /// </summary> public static Cipher Idea_OFB = new Cipher(Native.EVP_idea_ofb(), false); /// <summary> /// EVP_idea_cbc() /// </summary> public static Cipher Idea_CBC = new Cipher(Native.EVP_idea_cbc(), false); /// <summary> /// EVP_rc2_ecb() /// </summary> public static Cipher RC2_ECB = new Cipher(Native.EVP_rc2_ecb(), false); /// <summary> /// EVP_rc2_cbc() /// </summary> public static Cipher RC2_CBC = new Cipher(Native.EVP_rc2_cbc(), false); /// <summary> /// EVP_rc2_40_cbc() /// </summary> public static Cipher RC2_40_CBC = new Cipher(Native.EVP_rc2_40_cbc(), false); /// <summary> /// EVP_rc2_64_cbc() /// </summary> public static Cipher RC2_64_CBC = new Cipher(Native.EVP_rc2_64_cbc(), false); /// <summary> /// EVP_rc2_cfb64() /// </summary> public static Cipher RC2_CFB64 = new Cipher(Native.EVP_rc2_cfb64(), false); /// <summary> /// EVP_rc2_ofb() /// </summary> public static Cipher RC2_OFB = new Cipher(Native.EVP_rc2_ofb(), false); /// <summary> /// EVP_bf_ecb() /// </summary> public static Cipher Blowfish_ECB = new Cipher(Native.EVP_bf_ecb(), false); /// <summary> /// EVP_bf_cbc() /// </summary> public static Cipher Blowfish_CBC = new Cipher(Native.EVP_bf_cbc(), false); /// <summary> /// EVP_bf_cfb64() /// </summary> public static Cipher Blowfish_CFB64 = new Cipher(Native.EVP_bf_cfb64(), false); /// <summary> /// EVP_bf_ofb() /// </summary> public static Cipher Blowfish_OFB = new Cipher(Native.EVP_bf_ofb(), false); /// <summary> /// EVP_cast5_ecb() /// </summary> public static Cipher Cast5_ECB = new Cipher(Native.EVP_cast5_ecb(), false); /// <summary> /// EVP_cast5_cbc() /// </summary> public static Cipher Cast5_CBC = new Cipher(Native.EVP_cast5_cbc(), false); /// <summary> /// EVP_cast5_cfb64() /// </summary> public static Cipher Cast5_OFB64 = new Cipher(Native.EVP_cast5_cfb64(), false); /// <summary> /// EVP_cast5_ofb() /// </summary> public static Cipher Cast5_OFB = new Cipher(Native.EVP_cast5_ofb(), false); #if OPENSSL_RC5_SUPPORT public static Cipher RC5_32_12_16_CBC = new Cipher(Native.EVP_rc5_32_12_16_cbc(), false); public static Cipher RC5_32_12_16_ECB = new Cipher(Native.EVP_rc5_32_12_16_ecb(), false); public static Cipher RC5_32_12_16_CFB64 = new Cipher(Native.EVP_rc5_32_12_16_cfb64(), false); public static Cipher RC5_32_12_16_OFB = new Cipher(Native.EVP_rc5_32_12_16_ofb(), false); #endif /// <summary> /// EVP_aes_128_ecb() /// </summary> public static Cipher AES_128_ECB = new Cipher(Native.EVP_aes_128_ecb(), false); /// <summary> /// EVP_aes_128_cbc() /// </summary> public static Cipher AES_128_CBC = new Cipher(Native.EVP_aes_128_cbc(), false); /// <summary> /// EVP_aes_128_cfb1() /// </summary> public static Cipher AES_128_CFB1 = new Cipher(Native.EVP_aes_128_cfb1(), false); /// <summary> /// EVP_aes_128_cfb8() /// </summary> public static Cipher AES_128_CFB8 = new Cipher(Native.EVP_aes_128_cfb8(), false); /// <summary> /// EVP_aes_128_cfb128() /// </summary> public static Cipher AES_128_CFB128 = new Cipher(Native.EVP_aes_128_cfb128(), false); /// <summary> /// EVP_aes_128_ofb() /// </summary> public static Cipher AES_128_OFB = new Cipher(Native.EVP_aes_128_ofb(), false); /// <summary> /// EVP_aes_128_xts() /// </summary> public static Cipher AES_128_XTS = new Cipher(Native.EVP_aes_128_xts(), false); /// <summary> /// EVP_aes_192_ecb() /// </summary> public static Cipher AES_192_ECB = new Cipher(Native.EVP_aes_192_ecb(), false); /// <summary> /// EVP_aes_192_cbc() /// </summary> public static Cipher AES_192_CBC = new Cipher(Native.EVP_aes_192_cbc(), false); /// <summary> /// EVP_aes_192_cfb1() /// </summary> public static Cipher AES_192_CFB1 = new Cipher(Native.EVP_aes_192_cfb1(), false); /// <summary> /// EVP_aes_192_cfb8() /// </summary> public static Cipher AES_192_CFB8 = new Cipher(Native.EVP_aes_192_cfb8(), false); /// <summary> /// EVP_aes_192_cfb128() /// </summary> public static Cipher AES_192_CFB128 = new Cipher(Native.EVP_aes_192_cfb128(), false); /// <summary> /// EVP_aes_192_ofb() /// </summary> public static Cipher AES_192_OFB = new Cipher(Native.EVP_aes_192_ofb(), false); /// <summary> /// EVP_aes_256_ecb() /// </summary> public static Cipher AES_256_ECB = new Cipher(Native.EVP_aes_256_ecb(), false); /// <summary> /// EVP_aes_256_cbc() /// </summary> public static Cipher AES_256_CBC = new Cipher(Native.EVP_aes_256_cbc(), false); /// <summary> /// EVP_aes_256_cfb1() /// </summary> public static Cipher AES_256_CFB1 = new Cipher(Native.EVP_aes_256_cfb1(), false); /// <summary> /// EVP_aes_256_cfb8() /// </summary> public static Cipher AES_256_CFB8 = new Cipher(Native.EVP_aes_256_cfb8(), false); /// <summary> /// EVP_aes_256_cfb128() /// </summary> public static Cipher AES_256_CFB128 = new Cipher(Native.EVP_aes_256_cfb128(), false); /// <summary> /// EVP_aes_256_ofb() /// </summary> public static Cipher AES_256_OFB = new Cipher(Native.EVP_aes_256_ofb(), false); /// <summary> /// EVP_aes_256_xts() /// </summary> public static Cipher AES_256_XTS = new Cipher(Native.EVP_aes_256_xts(), false); /* TODO const EVP_CIPHER *EVP_aes_128_ctr(void); const EVP_CIPHER *EVP_aes_128_ccm(void); const EVP_CIPHER *EVP_aes_128_gcm(void); const EVP_CIPHER *EVP_aes_128_xts(void); const EVP_CIPHER *EVP_aes_192_ecb(void); const EVP_CIPHER *EVP_aes_192_cbc(void); const EVP_CIPHER *EVP_aes_192_cfb1(void); const EVP_CIPHER *EVP_aes_192_cfb8(void); const EVP_CIPHER *EVP_aes_192_cfb128(void); # define EVP_aes_192_cfb EVP_aes_192_cfb128 const EVP_CIPHER *EVP_aes_192_ofb(void); const EVP_CIPHER *EVP_aes_192_ctr(void); const EVP_CIPHER *EVP_aes_192_ccm(void); const EVP_CIPHER *EVP_aes_192_gcm(void); const EVP_CIPHER *EVP_aes_256_ecb(void); const EVP_CIPHER *EVP_aes_256_cbc(void); const EVP_CIPHER *EVP_aes_256_cfb1(void); const EVP_CIPHER *EVP_aes_256_cfb8(void); const EVP_CIPHER *EVP_aes_256_cfb128(void); # define EVP_aes_256_cfb EVP_aes_256_cfb128 const EVP_CIPHER *EVP_aes_256_ofb(void); const EVP_CIPHER *EVP_aes_256_ctr(void); const EVP_CIPHER *EVP_aes_256_ccm(void); const EVP_CIPHER *EVP_aes_256_gcm(void); const EVP_CIPHER *EVP_aes_256_xts(void); #if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA1) const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void); const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void); * */ #endregion #region Properties /// <summary> /// Returns the key_len field /// </summary> public int KeyLength { get { return this.raw.key_len; } } /// <summary> /// Returns the iv_len field /// </summary> public int IVLength { get { return this.raw.iv_len; } } /// <summary> /// Returns the block_size field /// </summary> public int BlockSize { get { return this.raw.block_size; } } /// <summary> /// Returns the flags field /// </summary> public uint Flags { get { return this.raw.flags; } } /// <summary> /// Returns the long name for the nid field using OBJ_nid2ln() /// </summary> public string LongName { get { return Native.OBJ_nid2ln(this.raw.nid); } } /// <summary> /// Returns the name for the nid field using OBJ_nid2sn() /// </summary> public string Name { get { return Native.OBJ_nid2sn(this.raw.nid); } } /// <summary> /// Returns EVP_CIPHER_type() /// </summary> public int Type { get { return Native.EVP_CIPHER_type(this.ptr); } } /// <summary> /// Returns the long name for the type using OBJ_nid2ln() /// </summary> public string TypeName { get { return Native.OBJ_nid2ln(this.Type); } } #endregion } #endregion /// <summary> /// Simple struct to encapsulate common parameters for crypto functions /// </summary> public struct Envelope { /// <summary> /// The key for a crypto operation /// </summary> public byte[][] Keys; /// <summary> /// The IV (Initialization Vector) /// </summary> public byte[] IV; /// <summary> /// The payload (contains plaintext or ciphertext) /// </summary> public byte[] Data; } public class EncryptCipherContext : Base, IDisposable { private Cipher cipher; public EncryptCipherContext(Cipher cipher, byte[] key, byte[] iv, int padding) { this.ptr = Native.EVP_CIPHER_CTX_new(); this.owner = true; this.OnNewHandle(this.ptr); this.cipher = cipher; byte[] real_key = SetupKey(key); byte[] real_iv = SetupIV(iv); Native.ExpectSuccess(Native.EVP_EncryptInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, null, null)); Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_key_length(this.ptr, real_key.Length)); if( padding >= 0 ) Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_padding(this.ptr, padding)); if ((this.cipher.Flags & Native.EVP_CIPH_MODE) == Native.EVP_CIPH_STREAM_CIPHER) { for (int i = 0; i < Math.Min(real_key.Length, iv.Length); i++) { real_key[i] ^= iv[i]; } Native.ExpectSuccess(Native.EVP_EncryptInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, null)); } else { Native.ExpectSuccess(Native.EVP_EncryptInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, real_iv)); } } public byte[] Encrypt(byte[] input, int count) { return Encrypt(input, null, count); } public byte[] Encrypt(byte[] input, byte[] iv, int count) { int total = Math.Max(count, this.cipher.BlockSize); byte[] buf = new byte[total]; MemoryStream memory = new MemoryStream(total); Native.ExpectSuccess(Native.EVP_EncryptInit_ex( this.ptr, IntPtr.Zero, IntPtr.Zero, null, iv)); int len = 0; Native.ExpectSuccess(Native.EVP_EncryptUpdate(this.ptr, buf, out len, input, count)); memory.Write(buf, 0, len); len = buf.Length; Native.EVP_EncryptFinal_ex(this.ptr, buf, ref len); memory.Write(buf, 0, len); return memory.ToArray(); } private byte[] SetupKey(byte[] key) { if (key == null) { key = new byte[this.cipher.KeyLength]; key.Initialize(); return key; } if (this.cipher.KeyLength == key.Length) { return key; } byte[] real_key = new byte[this.cipher.KeyLength]; real_key.Initialize(); Buffer.BlockCopy(key, 0, real_key, 0, Math.Min(key.Length, real_key.Length)); return real_key; } private byte[] SetupIV(byte[] iv) { if (this.cipher.IVLength > iv.Length) { byte[] ret = new byte[this.cipher.IVLength]; ret.Initialize(); Buffer.BlockCopy(iv, 0, ret, 0, iv.Length); return ret; } return iv; } protected override void OnDispose() { Native.EVP_CIPHER_CTX_free(this.ptr); } } public class DecryptCipherContext : Base, IDisposable { private Cipher cipher; public DecryptCipherContext(Cipher cipher, byte[] key, byte[] iv, int padding) { this.ptr = Native.EVP_CIPHER_CTX_new(); this.owner = true; this.OnNewHandle(this.ptr); this.cipher = cipher; byte[] real_key = SetupKey(key); byte[] real_iv = SetupIV(iv); Native.ExpectSuccess(Native.EVP_DecryptInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, null, null)); Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_key_length(this.ptr, real_key.Length)); if( padding >= 0 ) Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_padding(this.ptr, padding)); if ((this.cipher.Flags & Native.EVP_CIPH_MODE) == Native.EVP_CIPH_STREAM_CIPHER) { for (int i = 0; i < Math.Min(real_key.Length, iv.Length); i++) { real_key[i] ^= iv[i]; } Native.ExpectSuccess(Native.EVP_DecryptInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, null)); } else { Native.ExpectSuccess(Native.EVP_DecryptInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, real_iv)); } } public byte[] Decrypt(byte[] input, int count) { return Decrypt(input, null, count); } public byte[] Decrypt(byte[] input, byte[] iv, int count) { int total = Math.Max(count, this.cipher.BlockSize); byte[] buf = new byte[total]; MemoryStream memory = new MemoryStream(total); Native.ExpectSuccess(Native.EVP_DecryptInit_ex( this.ptr, IntPtr.Zero, IntPtr.Zero, null, iv)); int len = 0; Native.ExpectSuccess(Native.EVP_DecryptUpdate(this.ptr, buf, out len, input, count)); memory.Write(buf, 0, len); len = buf.Length; Native.EVP_DecryptFinal_ex(this.ptr, buf, ref len); memory.Write(buf, 0, len); return memory.ToArray(); } private byte[] SetupKey(byte[] key) { if (key == null) { key = new byte[this.cipher.KeyLength]; key.Initialize(); return key; } if (this.cipher.KeyLength == key.Length) { return key; } byte[] real_key = new byte[this.cipher.KeyLength]; real_key.Initialize(); Buffer.BlockCopy(key, 0, real_key, 0, Math.Min(key.Length, real_key.Length)); return real_key; } private byte[] SetupIV(byte[] iv) { if (this.cipher.IVLength > iv.Length) { byte[] ret = new byte[this.cipher.IVLength]; ret.Initialize(); Buffer.BlockCopy(iv, 0, ret, 0, iv.Length); return ret; } return iv; } protected override void OnDispose() { Native.EVP_CIPHER_CTX_free(this.ptr); } } /// <summary> /// Wraps the EVP_CIPHER_CTX object. /// </summary> public class CipherContext : Base, IDisposable { private Cipher cipher; /// <summary> /// Calls OPENSSL_malloc() and initializes the buffer using EVP_CIPHER_CTX_init() /// </summary> /// <param name="cipher"></param> public CipherContext(Cipher cipher) { this.ptr = Native.EVP_CIPHER_CTX_new(); this.owner = true; this.OnNewHandle(this.ptr); this.cipher = cipher; } /// <summary> /// Returns the cipher's LongName /// </summary> /// <param name="bio"></param> public override void Print(BIO bio) { bio.Write("CipherContext: " + this.cipher.LongName); } #region Methods /// <summary> /// Calls EVP_OpenInit() and EVP_OpenFinal() /// </summary> /// <param name="input"></param> /// <param name="ekey"></param> /// <param name="iv"></param> /// <param name="pkey"></param> /// <returns></returns> public byte[] Open(byte[] input, byte[] ekey, byte[] iv, CryptoKey pkey) { Native.ExpectSuccess(Native.EVP_OpenInit( this.ptr, this.cipher.Handle, ekey, ekey.Length, iv, pkey.Handle)); MemoryStream memory = new MemoryStream(); byte[] output = new byte[input.Length + this.Cipher.BlockSize]; int len; Native.ExpectSuccess(Native.EVP_DecryptUpdate(this.ptr, output, out len, input, input.Length)); memory.Write(output, 0, len); Native.ExpectSuccess(Native.EVP_OpenFinal(this.ptr, output, out len)); memory.Write(output, 0, len); return memory.ToArray(); } /// <summary> /// Calls EVP_SealInit() and EVP_SealFinal() /// </summary> /// <param name="pkeys"></param> /// <param name="input"></param> /// <returns></returns> public Envelope Seal(CryptoKey[] pkeys, byte[] input) { Envelope env = new Envelope(); var ptrs = new IntPtr[pkeys.Length]; try { env.Keys = new byte[pkeys.Length][]; IntPtr[] pubkeys = new IntPtr[pkeys.Length]; int[] ekeylens = new int[pkeys.Length]; for (int i = 0; i < pkeys.Length; i++) { ptrs[i] = Marshal.AllocHGlobal(pkeys[i].Size); pubkeys[i] = pkeys[i].Handle; } if (this.Cipher.IVLength > 0) { env.IV = new byte[this.Cipher.IVLength]; } Native.ExpectSuccess(Native.EVP_SealInit( this.ptr, this.Cipher.Handle, ptrs, ekeylens, env.IV, pubkeys, pubkeys.Length)); for (int i = 0; i < pkeys.Length; i++) { env.Keys[i] = new byte[ekeylens[i]]; Marshal.Copy(ptrs[i], env.Keys[i], 0, ekeylens[i]); } MemoryStream memory = new MemoryStream(); byte[] output = new byte[input.Length + this.Cipher.BlockSize]; int len; Native.ExpectSuccess(Native.EVP_EncryptUpdate(this.ptr, output, out len, input, input.Length)); memory.Write(output, 0, len); Native.ExpectSuccess(Native.EVP_SealFinal(this.ptr, output, out len)); memory.Write(output, 0, len); env.Data = memory.ToArray(); return env; } finally { foreach (var ptr in ptrs) { Marshal.FreeHGlobal(ptr); } } } /// <summary> /// Encrypts or decrypts the specified payload. /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <param name="doEncrypt"></param> /// <returns></returns> public byte[] Crypt(byte[] input, byte[] key, byte[] iv, bool doEncrypt) { return this.Crypt(input, key, iv, doEncrypt, -1); } private byte[] SetupKey(byte[] key) { if (key == null) { key = new byte[this.Cipher.KeyLength]; key.Initialize(); return key; } if (this.Cipher.KeyLength == key.Length) { return key; } byte[] real_key = new byte[this.Cipher.KeyLength]; real_key.Initialize(); Buffer.BlockCopy(key, 0, real_key, 0, Math.Min(key.Length, real_key.Length)); return real_key; } private byte[] SetupIV(byte[] iv) { if (this.cipher.IVLength > iv.Length) { byte[] ret = new byte[this.cipher.IVLength]; ret.Initialize(); Buffer.BlockCopy(iv, 0, ret, 0, iv.Length); return ret; } return iv; } /// <summary> /// Calls EVP_CipherInit_ex(), EVP_CipherUpdate(), and EVP_CipherFinal_ex() /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <param name="doEncrypt"></param> /// <param name="padding"></param> /// <returns></returns> public byte[] Crypt(byte[] input, byte[] key, byte[] iv, bool doEncrypt, int padding) { return Crypt(input, input.Length, key, iv, doEncrypt, padding); } /// <summary> /// Calls EVP_CipherInit_ex(), EVP_CipherUpdate(), and EVP_CipherFinal_ex() /// </summary> /// <param name="input"></param> /// <param name="count"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <param name="doEncrypt"></param> /// <param name="padding"></param> /// <returns></returns> public byte[] Crypt(byte[] input, int count, byte[] key, byte[] iv, bool doEncrypt, int padding) { int enc = doEncrypt ? 1 : 0; int total = Math.Max(count, this.cipher.BlockSize); byte[] real_key = SetupKey(key); byte[] real_iv = SetupIV(iv); byte[] buf = new byte[total]; MemoryStream memory = new MemoryStream(total); Native.ExpectSuccess(Native.EVP_CipherInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, null, null, enc)); Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_key_length(this.ptr, real_key.Length)); if (this.IsStream) { for (int i = 0; i < Math.Min(real_key.Length, iv.Length); i++) { real_key[i] ^= iv[i]; } Native.ExpectSuccess(Native.EVP_CipherInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, null, enc)); } else { Native.ExpectSuccess(Native.EVP_CipherInit_ex( this.ptr, this.cipher.Handle, IntPtr.Zero, real_key, real_iv, enc)); } if (padding >= 0) Native.ExpectSuccess(Native.EVP_CIPHER_CTX_set_padding(this.ptr, padding)); int len = 0; Native.ExpectSuccess(Native.EVP_CipherUpdate(this.ptr, buf, out len, input, count)); memory.Write(buf, 0, len); len = buf.Length; Native.EVP_CipherFinal_ex(this.ptr, buf, ref len); memory.Write(buf, 0, len); return memory.ToArray(); } /// <summary> /// Encrypts the specified plaintext /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public byte[] Encrypt(byte[] input, byte[] key, byte[] iv) { return this.Crypt(input, key, iv, true); } /// <summary> /// Decrypts the specified ciphertext /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <returns></returns> public byte[] Decrypt(byte[] input, byte[] key, byte[] iv) { return this.Crypt(input, key, iv, false); } /// <summary> /// Encrypts the specified plaintext /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <param name="padding"></param> /// <returns></returns> public byte[] Encrypt(byte[] input, byte[] key, byte[] iv, int padding) { return this.Crypt(input, key, iv, true, padding); } /// <summary> /// Decrypts the specified ciphertext /// </summary> /// <param name="input"></param> /// <param name="key"></param> /// <param name="iv"></param> /// <param name="padding"></param> /// <returns></returns> public byte[] Decrypt(byte[] input, byte[] key, byte[] iv, int padding) { return this.Crypt(input, key, iv, false, padding); } /// <summary> /// Calls EVP_BytesToKey /// </summary> /// <param name="md"></param> /// <param name="salt"></param> /// <param name="data"></param> /// <param name="count"></param> /// <param name="iv"></param> /// <returns></returns> public byte[] BytesToKey(MessageDigest md, byte[] salt, byte[] data, int count, out byte[] iv) { int keylen = this.Cipher.KeyLength; if (keylen == 0) { keylen = 8; } byte[] key = new byte[keylen]; int ivlen = this.Cipher.IVLength; if (ivlen == 0) { ivlen = 8; } iv = new byte[ivlen]; Native.ExpectSuccess(Native.EVP_BytesToKey( this.cipher.Handle, md.Handle, salt, data, data.Length, count, key, iv)); return key; } #endregion #region Properties /// <summary> /// Returns the EVP_CIPHER for this context. /// </summary> public Cipher Cipher { get { return this.cipher; } } public bool IsStream { get { return (this.cipher.Flags & Native.EVP_CIPH_MODE) == Native.EVP_CIPH_STREAM_CIPHER; } } #endregion #region IDisposable Members /// <summary> /// Calls EVP_CIPHER_CTX_clean() and then OPENSSL_free() /// </summary> protected override void OnDispose() { Native.EVP_CIPHER_CTX_free(this.ptr); } #endregion } }